问:
Compiling C program in NetBeans 7
I have a problem with netbeans 7 about debugging and running C program, the problem is that after I wrote the code as the following

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("done");
    "khaled";

    return 0;
}
</code>```

in the output panel everything goes well but there's not any real output project (excutable file) no window appears.

I use gcc complier as the C compiler.

ContentLicense: CC BY-SA 3.0

Title: Compiling C program in NetBeans 7

Body:
I have a problem with netbeans 7 about debugging and running C program, the problem is that after I wrote the code as the following

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("done");
    "khaled";

    return 0;
}

in the output panel everything goes well but there's not any real output project (excutable file) no window appears.

I use gcc complier as the C compiler.


来源: stackexchange

问:
Simplify SRTP resolved on return type
I have some production code that I'd like to simplify (especially in light of new SRTP F# behaviour).

The intention is to statically resolve a method/function based solely on the return type required.

A simplified version of it is this:

```<code>type TypeOf<'a> = T

type ZeroFactory = Z with
    static member Zero(_: ZeroFactory,_ : TypeOf<int>) : _ = 0
    static member Zero(_: ZeroFactory,_ : TypeOf<string>) : _ = ""

let inline inlineZero t =
    ((^T or ^N) : (static member Zero : ^T * TypeOf< ^N > -> ^N)
        (t, T))

let inline zero () = inlineZero Z

let foo : int = zero ()
let bar : string = zero ()
</code>```

this code compiles and does what I intend, but has always felt overly contrived.

I CAN write this:

```<code>let inline inlineZero2 t =
    (^T : (static member Zero : ^T * TypeOf< ^N > -> ^N)
        (t, T))
</code>```

and to my eyes, that would seem to be good enough, but if i write:

```<code>let inline zero2 () = inlineZero2 Z
</code>```

I get

```<code>Error   FS0043  A unique overload for method 'Zero' could not be determined based on type information prior to this program point. A type annotation may be needed.

Known return type: 'a

Known type parameters: < ZeroFactory , TypeOf<'a> >

Candidates:
 - static member ZeroFactory.Zero: ZeroFactory * TypeOf<int> -> int
 - static member ZeroFactory.Zero: ZeroFactory * TypeOf<string> ->
</code>```

my hunch is that all the static type parameters in the method specification have to be mentioned on the left.

ContentLicense: CC BY-SA 4.0

Title: Simplify SRTP resolved on return type

Body:
I have some production code that I'd like to simplify (especially in light of new SRTP F# behaviour).

The intention is to statically resolve a method/function based solely on the return type required.

A simplified version of it is this:

type TypeOf<'a> = T

type ZeroFactory = Z with
    static member Zero(_: ZeroFactory,_ : TypeOf<int>) : _ = 0
    static member Zero(_: ZeroFactory,_ : TypeOf<string>) : _ = ""

let inline inlineZero t =
    ((^T or ^N) : (static member Zero : ^T * TypeOf< ^N > -> ^N)
        (t, T))

let inline zero () = inlineZero Z

let foo : int = zero ()
let bar : string = zero ()

this code compiles and does what I intend, but has always felt overly contrived.

I CAN write this:

let inline inlineZero2 t =
    (^T : (static member Zero : ^T * TypeOf< ^N > -> ^N)
        (t, T))

and to my eyes, that would seem to be good enough, but if i write:

let inline zero2 () = inlineZero2 Z

I get

Error   FS0043  A unique overload for method 'Zero' could not be determined based on type information prior to this program point. A type annotation may be needed.

Known return type: 'a

Known type parameters: < ZeroFactory , TypeOf<'a> >

Candidates:
 - static member ZeroFactory.Zero: ZeroFactory * TypeOf<int> -> int
 - static member ZeroFactory.Zero: ZeroFactory * TypeOf<string> ->

my hunch is that all the static type parameters in the method specification have to be mentioned on the left.


问:
Apache Camel split plain text based on first character
I have an apache camel route which listens for plain text formatted files on an SFTP server. These files have a clear structure but can be any lenght. I would like to be memory efficient and split them into multiple messages which can be processed individually.

The files look like this:

```<code>A1
B123
B456
B789
A2
B422
B873
A3
B863
B376
</code>```

etc.

There are any number of A-records with a up to 30 B-records underneath. There is a clear relationship here. All the B-records belong to the nearest A-record above. The file is invalid if it does not start with an A record. In theory though, there can be A-records without matching B-records.

For now I have the following implementation:

```<code>from("sftp:MYsftpDetails)
  .convertBodyTo(String.class)
  .to("file:mydir?fileName=${file:name}")
  .process(new myProcessor())
</code>```

The processor in this case holds a giant string which I can use java util's scanner to process. However, some of the files will be rather big meaning that I will soon run out of memory.

I have also tried this setup:

```<code>from("sftp:MYsftpDetails)
  .convertBodyTo(String.class)
  .to("file:mydir?fileName=${file:name}")
  .split()
  .tokenize("^A", true)
</code>```

This setup does not work because the entire file is considered as 1 record and therefore the tokenize simply only matches with the first A record found (which happens to be on line 1).

What would be the most camel way to split these files into entities that consist of 1 A-record and all its associated B-records?

Body:
I have an apache camel route which listens for plain text formatted files on an SFTP server. These files have a clear structure but can be any lenght. I would like to be memory efficient and split them into multiple messages which can be processed individually.

The files look like this:

A1
B123
B456
B789
A2
B422
B873
A3
B863
B376

etc.

There are any number of A-records with a up to 30 B-records underneath. There is a clear relationship here. All the B-records belong to the nearest A-record above. The file is invalid if it does not start with an A record. In theory though, there can be A-records without matching B-records.

For now I have the following implementation:

from("sftp:MYsftpDetails)
  .convertBodyTo(String.class)
  .to("file:mydir?fileName=${file:name}")
  .process(new myProcessor())

The processor in this case holds a giant string which I can use java util's scanner to process. However, some of the files will be rather big meaning that I will soon run out of memory.

I have also tried this setup:

from("sftp:MYsftpDetails)
  .convertBodyTo(String.class)
  .to("file:mydir?fileName=${file:name}")
  .split()
  .tokenize("^A", true)

This setup does not work because the entire file is considered as 1 record and therefore the tokenize simply only matches with the first A record found (which happens to be on line 1).

What would be the most camel way to split these files into entities that consist of 1 A-record and all its associated B-records?


问:
I expected to see value in the section of View Child Value as i created a directive which is PaDisplayValue, but failed
```<code><div class="bg-info text-white m-2 p-2">
    View Child Value: <span PaDisplayValue> </span>
</div>

<div class="bg-info text-white m-2 p-2">
    Content Child Value: <ng-content></ng-content>
</div>
</code>```

Please find the whole project in the following git repo:
https://github.com/codezj/example-directive-issue.git

Body:
    View Child Value:

    Content Child Value: <ng-content></ng-content>

Please find the whole project in the following git repo:
https://github.com/codezj/example-directive-issue.git


问:
Determine whether a "Long tail" exists in a dataset
I am working with a 200MB database that stores feedback from users about products in different years (Assume that 1 record = 1 feedback). The DB has the following schema

asin is a unique identifier of a product.

I am trying to determine if in any given year 20% of the products("asin") are accountable for more than 65% of the all feedbacks in that year ("Long-tail phenomena").

I tried to refer to the ASIN and the Year as a unique key and assign the value 1 to each time they key appeared. Then I would aggregate these values and would check if the first 20 ASIN count is bigger than 65% of all the feedback count.
The following is an example of my code in PySpark:

```<code>reviews_rdd = reviews_df_split_date.rdd
print(type(reviews_rdd))

reviews_rdd\
.map(lambda r: ((r.asin, r.Year),1))\
.reduceByKey(lambda v1, v2: v1 + v2)\
.collect()
</code>```

which produced the following output:

That's where I got stucked and didn't know how to group all ASIN in a given year and check the ASIN with the most feedbacks.

How can I check whether if less than 20% of the products in any given year account for over than 65% of all the feedbacks given in that year?

Body:
I am working with a 200MB database that stores feedback from users about products in different years (Assume that 1 record = 1 feedback). The DB has the following schema

asin is a unique identifier of a product.

I am trying to determine if in any given year 20% of the products("asin") are accountable for more than 65% of the all feedbacks in that year ("Long-tail phenomena").

I tried to refer to the ASIN and the Year as a unique key and assign the value 1 to each time they key appeared. Then I would aggregate these values and would check if the first 20 ASIN count is bigger than 65% of all the feedback count.
The following is an example of my code in PySpark:

reviews_rdd = reviews_df_split_date.rdd
print(type(reviews_rdd))

reviews_rdd\
.map(lambda r: ((r.asin, r.Year),1))\
.reduceByKey(lambda v1, v2: v1 + v2)\
.collect()

which produced the following output:

That's where I got stucked and didn't know how to group all ASIN in a given year and check the ASIN with the most feedbacks.

How can I check whether if less than 20% of the products in any given year account for over than 65% of all the feedbacks given in that year?


问:
Celery rerun application with specify time
I have a question about Celery.
I have subscribe system and want to send message in telegram bot by specific time.

```<code>@celery.task
def subscribe(chat_id, refresh_time):
    //response from api and after sendmessage in bot with webhook
</code>```

This task need to work infinite with by sleeping refresh time.
How i can do that ?

Body:
I have a question about Celery.
I have subscribe system and want to send message in telegram bot by specific time.

@celery.task
def subscribe(chat_id, refresh_time):
    //response from api and after sendmessage in bot with webhook

This task need to work infinite with by sleeping refresh time.
How i can do that ?


问:
access outlook 365 inbox
Until a few weeks ago a java code of mine was able to access the 365 inbox, this week I noticed that the routines were stopped and it was giving the error AUTHENTICATE failed in the Java debug. From what I've researched, it refers to changes in the 365 portal and you have to change the code, but so far no code that I thought would solve it.I wanted to know what I would need to change in the code below and in the 365 portal</p>
```<code>System.out.println("Inside MailReader()...");
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
// Set manual Properties
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.setProperty("mail.imaps.sasl.mechanisms","XOAUTH2");
props.put("mail.imaps.host", "outlook.office365.com");

try {
    /* Create the session and get the store for read the mail. */

    Session session = Session.getDefaultInstance(System.getProperties(), null);
    Store store = session.getStore("imaps");
    store.connect("outlook.office365.com", 993, "user", "pass");
</code>```

Title: access outlook 365 inbox

Body:
Until a few weeks ago a java code of mine was able to access the 365 inbox, this week I noticed that the routines were stopped and it was giving the error AUTHENTICATE failed in the Java debug. From what I've researched, it refers to changes in the 365 portal and you have to change the code, but so far no code that I thought would solve it.I wanted to know what I would need to change in the code below and in the 365 portal

System.out.println("Inside MailReader()...");
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
// Set manual Properties
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.setProperty("mail.imaps.sasl.mechanisms","XOAUTH2");
props.put("mail.imaps.host", "outlook.office365.com");

try {
    /* Create the session and get the store for read the mail. */

    Session session = Session.getDefaultInstance(System.getProperties(), null);
    Store store = session.getStore("imaps");
    store.connect("outlook.office365.com", 993, "user", "pass");


问:
open() error File exists even if O_EXCL is removed
I have the simple part of code that tries to open the file or create a new one:

```<code>desc = open(path, 0600 | O_RDWR | O_CREAT);
if (desc == -1){
    fprintf(stderr, "process %d: open: ", i);
    perror("");
}
</code>```

But even without O_EXCL I get an error "File exists"

```<code>process: open: File exists
</code>```

So what's the matter of this issue could be?

Body:
I have the simple part of code that tries to open the file or create a new one:

desc = open(path, 0600 | O_RDWR | O_CREAT);
if (desc == -1){
    fprintf(stderr, "process %d: open: ", i);
    perror("");
}

But even without O_EXCL I get an error "File exists"

process: open: File exists

So what's the matter of this issue could be?


问:
How to give each new spawned clone new individual values?
The enemy has a health and level value. When the players level value goes the level value does too. How can i change only the value of clones that will spawn in the future and leave the values of the spawned enemies as they are?

or

How can i change only the value of clones that the player didnt damage yet and future clones?

I can use a bool to check if an enemy got damaged but how do i do it for every enemy individually and not only one.

Right now im stuck with only that the values of the (second) clone that spawned after the (first) clone that got destroyed change.

```<code>public float Health = 20f;
public static float maxHealth = 20f;
public static float XP = 100f;
public float GroundMobLevel = 1;
public static bool LevelUp = false;
public bool GotDamage = false;
</code>```
```<code>public void MobLeveler()
{
if (LevelUp)
    {
    XP *= 2f;
    maxHealth *= 2f;
    Health = maxHealth;
    Damage += 10;
    GroundMobLevel += 1;
    Debug.Log("GroundMobLevel: " + GroundMobLevel);
    LevelUp = false;
    }
}
</code>```

the LevelUp gets triggered when the player levels up so it stays balanced. (the values are just to test for now)
all non static elements will reset for a new clone but how do i make it so that the value only changes for the new clone and not every already spawned clone.

Body:
The enemy has a health and level value. When the players level value goes the level value does too. How can i change only the value of clones that will spawn in the future and leave the values of the spawned enemies as they are?

or

How can i change only the value of clones that the player didnt damage yet and future clones?

I can use a bool to check if an enemy got damaged but how do i do it for every enemy individually and not only one.

Right now im stuck with only that the values of the (second) clone that spawned after the (first) clone that got destroyed change.

public float Health = 20f;
public static float maxHealth = 20f;
public static float XP = 100f;
public float GroundMobLevel = 1;
public static bool LevelUp = false;
public bool GotDamage = false;

public void MobLeveler()
{
if (LevelUp)
    {
    XP *= 2f;
    maxHealth *= 2f;
    Health = maxHealth;
    Damage += 10;
    GroundMobLevel += 1;
    Debug.Log("GroundMobLevel: " + GroundMobLevel);
    LevelUp = false;
    }
}

the LevelUp gets triggered when the player levels up so it stays balanced. (the values are just to test for now)
all non static elements will reset for a new clone but how do i make it so that the value only changes for the new clone and not every already spawned clone.


问:
Match duration of two audio with each other by scaling the frame rate
```<code>from pydub import AudioSegment

# Set the paths to the audio files
file1_path = '1.wav'
file2_path = '2.wav'

# Load the audio files
file1 = AudioSegment.from_file(file1_path, format='wav')
file2 = AudioSegment.from_file(file2_path, format='wav')

# Get the duration of the audio files in seconds
original_duration = len(file1)  # in milliseconds
desired_duration = len(file2)  # in milliseconds

# Calculate the factor by which to increase the frame rate
factor =  (round(original_duration)/desired_duration)

# Increase the frame rate by the calculated factor
stretched_audio = file2.set_frame_rate(int(file2.frame_rate * factor)).speedup()

# Save the modified audio
stretched_audio.export("output.wav", format="wav")
</code>```

This code is not working.

I want to match the duration of two audios with each other, basically trying to make it of the same length, and without trimming it.

Body:
from pydub import AudioSegment

# Set the paths to the audio files
file1_path = '1.wav'
file2_path = '2.wav'

# Load the audio files
file1 = AudioSegment.from_file(file1_path, format='wav')
file2 = AudioSegment.from_file(file2_path, format='wav')

# Get the duration of the audio files in seconds
original_duration = len(file1)  # in milliseconds
desired_duration = len(file2)  # in milliseconds

# Calculate the factor by which to increase the frame rate
factor =  (round(original_duration)/desired_duration)

# Increase the frame rate by the calculated factor
stretched_audio = file2.set_frame_rate(int(file2.frame_rate * factor)).speedup()

# Save the modified audio
stretched_audio.export("output.wav", format="wav")

This code is not working.

I want to match the duration of two audios with each other, basically trying to make it of the same length, and without trimming it.


问:
Python's Zeep - How to allow multiple occurrences of the same tag?
How do you use Zeep to consume a webservice which allows for multiple occurrences of the same tag in the XML?

In Zeep's documentation, you can get an object:

```<code>from zeep import Client

client = Client('http://my-enterprise-endpoint.com')
order_type = client.get_type('ns0:Order')
order = order_type(number='1234', price=99)
client.service.submit_order(user_id=1, order=order)
</code>```

Or create a dictionary:

```<code>client = Client('http://my-enterprise-endpoint.com')
client.service.submit_order(user_id=1, order={'number': '1234','price': 99, })
</code>```

And Zeep will form the XML for you and submit to the method given. However, the dictionary can't have two keys of the exact same name, and I'm unsure that the object would allow two values for the same parameter.

Is there another way in Python to do this, or is Zeep pretty much my only hope?

E.g.:

```<code>client = Client('http://my-enterprise-endpoint.com')
client.service.submit_order(user_id=1, order={'number': '1234','price': 99, price': 88})
</code>```

Body:
How do you use Zeep to consume a webservice which allows for multiple occurrences of the same tag in the XML?

In Zeep's documentation, you can get an object:

from zeep import Client

client = Client('http://my-enterprise-endpoint.com')
order_type = client.get_type('ns0:Order')
order = order_type(number='1234', price=99)
client.service.submit_order(user_id=1, order=order)

Or create a dictionary:

client = Client('http://my-enterprise-endpoint.com')
client.service.submit_order(user_id=1, order={'number': '1234','price': 99, })

And Zeep will form the XML for you and submit to the method given. However, the dictionary can't have two keys of the exact same name, and I'm unsure that the object would allow two values for the same parameter.

Is there another way in Python to do this, or is Zeep pretty much my only hope?

E.g.:

client = Client('http://my-enterprise-endpoint.com')
client.service.submit_order(user_id=1, order={'number': '1234','price': 99, price': 88})


问:
Redis read from multiple streams using a single client connection
I'm using Redis server v=6.2.6 with 3 masters and 2 slaves for each master, hence total 9 nodes in the cluster.

I have 2 streams with some records in those streams. When I try to read from both the streams from redis-cli as:

```<code>xread STREAMS mystream stream02 0 0
</code>```

I see the error message:

(error) CROSSSLOT Keys in request don't hash to the same slot

Does it mean that practically we cannot read records from multiple streams in a single connection if the keys (stream names/id) hash to different owner/master nodes?

Isn't this very limiting?
What is the supposed way to consume records from multiple streams in a single client?

Body:
I'm using Redis server v=6.2.6 with 3 masters and 2 slaves for each master, hence total 9 nodes in the cluster.

I have 2 streams with some records in those streams. When I try to read from both the streams from redis-cli as:

xread STREAMS mystream stream02 0 0

I see the error message:

(error) CROSSSLOT Keys in request don't hash to the same slot

Does it mean that practically we cannot read records from multiple streams in a single connection if the keys (stream names/id) hash to different owner/master nodes?

Isn't this very limiting?
What is the supposed way to consume records from multiple streams in a single client?


问:
new installation of RStudio not working properly
I am having a lot of OS issues with the new version of RStudio.  I am working on a Mac.

It does not recognize the packages that I had to reinstall. The current problem I am dealing with is that source('filename.R') is not working.
I get the following:

```<code>Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

trying URL 'https://cran.mirrors.hoobly.com/src/contrib/rmarkdown_2.19.tar.gz'
Content type 'application/x-gzip' length 3243575 bytes (3.1 MB)
==================================================
downloaded 3.1 MB

* installing *source* package ‘rmarkdown’ ...
** package ‘rmarkdown’ successfully unpacked and MD5 sums checked

** using staged installation
** R
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
*** copying figures
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
* DONE (rmarkdown)

The downloaded source packages are in
    ‘/private/var/folders/yk/spk56bkn22n8w43h0mr6x59xtb6t8m/T/RtmpTD79O7/downloaded_packages’
Error in eval(ei, envir) : object 'xfun' not found
</code>```

I have re installed various libraries including xfun

I was having a lot of trouble knitting a markdown file so I tried to run the code from an r-script.
But I have the same error.
I am confused why it is trying to install rmarkdown and dplyr when I use source() in the script file.

Both dplyr and rmarkdown have already been installed as well as xfun.

So I think there is a problem with a path name where to find the various packages but I don't know how to fix this.

Body:
I am having a lot of OS issues with the new version of RStudio.  I am working on a Mac.

It does not recognize the packages that I had to reinstall. The current problem I am dealing with is that source('filename.R') is not working.
I get the following:

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

trying URL 'https://cran.mirrors.hoobly.com/src/contrib/rmarkdown_2.19.tar.gz'
Content type 'application/x-gzip' length 3243575 bytes (3.1 MB)
==================================================
downloaded 3.1 MB

* installing *source* package ‘rmarkdown’ ...
** package ‘rmarkdown’ successfully unpacked and MD5 sums checked

** using staged installation
** R
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
*** copying figures
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
* DONE (rmarkdown)

The downloaded source packages are in
    ‘/private/var/folders/yk/spk56bkn22n8w43h0mr6x59xtb6t8m/T/RtmpTD79O7/downloaded_packages’
Error in eval(ei, envir) : object 'xfun' not found

I have re installed various libraries including xfun

I was having a lot of trouble knitting a markdown file so I tried to run the code from an r-script.
But I have the same error.
I am confused why it is trying to install rmarkdown and dplyr when I use source() in the script file.

Both dplyr and rmarkdown have already been installed as well as xfun.

So I think there is a problem with a path name where to find the various packages but I don't know how to fix this.


问:
problem with viewpager2 and bottomnav working together in android studio
so I'm trying to make small application type of thing where it has bottom navigation bar and viewpager2 working in it. But I want it so that in the first fragment page that application loads in, only there viewpager2 is available to work and be able to swipe, when I switch to next fragment with navigation bar that viewpager2 should basically disappear and not work, therefore my logic was to put that viewpager2 in that single fragment and navigation bar outside in main activity for it to be able to be seen in every fragment. But there is a problem, it almost works, I switch to another fragment with bar view pager disappears but when I go back to that first fragment view pager is just gone, disappeared and I have no idea what's the problem. if necessary I can show what I have written. Thanks in advance</p>


问:
Firemonkey how to set font color for selected text in TEdit
I'm trying to find a way to use styles to set the color of the selected text in a TEdit in Firemonkey.
In Delphi VCL, the text color by default changes to white (or perhaps a windows constant) when the text is selected, so that it shows clearly through the selection highlight.
In FMX, the default style is for the text color not to change. That results in the text being hard to read.  I'd like to set it so that it works like VCL, but I can't find anywhere in the style to set the text color of the selected text.
Thanks for any help you can provide.
Scott</p>


问:
How do I draw an adaptive vertical slash line?
I'm just learning the layout and I would like to make a page where there are blocks and lines between them and when you scroll, they will appear
I need to draw a vertical line that will connect the blocks, but so that it was adaptive.
I tried using skew, but it is not adaptive

.skill-l{
    width: 100%;
    height: min-content;
    background-color: pink;

}
.skill-r{
    width: 100%;
    height: min-content;
    text-align: end;
    background-color: lightgreen;
}

.container-main{
    margin-left: 33%;
    margin-right: 33%;
}

.line-lr {
    height: 50vh;
    width: 3px;
    background: green;
    transform: skewX(30deg);
    margin-left: 50%;
    color: green;
}
.line-rl {
    height: 50vh;
    width: 3px;
    background: yellow;
    transform: skewX(-30deg);
    color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-main">
    <div class="skill-l text-white">
        <h2>DIV 1</h2>
    </div>
    <div class="line-lr mx-auto">
    </div>
    <div class="skill-r text-white">
        <h2>DIV 2</h2>
    </div>
    <div class="line-rl mx-auto"></div>
    <div class="skill-l text-white">
        <h2>DIV 3</h2>
    </div>
</div></code>```

My lines go over the block. How can I prevent that?

Body:
I'm just learning the layout and I would like to make a page where there are blocks and lines between them and when you scroll, they will appear
I need to draw a vertical line that will connect the blocks, but so that it was adaptive.
I tried using skew, but it is not adaptive

.skill-l{
    width: 100%;
    height: min-content;
    background-color: pink;

}
.skill-r{
    width: 100%;
    height: min-content;
    text-align: end;
    background-color: lightgreen;
}

.container-main{
    margin-left: 33%;
    margin-right: 33%;
}

.line-lr {
    height: 50vh;
    width: 3px;
    background: green;
    transform: skewX(30deg);
    margin-left: 50%;
    color: green;
}
.line-rl {
    height: 50vh;
    width: 3px;
    background: yellow;
    transform: skewX(-30deg);
    color: yellow;
}

DIV 1

DIV 2

DIV 3

My lines go over the block. How can I prevent that?


问:
How to set PasswordProtectedTransport and transient in spring-security-saml2-service-provider?
In the org.springframework.security.extensions versions of spring-security-saml2-core, we set the nameid-format:transient and classes:PasswordProtectedTransport in our service provider code like so:

```<code>WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions();
webSSOProfileOptions.setIncludeScoping ( false );
webSSOProfileOptions.setNameID ( "urn:oasis:names:tc:SAML:2.0:nameid-format:transient" );
List<String> ac = new ArrayList<String>();
ac.add ( "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" );
webSSOProfileOptions.setAuthnContexts ( ac );
</code>```

However, in the newer non-extension org.springframework.security implementations of spring-security-saml2-service-provider, there is no longer an WebSSOProfileOptions object.

How do we set nameid-format:transient and classes:PasswordProtectedTransport in the newer versions of Spring SAML?  For now, we would like to maintain Java 8 compatibility, so we're interested in Spring security versions 5.6.x and 5.7.x.

I tried Googling, looking at XML metadata samples, browsing Spring classes, reading some Spring documentation, and not much reading newer Spring source code to try to understand where the settings should be specified.

Body:
In the org.springframework.security.extensions versions of spring-security-saml2-core, we set the nameid-format:transient and classes:PasswordProtectedTransport in our service provider code like so:

WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions();
webSSOProfileOptions.setIncludeScoping ( false );
webSSOProfileOptions.setNameID ( "urn:oasis:names:tc:SAML:2.0:nameid-format:transient" );
List<String> ac = new ArrayList<String>();
ac.add ( "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" );
webSSOProfileOptions.setAuthnContexts ( ac );

However, in the newer non-extension org.springframework.security implementations of spring-security-saml2-service-provider, there is no longer an WebSSOProfileOptions object.

How do we set nameid-format:transient and classes:PasswordProtectedTransport in the newer versions of Spring SAML?  For now, we would like to maintain Java 8 compatibility, so we're interested in Spring security versions 5.6.x and 5.7.x.

I tried Googling, looking at XML metadata samples, browsing Spring classes, reading some Spring documentation, and not much reading newer Spring source code to try to understand where the settings should be specified.


问:
c# WebClient returns 403 when downloading the file from remote URL
When try to Download file, using WebClient, from remote website, I get an error: The remote server returned an error: (403) Forbidden. It is reproducing only on one laptop. On my local laptop everything works fine. I am using the header "User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)" but it is not helping. Anyway I can open that link manually and download that file. Are there any solutions of this problem? Thanks in advance.


问:
How do class-based views work in Django Rest Framework?
I want to have an understanding to reason about Django + DRF.

I'm following along the tutorial on the Django Rest Framework site

Consider the SnippetList class in views.py:

```<code>class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
    snippets = Snippet.objects.all()
    serializer = SnippetSerializer(snippets, many=True)
    return Response(serializer.data)
</code>```

I'm used to JavasCript and to a more imperative way of doing things and it feels that there is a lot of magic here since I'm not explicitly instantiating any classes nor calling any methods.

So, my question is, what happens when I request this view? How can I reason about the steps and the process?

I visit the endpoint in http://127.0.0.1:8000/snippets/ to get a list of all the snippets and what is the cascade of events thereafter?

How is the /snippets/ query parameter passed to the view class?

I realise it's it might not be a specific enough question but I'm trying to disentangle the magic happening behind the scenes.

Body:
I want to have an understanding to reason about Django + DRF.

I'm following along the tutorial on the Django Rest Framework site

Consider the SnippetList class in views.py:

class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
    snippets = Snippet.objects.all()
    serializer = SnippetSerializer(snippets, many=True)
    return Response(serializer.data)

I'm used to JavasCript and to a more imperative way of doing things and it feels that there is a lot of magic here since I'm not explicitly instantiating any classes nor calling any methods.

So, my question is, what happens when I request this view? How can I reason about the steps and the process?

I visit the endpoint in http://127.0.0.1:8000/snippets/ to get a list of all the snippets and what is the cascade of events thereafter?

How is the /snippets/ query parameter passed to the view class?

I realise it's it might not be a specific enough question but I'm trying to disentangle the magic happening behind the scenes.


问:
How to mock an imported function with jest
I have the following in my test:

```<code>import authMiddleware from '../../src/middleware/authMiddleware'
const mockAuth = jest.fn()
</code>```

Then I try the following:

```<code>jest.mock('../../src/middleware/authMiddleware', () => {
  return jest.fn().mockImplementation(() => mockAuth)
})
</code>```

But when I try in my test:

```<code>mockAuth.mockReturnValue(88)
console.log('ok?', authMiddleware())
</code>```

Then it logs the function, if I do authMiddleware()() then it logs 88

So I changed jest.mock to:

```<code>jest.mock('../../src/middleware/authMiddleware', () => {
  return jest.fn().mockImplementation(mockAuth)
})
</code>```

But that results in an error ReferenceError: Cannot access 'mockAuth' before initialization

Same error when trying:

```<code>jest.mock(
  '../../src/middleware/authMiddleware',
  jest.fn().mockImplementation(() => mockAuth)
)
</code>```

The example I found shows mocking classes but authMiddleware is exported default as a function:

```<code>const authMiddleware = (example)=>example;
export default authMiddleware
</code>```

Body:
I have the following in my test:

import authMiddleware from '../../src/middleware/authMiddleware'
const mockAuth = jest.fn()

Then I try the following:

jest.mock('../../src/middleware/authMiddleware', () => {
  return jest.fn().mockImplementation(() => mockAuth)
})

But when I try in my test:

mockAuth.mockReturnValue(88)
console.log('ok?', authMiddleware())

Then it logs the function, if I do authMiddleware()() then it logs 88

So I changed jest.mock to:

jest.mock('../../src/middleware/authMiddleware', () => {
  return jest.fn().mockImplementation(mockAuth)
})

But that results in an error ReferenceError: Cannot access 'mockAuth' before initialization

Same error when trying:

jest.mock(
  '../../src/middleware/authMiddleware',
  jest.fn().mockImplementation(() => mockAuth)
)

The example I found shows mocking classes but authMiddleware is exported default as a function:

const authMiddleware = (example)=>example;
export default authMiddleware


问:
How use Hibernate Envers with Teiid
I have a problem with the integration of hibernate envers on a application that use Teiid. This one doesn't support ddl like 'create table TABLE_NAME_AUD' or sequence generation.

I tried to split entity manager and tranction manager and delegate create table to another entity manager, but the transations on entities created by virtual table doesn't work. I also tried to create tables on DB, but the insert statement generated by hibernate dosn't work because the name of column of reventity is a keyword of teiid syntax and I can't change the name of column.
So, there's a way to implements hibernate envers with Teiid propertly?

Thanks!

Title: How use Hibernate Envers with Teiid


问:
Executable file is replaced after execve when debug using gdb
Sir, I have a simple code.

#include <unistd.h>

int main()
{
  char *argv[2];

  argv[0] = "/usr/bin/env";
  argv[1] = NULL;

  execve("/usr/bin/env", argv, NULL);
  return 0 ;
}
```

I build it with gcc -O0 test.c and try to use gdb to debug a.out. And I found that if I first type r to run it is starting program a.out, but when I type r again, the program is replaced by /usr/bin/env, I don't know whether it is a bug or feature.

Body:
Sir, I have a simple code.

#include <unistd.h>

int main()
{
  char *argv[2];

  argv[0] = "/usr/bin/env";
  argv[1] = NULL;

  execve("/usr/bin/env", argv, NULL);
  return 0 ;
}

I build it with gcc -O0 test.c and try to use gdb to debug a.out. And I found that if I first type r to run it is starting program a.out, but when I type r again, the program is replaced by /usr/bin/env, I don't know whether it is a bug or feature.


问:
Get Empty Rows in TypeORM
I'm trying to write a typeORM query which includes multiple where clauses. I am able to achieve this via where option as follows:

```<code>const categories = [
         { name: 'master', categoryTypeId: 2, parentId: 1, locationId: null },
         { name: 'food', categoryTypeId: 3, parentId: null, locationId: null }];

const rows = await Repo.find({
      where: categories.map((category) => ({
        name: category.name,
        categoryTypeId: category.categoryTypeId,
        locationId: category.locationId
      })),
});
</code>```

I would want to maintain the mapping b/w the input array and the rows returned. For example, I know that the  second category doesn't exist in the DB. I would want to have an empty object in the rows variable so that I know which categories didn't yield any result.

Upon research I have found that we can do something with SQL as mentioned here. But, I'm not sure how do I translate into typeORM if I can.

Title: Get Empty Rows in TypeORM

Body:
I'm trying to write a typeORM query which includes multiple where clauses. I am able to achieve this via where option as follows:

const categories = [
         { name: 'master', categoryTypeId: 2, parentId: 1, locationId: null },
         { name: 'food', categoryTypeId: 3, parentId: null, locationId: null }];

const rows = await Repo.find({
      where: categories.map((category) => ({
        name: category.name,
        categoryTypeId: category.categoryTypeId,
        locationId: category.locationId
      })),
});

I would want to maintain the mapping b/w the input array and the rows returned. For example, I know that the  second category doesn't exist in the DB. I would want to have an empty object in the rows variable so that I know which categories didn't yield any result.

Upon research I have found that we can do something with SQL as mentioned here. But, I'm not sure how do I translate into typeORM if I can.


问:
How to differentiate two signals -one with noise and one with pattern
I have two signals and I would like to differentiate these two signals. The pattern shown here is not constant, but the lack of pattern indicates a noisy signal. What measure could I use to differentiate these two - robustly.

Thanks.


问:
Making a socket that only exits if exit message is received
```<code>#include <io.h>
#include <stdio.h>
#include <winsock2.h>
#include <string.h>

#define MY_PORT     8989
#define MAXBUF      256

//function prototype
int exitmsg(const char *a, const char *b);

int main(int argc, char *argv[]){
    WSADATA wsa;
    SOCKET sockfd ,clientfd; //define 2 sockets
    struct sockaddr_in self;
    char buffer[MAXBUF];

    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0){
        printf("Failed. Error Code : %d",WSAGetLastError());
        return 1;
    }
    printf("Initialised.\n");

    /*---create streaming socket---*/
    if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ){
        perror("Socket");
        exit(errno);
    }
    printf("Socket created.\n");

    /*---initialize address/port structure---*/
    /* bzero(&self, sizeof(self));*/
    self.sin_family = AF_INET;
    self.sin_port = htons(MY_PORT);
    self.sin_addr.s_addr = INADDR_ANY;

    /*---assign a port number to the socket---*/
    if ((bind(sockfd, (struct sockaddr*)&self, sizeof(self)))!=0){
        perror("socket--bind");
        exit(errno);
    }
    puts("Bind done");

    /*---make it a "listening socket"---*/
    if ((listen(sockfd, 20))!=0){
        perror("socket--listen");
        exit(errno);
    }
    puts("Waiting for incoming connections...");

    /*---forever... ---*/
    while (1){
        struct sockaddr_in client_addr;
        int addrlen=sizeof(client_addr), checking;

        /*---accept a connection (creating a data pipe)---*/
        clientfd= accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
        char test[20]="exit server";
        int loop=0, len=strlen(buffer);
        char temp;  //temporary holds character to swap
        int length= recv(clientfd, buffer, MAXBUF, 0);

        // handle multiple requests
        do {
            //from server 1
            for(int i=0; i<len; i++){
                if(buffer[i]>=65 && buffer[i]<=90){ // check ascii value
                    buffer[i]= buffer[i]+32;        // if uppercase thn change
                }
            }

            //check if client want to exit
            checking= exitmsg(test, buffer);
            if (checking==1){
                printf("Message to exit received. \n");
            }

            else{
                //reverse
                len--;     // start from 0

                while (loop<len){
                    temp=buffer[loop];
                    buffer[loop]=buffer[len];
                    buffer[len]=temp;
                    loop++;
                    len--;
                }

                //outputs
                //ip and host port
                char *ipadd=inet_ntoa(client_addr.sin_addr);
                printf("IP address: %s \nPORT: %d\n", ipadd, ntohs(client_addr.sin_port));
                printf("Length of message: %d\n", length);

                //send back
                send(clientfd, buffer, strlen(buffer), 0);
            }
            length= recv(clientfd, buffer, MAXBUF, 0)>0;
        }while (length>0);

        /*---close connection---*/
        close(clientfd);
    }

    /*---clean up (should never get here!)---*/
    close(sockfd);
    WSACleanup();
    return 0;
}

int exitmsg(const char *a, const char *b){
    for(; (*a!='\0' && *b!='\0'); a++, b++){
        if(*a==*b){
            return 1;
        }
    }
    return 0;
}

</code>```

I tried to look for several references online and came up with this, however my server doesn't work as intended. Currently sends back only reverses first 3 letters string with a letter missing and secondly the original string with two characters missing. I'm using port 8989 with a passive Telnet connection. All pointers to understand what's happening would be useful as I'm very new to this.

I'm also attempting to print the ip address, port number and length of buffer for each connection made.

I'm trying to make the server handle multiple requests from a single client, however I'm wondering whether it's even possible....

Body:
#include <io.h>
#include <stdio.h>
#include <winsock2.h>
#include <string.h>

#define MY_PORT     8989
#define MAXBUF      256

//function prototype
int exitmsg(const char *a, const char *b);

int main(int argc, char *argv[]){
    WSADATA wsa;
    SOCKET sockfd ,clientfd; //define 2 sockets
    struct sockaddr_in self;
    char buffer[MAXBUF];

    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0){
        printf("Failed. Error Code : %d",WSAGetLastError());
        return 1;
    }
    printf("Initialised.\n");

    /*---create streaming socket---*/
    if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ){
        perror("Socket");
        exit(errno);
    }
    printf("Socket created.\n");

    /*---initialize address/port structure---*/
    /* bzero(&self, sizeof(self));*/
    self.sin_family = AF_INET;
    self.sin_port = htons(MY_PORT);
    self.sin_addr.s_addr = INADDR_ANY;

    /*---assign a port number to the socket---*/
    if ((bind(sockfd, (struct sockaddr*)&self, sizeof(self)))!=0){
        perror("socket--bind");
        exit(errno);
    }
    puts("Bind done");

    /*---make it a "listening socket"---*/
    if ((listen(sockfd, 20))!=0){
        perror("socket--listen");
        exit(errno);
    }
    puts("Waiting for incoming connections...");

    /*---forever... ---*/
    while (1){
        struct sockaddr_in client_addr;
        int addrlen=sizeof(client_addr), checking;

        /*---accept a connection (creating a data pipe)---*/
        clientfd= accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
        char test[20]="exit server";
        int loop=0, len=strlen(buffer);
        char temp;  //temporary holds character to swap
        int length= recv(clientfd, buffer, MAXBUF, 0);

        // handle multiple requests
        do {
            //from server 1
            for(int i=0; i<len; i++){
                if(buffer[i]>=65 && buffer[i]<=90){ // check ascii value
                    buffer[i]= buffer[i]+32;        // if uppercase thn change
                }
            }

            //check if client want to exit
            checking= exitmsg(test, buffer);
            if (checking==1){
                printf("Message to exit received. \n");
            }

            else{
                //reverse
                len--;     // start from 0

                while (loop<len){
                    temp=buffer[loop];
                    buffer[loop]=buffer[len];
                    buffer[len]=temp;
                    loop++;
                    len--;
                }

                //outputs
                //ip and host port
                char *ipadd=inet_ntoa(client_addr.sin_addr);
                printf("IP address: %s \nPORT: %d\n", ipadd, ntohs(client_addr.sin_port));
                printf("Length of message: %d\n", length);

                //send back
                send(clientfd, buffer, strlen(buffer), 0);
            }
            length= recv(clientfd, buffer, MAXBUF, 0)>0;
        }while (length>0);

        /*---close connection---*/
        close(clientfd);
    }

    /*---clean up (should never get here!)---*/
    close(sockfd);
    WSACleanup();
    return 0;
}

int exitmsg(const char *a, const char *b){
    for(; (*a!='\0' && *b!='\0'); a++, b++){
        if(*a==*b){
            return 1;
        }
    }
    return 0;
}

I tried to look for several references online and came up with this, however my server doesn't work as intended. Currently sends back only reverses first 3 letters string with a letter missing and secondly the original string with two characters missing. I'm using port 8989 with a passive Telnet connection. All pointers to understand what's happening would be useful as I'm very new to this.

I'm also attempting to print the ip address, port number and length of buffer for each connection made.

I'm trying to make the server handle multiple requests from a single client, however I'm wondering whether it's even possible....


问:
Web Socket Server in vb.net
I am trying to create the simplest WebSocket server with VB.NET like this websocket.I copied some code from google but haven't able to implement it in right way. you need a webserver, a browser and the web socket server to run simultaneously in order for it to work. please help me to solve this.

```<code>Imports System.Net.Sockets
Imports System.Threading
Public Class Form1
    Dim serverTcp As TcpListener
    Dim serverThread As Thread
    Sub Main()

        '' Start server
        serverThread = New Thread(AddressOf serverProc)
        serverThread.Start()
    End Sub
    Private Sub serverProc()

        '' Listen to port 8181
        serverTcp = New TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 8181)
        serverTcp.Start()

        Console.WriteLine("Listen to port 8181 ...")

        '' Accept any connection
        While (True)
            Dim curSocket As Socket = serverTcp.AcceptSocket()
            Dim thread As New Thread(AddressOf clientProc)
            thread.Start(curSocket)
        End While
    End Sub
    Private Sub clientProc(ByVal sck As Socket)
        Dim netStream As New NetworkStream(sck)
        Dim netReader As New IO.StreamReader(netStream)
        Dim netWriter As New IO.StreamWriter(netStream)

        Dim key As String = ""

        Console.WriteLine("Accept new connection ...")

        '' Reading handshake message
        While (True)
            Dim line As String = netReader.ReadLine()
            If line.Length = 0 Then
                Exit While
            End If

            If (line.StartsWith("Sec-WebSocket-Key: ")) Then
                key = line.Split(":")(1).Trim()
            End If

            Console.WriteLine("Data: " & line)
        End While

        '' Calculate accept-key
        key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        key = getSHA1Hash(key)

        '' Response handshake message
        Dim response As String
        response = "HTTP/1.1 101 Switching Protocols" & vbCrLf
        response &= "Upgrade: websocket" & vbCrLf
        response &= "Connection: Upgrade" & vbCrLf
        response &= "Sec-WebSocket-Accept: " & key & vbCrLf & vbCrLf
        netWriter.Write(response)
        netWriter.Flush()

        '' Sending Hello World message
        Dim message As String = "Hello World"
        Dim messageByte() As Byte = System.Text.Encoding.UTF8.GetBytes(message)
        Dim startByte() As Byte = {&H0}
        Dim endByte() As Byte = {&HFF}

        sck.Send(startByte, 1, 0)
        sck.Send(messageByte)
        sck.Send(endByte, 1, 0)
    End Sub
    Function getSHA1Hash(ByVal strToHash As String) As String
        Dim sha1Obj As New Security.Cryptography.SHA1CryptoServiceProvider
        Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
        Dim result As String

        bytesToHash = sha1Obj.ComputeHash(bytesToHash)
        result = Convert.ToBase64String(bytesToHash)

        Return result
    End Function
End Class
</code>```

My html5 code on http://localhost:8080/

    <title>Web Socket Chat</title>

Web Socket Chat

Server
        <input type="text" name="host" id="host" value="ws://localhost:8181/chat" />
        <input type="submit" name="host_connect" id="host_connect" value="Reconnect!" />

Type /nick your_nickname to change your nick

```
    <input type="text" name="console_input" id="console_input" value="" />
    <input type="submit" name="console_send" id="console_send" value="Send" />
</div>

</body>

</html></code>```

Title: Web Socket Server in vb.net

Body:
I am trying to create the simplest WebSocket server with VB.NET like this websocket.I copied some code from google but haven't able to implement it in right way. you need a webserver, a browser and the web socket server to run simultaneously in order for it to work. please help me to solve this.

Imports System.Net.Sockets
Imports System.Threading
Public Class Form1
    Dim serverTcp As TcpListener
    Dim serverThread As Thread
    Sub Main()

        '' Start server
        serverThread = New Thread(AddressOf serverProc)
        serverThread.Start()
    End Sub
    Private Sub serverProc()

        '' Listen to port 8181
        serverTcp = New TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 8181)
        serverTcp.Start()

        Console.WriteLine("Listen to port 8181 ...")

        '' Accept any connection
        While (True)
            Dim curSocket As Socket = serverTcp.AcceptSocket()
            Dim thread As New Thread(AddressOf clientProc)
            thread.Start(curSocket)
        End While
    End Sub
    Private Sub clientProc(ByVal sck As Socket)
        Dim netStream As New NetworkStream(sck)
        Dim netReader As New IO.StreamReader(netStream)
        Dim netWriter As New IO.StreamWriter(netStream)

        Dim key As String = ""

        Console.WriteLine("Accept new connection ...")

        '' Reading handshake message
        While (True)
            Dim line As String = netReader.ReadLine()
            If line.Length = 0 Then
                Exit While
            End If

            If (line.StartsWith("Sec-WebSocket-Key: ")) Then
                key = line.Split(":")(1).Trim()
            End If

            Console.WriteLine("Data: " & line)
        End While

        '' Calculate accept-key
        key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        key = getSHA1Hash(key)

        '' Response handshake message
        Dim response As String
        response = "HTTP/1.1 101 Switching Protocols" & vbCrLf
        response &= "Upgrade: websocket" & vbCrLf
        response &= "Connection: Upgrade" & vbCrLf
        response &= "Sec-WebSocket-Accept: " & key & vbCrLf & vbCrLf
        netWriter.Write(response)
        netWriter.Flush()

        '' Sending Hello World message
        Dim message As String = "Hello World"
        Dim messageByte() As Byte = System.Text.Encoding.UTF8.GetBytes(message)
        Dim startByte() As Byte = {&H0}
        Dim endByte() As Byte = {&HFF}

        sck.Send(startByte, 1, 0)
        sck.Send(messageByte)
        sck.Send(endByte, 1, 0)
    End Sub
    Function getSHA1Hash(ByVal strToHash As String) As String
        Dim sha1Obj As New Security.Cryptography.SHA1CryptoServiceProvider
        Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
        Dim result As String

        bytesToHash = sha1Obj.ComputeHash(bytesToHash)
        result = Convert.ToBase64String(bytesToHash)

        Return result
    End Function
End Class

My html5 code on http://localhost:8080/

    <title>Web Socket Chat</title>

Web Socket Chat

Server
        <input type="text" name="host" id="host" value="ws://localhost:8181/chat" />
        <input type="submit" name="host_connect" id="host_connect" value="Reconnect!" />

Type /nick your_nickname to change your nick

    <input type="text" name="console_input" id="console_input" value="" />
    <input type="submit" name="console_send" id="console_send" value="Send" />


问:
EACCES: permission denied, open
Can someone help me? My Problem is the following: I have a nodejs application that I published on digitalocean with docker, but when I try to publish an article with an image I receive the following error: Error: EACCES: permission denied, open 'uploads /9d607de9b2483a9e92120979cfca666f'</p>

Title: EACCES: permission denied, open


问:
Matching Satellite Images to map
I'm currently a little stuck with a problem, that sounds easier than it is (at least for me):

Let's say you have satellite images taken from LEO that show an approximately 1000 km wide area (the image axis of the camera is more or less perpendicular to the ground). There is no additional location data stored in the image, so no way of directly extracting the position the image was taken).

What I want to do is write a program (in python) that can find the location the image was taken from by matching it to a map of earth. this should be done automatically (more or less in real time) for the purpose of calculating the orbit of the satellite taking the images.

I've no problem calculating the orbit, once I have location data (even if it's very noisy), using a technique based on an Extended Kalman Filter.

Matching a satellite image to a map of earth by just using the image data, on the other hand.... I honestly don't even know where to start.

I know this is an incredibly unspecific question and not related to a specific problem, but maybe someone could point me in the right direction...

EDIT:
Just to give you an idea how unprocessed images from LEO look, I included a few reasonably good images taken over one orbit of earth.

Images have been taken with a NIR camera. Resolution of the images I included have been only 640x480 (by mistake!), but image resolution should be around 4k.

These images have some artifacts in them due to the fact that they where taken through a thick glass window of the ISS - so there are some reflections happening there...

Title: Matching Satellite Images to map


问:
Recreate resulting CSV as own file in Azure blob
When writing out my dataframe, it drop the result into a folder called "file.csv" with a "part-000..." file.  I need to take this resulting file and write it out/copy it as its own csv file with a name.  I am using the logic here, but it appears this won't suffice for Azure blob as it's not recognizing a WASB path.

Code to create the dataframe:

```<code>val dfOutput = spark.sql("""SELECT * FROM Query""")
dfOutput.coalesce(1).write.option("header","true").mode("overwrite").format("csv").save(OutputFile)
</code>```

Creates and outputs the dataframe as a CSV file within a folder as a "part-000..." file.  The output path in this case is wasb:/mycontainer@myexamplestorage.blob.core.windows.net/file.csv (example).

The next part should grab the "part-000..." file and create it under its own file by copying it with the FileUtil then remove the "file.csv" path.

```<code>import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, FileUtil, Path}
import java.io.{File}

val hadoopConfig = new Configuration()
val hdfs = FileSystem.get(hadoopConfig)
val srcPath = new Path(OutputFile)
val destPath = new Path("wasb://mycontainer@myexamplestorage.blob.core.windows.net/resultfile.csv")
val srcFile = FileUtil.listFiles(new File(OutputFile))
           .filterNot(f=>f.getPath.endsWith(".csv"))(0)

FileUtil.copy(srcFile,hdfs,destPath,true,hadoopConfig)
hdfs.delete(srcPath,true)
</code>```

This next part fails on the listFiles with the error "
IOException: Invalid directory or I/O error occurred for dir: wasb://mycontainer@myexamplestorage.blob.core.windows.net/file.csv" and from what I can tell this is caused because it's not able to list files from Azure blob storage.

I need to be able to get the CSV file from Azure blob, then copy it as its own file to Azure blob without the folder and "part-000..." file.  I played around with setting the file configuration, but this entire approach appears to be incompatible with Azure blob storage or there is a configuration missing somewhere that allows these to query blob storage.

Body:
When writing out my dataframe, it drop the result into a folder called "file.csv" with a "part-000..." file.  I need to take this resulting file and write it out/copy it as its own csv file with a name.  I am using the logic here, but it appears this won't suffice for Azure blob as it's not recognizing a WASB path.

Code to create the dataframe:

val dfOutput = spark.sql("""SELECT * FROM Query""")
dfOutput.coalesce(1).write.option("header","true").mode("overwrite").format("csv").save(OutputFile)

Creates and outputs the dataframe as a CSV file within a folder as a "part-000..." file.  The output path in this case is wasb:/mycontainer@myexamplestorage.blob.core.windows.net/file.csv (example).

The next part should grab the "part-000..." file and create it under its own file by copying it with the FileUtil then remove the "file.csv" path.

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, FileUtil, Path}
import java.io.{File}

val hadoopConfig = new Configuration()
val hdfs = FileSystem.get(hadoopConfig)
val srcPath = new Path(OutputFile)
val destPath = new Path("wasb://mycontainer@myexamplestorage.blob.core.windows.net/resultfile.csv")
val srcFile = FileUtil.listFiles(new File(OutputFile))
           .filterNot(f=>f.getPath.endsWith(".csv"))(0)

FileUtil.copy(srcFile,hdfs,destPath,true,hadoopConfig)
hdfs.delete(srcPath,true)

This next part fails on the listFiles with the error "
IOException: Invalid directory or I/O error occurred for dir: wasb://mycontainer@myexamplestorage.blob.core.windows.net/file.csv" and from what I can tell this is caused because it's not able to list files from Azure blob storage.

I need to be able to get the CSV file from Azure blob, then copy it as its own file to Azure blob without the folder and "part-000..." file.  I played around with setting the file configuration, but this entire approach appears to be incompatible with Azure blob storage or there is a configuration missing somewhere that allows these to query blob storage.


问:
Firestore how to get the collection value from another collection document id is referenced
I have two collections and I want to extract information from one to the other collection. I have only the id to use for this process.

user_id:

Code snippet:


问:
How to display error message from progressErrorCollection.getErrors().toString() in Jira screen, scriptrunner postfunction
I have an error message that is thrown when I try to execute a postfunction, the error message is:

org.ofbiz.core.entity.GenericTransactionException: Commit failed, rollback previously requested by nested transaction.

You can see the error message in this screenshot:

In my code, I am using the line :

        log.warn("MOUNA here 2 "+progressErrorCollection.getErrors().toString()) which is displaying a more meaninful message to the user which is: fixVersions:Fix Version/s is required. I would like to print this message instead to the user instead of org.ofbiz.core.entity.GenericTransactionException: Commit failed, rollback previously requested by nested transaction.
How can I enforce this? I have tried using
      UserMessageUtil.error(progressErrorCollection.getErrors().toString()) but it is not working. Anyone knows? Here is my code below:

```<code>package CombineTransitions

import com.onresolve.scriptrunner.runner.util.UserMessageUtil

import com.atlassian.jira.issue.Issue;

import org.apache.log4j.Logger

import com.atlassian.jira.bc.issue.IssueService

import com.atlassian.jira.issue.Issue;

import CombineTransitions.Configuration_CombineTransitions

import com.atlassian.jira.bc.issue.IssueService.IssueResult

import com.atlassian.jira.bc.issue.IssueService.TransitionValidationResult

import com.atlassian.jira.event.type.EventDispatchOption

import  java.util.concurrent.TimeUnit

import  java.util.concurrent.ScheduledExecutorService

import java.util.concurrent.Executors

import com.atlassian.jira.component.ComponentAccessor

import com.atlassian.jira.issue.MutableIssue

import com.atlassian.jira.workflow.WorkflowTransitionUtil

import com.opensymphony.workflow.WorkflowContext;

import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl;

import com.atlassian.jira.util.JiraUtils;

import com.atlassian.jira.issue.MutableIssue;

import com.atlassian.jira.util.ErrorCollection

import com.atlassian.jira.workflow.WorkflowException

def log1 = Logger.getLogger("atlassian-jira.log")

def combineTransitionsHashMap= Configuration_CombineTransitions.getCombineTransitionsHashMap()

def issueStatusTypeId = combineTransitionsHashMap["issueStatusTypeId"] as String;

def transitionFromOpentoFixed = combineTransitionsHashMap["transitionFromOpentoFixed"] as Integer;

def transitionFromFixedToTested = combineTransitionsHashMap["transitionFromFixedToTested"] as Integer;

def transitionFromTestedToCompleted = combineTransitionsHashMap["transitionFromTestedToCompleted"] as Integer;

def fixedStatusName = combineTransitionsHashMap["fixedStatusName"] as String;

def testedStatusName = combineTransitionsHashMap["testedStatusName"] as String;

def completedStatusName = combineTransitionsHashMap["completedStatusName"] as String;

def fixedStatusId = combineTransitionsHashMap["fixedStatusId"] as String;

def testedStatusId = combineTransitionsHashMap["testedStatusId"] as String;

def completedStatusId = combineTransitionsHashMap["completedStatusId"] as String;

if (issue.getStatus().getSimpleStatus().getId().equals(issueStatusTypeId)) {

        def ok = false

         ok=performTransition(transitionFromOpentoFixed, fixedStatusName, fixedStatusId);

         log.warn("MOUNA first boolean "+ok +" "+fixedStatusName)

   if(ok){

         ok= performTransition(transitionFromFixedToTested, testedStatusName, testedStatusId);

         log.warn("MOUNA second boolean "+ok +" "+testedStatusName)

         if(ok){

          ok= performTransition(transitionFromTestedToCompleted, completedStatusName, completedStatusId);

          log.warn("MOUNA third boolean "+ok +" "+completedStatusName)

         }

  }

}

def  performTransition(int transitionToBeDone, String destinationStatus, String statusId ) {

  log.warn("MOUNA  ORIGINAL STATUS "+ issue.getStatus()  + "DEST STATUS "+ destinationStatus)

issue = ComponentAccessor.getIssueManager().getIssueObject(issue.id)

  def currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

  String issueKey = issue.getKey()

  IssueService issueService = ComponentAccessor.getIssueService()

  def issueInputParameters = issueService.newIssueInputParameters()

  issueInputParameters.setComment("Transitioning issue from status "+ issue.getStatus().getName()+" to status "+ destinationStatus );

WorkflowTransitionUtil workflowTransitionUtil = (WorkflowTransitionUtil) JiraUtils.loadComponent(WorkflowTransitionUtilImpl.class)

workflowTransitionUtil.setIssue(issue)

workflowTransitionUtil.setAction(transitionToBeDone)

ErrorCollection errorCollection=workflowTransitionUtil.validate()

if (errorCollection.hasAnyErrors()) {

    log.warn("MOUNA here 1 "+errorCollection.getErrorMessages().toString())

return false;

}else{

    ErrorCollection progressErrorCollection=workflowTransitionUtil.progress()

    if(progressErrorCollection.hasAnyErrors()){

        log.warn("MOUNA here 2 "+progressErrorCollection.getErrors().toString())

            //  throw new WorkflowException(progressErrorCollection.getErrors().toString());

      UserMessageUtil.error(progressErrorCollection.getErrors().toString())

          return false;

    }else{

      return true;

    }

}

}
</code>```

Body:
I have an error message that is thrown when I try to execute a postfunction, the error message is:

org.ofbiz.core.entity.GenericTransactionException: Commit failed, rollback previously requested by nested transaction.

You can see the error message in this screenshot:

In my code, I am using the line :

        log.warn("MOUNA here 2 "+progressErrorCollection.getErrors().toString()) which is displaying a more meaninful message to the user which is: fixVersions:Fix Version/s is required. I would like to print this message instead to the user instead of org.ofbiz.core.entity.GenericTransactionException: Commit failed, rollback previously requested by nested transaction.
How can I enforce this? I have tried using
      UserMessageUtil.error(progressErrorCollection.getErrors().toString()) but it is not working. Anyone knows? Here is my code below:

package CombineTransitions

import com.onresolve.scriptrunner.runner.util.UserMessageUtil

import com.atlassian.jira.issue.Issue;

import org.apache.log4j.Logger

import com.atlassian.jira.bc.issue.IssueService

import com.atlassian.jira.issue.Issue;

import CombineTransitions.Configuration_CombineTransitions

import com.atlassian.jira.bc.issue.IssueService.IssueResult

import com.atlassian.jira.bc.issue.IssueService.TransitionValidationResult

import com.atlassian.jira.event.type.EventDispatchOption

import  java.util.concurrent.TimeUnit

import  java.util.concurrent.ScheduledExecutorService

import java.util.concurrent.Executors

import com.atlassian.jira.component.ComponentAccessor

import com.atlassian.jira.issue.MutableIssue

import com.atlassian.jira.workflow.WorkflowTransitionUtil

import com.opensymphony.workflow.WorkflowContext;

import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl;

import com.atlassian.jira.util.JiraUtils;

import com.atlassian.jira.issue.MutableIssue;

import com.atlassian.jira.util.ErrorCollection

import com.atlassian.jira.workflow.WorkflowException

def log1 = Logger.getLogger("atlassian-jira.log")

def combineTransitionsHashMap= Configuration_CombineTransitions.getCombineTransitionsHashMap()

def issueStatusTypeId = combineTransitionsHashMap["issueStatusTypeId"] as String;

def transitionFromOpentoFixed = combineTransitionsHashMap["transitionFromOpentoFixed"] as Integer;

def transitionFromFixedToTested = combineTransitionsHashMap["transitionFromFixedToTested"] as Integer;

def transitionFromTestedToCompleted = combineTransitionsHashMap["transitionFromTestedToCompleted"] as Integer;

def fixedStatusName = combineTransitionsHashMap["fixedStatusName"] as String;

def testedStatusName = combineTransitionsHashMap["testedStatusName"] as String;

def completedStatusName = combineTransitionsHashMap["completedStatusName"] as String;

def fixedStatusId = combineTransitionsHashMap["fixedStatusId"] as String;

def testedStatusId = combineTransitionsHashMap["testedStatusId"] as String;

def completedStatusId = combineTransitionsHashMap["completedStatusId"] as String;

if (issue.getStatus().getSimpleStatus().getId().equals(issueStatusTypeId)) {

        def ok = false

         ok=performTransition(transitionFromOpentoFixed, fixedStatusName, fixedStatusId);

         log.warn("MOUNA first boolean "+ok +" "+fixedStatusName)

   if(ok){

         ok= performTransition(transitionFromFixedToTested, testedStatusName, testedStatusId);

         log.warn("MOUNA second boolean "+ok +" "+testedStatusName)

         if(ok){

          ok= performTransition(transitionFromTestedToCompleted, completedStatusName, completedStatusId);

          log.warn("MOUNA third boolean "+ok +" "+completedStatusName)

         }

  }

}

def  performTransition(int transitionToBeDone, String destinationStatus, String statusId ) {

  log.warn("MOUNA  ORIGINAL STATUS "+ issue.getStatus()  + "DEST STATUS "+ destinationStatus)

issue = ComponentAccessor.getIssueManager().getIssueObject(issue.id)

  def currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

  String issueKey = issue.getKey()

  IssueService issueService = ComponentAccessor.getIssueService()

  def issueInputParameters = issueService.newIssueInputParameters()

  issueInputParameters.setComment("Transitioning issue from status "+ issue.getStatus().getName()+" to status "+ destinationStatus );

WorkflowTransitionUtil workflowTransitionUtil = (WorkflowTransitionUtil) JiraUtils.loadComponent(WorkflowTransitionUtilImpl.class)

workflowTransitionUtil.setIssue(issue)

workflowTransitionUtil.setAction(transitionToBeDone)

ErrorCollection errorCollection=workflowTransitionUtil.validate()

if (errorCollection.hasAnyErrors()) {

    log.warn("MOUNA here 1 "+errorCollection.getErrorMessages().toString())

return false;

}else{

    ErrorCollection progressErrorCollection=workflowTransitionUtil.progress()

    if(progressErrorCollection.hasAnyErrors()){

        log.warn("MOUNA here 2 "+progressErrorCollection.getErrors().toString())

            //  throw new WorkflowException(progressErrorCollection.getErrors().toString());

      UserMessageUtil.error(progressErrorCollection.getErrors().toString())

          return false;

    }else{

      return true;

    }

}

}


问:
How to beat Scaled Coordinates inside Chrome's Viewport
The coordinates of DOM elements we get from javascript aren't real.

What I mean is: even if we know the bounding box of Chrome's viewport (without top toolbar, omnibox, etc.), we still won't get the real coordinates via plain javascript.

Easily checked comparing the window.innerWidth and window.innerHeight to the real dimensions of your viewport.

Clearly demonstrated on the screenshot below:

The console.log(window.innerWidth, window.innerHeight) says 1221 775, but in fact the viewport is around 1524x964.

Obviosly, Chrome uses scaling of sorts. I've also checked on another machine - the result is roughly the same.

But then, how to determine the real OS on-screen coordinates (considering we know viewport's bounding box)? Is there a native in-browser way?


问:
My IF statement doesn't give the correct output
I have a shell script that is suppose to take the output of autorep command and use that output in the IF statement but its not working

```<code>#!/bin/bash

 read -r i

output=$(autorep -j $i -q | awk '/^insert_job:/ {printf "%s\n", $4}')

if [ $output == "CMD" ] || [ $output == "BOX" ];
  then
 echo "its a command or box job"

else

echo "Not a command or box job"

fi
</code>```

if i modify this script to echo the output of the command

```<code>#!/bin/bash

 read -r i

output=$(autorep -j $i -q | awk '/^insert_job:/ {printf "%s\n", $4}')

echo $output
</code>```

then I get the result as:

```<code>CMD CMD CMD BOX BOX BOX CMD BOX
</code>```

but the output should come on each line

The $i is suppose to be a Wildcard that resolves to a series of jobs. Is there anything I am doing wrong here?

Body:
I have a shell script that is suppose to take the output of autorep command and use that output in the IF statement but its not working

#!/bin/bash

 read -r i

output=$(autorep -j $i -q | awk '/^insert_job:/ {printf "%s\n", $4}')

if [ $output == "CMD" ] || [ $output == "BOX" ];
  then
 echo "its a command or box job"

else

echo "Not a command or box job"

fi

if i modify this script to echo the output of the command

#!/bin/bash

 read -r i

output=$(autorep -j $i -q | awk '/^insert_job:/ {printf "%s\n", $4}')

echo $output

then I get the result as:

CMD CMD CMD BOX BOX BOX CMD BOX

but the output should come on each line

The $i is suppose to be a Wildcard that resolves to a series of jobs. Is there anything I am doing wrong here?


问:
[modules RTC BridgeChannel.js e.onclose : Channel closed: 1006 - Jitsi Meet JVB
I have installed jitsi Meet using below link on ubuntu 22.04

https://meetrix.io/blog/webrtc/jitsi/setup-%20install-jitsi-meet-jvb-on-ubuntu-20.html

Up to 2 participant its connecting audio and video , But after 3rd participant it is disconnecting audio and video , when any one removed from 3 , automatically connecting audio and video.

in browser console it shows

BridgeChannel.js:87 WebSocket connection to 'wss://meet.**domian.com/colibri-ws/default-id/376f2ff95d8ada38/319d2637?pwd=u38l9jh17sgk4pkdte6ikc9h0' failed:
_initWebSocket @ BridgeChannel.js:87
t @ BridgeChannel.js:106
Logger.js:154 2022-12-23T15:00:58.328Z [modules/RTC/BridgeChannel.js] <e.onclose>:  Channel closed by server


问:
Using scholarly to get data from Google Scholar gives "Cannot Fetch from Google Scholar"
I'm trying to get data from Google Scholar

```<code>from scholarly import scholarly

search_query = scholarly.search_author('Albert Einstein')
author = next(search_query).fill()
</code>```

and the output that I obtain is:

```<code>MaxTriesExceededException: Cannot Fetch from Google Scholar.
</code>```

Any idea of what it's going wrong?

I'm using scholarly == 1.7.6 and I'm using a VPN so it shouldn't be an IP problem.

Body:
I'm trying to get data from Google Scholar

from scholarly import scholarly

search_query = scholarly.search_author('Albert Einstein')
author = next(search_query).fill()

and the output that I obtain is:

MaxTriesExceededException: Cannot Fetch from Google Scholar.

Any idea of what it's going wrong?

I'm using scholarly == 1.7.6 and I'm using a VPN so it shouldn't be an IP problem.


问:
Is there a way to persist data under multiple keys using redux-persist?
I work on a big application where we store some data locally using react-persist using AsyncStorage. Since all the data is stored under a single key in react-persist, this fills up the read buffer limitation of 2MB for SQLite on Android. I was wondering if there's a way to store that data under multiple keys and not run into the problem that we are right now.</p>


问:
rmarkdown: Tables inclusion in report doesn't work in a loop
I try to create a pdf report using Rmarkdown, but when I try to make a loop in fuction of the Periodo variable,
the tables inclusion in params <- list(res1 = medias.F)  doesn't work. I always have as output the report (test.pdf) without any result table:

My R code is:

```<code># Packages
library(tidyverse)
library(hnp)
library(multcomp)
library(rmarkdown)

# Open data set
df_trats <- read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/data.csv",sep=";")
df_trats $Tratamento <- as.factor(df_trats $Tratamento)
str(df_trats )
names_trat<-unique(df_trats$Tratamento)

# Loop for each Periodo variable

res <- NULL

id.tempo <- unique(unique(df$Periodo))

for(i in 1:length(id.tempo)){

  print("Período de tempo analisado")
  print(id.tempo[i])

  df.subset <- df_trats%>%dplyr::filter(Periodo==id.tempo[i])
  df.subset$Tratamento <- as.factor(df.subset$Tratamento)

  # Models
  model1<-glm(Evento~Tratamento, family="binomial", data=df.subset)
  model2<-glm(Evento~Tratamento, family="quasibinomial", data=df.subset)

  B<-hnp::hnp(model1, print.on = TRUE, plot=FALSE)
  qB<-hnp::hnp(model2, print.on = TRUE, plot=FALSE)

  pB<-B$out/B$total
  pqB<-qB$out/qB$total

  tvalues<-as.data.frame(rbind(pB=pB,pqB=pqB))
  choose.model <- rownames(tvalues%>%filter(V1==min(V1)))

  # Anova
  if(pB == choose.model){
    anova.df.B<-anova(model1, test="Chisq")
    print(anova(model1, test="Chisq"))
  } else(pqB == choose.model)
  anova.df.qB<-anova(model2, test="F")
  print(anova(model2, test="F"))
  #

  # Pairwise comparisions
  if(pB == choose.model){
    print("Medias dos tratamentos")
    medias <- df.subset %>%
      dplyr::group_by(Tratamento) %>%
      dplyr::summarize(Mortalidade=mean(Evento)*100, EP = (stats::sd(Evento)/sqrt(n()-1))*100)
    Comparacoes<-summary(glht(model1, linfct=mcp(Tratamento="Tukey")))
    (Comparacoes_up<-summary(Comparacoes, test = univariate()))
    pairwise.res.pB <- cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
    medias.lcd<-cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
    medias.F <- cbind(medias,as.vector(medias.lcd$mcletters$Letters))
    colnames(medias.F)<-c("Tratamento","Mortalidade","EP","Índice")
    print(medias.F)
  } else(pqB == choose.model)
  print("Medias dos tratamentos")
  medias <- df.subset %>%
    dplyr::group_by(Tratamento) %>%
    dplyr::summarize(Mortalidade=mean(Evento)*100, EP = (stats::sd(Evento)/sqrt(n()-1))*100)
  Comparacoes<-summary(glht(model2, linfct=mcp(Tratamento="Tukey")))
  (Comparacoes_up<-summary(Comparacoes, test = univariate()))
  pairwise.res.pqB <- cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
  medias.lcd<-cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
  medias.F <- cbind(medias,as.vector(medias.lcd$mcletters$Letters))
  colnames(medias.F)<-c("Tratamento","Mortalidade","EP","Índice")
  print(medias.F)
  params <- list(res1 = medias.F) # ... whatever you have to send to the report
rmarkdown::render("test.Rmd",
                    params = params,
                    output_file ="test.pdf",
                  envir = new.env())

}
##
# <END> -
</code>```

My test.Rmd is:

```<code>---
title:  "Relatório dos tratamentos: `r names_trat`"
author: "Vittia"
date: "date: `r Sys.Date()`"
params:
  res1: res1
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

Please any help with it?

Body:
I try to create a pdf report using Rmarkdown, but when I try to make a loop in fuction of the Periodo variable,
the tables inclusion in params <- list(res1 = medias.F)  doesn't work. I always have as output the report (test.pdf) without any result table:

My R code is:

# Packages
library(tidyverse)
library(hnp)
library(multcomp)
library(rmarkdown)

# Open data set
df_trats <- read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/data.csv",sep=";")
df_trats $Tratamento <- as.factor(df_trats $Tratamento)
str(df_trats )
names_trat<-unique(df_trats$Tratamento)

# Loop for each Periodo variable

res <- NULL

id.tempo <- unique(unique(df$Periodo))

for(i in 1:length(id.tempo)){

  print("Período de tempo analisado")
  print(id.tempo[i])

  df.subset <- df_trats%>%dplyr::filter(Periodo==id.tempo[i])
  df.subset$Tratamento <- as.factor(df.subset$Tratamento)

  # Models
  model1<-glm(Evento~Tratamento, family="binomial", data=df.subset)
  model2<-glm(Evento~Tratamento, family="quasibinomial", data=df.subset)

  B<-hnp::hnp(model1, print.on = TRUE, plot=FALSE)
  qB<-hnp::hnp(model2, print.on = TRUE, plot=FALSE)

  pB<-B$out/B$total
  pqB<-qB$out/qB$total

  tvalues<-as.data.frame(rbind(pB=pB,pqB=pqB))
  choose.model <- rownames(tvalues%>%filter(V1==min(V1)))

  # Anova
  if(pB == choose.model){
    anova.df.B<-anova(model1, test="Chisq")
    print(anova(model1, test="Chisq"))
  } else(pqB == choose.model)
  anova.df.qB<-anova(model2, test="F")
  print(anova(model2, test="F"))
  #

  # Pairwise comparisions
  if(pB == choose.model){
    print("Medias dos tratamentos")
    medias <- df.subset %>%
      dplyr::group_by(Tratamento) %>%
      dplyr::summarize(Mortalidade=mean(Evento)*100, EP = (stats::sd(Evento)/sqrt(n()-1))*100)
    Comparacoes<-summary(glht(model1, linfct=mcp(Tratamento="Tukey")))
    (Comparacoes_up<-summary(Comparacoes, test = univariate()))
    pairwise.res.pB <- cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
    medias.lcd<-cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
    medias.F <- cbind(medias,as.vector(medias.lcd$mcletters$Letters))
    colnames(medias.F)<-c("Tratamento","Mortalidade","EP","Índice")
    print(medias.F)
  } else(pqB == choose.model)
  print("Medias dos tratamentos")
  medias <- df.subset %>%
    dplyr::group_by(Tratamento) %>%
    dplyr::summarize(Mortalidade=mean(Evento)*100, EP = (stats::sd(Evento)/sqrt(n()-1))*100)
  Comparacoes<-summary(glht(model2, linfct=mcp(Tratamento="Tukey")))
  (Comparacoes_up<-summary(Comparacoes, test = univariate()))
  pairwise.res.pqB <- cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
  medias.lcd<-cld(Comparacoes_up, level=0.05, Letters= c(LETTERS, letters), decreasing=TRUE)
  medias.F <- cbind(medias,as.vector(medias.lcd$mcletters$Letters))
  colnames(medias.F)<-c("Tratamento","Mortalidade","EP","Índice")
  print(medias.F)
  params <- list(res1 = medias.F) # ... whatever you have to send to the report
rmarkdown::render("test.Rmd",
                    params = params,
                    output_file ="test.pdf",
                  envir = new.env())

}
##
# <END> -

My test.Rmd is:

---
title:  "Relatório dos tratamentos: `r names_trat`"
author: "Vittia"
date: "date: `r Sys.Date()`"
params:
  res1: res1
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

Please any help with it?


问:
Get radio metadata using curl
I am trying to use curl to solve cors issue with XMLHttpRequest while trying to get radio metadata (I cant use jQuery jsonp for this). I am not sure if curl can achieve this.

```<code>        var xhr = new XMLHttpRequest;
        xhr.onerror = function (e) {
            console.error(e);
        };
        xhr.onreadystatechange = function () {
            if (this.readyState == 4){

                if(xhr_radioData.status == 200){

                }
            }
        };

        var url = 'http://stream.rockradio.si:9034/stats?sid=1&json=1;

        var params = 'url='+url;
        var curl = 'jsonp.php';

        xhr.open("POST", curl);
        xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
        xhr.send(params);
</code>```

json.php

```<code><?php

$url = $_POST['url'];

$curl = curl_init($url);

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-Requested-With: XMLHttpRequest'
));

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 120);

$response = curl_exec($curl);
$err = curl_error($curl);

if($err){
    echo "cURL Error #:" . $err;
}else{
    echo ($response);
}

exit;

?>
</code>```

I am getting an error:

cURL Error #:Failed to connect to stream.rockradio.si port 9034 after 2003 ms: Connection refused

Title: Get radio metadata using curl

Body:
I am trying to use curl to solve cors issue with XMLHttpRequest while trying to get radio metadata (I cant use jQuery jsonp for this). I am not sure if curl can achieve this.

        var xhr = new XMLHttpRequest;
        xhr.onerror = function (e) {
            console.error(e);
        };
        xhr.onreadystatechange = function () {
            if (this.readyState == 4){

                if(xhr_radioData.status == 200){

                }
            }
        };

        var url = 'http://stream.rockradio.si:9034/stats?sid=1&json=1;

        var params = 'url='+url;
        var curl = 'jsonp.php';

        xhr.open("POST", curl);
        xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
        xhr.send(params);

json.php

<?php

$url = $_POST['url'];

$curl = curl_init($url);

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-Requested-With: XMLHttpRequest'
));

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 120);

$response = curl_exec($curl);
$err = curl_error($curl);

if($err){
    echo "cURL Error #:" . $err;
}else{
    echo ($response);
}

exit;

?>

I am getting an error:

cURL Error #:Failed to connect to stream.rockradio.si port 9034 after 2003 ms: Connection refused


问:
Nestjs wont reload in file change
Dockerfile:

```<code>\`FROM node:lts-alpine as development

WORKDIR /usr/src/app

COPY package.json yarn.lock ./

RUN yarn --frozen-lockfile --production=false

COPY . .

RUN yarn prisma generate

RUN yarn build

FROM node:lts-alpine as production`your text`

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/app

COPY package.json yarn.lock ./

RUN yarn --frozen-lockfile --production=true

COPY --from=development /usr/src/app/dist ./dist
COPY --from=development /usr/src/app/prisma ./prisma

EXPOSE 3000

CMD \["yarn", "start:prod"\]\`
</code>```

docker-compose.yml:

```<code>version: '3.7'

services:
  postgres_db:
    image: postgres:12.2
    container_name: postgres_db
    restart: always
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_USER: user
      POSTGRES_DB: db
    ports:
      - 5432:5432
    volumes:
      - ./db:/var/lib/postgresql/data

  nestjs_server:
    build:
      context: ./nestjs_server
      dockerfile: Dockerfile
      target: development
    container_name: nestjs_server
    volumes:
      - ./nestjs_server:/usr/src/app
      - /usr/src/app/node_modules
    restart: always
    environment:
      DATABASE_URL: "postgresql://user:password@postgres_db:5432/mydb?schema=public"
    ports:
      - 3000:3000
    depends_on:
      - postgres_db
    command: yarn start:debug

volumes:
  postgres_db:
    name: postgres_db
</code>```

Structure:

It works perfectly fine but when I change something on the files I won't recompile.

Title: Nestjs wont reload in file change

Body:
Dockerfile:

\`FROM node:lts-alpine as development

WORKDIR /usr/src/app

COPY package.json yarn.lock ./

RUN yarn --frozen-lockfile --production=false

COPY . .

RUN yarn prisma generate

RUN yarn build

FROM node:lts-alpine as production`your text`

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/app

COPY package.json yarn.lock ./

RUN yarn --frozen-lockfile --production=true

COPY --from=development /usr/src/app/dist ./dist
COPY --from=development /usr/src/app/prisma ./prisma

EXPOSE 3000

CMD \["yarn", "start:prod"\]\`

docker-compose.yml:

version: '3.7'

services:
  postgres_db:
    image: postgres:12.2
    container_name: postgres_db
    restart: always
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_USER: user
      POSTGRES_DB: db
    ports:
      - 5432:5432
    volumes:
      - ./db:/var/lib/postgresql/data

  nestjs_server:
    build:
      context: ./nestjs_server
      dockerfile: Dockerfile
      target: development
    container_name: nestjs_server
    volumes:
      - ./nestjs_server:/usr/src/app
      - /usr/src/app/node_modules
    restart: always
    environment:
      DATABASE_URL: "postgresql://user:password@postgres_db:5432/mydb?schema=public"
    ports:
      - 3000:3000
    depends_on:
      - postgres_db
    command: yarn start:debug

volumes:
  postgres_db:
    name: postgres_db

Structure:

It works perfectly fine but when I change something on the files I won't recompile.


问:
Transforming Results from Rows into Columns
I have a data set that contains both common and unique values, which I am attempting to return in a useable format to allow further analyse/work to be taken based on said results.

The desired result would be to have a script that would recognise the common values such as mpan/serial_number/read_at so as to only return a single row, but also to recognise the unique values those being the read_at and identifier.

Currently my script returns a unique row based on the identifier and the value, but I would like to be able to return a unique row for the read_at date for as many identifiers and values as are held. In most cases there are only two identifiers and values, but there could be as many as five.

The issue I have is that when I try to make distinct work, it will only then return the first found result, where I am expecting a pair of results at minimum. I am also unclear as to how I could stop getting a new row and instead create the result as an additional column?

My base script which pulls everything is as below, I have tried a few variances on this, but think this would likely be the best place to start from with regards to any help you may be able to offer?

```<code>SELECT *
FROM consumer.stg_d0010_v2_026_027
/*LEFT JOIN consumer.stg_d0010_v2_026_028_029
ON consumer.stg_d0010_v2_026_028_029.file_identifier = consumer.stg_d0010_v2_026_027.file_identifier
AND consumer.stg_d0010_v2_026_028_029.mpan = consumer.stg_d0010_v2_026_027.mpan*/

LEFT JOIN consumer.stg_d0010_v2_026_028_030_032
ON consumer.stg_d0010_v2_026_028_030_032.file_identifier = consumer.stg_d0010_v2_026_027.file_identifier
AND consumer.stg_d0010_v2_026_028_030_032.mpan = consumer.stg_d0010_v2_026_027.mpan

LEFT JOIN consumer.stg_d0010_v2_026_028_030_033
ON consumer.stg_d0010_v2_026_028_030_033.file_identifier = consumer.stg_d0010_v2_026_027.file_identifier
AND consumer.stg_d0010_v2_026_028_030_033.mpan = consumer.stg_d0010_v2_026_027.mpan

where consumer.stg_d0010_v2_026_028_030_032.read_At > '2022-10-01'
and consumer.stg_d0010_v2_026_027.mpan in (

)

</code>```

Example dataset in image below.

enter image description here

And desired outcome

enter image description here

The issue I have is that when I try to make distinct work, it will only then return the first found result, where I am expecting a pair of results at minimum. I am also unclear as to how I could stop getting a new row and instead create the result as an additional column?

Body:
I have a data set that contains both common and unique values, which I am attempting to return in a useable format to allow further analyse/work to be taken based on said results.

The desired result would be to have a script that would recognise the common values such as mpan/serial_number/read_at so as to only return a single row, but also to recognise the unique values those being the read_at and identifier.

Currently my script returns a unique row based on the identifier and the value, but I would like to be able to return a unique row for the read_at date for as many identifiers and values as are held. In most cases there are only two identifiers and values, but there could be as many as five.

The issue I have is that when I try to make distinct work, it will only then return the first found result, where I am expecting a pair of results at minimum. I am also unclear as to how I could stop getting a new row and instead create the result as an additional column?

My base script which pulls everything is as below, I have tried a few variances on this, but think this would likely be the best place to start from with regards to any help you may be able to offer?

SELECT *
FROM consumer.stg_d0010_v2_026_027
/*LEFT JOIN consumer.stg_d0010_v2_026_028_029
ON consumer.stg_d0010_v2_026_028_029.file_identifier = consumer.stg_d0010_v2_026_027.file_identifier
AND consumer.stg_d0010_v2_026_028_029.mpan = consumer.stg_d0010_v2_026_027.mpan*/

LEFT JOIN consumer.stg_d0010_v2_026_028_030_032
ON consumer.stg_d0010_v2_026_028_030_032.file_identifier = consumer.stg_d0010_v2_026_027.file_identifier
AND consumer.stg_d0010_v2_026_028_030_032.mpan = consumer.stg_d0010_v2_026_027.mpan

LEFT JOIN consumer.stg_d0010_v2_026_028_030_033
ON consumer.stg_d0010_v2_026_028_030_033.file_identifier = consumer.stg_d0010_v2_026_027.file_identifier
AND consumer.stg_d0010_v2_026_028_030_033.mpan = consumer.stg_d0010_v2_026_027.mpan

where consumer.stg_d0010_v2_026_028_030_032.read_At > '2022-10-01'
and consumer.stg_d0010_v2_026_027.mpan in (

)

Example dataset in image below.

enter image description here

And desired outcome

enter image description here

The issue I have is that when I try to make distinct work, it will only then return the first found result, where I am expecting a pair of results at minimum. I am also unclear as to how I could stop getting a new row and instead create the result as an additional column?


问:
SSRS RDL paginated reporting - Every time I edit an RDL report it removes the selected filters in report builder
SSRS RDL paginated reporting - Every time I edit an RDL report it removes the selected filters in report builder

It started a couple years ago periodically, when I would open to edit an existing rdl report the filters would remain but fields were blank. I logged a ticket with my saas vendor who came back with it being a known issue with MS but I wasn't able to find any reference online.

Some reports are from years ago, and having hundreds I need to review the MDX in the query before editing to remember what the default or filter values were...

Anyone else experiencing this?

I tried editing an rdl file in report builder and was expecting the filter selections to remain and not be blown out.


问:
Do we need to define the val_accuracy before using?
```<code>neural_network = keras.Sequential([Dense(512, activation="relu", kernel_regularizer=keras.regularizers.l2(0.0001)),
                                   Dropout(0.2),
                                   Dense(128, activation="relu", kernel_regularizer=keras.regularizers.l2(0.0001)),
                                   Dropout(0.2),
                                   Dense(1, activation="sigmoid")])

neural_network.compile(optimizer=Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy',get_f1,precision,recall])

history = neural_network.fit(x_train_nn, y_train, epochs=15, batch_size=64)
</code>```
```<code>neural_network.evaluate(x_val_nn, y_val)
</code>```
```<code>plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
</code>```

I am getting an error-

```<code>KeyError                                  Traceback (most recent call last)
Cell In [26], line 4
      1 import matplotlib.pyplot as plt
      3 plt.plot(history.history['accuracy'])
----> 4 plt.plot(history.history['val_accuracy'])
      5 plt.title('Model accuracy')
      6 plt.ylabel('Accuracy')

KeyError: 'val_accuracy'
</code>```

I want to know where should I define 'val_accuracy'? Why do I see this error? If anyone can spot the wrong statement, please help.

Body:
neural_network = keras.Sequential([Dense(512, activation="relu", kernel_regularizer=keras.regularizers.l2(0.0001)),
                                   Dropout(0.2),
                                   Dense(128, activation="relu", kernel_regularizer=keras.regularizers.l2(0.0001)),
                                   Dropout(0.2),
                                   Dense(1, activation="sigmoid")])

neural_network.compile(optimizer=Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy',get_f1,precision,recall])

history = neural_network.fit(x_train_nn, y_train, epochs=15, batch_size=64)

neural_network.evaluate(x_val_nn, y_val)

plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()

I am getting an error-

KeyError                                  Traceback (most recent call last)
Cell In [26], line 4
      1 import matplotlib.pyplot as plt
      3 plt.plot(history.history['accuracy'])
----> 4 plt.plot(history.history['val_accuracy'])
      5 plt.title('Model accuracy')
      6 plt.ylabel('Accuracy')

KeyError: 'val_accuracy'

I want to know where should I define 'val_accuracy'? Why do I see this error? If anyone can spot the wrong statement, please help.