问:
Fetch API cannot load localhost:(port&path). URL scheme "localhost" is not supported
I create react app that use API created with Spring Boot.

I would like to send a file to the server via the form in my react app (The server works good because I can upload file in Postman).

This is my form:

```<code>   <form onSubmit={e => uploadFile(e)} >
           <input type="file" name="img" onChange={changeHandler} />
           <button>Add!</button>
   </form>
</code>```

uploadFile and changeHandler methods:

```<code> const [selectedFile, setSelectedFile] = useState()

const uploadFile = () => {
        const formData = new FormData()
        formData.append('File', selectedFile)

        fetch(`localhost:8080/courses/1/comments/1/img`, {
            method: 'post',
            body: formData
        })
            .then(resp => resp.json())
            .then(data => console.log(data))
            .catch(err => console.log(err))
    }

    const changeHandler = (e) => {
        setSelectedFile(e.target.files[0])
    }
</code>```

When I submit this form I get this:

```<code>Fetch API cannot load localhost:8080/courses/18/comments/1/img. URL scheme "localhost" is not supported.
</code>```

How to solve this problem ?

答:
You might be forgot to specify the http protocol in the URL.

So, replace localhost:8080/courses/1/comments/1/img in the fetch method with http://localhost:8080/courses/1/comments/1/img

```<code>fetch(`http://localhost:8080/courses/1/comments/1/img`, {
    method: 'post',
    body: formData
})
</code>```

Body:
I create react app that use API created with Spring Boot.

I would like to send a file to the server via the form in my react app (The server works good because I can upload file in Postman).

This is my form:

   <form onSubmit={e => uploadFile(e)} >
           <input type="file" name="img" onChange={changeHandler} />
           <button>Add!</button>
   </form>

uploadFile and changeHandler methods:

 const [selectedFile, setSelectedFile] = useState()

const uploadFile = () => {
        const formData = new FormData()
        formData.append('File', selectedFile)

        fetch(`localhost:8080/courses/1/comments/1/img`, {
            method: 'post',
            body: formData
        })
            .then(resp => resp.json())
            .then(data => console.log(data))
            .catch(err => console.log(err))
    }

    const changeHandler = (e) => {
        setSelectedFile(e.target.files[0])
    }

When I submit this form I get this:

Fetch API cannot load localhost:8080/courses/18/comments/1/img. URL scheme "localhost" is not supported.

How to solve this problem ?

Body:
You might be forgot to specify the http protocol in the URL.

So, replace localhost:8080/courses/1/comments/1/img in the fetch method with http://localhost:8080/courses/1/comments/1/img

fetch(`http://localhost:8080/courses/1/comments/1/img`, {
    method: 'post',
    body: formData
})


来源: stackexchange

问:
Pandas - assign incremented value if condition in other column is matched
This is my dataset:

# dataset
  DATE            NUMBER
0 10. 9. 2002     NaN
1 10. 9. 2002     8.0
2 10. 9. 2002     9.0
3 10. 9. 2002     NaN
4 10. 9. 2002     11.0
```
<p>I would like to add a new column 'T_ID' where I will store number that increments every time the value in 'NUMBER' column is NaN.</p>
<p>My expected table should look like this:</p>
<pre class="lang-py prettyprint-override"><code># dataset
  DATE            NUMBER    T_ID
0 10. 9. 2002     NaN       1
1 10. 9. 2002     8.0       1
2 10. 9. 2002     9.0       1
3 10. 9. 2002     NaN       2
4 10. 9. 2002     11.0      2
</code>```

Thanks for all your answers.

答:
Use

```<code>df['T_ID'] = df.NUMBER.isna().cumsum()
</code>```

This uses isna() to get an array with bools. This can be used by cumsum() which returns a cumulative sum over this boolean array.

ContentLicense: CC BY-SA 4.0

Body:
This is my dataset:

# dataset
  DATE            NUMBER
0 10. 9. 2002     NaN
1 10. 9. 2002     8.0
2 10. 9. 2002     9.0
3 10. 9. 2002     NaN
4 10. 9. 2002     11.0

I would like to add a new column 'T_ID' where I will store number that increments every time the value in 'NUMBER' column is NaN.

My expected table should look like this:

# dataset
  DATE            NUMBER    T_ID
0 10. 9. 2002     NaN       1
1 10. 9. 2002     8.0       1
2 10. 9. 2002     9.0       1
3 10. 9. 2002     NaN       2
4 10. 9. 2002     11.0      2

Thanks for all your answers.

Body:
Use

df['T_ID'] = df.NUMBER.isna().cumsum()

This uses isna() to get an array with bools. This can be used by cumsum() which returns a cumulative sum over this boolean array.


问:
jQuery addClass() not working in IE (8, 9 and probably the other one too)
Simple html:

```<code><div class="stuff-choice">
  <div class="item a">
    <label class="signup-checkbox">
      <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things">
      <strong>A</strong>
    </label>
  </div>
</div>
</code>```

Basically I detect when someone click on the checkbox with the css class .things, and then I updated the parent
 with a css class .selected.

The JS: (with a $(document).ready(function(){ ...

```<code>$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        $(item).addClass('selected');
    else
        $(item).removeClass('selected');
});
</code>```

This works like a charm under:
- Safari (mac & win)
- Firefox (mac & win)

But not under IE !?!?

I have no clue why...

Thanks,

Alex

答:
I think you're issue is the object you're calling .addClass on.

```<code>item = $(this).closest("div");
</code>```

In this line, item is set to a jQuery object.

Therefore, in your next statement, you don't need the $(item) syntax, just use item.

```<code>$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        item.addClass('selected');
    else
        item.removeClass('selected');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Simple html:

      <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things">
      A

Basically I detect when someone click on the checkbox with the css class .things, and then I updated the parent
 with a css class .selected.

The JS: (with a $(document).ready(function(){ ...

$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        $(item).addClass('selected');
    else
        $(item).removeClass('selected');
});

This works like a charm under:
- Safari (mac & win)
- Firefox (mac & win)

But not under IE !?!?

I have no clue why...

Thanks,

Alex

Body:
I think you're issue is the object you're calling .addClass on.

item = $(this).closest("div");

In this line, item is set to a jQuery object.

Therefore, in your next statement, you don't need the $(item) syntax, just use item.

$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        item.addClass('selected');
    else
        item.removeClass('selected');
});


问:
How to enforce implementation of nested class properties?
I'm trying to implement my own multi-language feature in Blazor WASM. Nothing fancy but I would like to make sure I don't forget to implement properties in a specific language. In TypeScript this would work with typing or interfacing objects. In C# the equivalent of such an object would be a class. I tried using interfaces and abstract classes in C# but I'm not getting the desired result.

The desired result would be for my code editor to hint when I forgot to implement a property. How should I proceed?

I could just put all properties directly into the Translation class to enforce their implementation but than I'll have one very long list of properties, I'd prefer to chop them up a bit.

```<code>    public class NavMenuProps
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";
    }

    public abstract class Translation
    {
        public abstract NavMenuProps NavMenu();
    }

    public class English : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps();
        }
    }

    public class Dutch : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps
            {
                FirstMenuHeader = "Honden",
                SecondMenuHeader = ""
            };
        }
    }

    public class French : Translation
    {
        public override NavMenuProps NavMenu()
        {
            throw new System.NotImplementedException();
        }
    }
</code>```

In TypeScript it would work like this:

```<code>
type TNavMenuProps = {
    firstMenuHeader: string;
    secondMenuHeader: string;
    thirdMenuHeader: string;
    ...
}

type TLoginPageProps = {
    firstLabel: string;
    secondLabel: string;
    ...
}

type TTranslation = {
    navMenu: TNavMenuProps;
    loginPage: TLoginPageProps;
    ...
}

const englishTranslations: TTranslation = {
    navMenu: {
        firstMenuHeader: "first";
        secondMenuHeader: "second";
        // Would complain I forgot "thirdMenuHeader".
    },
    loginPage: {
        firstLabel: "1st label";
        secondLabel: "2nd label";
    },
    ...
}

</code>```

答:
If I understand your requirements correctly, this could be a way to go: Make NavMenuProps abstract, and implement NavMenu() inside Translation. Now, rather than implementing NavMenu() in all of the classes that inherit Translation, you rather need to implement all properties in NavMenuProps in all those classes.

```<code>public abstract class NavMenuProps
{
    public abstract string FirstMenuHeader { get; }
    public abstract string SecondMenuHeader { get; }
    public abstract string ThirdMenuHeader { get; }
}

public abstract class Translation : NavMenuProps
{
    public Translation NavMenu() => this;
}

public class English : Translation
{
    public override string FirstMenuHeader => "First";
    public override string SecondMenuHeader => "Second";
    public override string ThirdMenuHeader => "Third";
}
</code>```

Now you can call

```<code>var englishMenu = new English().NavMenu();
</code>```

If there is any need to implement NavMenu() in any other way for some classes, you could make it virtual and override it where needed:

```<code>public abstract class Translation : NavMenuProps
{
    public virtual Translation NavMenu() => this;
}

public class English : Translation
{
    //...

    public override Translation NavMenu()
    {
        //return base.NavMenu();
    }
}

</code>```

Body:
I'm trying to implement my own multi-language feature in Blazor WASM. Nothing fancy but I would like to make sure I don't forget to implement properties in a specific language. In TypeScript this would work with typing or interfacing objects. In C# the equivalent of such an object would be a class. I tried using interfaces and abstract classes in C# but I'm not getting the desired result.

The desired result would be for my code editor to hint when I forgot to implement a property. How should I proceed?

I could just put all properties directly into the Translation class to enforce their implementation but than I'll have one very long list of properties, I'd prefer to chop them up a bit.

    public class NavMenuProps
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";
    }

    public abstract class Translation
    {
        public abstract NavMenuProps NavMenu();
    }

    public class English : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps();
        }
    }

    public class Dutch : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps
            {
                FirstMenuHeader = "Honden",
                SecondMenuHeader = ""
            };
        }
    }

    public class French : Translation
    {
        public override NavMenuProps NavMenu()
        {
            throw new System.NotImplementedException();
        }
    }

In TypeScript it would work like this:

type TNavMenuProps = {
    firstMenuHeader: string;
    secondMenuHeader: string;
    thirdMenuHeader: string;
    ...
}

type TLoginPageProps = {
    firstLabel: string;
    secondLabel: string;
    ...
}

type TTranslation = {
    navMenu: TNavMenuProps;
    loginPage: TLoginPageProps;
    ...
}

const englishTranslations: TTranslation = {
    navMenu: {
        firstMenuHeader: "first";
        secondMenuHeader: "second";
        // Would complain I forgot "thirdMenuHeader".
    },
    loginPage: {
        firstLabel: "1st label";
        secondLabel: "2nd label";
    },
    ...
}

Body:
If I understand your requirements correctly, this could be a way to go: Make NavMenuProps abstract, and implement NavMenu() inside Translation. Now, rather than implementing NavMenu() in all of the classes that inherit Translation, you rather need to implement all properties in NavMenuProps in all those classes.

public abstract class NavMenuProps
{
    public abstract string FirstMenuHeader { get; }
    public abstract string SecondMenuHeader { get; }
    public abstract string ThirdMenuHeader { get; }
}

public abstract class Translation : NavMenuProps
{
    public Translation NavMenu() => this;
}

public class English : Translation
{
    public override string FirstMenuHeader => "First";
    public override string SecondMenuHeader => "Second";
    public override string ThirdMenuHeader => "Third";
}

Now you can call

var englishMenu = new English().NavMenu();

If there is any need to implement NavMenu() in any other way for some classes, you could make it virtual and override it where needed:

public abstract class Translation : NavMenuProps
{
    public virtual Translation NavMenu() => this;
}

public class English : Translation
{
    //...

    public override Translation NavMenu()
    {
        //return base.NavMenu();
    }
}


问:
How do I replace custom BBCode style tag with a hyperlink
I've got a bunch of text which can contain custom tags in this format:

```<code>[MYLINK ID="1234" URL="http://mywebsite.com" TEXT="Website link"]
</code>```

The text can contain multiple links.  What I'm trying to do is to translate the tags to normal html links and grab the IDs in C# code.  The resulting replaced tag should be in this format:

```<code><a href="http://mywebsite.com?id=1234">Website link</a>
</code>```

So to clarify, if I had the following chunk of text:

```<code>This is a test [MYLINK ID="1234" URL="http://mywebsite.com" TEXT="website link"] with some more text and [MYLINK ID="2345" URL="http://mywebsite2.com" TEXT="another link"] here too.
</code>```

It should translate to this:

```<code>This is a test <a href="http://mywebsite.com?id=1234">website link</a> with some more text and <a href="http://mywebsite2.com?id=2345">another link</a> here too.
</code>```

EDIT: Been faffing with Regex for the last couple of hours and have managed to get the following to match the tag but don't know what to do next...

```<code>\[MYLINK ID=\"(.*?)\" URL=\"(.*?)\" TEXT=\"(.*?)\"\]
</code>```

Any help would be greatly appreciated. Cheers,

答:
If the attributes always in the order you showed, you can use

var text = "[MYLINK ID=\"1234\" URL=\"http://mywebsite.com\" TEXT=\"Website link\"]";
var pattern = "\\[MYLINK\\s+ID=\"([^\"]*)\"\\s+URL=\"([^\"]*)\"\\s+TEXT=\"([^\"]*)\"]";
var replacement = "$3";
var result = Regex.Replace(text, pattern, replacement, RegexOptions.IgnoreCase);
// => Website link
```

See the .NET regex demo and the C# demo.

Details:

\[MYLINK - [MYLINK text

\s+ - any one or more whitespaces

ID=\" - ID=" text

([^\"]*) - Group 1 ($1): zero or more chars other than "

\"\s+URL=\" - ", one or more whitespaces, URL=" text

([^\"]*) - Group 2 ($2): zero or more chars other than "

\"\s+TEXT=\" - ", one or more whitespaces, TEXT=" text

([^\"]*) - Group 3 ($3): zero or more chars other than "

\"] - "] text.

Body:
I've got a bunch of text which can contain custom tags in this format:

[MYLINK ID="1234" URL="http://mywebsite.com" TEXT="Website link"]

The text can contain multiple links.  What I'm trying to do is to translate the tags to normal html links and grab the IDs in C# code.  The resulting replaced tag should be in this format:

Website link

So to clarify, if I had the following chunk of text:

This is a test [MYLINK ID="1234" URL="http://mywebsite.com" TEXT="website link"] with some more text and [MYLINK ID="2345" URL="http://mywebsite2.com" TEXT="another link"] here too.

It should translate to this:

This is a test website link with some more text and another link here too.

EDIT: Been faffing with Regex for the last couple of hours and have managed to get the following to match the tag but don't know what to do next...

\[MYLINK ID=\"(.*?)\" URL=\"(.*?)\" TEXT=\"(.*?)\"\]

Any help would be greatly appreciated. Cheers,

Body:
If the attributes always in the order you showed, you can use

var text = "[MYLINK ID=\"1234\" URL=\"http://mywebsite.com\" TEXT=\"Website link\"]";
var pattern = "\\[MYLINK\\s+ID=\"([^\"]*)\"\\s+URL=\"([^\"]*)\"\\s+TEXT=\"([^\"]*)\"]";
var replacement = "<a href=\"$2?id=$1\">$3</a>";
var result = Regex.Replace(text, pattern, replacement, RegexOptions.IgnoreCase);
// => <a href="http://mywebsite.com?id=1234">Website link</a>

See the .NET regex demo and the C# demo.

Details:

\[MYLINK - [MYLINK text

\s+ - any one or more whitespaces

ID=\" - ID=" text

([^\"]*) - Group 1 ($1): zero or more chars other than "

\"\s+URL=\" - ", one or more whitespaces, URL=" text

([^\"]*) - Group 2 ($2): zero or more chars other than "

\"\s+TEXT=\" - ", one or more whitespaces, TEXT=" text

([^\"]*) - Group 3 ($3): zero or more chars other than "

\"] - "] text.


问:
How to refer to a merged cell in a formula (or to a "bottom-up" range)
I've got this (long) table on Google Sheets:

The cells of column B may be vertically merged, but the number of rows for each multi-cell is random.

Since, for each multi-cell, the top cell is the one containing the value, I need to use a formula which refers, for instance, to the cell B1 in the cells A1 and A2, to the cell B3 in the cells A3, A4 and A5, and so forth.

I thought to build a kind of bottom-up coalesce. E.g. if I'm in cell A10, I want to go from $B10 towards the top until I find a non-null value (i.e. until $B7).
For doing this, I tried to insert the above formula in A10:

```<code>=INDEX($B10:$B$1,MATCH(FALSE,ISBLANK($B10:$B$1),FALSE))
</code>```

but it doesn't accept a range starting from a lower position with respect to the endpoint. Or, better, such range will be automatically flipped to $B$1:$B10. It follows that the first non-empty value is the one of $B$1 and the returned value in A10 is 3 instead of 1.

Is there a way to express such inverted range? In case it isn't possible, how can I solve this problem?

答:
You can fill column C with values

```<code>=ArrayFormula(lookup(row(B1:B),row(B1:B)/if(B1:B<>"",1,0),B1:B))
</code>```

or, for one specific row, you can retrieve the last value by

```<code>=ArrayFormula(lookup(row(),row(B$1:B)/if(B$1:B<>"",1,0),B$1:B))
</code>```

Body:
I've got this (long) table on Google Sheets:

The cells of column B may be vertically merged, but the number of rows for each multi-cell is random.

Since, for each multi-cell, the top cell is the one containing the value, I need to use a formula which refers, for instance, to the cell B1 in the cells A1 and A2, to the cell B3 in the cells A3, A4 and A5, and so forth.

I thought to build a kind of bottom-up coalesce. E.g. if I'm in cell A10, I want to go from $B10 towards the top until I find a non-null value (i.e. until $B7).
For doing this, I tried to insert the above formula in A10:

=INDEX($B10:$B$1,MATCH(FALSE,ISBLANK($B10:$B$1),FALSE))

but it doesn't accept a range starting from a lower position with respect to the endpoint. Or, better, such range will be automatically flipped to $B$1:$B10. It follows that the first non-empty value is the one of $B$1 and the returned value in A10 is 3 instead of 1.

Is there a way to express such inverted range? In case it isn't possible, how can I solve this problem?

Body:
You can fill column C with values

=ArrayFormula(lookup(row(B1:B),row(B1:B)/if(B1:B<>"",1,0),B1:B))

or, for one specific row, you can retrieve the last value by

=ArrayFormula(lookup(row(),row(B$1:B)/if(B$1:B<>"",1,0),B$1:B))


问:
UIImage is rotated 90 degrees when creating from url and set to the pasteboard
What do I simply do?

```<code>let pasteboard = UIPasteboard.general
let base64EncodedImageString = "here_base_64_string_image"
let data = Data(base64Encoded: base64EncodedImageString)
let url = data?.write(withName: "image.jpeg")
pasteboard.image = UIImage(url: url) //and now when I try to paste somewhere that image for example in imessage, it is rotated... why?
</code>```

What may be important:

It happens only for images created by camera.

However, if use exactly the same process (!) to create activityItems for UIActivityViewController and try to use iMessage app, then it works... why? What makes the difference?

I use above two simple extensions for UIImage and Data:

```<code>extension Data {
    func write(withName name: String) -> URL {
        let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)
        do {
            try write(to: url, options: NSData.WritingOptions.atomic)
            return url
        } catch {
            return url
        }
    }
}

extension UIImage {
    convenience init?(url: URL?) {
        guard let url = url else {
            return nil
        }
        do {
            self.init(data: try Data(contentsOf: url))
        } catch {
            return nil
        }
    }
}
</code>```

Before server returns base64EncodedString I upload an image from camera like this:

```<code>func imagePickerController(
    _ picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
    let image = info[.originalImage] as? UIImage
    let encodedBase64 = image?.jpegData(compressionQuality: 0.9)?.base64EncodedString() ?? ""
    //upload encodedBase64 to the server... that is all
}
</code>```

答:
I am not sure but I think UIPasteBoard converts your image to PNG and discards its orientation. You can explicitly tell the kind of data you are adding to the pasteboard but I am not sure if this would work for your scenery.

```<code>extension Data {
    var image: UIImage? { UIImage(data: self) }
}
</code>```

setting your pasteboard data

```<code>UIPasteboard.general.setData(jpegData, forPasteboardType: "public.jpeg")
</code>```

loading the data from pasteboard

```<code>if let pbImage = UIPasteboard.general.data(forPasteboardType: "public.jpeg")?.image {

}
</code>```

Or Redrawing your image before setting your pasteboard image property

```<code>extension UIImage {
    func flattened(isOpaque: Bool = true) -> UIImage? {
        if imageOrientation == .up { return self }
        UIGraphicsBeginImageContextWithOptions(size, isOpaque, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
</code>```

```<code>UIPasteboard.general.image = image.flattened()
</code>```

Body:
What do I simply do?

let pasteboard = UIPasteboard.general
let base64EncodedImageString = "here_base_64_string_image"
let data = Data(base64Encoded: base64EncodedImageString)
let url = data?.write(withName: "image.jpeg")
pasteboard.image = UIImage(url: url) //and now when I try to paste somewhere that image for example in imessage, it is rotated... why?

What may be important:

It happens only for images created by camera.

However, if use exactly the same process (!) to create activityItems for UIActivityViewController and try to use iMessage app, then it works... why? What makes the difference?

I use above two simple extensions for UIImage and Data:

extension Data {
    func write(withName name: String) -> URL {
        let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)
        do {
            try write(to: url, options: NSData.WritingOptions.atomic)
            return url
        } catch {
            return url
        }
    }
}

extension UIImage {
    convenience init?(url: URL?) {
        guard let url = url else {
            return nil
        }
        do {
            self.init(data: try Data(contentsOf: url))
        } catch {
            return nil
        }
    }
}

Before server returns base64EncodedString I upload an image from camera like this:

func imagePickerController(
    _ picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
    let image = info[.originalImage] as? UIImage
    let encodedBase64 = image?.jpegData(compressionQuality: 0.9)?.base64EncodedString() ?? ""
    //upload encodedBase64 to the server... that is all
}

Body:
I am not sure but I think UIPasteBoard converts your image to PNG and discards its orientation. You can explicitly tell the kind of data you are adding to the pasteboard but I am not sure if this would work for your scenery.

extension Data {
    var image: UIImage? { UIImage(data: self) }
}

setting your pasteboard data

UIPasteboard.general.setData(jpegData, forPasteboardType: "public.jpeg")

loading the data from pasteboard

if let pbImage = UIPasteboard.general.data(forPasteboardType: "public.jpeg")?.image {

}

Or Redrawing your image before setting your pasteboard image property

extension UIImage {
    func flattened(isOpaque: Bool = true) -> UIImage? {
        if imageOrientation == .up { return self }
        UIGraphicsBeginImageContextWithOptions(size, isOpaque, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

UIPasteboard.general.image = image.flattened()


问:
How to iterate over array and save data using hooks
Tha idea is iterate over a array and save (or update) values.

```<code>const [skills, setSkills] = useState([]);

useEffect(() => {
    Object.entries(array).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills({ ...skills, [k]: v })
    });
}, [array]);
</code>```

The output is:

```<code>The skill is:  1  and value:  30
The skill is:  2  and value:  40
The skill is:  3  and value:  90
</code>```

That's ok and I assume that "skills" should be:

```<code>{1: 30, 2: 40, 3: 90}
   1: 30
   2: 40
   3: 90
</code>```

but actually, it only saving the last input. I mean, I see the following:

```<code>{3: 90}
   3: 90
</code>```

Please, somebody can explain why? And how to do it the right way?
Thanks!!!

答:
Skills are array of objects at first but you change it to single object in the loop that's why you only see the last output in the state

this should fix your problem

```<code>useEffect(() => {
    Object.entries(json_h).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills([ ...skills, {[k]: v} ]) // notice changes here
    });
}, [json_h]);
</code>```

though I suggest save the new values in a temporary array then change the state once this will get rid of unnecessary setState calls

```<code>useEffect(() => {
    let tempArr = [];
    Object.entries(json_h).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       tempArr.push({[k]: v})
    });
    setSkills([...skills, ...tempArr])
}, [json_h]);
</code>```

Body:
Tha idea is iterate over a array and save (or update) values.

const [skills, setSkills] = useState([]);

useEffect(() => {
    Object.entries(array).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills({ ...skills, [k]: v })
    });
}, [array]);

The output is:

The skill is:  1  and value:  30
The skill is:  2  and value:  40
The skill is:  3  and value:  90

That's ok and I assume that "skills" should be:

{1: 30, 2: 40, 3: 90}
   1: 30
   2: 40
   3: 90

but actually, it only saving the last input. I mean, I see the following:

{3: 90}
   3: 90

Please, somebody can explain why? And how to do it the right way?
Thanks!!!

Body:
Skills are array of objects at first but you change it to single object in the loop that's why you only see the last output in the state

this should fix your problem

useEffect(() => {
    Object.entries(json_h).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills([ ...skills, {[k]: v} ]) // notice changes here
    });
}, [json_h]);

though I suggest save the new values in a temporary array then change the state once this will get rid of unnecessary setState calls

useEffect(() => {
    let tempArr = [];
    Object.entries(json_h).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       tempArr.push({[k]: v})
    });
    setSkills([...skills, ...tempArr])
}, [json_h]);


问:
Discord.py create a maximum of 1 channel per user
```<code>if message_id == 941751519781466172 and emoji == "":

    self.ticket_creator = user_id

    message = await channel.fetch_message(message_id)
    await message.remove_reaction("",user)

    member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
    support_role = guild.get_role(941751615998791740)
    category = guild.get_channel(941749835328012328)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(read_messages=True, send_messages=True),
        support_role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
    }
    self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

    embed = discord.Embed(
        title="Yetkililer en yakın zamanda yardımcı olmak için sizinle iletişime geçecek lütfen bekleyiniz.\n"
              "Övgü satın alımı için ''Fiyatlar'' yazarak öğrenebilirsiniz.",
        color=0xf1c40f)

    msg = await self.channel_ticket.send(embed=embed)

    dmmessage = (f'Övgü kanalınız oluşturuldu. (SAĞDAKİ YAZIYA TIKLAGİT)=====> <#{self.channel_ticket.id}> ')

    dm = await user.send(dmmessage)
</code>```

when the user clicks on the emoji in the message, it creates a private text channel for him and send a dm message that private channel has been created. a new channel is created every time the user clicks on it, how can I block it ?

if the user has created a private channel, I want him to send a dm message because you have already created a private channel.

nickname of the user becomes the name of the channel.

答:
You can use an array to store the user id's on creation and only create a channel if the user id is not already in there. Like I mentioned you can also use a .json file or a database. The reason you would want to use one of these instead of a plain array is so that it is stored even if your script is turned off (say for maintenance purposes) the list of open channels will still be stored unlike in a plain array where it will get reset.

open_user_channels = []

if message_id == 941751519781466172 and emoji == "" and user_id not in open_user_channels:

    self.ticket_creator = user_id

    message = await channel.fetch_message(message_id)
    await message.remove_reaction("",user)

    member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
    support_role = guild.get_role(941751615998791740)
    category = guild.get_channel(941749835328012328)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(read_messages=True, send_messages=True),
        support_role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
    }

    self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

    embed = discord.Embed(
        title="Yetkililer en yakın zamanda yardımcı olmak için sizinle iletişime geçecek lütfen bekleyiniz.\n"
              "Övgü satın alımı için ''Fiyatlar'' yazarak öğrenebilirsiniz.",
        color=0xf1c40f)

    await self.channel_ticket.send(embed=embed)

    dmmessage = (f'Övgü kanalınız oluşturuldu. (SAĞDAKİ YAZIYA TIKLAGİT)=====> <#{self.channel_ticket.id}> ')

    await user.send(dmmessage)

    open_user_channels.append(user_id)

else:
    await user.send("There is an open channel already.")
```

Body:
if message_id == 941751519781466172 and emoji == "":

    self.ticket_creator = user_id

    message = await channel.fetch_message(message_id)
    await message.remove_reaction("",user)

    member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
    support_role = guild.get_role(941751615998791740)
    category = guild.get_channel(941749835328012328)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(read_messages=True, send_messages=True),
        support_role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
    }
    self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

    embed = discord.Embed(
        title="Yetkililer en yakın zamanda yardımcı olmak için sizinle iletişime geçecek lütfen bekleyiniz.\n"
              "Övgü satın alımı için ''Fiyatlar'' yazarak öğrenebilirsiniz.",
        color=0xf1c40f)

    msg = await self.channel_ticket.send(embed=embed)

    dmmessage = (f'Övgü kanalınız oluşturuldu. (SAĞDAKİ YAZIYA TIKLAGİT)=====> <#{self.channel_ticket.id}> ')

    dm = await user.send(dmmessage)

when the user clicks on the emoji in the message, it creates a private text channel for him and send a dm message that private channel has been created. a new channel is created every time the user clicks on it, how can I block it ?

if the user has created a private channel, I want him to send a dm message because you have already created a private channel.

nickname of the user becomes the name of the channel.


问:
How to return data in an async function in node.js? My code return [object Promise] but I want the response.length
I want the array length,  but the function returns [object Promise]. I send a correct email and I just need know if it's already in collection.</p>
```<code> const res = require('express/lib/response');

 async function emailUnique(email){

    var query = { email: email };

    const response = await dbo.collection('users').find(query).toArray();

    const tot = response.length;

    return tot;

}

const emailValidate = function (email) {

    if (email.indexOf('@') === -1 || email.indexOf('.') < 0) {
        message = 'Invalid entries. Try again.';
    }else{

        let quantos = emailUnique(email);

        message = quantos;

    }

    return message;

};

module.exports = emailValidate;
</code>```

答:
Thanks, Its a simplified answer:

emailValidate.mod.js

```<code>const res = require('express/lib/response');

function emailValidate(email) {
    return new Promise((resolve) => { // return a promise
        var query = { email: email };
        dbo.collection('users').find(query).toArray((_err, result) => {
            resolve(result.length); //the returned value
        });
    });
}

module.exports = emailValidate;
</code>```

user.js

```<code>const mod_emailValidate = require('./emailValidate.mod');

exports.getUsers = (req, res) => {
    const { name } = req.body;
    const { email } = req.body;
    const { password } = req.body;

    async function run() { // make an async function
        let data = await mod_emailValidate(email); //call the function with await
        console.log(`Retornou: ${data}`);
    }

    run();

    res.status(400).send({ message: 'Fired' });
};

</code>```

Body:
I want the array length,  but the function returns [object Promise]. I send a correct email and I just need know if it's already in collection.

 const res = require('express/lib/response');

 async function emailUnique(email){

    var query = { email: email };

    const response = await dbo.collection('users').find(query).toArray();

    const tot = response.length;

    return tot;

}

const emailValidate = function (email) {

    if (email.indexOf('@') === -1 || email.indexOf('.') < 0) {
        message = 'Invalid entries. Try again.';
    }else{

        let quantos = emailUnique(email);

        message = quantos;

    }

    return message;

};

module.exports = emailValidate;

Body:
Thanks, Its a simplified answer:

emailValidate.mod.js

const res = require('express/lib/response');

function emailValidate(email) {
    return new Promise((resolve) => { // return a promise
        var query = { email: email };
        dbo.collection('users').find(query).toArray((_err, result) => {
            resolve(result.length); //the returned value
        });
    });
}

module.exports = emailValidate;

user.js

const mod_emailValidate = require('./emailValidate.mod');

exports.getUsers = (req, res) => {
    const { name } = req.body;
    const { email } = req.body;
    const { password } = req.body;

    async function run() { // make an async function
        let data = await mod_emailValidate(email); //call the function with await
        console.log(`Retornou: ${data}`);
    }

    run();

    res.status(400).send({ message: 'Fired' });
};


问:
CSS dropdown menu lined up with viewport, not parent to impede crazy scrolling
Most CSS dropmenus tend to line up the top of the list of children
 with the top of the parent
.

But that  breaks down easily the longer the menus and lengthier the list of children, which then drop out of the view port, create scrolling issues and so forth.

Given this codepen  how can the submenu be aligned with the height of the parent menu, say offset down by 50px ?

答:
You'll have to offset up to hit the top off the viewport by adding a sub-menu class and changing the relative parent:

```<code>.li-sub ul {
  top: 0px !important;
  left: 250px !important;
 }
</code>```

Here's the same fiddle but with the adjustments: https://jsfiddle.net/getr0cou/4/

Body:
You'll have to offset up to hit the top off the viewport by adding a sub-menu class and changing the relative parent:

.li-sub ul {
  top: 0px !important;
  left: 250px !important;
 }

Here's the same fiddle but with the adjustments: https://jsfiddle.net/getr0cou/4/


问:
Remove duplicates from a nested array of objects
I'm trying to remove duplicates from a nested array of objects.

```<code>let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},
{
  type: "horizontal",
  tiles: [{ col: 1, row: 3 }, { col: 2, row: 3 }, { col: 0, row: 3 }]
},
{
  type: "horizontal",
  tiles: [{ col: 2, row: 3 }, { col: 1, row: 3 }, { col: 0, row: 3 }],
},
{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];
</code>```

I'm trying to only keep the top level objects if they are unique. As you can see the tiles array isn't necessarily sorted by col/row.

So arr here would become:

```<code>let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];
</code>```

I've looked extensively but can't quite find something that solves the same problem I'm trying to solve.

答:
Okay this may be a little long but I couldn't find a shorter way of doing.
My plan was to get a Set of JSON strings (which gives unique) and to convert it back to array of JS objects (Set of JS objects won't remove duplicates). This way will get only the unique values.

But for the JSON strings to be equal for unique records the tiles array has to be in same order so I ran sort on tiles first to make sure the order is same

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},{
  type: "horizontal",
  tiles: [{ col: 1, row: 3 }, { col: 2, row: 3 }, { col: 0, row: 3 }]
},{
  type: "horizontal",
  tiles: [{ col: 2, row: 3 }, { col: 1, row: 3 }, { col: 0, row: 3 }],
},{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

//sort for ascending order of col field
arr.forEach((o,i,a) => {
    a[i].tiles.sort((a,b) => a.col-b.col)
})

let mySet = new Set();
arr.forEach(item => mySet.add(JSON.stringify(item)))

let result = []
mySet.forEach((el) => {
    result.push(JSON.parse(el))
})

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm trying to remove duplicates from a nested array of objects.

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},
{
  type: "horizontal",
  tiles: [{ col: 1, row: 3 }, { col: 2, row: 3 }, { col: 0, row: 3 }]
},
{
  type: "horizontal",
  tiles: [{ col: 2, row: 3 }, { col: 1, row: 3 }, { col: 0, row: 3 }],
},
{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

I'm trying to only keep the top level objects if they are unique. As you can see the tiles array isn't necessarily sorted by col/row.

So arr here would become:

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

I've looked extensively but can't quite find something that solves the same problem I'm trying to solve.

Body:
Okay this may be a little long but I couldn't find a shorter way of doing.
My plan was to get a Set of JSON strings (which gives unique) and to convert it back to array of JS objects (Set of JS objects won't remove duplicates). This way will get only the unique values.

But for the JSON strings to be equal for unique records the tiles array has to be in same order so I ran sort on tiles first to make sure the order is same

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},{
  type: "horizontal",
  tiles: [{ col: 1, row: 3 }, { col: 2, row: 3 }, { col: 0, row: 3 }]
},{
  type: "horizontal",
  tiles: [{ col: 2, row: 3 }, { col: 1, row: 3 }, { col: 0, row: 3 }],
},{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

//sort for ascending order of col field
arr.forEach((o,i,a) => {
    a[i].tiles.sort((a,b) => a.col-b.col)
})

let mySet = new Set();
arr.forEach(item => mySet.add(JSON.stringify(item)))

let result = []
mySet.forEach((el) => {
    result.push(JSON.parse(el))
})

console.log(result)

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Alternative way to populate selected value in HTML.Dropdownlistfor in MVC3.0
In the below code, though model.Title is holding the proper selected value, Its not getting set in the ddl, having id 'Title'.

Can I set the selected value in any other way? (like in document ready?)

```<code>    <td>
@Html.DropDownListFor(model => model.Title, Model.TitleList, !Model.IsTitleEditable ? (object)new { id = "Title", @disabled = "disabled", @style = "width:250px;" } : (object)new { id = "Title", @style = "width:250px" })
</td>
</code>```

In my controller the selectlist is getting filled as below:

```<code>model.TitleList = new SelectList(GetAllTitles(), "Code","Value");
</code>```

In this case as I m using the other overloaded method, how to set the selectedValue property of this selectList?

答:
If Model.TitleList is a SelectList, you can specify the selected value when you populate the SelectList during your model creation. As an illustration:

```<code>var model = new MyViewModel();
var domainEntity = GetMyDomainEntity(id);

// Create a selectlist using all your titles and specifying the Title value of the item
// you're viewing as the selected item. See parameter options if you're not supplying
// an object as the selected item value
model.TitleList = new SelectList(GetAllTitles(), domainEntity.Title)
</code>```

Then you'd simply do your Html.DropDownListFor in your view.

Body:
In the below code, though model.Title is holding the proper selected value, Its not getting set in the ddl, having id 'Title'.

Can I set the selected value in any other way? (like in document ready?)

@Html.DropDownListFor(model => model.Title, Model.TitleList, !Model.IsTitleEditable ? (object)new { id = "Title", @disabled = "disabled", @style = "width:250px;" } : (object)new { id = "Title", @style = "width:250px" })

In my controller the selectlist is getting filled as below:

model.TitleList = new SelectList(GetAllTitles(), "Code","Value");

In this case as I m using the other overloaded method, how to set the selectedValue property of this selectList?

Body:
If Model.TitleList is a SelectList, you can specify the selected value when you populate the SelectList during your model creation. As an illustration:

var model = new MyViewModel();
var domainEntity = GetMyDomainEntity(id);

// Create a selectlist using all your titles and specifying the Title value of the item
// you're viewing as the selected item. See parameter options if you're not supplying
// an object as the selected item value
model.TitleList = new SelectList(GetAllTitles(), domainEntity.Title)

Then you'd simply do your Html.DropDownListFor in your view.


问:
Sum of a list 2 elements by 2 elements
I have a 25 elements list like

```<code>tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
</code>```

And I want to create a new list tab1 which display the sum of the elements of the list two by two, if the list is odd I don't have to calculate the sum on the last element.
And it has to be done with a for loop for... any ideas?
Any help would be appreciated.
I tried on my side but without success.

i tried this :

```<code>for i in tab:
print(sum(i:len(tab))
</code>```

it gives me a syntax error and i tried some of others things but didn't work...

i tried this too

```<code>for i in tab:
print(sum(i,i+1))
</code>```

didn't work too

and when i do this

```<code>sum=0
for i in tab:
print(sum(tab[i]+tab[i+1]))
</code>```

it gives me back : TypeError: 'int' object is not callable

答:
This can be achieved by:

```<code>tab = [6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
tab1 = []
initial_pos = 0

for i in range(2, len(tab), 2):
    tab1.append(sum(tab[initial_pos:i]))
    initial_pos = I

    if i == len(tab) - 2:
        tab1.append(sum(tab[i:]))

</code>```

What is happening here is we are iterating through tab starting at the third element and summing the values of elements of the slice tab[0:2], then initial_pos will assume the value of 2 and I the value of 4, so in the next iteration we will be appending sum(tab[2:4])to tab1 and so forth.

The if statement makes sure this works for odd lists and even lists.

Title: Sum of a list 2 elements by 2 elements

Body:
I have a 25 elements list like

tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]

And I want to create a new list tab1 which display the sum of the elements of the list two by two, if the list is odd I don't have to calculate the sum on the last element.
And it has to be done with a for loop for... any ideas?
Any help would be appreciated.
I tried on my side but without success.

i tried this :

for i in tab:
print(sum(i:len(tab))

it gives me a syntax error and i tried some of others things but didn't work...

i tried this too

for i in tab:
print(sum(i,i+1))

didn't work too

and when i do this

sum=0
for i in tab:
print(sum(tab[i]+tab[i+1]))

it gives me back : TypeError: 'int' object is not callable

Body:
This can be achieved by:

tab = [6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
tab1 = []
initial_pos = 0

for i in range(2, len(tab), 2):
    tab1.append(sum(tab[initial_pos:i]))
    initial_pos = I

    if i == len(tab) - 2:
        tab1.append(sum(tab[i:]))

What is happening here is we are iterating through tab starting at the third element and summing the values of elements of the slice tab[0:2], then initial_pos will assume the value of 2 and I the value of 4, so in the next iteration we will be appending sum(tab[2:4])to tab1 and so forth.

The if statement makes sure this works for odd lists and even lists.


问:
Typescript typing a reference for third party custom components (react-player)

Description

I'm struggling to add the type annotation of a useRef attached on this player component: react-player to get access to the seekTo instance method as per the documentation demo source code. I can't seem to get the type to work - I'm kinda new to typescript and probably going about this wrong so any pointers would be helpful! I've looked at the react-player index.d.ts and can see the function is listed there, just need to know how I'm supposed to be writing this in.

Expected Behavior

Have access to the instance methods of the player.

Error

Property 'seekTo' does not exist on type 'MutableRefObject<ReactPlayer | null>'.ts(2339)

Steps to Reproduce

I made a small codeSandbox - basically trying to mimic the demo source for adding a ref to utilise the seekTo method onMouseUp on a range type input.

https://codesandbox.io/s/react-typescript-lqgvr?file=/src/index.tsx

Thanks!

答:
I'm on a project using TS with React. I was able to get everything working by declaring:

```<code>const player = useRef<ReactPlayer>(null);
</code>```

And then in my :

```<code>    <ReactPlayer ref={player} />
</code>```

So any time I need to use a function like seekTo() it looks like:

```<code>player?.current?.seekTo(seconds);
</code>```

No need to use:

```<code>import { BaseReactPlayerProps } from 'react-player/base';
</code>```

Body:
I'm on a project using TS with React. I was able to get everything working by declaring:

const player = useRef<ReactPlayer>(null);

And then in my :

    <ReactPlayer ref={player} />

So any time I need to use a function like seekTo() it looks like:

player?.current?.seekTo(seconds);

No need to use:

import { BaseReactPlayerProps } from 'react-player/base';


问:
PicoCTF General Skills PW Crack Level4
I'm working on the PW Crack Level4 in the PicoCTF General Skills section. I'm very new to python and CTF's in general. The challenge is to find the right pw from the included list of 100 possibles. I could have, by now, simply entered each one, lol, but that's not the point I think. So I am trying to modify the code to iterate through the list of pw's and pass each one to the part of the code that checks it.

That's where I'm stuck. The for loop seems to run through the list without passing each pw to the part of the code that should check it... I feel like the answer is on the tip of my tongue. But I'm too new to see it.

Here's my code

```<code>import hashlib

### THIS FUNCTION WILL NOT HELP YOU FIND THE FLAG --LT ########################
def str_xor(secret, key):
    #extend key to secret length
    new_key = key
    i = 0
    while len(new_key) < len(secret):
        new_key = new_key + key[i]
        i = (i + 1) % len(key)
    return "".join([chr(ord(secret_c) ^ ord(new_key_c)) for (secret_c,new_key_c) in zip(secret,new_key)])
###############################################################################

flag_enc = open('level4.flag.txt.enc', 'rb').read()
correct_pw_hash = open('level4.hash.bin', 'rb').read()

def hash_pw(pw_str):
    pw_bytes = bytearray()
    pw_bytes.extend(pw_str.encode())
    m = hashlib.md5()
    m.update(pw_bytes)
    return m.digest()

pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]

def level_4_pw_check():
    for x in pos_pw_list: # for loop to iterate through the pos_pw_list
        user_pw = input(x)
        # print(user_pw) # printing user_pw just to make sure the loop is working - it is
        user_pw_hash = hash_pw(user_pw)
    if( user_pw_hash == correct_pw_hash ):
        print("Welcome back... your flag, user:")
        decryption = str_xor(flag_enc.decode(), user_pw)
        print(decryption)
        return
    print("That password is incorrect")

level_4_pw_check()

# The strings below are 100 possibilities for the correct password.
#   (Only 1 is correct)
pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]
</code>```

答:
I'm not too experienced myself, but I think I know what you're doing wrong. I'll try to give you a small tip that will probably help you solve the problem without giving you the answer full out.

I think where you're going wrong is that you're still asking for input. Since you're comparing a list of possible passwords to the actual possible password, you don't need to ask for input anywhere in your code.

I hope this helps you out!

Title: PicoCTF General Skills PW Crack Level4

Body:
I'm working on the PW Crack Level4 in the PicoCTF General Skills section. I'm very new to python and CTF's in general. The challenge is to find the right pw from the included list of 100 possibles. I could have, by now, simply entered each one, lol, but that's not the point I think. So I am trying to modify the code to iterate through the list of pw's and pass each one to the part of the code that checks it.

That's where I'm stuck. The for loop seems to run through the list without passing each pw to the part of the code that should check it... I feel like the answer is on the tip of my tongue. But I'm too new to see it.

Here's my code

import hashlib

### THIS FUNCTION WILL NOT HELP YOU FIND THE FLAG --LT ########################
def str_xor(secret, key):
    #extend key to secret length
    new_key = key
    i = 0
    while len(new_key) < len(secret):
        new_key = new_key + key[i]
        i = (i + 1) % len(key)
    return "".join([chr(ord(secret_c) ^ ord(new_key_c)) for (secret_c,new_key_c) in zip(secret,new_key)])
###############################################################################

flag_enc = open('level4.flag.txt.enc', 'rb').read()
correct_pw_hash = open('level4.hash.bin', 'rb').read()

def hash_pw(pw_str):
    pw_bytes = bytearray()
    pw_bytes.extend(pw_str.encode())
    m = hashlib.md5()
    m.update(pw_bytes)
    return m.digest()

pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]

def level_4_pw_check():
    for x in pos_pw_list: # for loop to iterate through the pos_pw_list
        user_pw = input(x)
        # print(user_pw) # printing user_pw just to make sure the loop is working - it is
        user_pw_hash = hash_pw(user_pw)
    if( user_pw_hash == correct_pw_hash ):
        print("Welcome back... your flag, user:")
        decryption = str_xor(flag_enc.decode(), user_pw)
        print(decryption)
        return
    print("That password is incorrect")

level_4_pw_check()

# The strings below are 100 possibilities for the correct password.
#   (Only 1 is correct)
pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]


问:
How to make rule "all" in Snakefile condition on completion of parallel wildcard rule
I have some TGZ files containing audio SPH samples, which I unpack in snakemake like this:

```<code>tgz_files = ["a.tgz", "b.tgz"]
tgz_dirs = ["a", "b"]
rule untar_tgz_files:
     input:
        tgz_files
     output:
        directory(tgz_dirs)
     shell:
        tar -xzvf {input}
</code>```

I don't know the names of the SPH sample files until after the untar.  I then have a rule which translates the SPH files to WAV files, like this:

```<code>rule sph_to_wav:
     input:
        "{root}/{filename}.sph"
     output:
        "{root}_wav/{filename}.wav"
     shell:
        sox -t sph {input} -b 16  -t wav {output}
</code>```

I want my Snakefile to run both of these steps (untar and convert), not knowing in advance the exact names of the SPH files in the TGZ archives.   I need something like this to mark the completion of the sph_to_wav rule:

```<code>rule sph_to_wav_finished:
     input:
        "{root}_wav/{filename}.wav"
     output:
        "sph_to_wav_finished.txt"
</code>```

and then I want to condition rule all on both of these processes:

```<code>rule all:
     input:
         tgz_dirs, "sph_to_wav_finished.txt"
</code>```

However, I get the error:

```<code>Building DAG of jobs...
MissingInputException in Snakefile:
Missing input files for rule all:
sph_to_wav_finished.txt
</code>```

How do I write this so that

Snakemake doesn't complain and runs the unpack and sph to wav

Runs the sph to wav after the unpack

?

答:
This sounds like a use-case for a checkpoint. Since rule untar_tgz_files generates files that are not known in advance, you can convert it into a checkpoint:

checkpoint untar_tgz_files:
    ... # everything defined as in a regular rule
```
<p>This will tell <code>snakemake</code> that once this <code>checkpoint</code> has been completed, DAG needs to be re-evaluated to take into account of the new files that were created.</p>
<p>Downstream rules will need to find out about the new files, so typically you will do some sort of <code>glob.glob</code> to get the list of new files. This is a rough idea, but you might need to fine tune it:</p>
<pre class="lang-py prettyprint-override"><code>def list_new_files(wildcards):
    output_dir = checkpoints. untar_tgz_files.get(sample=wildcards.sample).output
    # you will also want to parse "root" here, skipping it for simplicity
    filenames, _ = glob_wildcards(output_dir+"/{filename}.sph")
    new_files = expand("{filename}.wav", filename=filenames)
    return new_files
</code>```

Finally, collect all the translated files with:

rule sph_to_wav_finished:
     input:
        list_new_files,
     output:
        "sph_to_wav_finished.txt"
```

Body:
I have some TGZ files containing audio SPH samples, which I unpack in snakemake like this:

tgz_files = ["a.tgz", "b.tgz"]
tgz_dirs = ["a", "b"]
rule untar_tgz_files:
     input:
        tgz_files
     output:
        directory(tgz_dirs)
     shell:
        tar -xzvf {input}

I don't know the names of the SPH sample files until after the untar.  I then have a rule which translates the SPH files to WAV files, like this:

rule sph_to_wav:
     input:
        "{root}/{filename}.sph"
     output:
        "{root}_wav/{filename}.wav"
     shell:
        sox -t sph {input} -b 16  -t wav {output}

I want my Snakefile to run both of these steps (untar and convert), not knowing in advance the exact names of the SPH files in the TGZ archives.   I need something like this to mark the completion of the sph_to_wav rule:

rule sph_to_wav_finished:
     input:
        "{root}_wav/{filename}.wav"
     output:
        "sph_to_wav_finished.txt"

and then I want to condition rule all on both of these processes:

rule all:
     input:
         tgz_dirs, "sph_to_wav_finished.txt"

However, I get the error:

Building DAG of jobs...
MissingInputException in Snakefile:
Missing input files for rule all:
sph_to_wav_finished.txt

How do I write this so that

Snakemake doesn't complain and runs the unpack and sph to wav

Runs the sph to wav after the unpack

?

Body:
This sounds like a use-case for a checkpoint. Since rule untar_tgz_files generates files that are not known in advance, you can convert it into a checkpoint:

checkpoint untar_tgz_files:
    ... # everything defined as in a regular rule

This will tell snakemake that once this checkpoint has been completed, DAG needs to be re-evaluated to take into account of the new files that were created.

Downstream rules will need to find out about the new files, so typically you will do some sort of glob.glob to get the list of new files. This is a rough idea, but you might need to fine tune it:

def list_new_files(wildcards):
    output_dir = checkpoints. untar_tgz_files.get(sample=wildcards.sample).output
    # you will also want to parse "root" here, skipping it for simplicity
    filenames, _ = glob_wildcards(output_dir+"/{filename}.sph")
    new_files = expand("{filename}.wav", filename=filenames)
    return new_files

Finally, collect all the translated files with:

rule sph_to_wav_finished:
     input:
        list_new_files,
     output:
        "sph_to_wav_finished.txt"


问:
IPhone Native App using PhoneGap and PHP
I want to develop an iPhone native app, that sync with a remote DB.Is it possible to develop this application using PhoneGap.If I use PhoneGap, how do I get data from an external DB? Can I use PHP on PhoneGap?</p>

答:
I just compiled a PhoneGap app with PHP using Ajax to get content.

First, load jQuery library at index.html head. At function onBodyLoad(), put the Ajax call for the PHP file:

```<code>$('#content').load('http://www.example.com/test.php');
</code>```

at the HTML session, put the div id="content" where do you want to show content.

PHP:

```<code>for($i=1; $i<=10; $i++) {
    echo '<p>I\'m a PHP Loop! Value: ' . $i . ' of 10.</p>';
}
</code>```

HTML will print:

```<code><p>I'm a PHP Loop! Value: 1 of 10.</p>
<p>I'm a PHP Loop! Value: 2 of 10.</p>
<p>I'm a PHP Loop! Value: 3 of 10.</p>
<p>I'm a PHP Loop! Value: 4 of 10.</p>
<p>I'm a PHP Loop! Value: 5 of 10.</p>
<p>I'm a PHP Loop! Value: 6 of 10.</p>
<p>I'm a PHP Loop! Value: 7 of 10.</p>
<p>I'm a PHP Loop! Value: 8 of 10.</p>
<p>I'm a PHP Loop! Value: 9 of 10.</p>
<p>I'm a PHP Loop! Value: 10 of 10.</p>
</code>```

You could also use

```<code>$.get('test.php?name', function(data) {
    $('#content').html(data);
});
</code>```

And your test.php could have something like:

```<code>if (isset($_GET['name'])) {
    echo "Asked for name!";
}
</code>```

With this, you can go on and make some nice stuff. I have one doubt on the subject: can I host external PHP files and deploy the app on app store? There's any restrictions about that?

Body:
I just compiled a PhoneGap app with PHP using Ajax to get content.

First, load jQuery library at index.html head. At function onBodyLoad(), put the Ajax call for the PHP file:

$('#content').load('http://www.example.com/test.php');

at the HTML session, put the div id="content" where do you want to show content.

PHP:

for($i=1; $i<=10; $i++) {
    echo '<p>I\'m a PHP Loop! Value: ' . $i . ' of 10.</p>';
}

HTML will print:

<p>I'm a PHP Loop! Value: 1 of 10.</p>
<p>I'm a PHP Loop! Value: 2 of 10.</p>
<p>I'm a PHP Loop! Value: 3 of 10.</p>
<p>I'm a PHP Loop! Value: 4 of 10.</p>
<p>I'm a PHP Loop! Value: 5 of 10.</p>
<p>I'm a PHP Loop! Value: 6 of 10.</p>
<p>I'm a PHP Loop! Value: 7 of 10.</p>
<p>I'm a PHP Loop! Value: 8 of 10.</p>
<p>I'm a PHP Loop! Value: 9 of 10.</p>
<p>I'm a PHP Loop! Value: 10 of 10.</p>

You could also use

$.get('test.php?name', function(data) {
    $('#content').html(data);
});

And your test.php could have something like:

if (isset($_GET['name'])) {
    echo "Asked for name!";
}

With this, you can go on and make some nice stuff. I have one doubt on the subject: can I host external PHP files and deploy the app on app store? There's any restrictions about that?


问:
Finding the last 4, 3, 2, 1 months consecutive order drops among clients based on drop variance
Here I have this query that finds out the drop percentage of a bunch of clients based on the orders they have received(i.e. It finds the percentage difference in orders by comparing the current month with the previous month). What I want to achieve here is to have a field where I can see the clients who had 4 months continuous drop, 3 months drop, 2 months drop, and 1 month drop.

I know, it can only be achieved by comparing the last 4 months using the lag function or sub queries. can you guys pls help me out on this one, would appreciate it very much

```<code>select
fd.customers2, fd.Month1, fd.year1, fd.variance, case when
 (fd.variance < -0.00001 and fd.year1 = '2022.0' and fd.Month1 = '1')
 then '1month drop' else fd.customers2 end as 1_most_host_drop

from

(SELECT
c.*,
sa.customers as customers2,
sum(sa.order) as orders,
date_part(mon, sa.date) as Month1,
date_part(year, sa.date) as year1,
(cast(orders - LAG(orders) OVER(Partition by customers2 ORDER BY
 year1, Month1) as NUMERIC(10,2))/NULLIF(LAG(orders)
OVER(partition by customers2 ORDER BY year1, Month1) * 1, 0)) AS variance
FROM stats sa join (select distinct
    d.id, d.customers
     from configer d
    ) c on sa.customers=c.customers
WHERE sa.date >= '2021-04-1'
GROUP BY Month1, sa.customers, c.id,  year1,
     c.customers)fd

</code>```

答:
In a spirit of friendliness: I think you are a little premature in posting this here as there are several issues with the syntax before even reaching the point where you can solve the problem:

You have at least two places with a comma immediately preceding the word FROM:

...AS variance, FROM stats_archive sa ...

...d.customers, FROM config d...

Recommend you don't use VARIANCE as an alias (it is a system function in PostgreSQL and so is likely also a system function name in Redshift)

Not super important, but there's no need for c.* - just select the columns you will use

DATE_PART requires a string as the first parameter DATE_PART('mon',current_date)

I might be wrong about this, but I suspect you cannot use column aliases in the partition by or order by of a window function. Put the originating expressions there instead:

... OVER (PARTITION BY customers2 ORDER BY DATE_PART('year',sa.date),DATE_PART('mon',sa.date))

LAG has three parameters. (1) The column you want to retrieve the value from, (2) the row offset, where a positive integer indicates how many rows prior to the current row you should retrieve a value from according to the partition and order context and (3) the value the function should return as a default (in case of the first row in the partition). As such, you don't need NULLIF. So, to get the row immediately prior to the current row, or return 0 in case the current row is the first row in the partition:

LAG(orders,1,0) OVER (PARTITION BY customers2 ORDER BY DATE_PART('year',sa.date),DATE_PART('mon',sa.date))

If you use 0 as a default in the calculation of what is currently aliased variance, you will almost certainly run into a div/0 error either now, or worse, when you least expect it in the future. You should protect against that with some CASE logic or better, provide a more appropriate default value or even better, calculate the LAG with the default 0, then filter out the 0 rows before doing the calculation.

You can't use column aliases in the GROUP BY. You must reference each field that is not participating in an aggregate in the group by, whether through direct mention (sa.date) or indirectly in an expression (DATE_PART('mon',sa.date))

Your date should be '2021-04-01'

All in all, without sample data, expected results using the posted sample data and without first removing syntax errors, it is a tall order to attempt to offer advice on the problem which is any more specific than:

Build the source of the calculation as a completely separate query first. Calculate the LAG in that source query. Only when you've run that source query and verified that the LAG is producing the correct result should you then wrap it as a sub-query or CTE (not sure if Redshift supports these, but presumably) at which point you can filter out the rows with a zero as the denominator (the first month of orders for each customer).

Good luck!

Body:
Here I have this query that finds out the drop percentage of a bunch of clients based on the orders they have received(i.e. It finds the percentage difference in orders by comparing the current month with the previous month). What I want to achieve here is to have a field where I can see the clients who had 4 months continuous drop, 3 months drop, 2 months drop, and 1 month drop.

I know, it can only be achieved by comparing the last 4 months using the lag function or sub queries. can you guys pls help me out on this one, would appreciate it very much

select
fd.customers2, fd.Month1, fd.year1, fd.variance, case when
 (fd.variance < -0.00001 and fd.year1 = '2022.0' and fd.Month1 = '1')
 then '1month drop' else fd.customers2 end as 1_most_host_drop

from

(SELECT
c.*,
sa.customers as customers2,
sum(sa.order) as orders,
date_part(mon, sa.date) as Month1,
date_part(year, sa.date) as year1,
(cast(orders - LAG(orders) OVER(Partition by customers2 ORDER BY
 year1, Month1) as NUMERIC(10,2))/NULLIF(LAG(orders)
OVER(partition by customers2 ORDER BY year1, Month1) * 1, 0)) AS variance
FROM stats sa join (select distinct
    d.id, d.customers
     from configer d
    ) c on sa.customers=c.customers
WHERE sa.date >= '2021-04-1'
GROUP BY Month1, sa.customers, c.id,  year1,
     c.customers)fd


问:
Multistep Sankey Graph from Dataframe
I have a dataframe with the following structure

INDEX
ANO
DISTRITO
CONCELHO
NCCO

0
2013.0
Aveiro
Albergaria-a-Velha
98

1
2013.0
Aveiro
Albergaria-a-velha
1

2
2013.0
Aveiro
Anadia
41

The full dataset can be found here

This data set ranges from 2013 to 2022 (ANO), and includes 18 different districts (DISTRITO), 278 different counties (CONCELHO) and the number of forest fires per CONCELHO (`NCCO´)

I'm able to produce a one step Sankey graph with this code, that I adapted from here

```<code>df = pd.read_csv('heatmap_full.csv') #generated by ingestor.py

all_nodes = df.ANO.values.tolist() + df.DISTRITO.values.tolist()
source_indices = [all_nodes.index(ANO) for ANO in df.ANO]
target_indices = [all_nodes.index(DISTRITO) for DISTRITO in df.DISTRITO]

colors = px.colors.qualitative.D3
node_colors = [np.random.choice(colors) for node in all_nodes]

fig = go.Figure(data=[go.Sankey(
    # Define nodes
    node = dict(
    pad = 20,
    thickness = 20,
    line = dict(color = "black", width = 1.0),
    label =  all_nodes,
    color =  node_colors,
    ),

    # Add links
    link = dict(
      source =  source_indices,
      target =  target_indices,
      value =  df.NCCO,
))])

fig.update_layout(title_text="FOREST FIRES IN PORTUGAL",
                height = 900,
                width=1200,
                font_size=18)
fig.show()
</code>```

My Problem/Question

I would like to have a step after DISTRITO for CONCELHO appearing in the Sankey graph, but I can't figure it out.

Can I add a new trace to the figure? Do I need to treat my original dataset in another way?

Any help would be much appreciated

Disclosure This is not meant for commercial use.

答:
reusing this answer to build a Sankey Diagram plotly sankey graph data formatting

build data frame of source and target values.  Note two data cleanups

there are duplicate CONCELHO due to capitalisation

there are same values in CONCELHO and DISTRITO.  modify so that no circular items in sankey

as per comments there really are too many nodes to represent in a sankey

```<code>import pandas as pd
import numpy as np
import plotly.graph_objects as go

df_in = pd.read_csv("https://raw.githubusercontent.com/vostpt/ICNF_DATA/main/heatmap_full.csv")

# too much data
df_in = df_in.sample(100)

# cleanup where same values exist in two columns
df_in["CONCELHO"] = np.where(df_in["DISTRITO"]==df_in["CONCELHO"], df_in["CONCELHO"]+"_c", df_in["CONCELHO"])
# deal with some duplicates names across source and target...
df_in["CONCELHO"] = df_in["CONCELHO"].str.capitalize()
df = df_in.groupby(["ANO","DISTRITO"], as_index=False)["NCCO"].sum().rename(columns={"ANO":"source","DISTRITO":"target","NCCO":"value"})
df["source"] = df["source"].astype(int).astype(str)

df = pd.concat([df, df_in.groupby(["DISTRITO","CONCELHO"], as_index=False)["NCCO"].sum().rename(columns={"DISTRITO":"source","CONCELHO":"target", "NCCO":"value"})])

nodes = np.unique(df[["source","target"]], axis=None)
nodes = pd.Series(index=nodes, data=range(len(nodes)))

go.Figure(
    go.Sankey(
        node={"label": nodes.index},
        link={
            "source": nodes.loc[df["source"]],
            "target": nodes.loc[df["target"]],
            "value": df["value"],
        },
    )
)

</code>```

Title: Multistep Sankey Graph from Dataframe

Body:
I have a dataframe with the following structure

INDEX
ANO
DISTRITO
CONCELHO
NCCO

0
2013.0
Aveiro
Albergaria-a-Velha
98

1
2013.0
Aveiro
Albergaria-a-velha
1

2
2013.0
Aveiro
Anadia
41

The full dataset can be found here

This data set ranges from 2013 to 2022 (ANO), and includes 18 different districts (DISTRITO), 278 different counties (CONCELHO) and the number of forest fires per CONCELHO (`NCCO´)

I'm able to produce a one step Sankey graph with this code, that I adapted from here

df = pd.read_csv('heatmap_full.csv') #generated by ingestor.py

all_nodes = df.ANO.values.tolist() + df.DISTRITO.values.tolist()
source_indices = [all_nodes.index(ANO) for ANO in df.ANO]
target_indices = [all_nodes.index(DISTRITO) for DISTRITO in df.DISTRITO]

colors = px.colors.qualitative.D3
node_colors = [np.random.choice(colors) for node in all_nodes]

fig = go.Figure(data=[go.Sankey(
    # Define nodes
    node = dict(
    pad = 20,
    thickness = 20,
    line = dict(color = "black", width = 1.0),
    label =  all_nodes,
    color =  node_colors,
    ),

    # Add links
    link = dict(
      source =  source_indices,
      target =  target_indices,
      value =  df.NCCO,
))])

fig.update_layout(title_text="FOREST FIRES IN PORTUGAL",
                height = 900,
                width=1200,
                font_size=18)
fig.show()

My Problem/Question

I would like to have a step after DISTRITO for CONCELHO appearing in the Sankey graph, but I can't figure it out.

Can I add a new trace to the figure? Do I need to treat my original dataset in another way?

Any help would be much appreciated

Disclosure This is not meant for commercial use.

Body:
reusing this answer to build a Sankey Diagram plotly sankey graph data formatting

build data frame of source and target values.  Note two data cleanups

there are duplicate CONCELHO due to capitalisation

there are same values in CONCELHO and DISTRITO.  modify so that no circular items in sankey

as per comments there really are too many nodes to represent in a sankey

import pandas as pd
import numpy as np
import plotly.graph_objects as go

df_in = pd.read_csv("https://raw.githubusercontent.com/vostpt/ICNF_DATA/main/heatmap_full.csv")

# too much data
df_in = df_in.sample(100)

# cleanup where same values exist in two columns
df_in["CONCELHO"] = np.where(df_in["DISTRITO"]==df_in["CONCELHO"], df_in["CONCELHO"]+"_c", df_in["CONCELHO"])
# deal with some duplicates names across source and target...
df_in["CONCELHO"] = df_in["CONCELHO"].str.capitalize()
df = df_in.groupby(["ANO","DISTRITO"], as_index=False)["NCCO"].sum().rename(columns={"ANO":"source","DISTRITO":"target","NCCO":"value"})
df["source"] = df["source"].astype(int).astype(str)

df = pd.concat([df, df_in.groupby(["DISTRITO","CONCELHO"], as_index=False)["NCCO"].sum().rename(columns={"DISTRITO":"source","CONCELHO":"target", "NCCO":"value"})])

nodes = np.unique(df[["source","target"]], axis=None)
nodes = pd.Series(index=nodes, data=range(len(nodes)))

go.Figure(
    go.Sankey(
        node={"label": nodes.index},
        link={
            "source": nodes.loc[df["source"]],
            "target": nodes.loc[df["target"]],
            "value": df["value"],
        },
    )
)


问:
jQuery addClass() not working in IE (8, 9 and probably the other one too)
Simple html:

```<code><div class="stuff-choice">
  <div class="item a">
    <label class="signup-checkbox">
      <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things">
      <strong>A</strong>
    </label>
  </div>
</div>
</code>```

Basically I detect when someone click on the checkbox with the css class .things, and then I updated the parent
 with a css class .selected.

The JS: (with a $(document).ready(function(){ ...

```<code>$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        $(item).addClass('selected');
    else
        $(item).removeClass('selected');
});
</code>```

This works like a charm under:
- Safari (mac & win)
- Firefox (mac & win)

But not under IE !?!?

I have no clue why...

Thanks,

Alex

答:
IE is notorious for freaking out if you don't declare your variables by prefixing them with "var".

So try this:

```<code>var item = $(this).closest("div");
</code>```

Body:
Simple html:

      <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things">
      A

Basically I detect when someone click on the checkbox with the css class .things, and then I updated the parent
 with a css class .selected.

The JS: (with a $(document).ready(function(){ ...

$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        $(item).addClass('selected');
    else
        $(item).removeClass('selected');
});

This works like a charm under:
- Safari (mac & win)
- Firefox (mac & win)

But not under IE !?!?

I have no clue why...

Thanks,

Alex

Body:
IE is notorious for freaking out if you don't declare your variables by prefixing them with "var".

So try this:

var item = $(this).closest("div");


问:
legend not appearing for ggplot geom_point color aesthetics
I am attempting to generate a legend for ggplot geom_point color aesthetics. I have tried various combinations and browsed through already asked questions but have not come up with a solution.

```<code>library (tidyverse)
library (ggplot2)

df <- structure(list(name = c("name1.1", "name1.2", "name1.3",
                        "name2.1", "name2.2", "name2.3", "name3.1", "name3.2", "name3.3"),
                     shape = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("shape1", "shape2", "shape3"), class = "factor"),
group_num = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("group_1", "group_2", "group_3"), class = "factor"),
x_value = c(0.9, 1, 1.1, 0.9, 1, 1.1, 0.9, 1, 1.1),
var1 = c(8762, 40679, 49441, 4544, 21064, 25608, 4218, 19615, 23833),
var2 = c(3.31, 3.02, 3.07, 3.23, 2.88, 2.94, 3.39, 3.17, 3.21),
var3 = c(28994.1, 122769.8, 151763.9, 14689.2, 60675.8, 75365, 14304.9, 62094, 76398.9),
var4 = c(230344, 944725, 1175069, 230344, 944725, 1175069, NA, NA, NA),
var5 = c(26.29, 23.22, 23.77, 50.69, 44.85, 45.89, NA, NA, NA)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))

df.plot <- ggplot(df, aes(x = x_value,
                          y = var2)) +
  geom_point(aes(
    size = var4,
    shape = shape,
    #color = shape)) +
    color = var5),
    alpha = 0.8) +
  scale_shape_manual(values = c("shape1" = 19, "shape2" = 15, "shape3" = 17), name = "Shapes", guide = guide_legend(override.aes = list(size = 3, fill = "black"))) +
  scale_size (range = c(2, 10), breaks = c(250000, 500000, 1000000), labels = c("250,000", "500,000", "1,000,000")) +
  #scale_fill_continuous(palette = viridis) +
  #scale_fill_gradient(low="orange2", high="darkblue", na.value ="gray30") +
  scale_color_viridis (breaks = c(10, 15, 21), labels = c("10", "15", "21"), name = "Var5") +
  coord_cartesian(xlim=c(0.7, 1.3), ylim=c(2.8, 3.4)) +
  scale_y_continuous(breaks = c(seq (from = 2.8, to = 3.4, by = 0.2))) +
  scale_x_continuous(breaks = c(seq (from = 0.7, to = 1.3, by = 0.1))) +
  geom_point(data = subset(df, is.na(var4)), aes(shape = shape, color = var5),  ####create similar shapes with gray color when var4 and/or var5 are NA
            size = 1.5, fill = "gray30") +
  theme_bw() +
  #guides(color = guide_legend(override.aes = list(size = 3), list(fill = scale_color_viridis ()))) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.title.x = element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x = element_blank()) +
  facet_wrap(~ group_num)
</code>```

Output I get:

If I try without scale_color_viridis (breaks = c(10, 15, 21), labels = c("10", "15", "21"), name = "Var5") I get the following plot.

What I would like to generate is the color legend in the viridis palette.

I have attempted using guide_legend(override.aes) and guides argument outside of aes with no luck

Any help would be appreciated

答:
The problem is that none of your specified breaks fall within the range of the data. There is therefore nothing to colour, and so no scale to show.

range(df$var5, na.rm = T)
#> [1] 23.22 50.69
```
<p>If you change to say:</p>
<pre class="lang-r prettyprint-override"><code>scale_colour_viridis_c(breaks = c(10, 15, 21, 30, 40, 50), limits = c(10, 50))
</code>```

You'll get

Body:
I am attempting to generate a legend for ggplot geom_point color aesthetics. I have tried various combinations and browsed through already asked questions but have not come up with a solution.

library (tidyverse)
library (ggplot2)

df <- structure(list(name = c("name1.1", "name1.2", "name1.3",
                        "name2.1", "name2.2", "name2.3", "name3.1", "name3.2", "name3.3"),
                     shape = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("shape1", "shape2", "shape3"), class = "factor"),
group_num = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("group_1", "group_2", "group_3"), class = "factor"),
x_value = c(0.9, 1, 1.1, 0.9, 1, 1.1, 0.9, 1, 1.1),
var1 = c(8762, 40679, 49441, 4544, 21064, 25608, 4218, 19615, 23833),
var2 = c(3.31, 3.02, 3.07, 3.23, 2.88, 2.94, 3.39, 3.17, 3.21),
var3 = c(28994.1, 122769.8, 151763.9, 14689.2, 60675.8, 75365, 14304.9, 62094, 76398.9),
var4 = c(230344, 944725, 1175069, 230344, 944725, 1175069, NA, NA, NA),
var5 = c(26.29, 23.22, 23.77, 50.69, 44.85, 45.89, NA, NA, NA)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))

df.plot <- ggplot(df, aes(x = x_value,
                          y = var2)) +
  geom_point(aes(
    size = var4,
    shape = shape,
    #color = shape)) +
    color = var5),
    alpha = 0.8) +
  scale_shape_manual(values = c("shape1" = 19, "shape2" = 15, "shape3" = 17), name = "Shapes", guide = guide_legend(override.aes = list(size = 3, fill = "black"))) +
  scale_size (range = c(2, 10), breaks = c(250000, 500000, 1000000), labels = c("250,000", "500,000", "1,000,000")) +
  #scale_fill_continuous(palette = viridis) +
  #scale_fill_gradient(low="orange2", high="darkblue", na.value ="gray30") +
  scale_color_viridis (breaks = c(10, 15, 21), labels = c("10", "15", "21"), name = "Var5") +
  coord_cartesian(xlim=c(0.7, 1.3), ylim=c(2.8, 3.4)) +
  scale_y_continuous(breaks = c(seq (from = 2.8, to = 3.4, by = 0.2))) +
  scale_x_continuous(breaks = c(seq (from = 0.7, to = 1.3, by = 0.1))) +
  geom_point(data = subset(df, is.na(var4)), aes(shape = shape, color = var5),  ####create similar shapes with gray color when var4 and/or var5 are NA
            size = 1.5, fill = "gray30") +
  theme_bw() +
  #guides(color = guide_legend(override.aes = list(size = 3), list(fill = scale_color_viridis ()))) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.title.x = element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x = element_blank()) +
  facet_wrap(~ group_num)

Output I get:

If I try without scale_color_viridis (breaks = c(10, 15, 21), labels = c("10", "15", "21"), name = "Var5") I get the following plot.

What I would like to generate is the color legend in the viridis palette.

I have attempted using guide_legend(override.aes) and guides argument outside of aes with no luck

Any help would be appreciated

Body:
The problem is that none of your specified breaks fall within the range of the data. There is therefore nothing to colour, and so no scale to show.

range(df$var5, na.rm = T)
#> [1] 23.22 50.69

If you change to say:

scale_colour_viridis_c(breaks = c(10, 15, 21, 30, 40, 50), limits = c(10, 50))

You'll get


问:
Insert commas into string number
I have this code, and I want to put commas.

I've seen many examples, but I dont now were put the code.

This is my AS3 code:

```<code>calccn.addEventListener(MouseEvent.CLICK,result1);

function result1(e:MouseEvent)
{

var vev: Number = (Number(vev.text));
var cn1: Number = (Number(3/100));

var result1f: Number = (Number(vev*cn1));
var round;
round=result1f.toFixed(0);
v3.text = String(round);
}
</code>```

Example
If the result give me 1528000,32
I want that the result is 1.528.000 or 1 528 000

答:
I didn't know (live and learn, eh), but there's actually a dedicated class: NumberFormatter.

If you want to do the thing on a regular basis, you might want a method to call:

```<code>// Implementation.
import flash.globalization.NumberFormatter;

// The default separator is comma.
function formattedNumber(value:Number, separator:String = ","):String
{
    var NF:NumberFormatter;

    NF = new NumberFormatter("en_US");

    // Enforce the use of the given separator.
    NF.groupingSeparator = separator;

    // Ignore the fraction part.
    NF.fractionalDigits = 0;

    return NF.formatNumber(value);
}

// Usage.

//Format the given number with spaces for separator.
trace(formattedNumber(1528000.32, " ")); // 1 528 000

//Format the given number with the default separator.
trace(formattedNumber(1528000.32)); // 1,528,000
</code>```

But if you want just a simple one-timer, and don't really care if it is commas or spaces as long as they present you may just condense in into a single expression:

```<code>calccn.addEventListener(MouseEvent.CLICK, result1);

function result1(e:MouseEvent):void
{
    // Declaring variables with the same names as
    // other entities is a generally bad idea.
    var input:Number = Number(vev.text);
    var cn1:Number = 3.0 / 100.0;

    // Keep in mind that I used int() here as
    // a simple tool to remove the fraction part.
    v3.text = (new NumberFormatter("en_US")).formatNumber(int(input * cn1));
}
</code>```

Title: Insert commas into string number

Body:
I have this code, and I want to put commas.

I've seen many examples, but I dont now were put the code.

This is my AS3 code:

calccn.addEventListener(MouseEvent.CLICK,result1);

function result1(e:MouseEvent)
{

var vev: Number = (Number(vev.text));
var cn1: Number = (Number(3/100));

var result1f: Number = (Number(vev*cn1));
var round;
round=result1f.toFixed(0);
v3.text = String(round);
}

Example
If the result give me 1528000,32
I want that the result is 1.528.000 or 1 528 000

Body:
I didn't know (live and learn, eh), but there's actually a dedicated class: NumberFormatter.

If you want to do the thing on a regular basis, you might want a method to call:

// Implementation.
import flash.globalization.NumberFormatter;

// The default separator is comma.
function formattedNumber(value:Number, separator:String = ","):String
{
    var NF:NumberFormatter;

    NF = new NumberFormatter("en_US");

    // Enforce the use of the given separator.
    NF.groupingSeparator = separator;

    // Ignore the fraction part.
    NF.fractionalDigits = 0;

    return NF.formatNumber(value);
}

// Usage.

//Format the given number with spaces for separator.
trace(formattedNumber(1528000.32, " ")); // 1 528 000

//Format the given number with the default separator.
trace(formattedNumber(1528000.32)); // 1,528,000

But if you want just a simple one-timer, and don't really care if it is commas or spaces as long as they present you may just condense in into a single expression:

calccn.addEventListener(MouseEvent.CLICK, result1);

function result1(e:MouseEvent):void
{
    // Declaring variables with the same names as
    // other entities is a generally bad idea.
    var input:Number = Number(vev.text);
    var cn1:Number = 3.0 / 100.0;

    // Keep in mind that I used int() here as
    // a simple tool to remove the fraction part.
    v3.text = (new NumberFormatter("en_US")).formatNumber(int(input * cn1));
}


问:
How to change 1d array to 2d array under certain conditions
Is there a way through python numpy operations to produce the following result?

Input 1d array :

```<code>[3, 0, 0, 2, 2, 1]
</code>```

Output 2d array :

```<code>3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1
</code>```

答: Assuming the input array always contains increasing values, you can use np.maximum(arr[None,:], arr[:, None]). This compute the maximum of arr[i] and arr[j] for all items at the location (i, j) of the output array thanks to Numpy broadcasting. If the input does not always contains increasing values, then the out needs to be better defined.

Body:
Is there a way through python numpy operations to produce the following result?

Input 1d array :

[3, 0, 0, 2, 2, 1]

Output 2d array :

3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1


问:
Cannot verify JWT - UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed
I have function that just send data to database (my posts). I use private and public keys to sign and verify tokens. I can send this token in header from front-end to back-end, but has problem with verifying it. Here is how this flow looks like:

Front-end

router.post(`/p-p`, async (req, res) => {
  try {
    const data = await api.post(`/post-post`, req.body, {
      headers: {
        Authorization: 'Bearer ' + req.body.token
      }
    })
    res.json(data.data)
  } catch (e) {
    res.status(e.response.status).json(e.response.data)
  }
})
```
<h2>Back-end</h2>
<pre class="lang-js prettyprint-override"><code>router.post(
  "/post-post",
  auth,
  wrapAsync(generalController.postPost)
)
</code>```

Middleware auth

const jwtService = require('./../services/jwtService')

module.exports = async(req, res, next) => {
  if (req.headers.authorization) {
    const user = await jwtService.getUser(req.headers.authorization.split(' ')[1])
    if (user) {
      next();
    } else {
      res.status(401).json({
        error: 'Unauthorized'
      })
    }
  } else {
    res.status(401).json({
      error: 'Unauthorized'
    })
  }
}
```
<h3>And JWT service</h3>
<pre class="lang-js prettyprint-override"><code>const jwt = require('jsonwebtoken');
const fs = require("fs");
const path = require("path");

const pathToKeys = path.resolve(__dirname, "../../keys");

module.exports = {
  sign(payload) {
    const cert = fs.readFileSync(`${pathToKeys}/private.pem`);
    return jwt.sign(
      payload,
      {
        key: cert,
        passphrase: process.env.JWT_PASSPHRASE
      },
      {
        algorithm: "RS256",
        expiresIn: "30m"
      }
    )
  },
  getUserPromise(token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, fs.readFileSync(`${pathToKeys}/public.pem`), (err, decoded) => {
        if(!err) {
          return resolve(decoded);
        } else {
          return reject(err);
        }
      })
    })
  },
  async getUser (token) {
    return await this.getUserPromise(token)
  }
}

</code>```

The problem starts after getUserPromise function. This function can get a token, but can't verify it and I have this problem:

UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed

Actually, I have no idea where problem is. I generated key pair, and sign function can sing and return token, which looks like this: 351e38a4bbc517b1c81e180479a221d404c724107988852c7768d813dd0510e6183306b1d837091b2cddaa07f2427b7a

So, what's the problem?

答:
I have found the solution of this problem and it feels shame. In JWT service pay attention to this string:

algorithm: "RS256"

As you can see I use RS256, but I generated certificates in other format, so, because of this I got that error.

So, if you use RSA certificates, pay attention to algorithm!

EDIT:

Here is how you can generate pair for RS256:

Private

```<code>openssl genrsa -out private.pem -aes256 4096
</code>```

Public from private

```<code>openssl rsa -in private.pem -pubout > public.pem
</code>```

Body:
I have function that just send data to database (my posts). I use private and public keys to sign and verify tokens. I can send this token in header from front-end to back-end, but has problem with verifying it. Here is how this flow looks like:

Front-end

router.post(`/p-p`, async (req, res) => {
  try {
    const data = await api.post(`/post-post`, req.body, {
      headers: {
        Authorization: 'Bearer ' + req.body.token
      }
    })
    res.json(data.data)
  } catch (e) {
    res.status(e.response.status).json(e.response.data)
  }
})

Back-end

router.post(
  "/post-post",
  auth,
  wrapAsync(generalController.postPost)
)

Middleware auth

const jwtService = require('./../services/jwtService')

module.exports = async(req, res, next) => {
  if (req.headers.authorization) {
    const user = await jwtService.getUser(req.headers.authorization.split(' ')[1])
    if (user) {
      next();
    } else {
      res.status(401).json({
        error: 'Unauthorized'
      })
    }
  } else {
    res.status(401).json({
      error: 'Unauthorized'
    })
  }
}

And JWT service

const jwt = require('jsonwebtoken');
const fs = require("fs");
const path = require("path");

const pathToKeys = path.resolve(__dirname, "../../keys");

module.exports = {
  sign(payload) {
    const cert = fs.readFileSync(`${pathToKeys}/private.pem`);
    return jwt.sign(
      payload,
      {
        key: cert,
        passphrase: process.env.JWT_PASSPHRASE
      },
      {
        algorithm: "RS256",
        expiresIn: "30m"
      }
    )
  },
  getUserPromise(token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, fs.readFileSync(`${pathToKeys}/public.pem`), (err, decoded) => {
        if(!err) {
          return resolve(decoded);
        } else {
          return reject(err);
        }
      })
    })
  },
  async getUser (token) {
    return await this.getUserPromise(token)
  }
}

The problem starts after getUserPromise function. This function can get a token, but can't verify it and I have this problem:

UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed

Actually, I have no idea where problem is. I generated key pair, and sign function can sing and return token, which looks like this: 351e38a4bbc517b1c81e180479a221d404c724107988852c7768d813dd0510e6183306b1d837091b2cddaa07f2427b7a

So, what's the problem?

Body:
I have found the solution of this problem and it feels shame. In JWT service pay attention to this string:

algorithm: "RS256"

As you can see I use RS256, but I generated certificates in other format, so, because of this I got that error.

So, if you use RSA certificates, pay attention to algorithm!

EDIT:

Here is how you can generate pair for RS256:

Private

openssl genrsa -out private.pem -aes256 4096

Public from private

openssl rsa -in private.pem -pubout > public.pem