问:
How to NSKeyedUnarchiver.unarchiveObject
I have a working code that works but deprecated:

This part is fine:

```<code> let archived = try? NSKeyedArchiver.archivedData(withRootObject: [defaultRecord] as NSArray, requiringSecureCoding: false)
</code>```

This is Deprecated:

```<code> let records = NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Record]
</code>```

'unarchiveObject(with:)' was deprecated in iOS 12.0: Use
  +unarchivedObjectOfClass:fromData:error: instead

Sounds simple as it is, I couldn't find a way to use the suggested method without getting errors in every combination I tried.

Any working example of this?

答:
If anyone is interested in the Objective C code, here it is:

```<code>// pointer to storage for error message
NSError *error = nil;

// read data from "dataPath" location
NSData *codedData = [[NSData alloc] initWithContentsOfFile:dataPath];

// create a set of root class (the array) and the data object class
NSSet<Class> *classes = [NSSet setWithObjects:NSArray.class, Record.class, nil];

// read using classes, not only single class
NSArray *data = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:codedData error:&error];
</code>```

Again, this is just a "translation" of the code @vadian correctly pointed out (and saved my day!).

Body:
I have a working code that works but deprecated:

This part is fine:

 let archived = try? NSKeyedArchiver.archivedData(withRootObject: [defaultRecord] as NSArray, requiringSecureCoding: false)

This is Deprecated:

 let records = NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Record]

'unarchiveObject(with:)' was deprecated in iOS 12.0: Use
  +unarchivedObjectOfClass:fromData:error: instead

Sounds simple as it is, I couldn't find a way to use the suggested method without getting errors in every combination I tried.

Any working example of this?

Body:
If anyone is interested in the Objective C code, here it is:

// pointer to storage for error message
NSError *error = nil;

// read data from "dataPath" location
NSData *codedData = [[NSData alloc] initWithContentsOfFile:dataPath];

// create a set of root class (the array) and the data object class
NSSet<Class> *classes = [NSSet setWithObjects:NSArray.class, Record.class, nil];

// read using classes, not only single class
NSArray *data = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:codedData error:&error];

Again, this is just a "translation" of the code @vadian correctly pointed out (and saved my day!).


来源: stackexchange

问:
Running stand-alone Rails script
I'm submitting a bug report to jsonapi-resources. Their issue template asks that I create a MCVE using their template. This looks like a self-contained script for a rails-based project. I've only ever run similar code as an actual rails project with separate files and using rails server. My question is, how do I run this self-contained script?

答:
I ran it with

```<code>ruby <filename>
</code>```

It seems to programmatically install gems.

ContentLicense: CC BY-SA 4.0

Title: Running stand-alone Rails script

Body:
I ran it with

ruby <filename>

It seems to programmatically install gems.


问:
Pandas not assuming dtypes when using read_sql?
I have a table in sql I'm looking to read into a pandas dataframe. I can read the table in but all column dtypes are being read in as objects. When I write the table to a csv then re-read it back in using read_csv, the correct data types are assumed. Obviously this intermediate step is inefficient and I just want to be able to read the data directly from sql with the correct data types assumed.

I have 650 columns in the df so obviously manually specifying the data types is not possible.

答:
No, doesn't really check on metadata.

Per pandas doc data types are inferred by default, while others enabled on demand (extra guidance is needed for date formats, for example).

Thus bare pd.read_sql is not fully robust, but may work on your specific data.

On my Postgres this looks like

```<code>column_name     postgres    pandas
patient_id  character varying   object
spell_id    character varying   object
spell_start_date    date    object
spell_start_time    time without time zone  object
spell_end_date  date    object
spell_end_time  time without time zone  object
</code>```

Body:
No, doesn't really check on metadata.

Per pandas doc data types are inferred by default, while others enabled on demand (extra guidance is needed for date formats, for example).

Thus bare pd.read_sql is not fully robust, but may work on your specific data.

On my Postgres this looks like

column_name     postgres    pandas
patient_id  character varying   object
spell_id    character varying   object
spell_start_date    date    object
spell_start_time    time without time zone  object
spell_end_date  date    object
spell_end_time  time without time zone  object


问:
Jenkins svn commit post-build
I'm trying to make a post-build commit in Jenkins CI when it's succeeded.

Is there a way to make this?

My problem is that when i build it generates some dll's in the workspace that i need to commit to the svn.

答:
It depends on the build technology (e.g. Ant, Maven, MSBuild or FianlBuilder) you use for building your source code. To check-in your build results into your svn, you should add some new steps at the end of your build scripts. This step will simply add your build results to svn. For example your step may contain:

svn commit --file build-output.1 build-output.2

It should be noted that some build technologies are equipped with build-in tasks or actions for working with svn.

ContentLicense: CC BY-SA 3.0

Title: Jenkins svn commit post-build


问:
React Native: Exception thrown while executing UI block
I'm building an iOS react-native app, and I'm currently using the react-native-swipe-card package to build "tinder" like swipe cards for my app. The app works fine however when I go to swipe a card left or right, and let it go while it's halfway off the screen I'm getting the following error:

ExceptionsManager.js:71 Exception thrown while executing UI block: -[NSNull floatValue]: unrecognized selector sent to instance 0x1075b5130

答:
I got the same error when passing an undefined to the defaultSource prop of an Image.

```<code><Image
    style={styles.imageStyle}
    source={someImageSource}
    defaultSource={imageFallback}
/>
</code>```

When imageFallback is undefined, I got this error.

Previous answers mention passing an undefined into Animated.Value.  Given that my experience is via a different component, this error probably means you're passing an undefined somewhere.

I found the culprit by commenting out varying lines of code to see what caused the error to appear.  Tedious but effective.

Body:
I got the same error when passing an undefined to the defaultSource prop of an Image.

<Image
    style={styles.imageStyle}
    source={someImageSource}
    defaultSource={imageFallback}
/>

When imageFallback is undefined, I got this error.

Previous answers mention passing an undefined into Animated.Value.  Given that my experience is via a different component, this error probably means you're passing an undefined somewhere.

I found the culprit by commenting out varying lines of code to see what caused the error to appear.  Tedious but effective.


问:
In Javascript remove keys from object not in an Array
Suppose I have a list of objects with many keys and I want to keep only certain keys from them.
This is how I am doing it.

The Problem with other good solutions on SO are that if a key is not present in the keys to keep it still adds a key, value where the value is undefined.

```<code>let data = [{
   'a': 1,
   'b': 2,
   'c': 3
 },
 {
   'a': 1,
   'c': 3,
   'd': 4
 }]

const keys_to_keep = ['a', 'b']

data = data.map((obj) => {
  Object.keys(obj).forEach(function(key) {
    if(!keys_to_keep.includes(key))
      delete obj[key]
  });
  return obj;
})
</code>```

Output :

```<code>[ { a: 1, b: 2 }, { a: 1} ]
</code>```

Is there a better way to get this done.
Any help is appreciated.

答:
You can use Object.fromEntries, after map and filter to keep only the relevant keys:

let data = [{'a': 1,'b': 2,'c': 3},{'a': 1,'c': 3,'d': 4}]
const keys_to_keep = ['a', 'b']

var result = data.map(obj =>
    Object.fromEntries(keys_to_keep.map(key =>
        obj.hasOwnProperty(key) && [key, obj[key]]
    ).filter(Boolean))
);

console.log(result);```

Body:
Suppose I have a list of objects with many keys and I want to keep only certain keys from them.
This is how I am doing it.

The Problem with other good solutions on SO are that if a key is not present in the keys to keep it still adds a key, value where the value is undefined.

let data = [{
   'a': 1,
   'b': 2,
   'c': 3
 },
 {
   'a': 1,
   'c': 3,
   'd': 4
 }]

const keys_to_keep = ['a', 'b']

data = data.map((obj) => {
  Object.keys(obj).forEach(function(key) {
    if(!keys_to_keep.includes(key))
      delete obj[key]
  });
  return obj;
})

Output :

[ { a: 1, b: 2 }, { a: 1} ]

Is there a better way to get this done.
Any help is appreciated.


问:
Why do I have this error 'video system not initialized'?
I already checked solutions but they dont work, I have python 3.10. Suddenly pygame isn't working. To use pygame.unit isnt not the solution, although I always use it. Reinstalling doesnt help either.</p>
```<code>import pygame
import sys
import random
import time

pygame.init()
pygame.display.init()

window = pygame.display.set_mode((1600, 900))
pygame.display.set_caption("Tower Defense")

# COLORS

clock = pygame.time.Clock()
while True:

    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.quit():
            sys.exit()

    pygame.display.flip()```
</code>```

答:
I found the solution, so easy,

what I did was (if event.type == pygame.quit():)

```<code>for event in pygame.event.get():
        if event.type == pygame.quit():
            sys.exit()
</code>```

but actually it is (if event.type == pygame.QUIT:)

```<code>for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
</code>```

Body:
I already checked solutions but they dont work, I have python 3.10. Suddenly pygame isn't working. To use pygame.unit isnt not the solution, although I always use it. Reinstalling doesnt help either.

import pygame
import sys
import random
import time

pygame.init()
pygame.display.init()

window = pygame.display.set_mode((1600, 900))
pygame.display.set_caption("Tower Defense")

# COLORS

clock = pygame.time.Clock()
while True:

    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.quit():
            sys.exit()

    pygame.display.flip()```

Body:
I found the solution, so easy,

what I did was (if event.type == pygame.quit():)

for event in pygame.event.get():
        if event.type == pygame.quit():
            sys.exit()

but actually it is (if event.type == pygame.QUIT:)

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()


问:
Can cython optimize python dictionary memory and lookup speed as well?
I have a class which primarily contains the three dicts:

```<code>class KB(object):

  def __init__(self):

    # key:str value: list of str
    linear_patterns = defaultdict(list)

    # key:str value: list of str
    nonlinear_patterns = defaultdict(list)

    # key: str value: dict
    pattern_meta_info = {}
    ...
    self.__initialize()

def __initialize(self):
    # the 3 dicts are populated
    ...
</code>```

The size of the 3 dicts are below:

```<code>linear_patterns: 100,000
non_linear_patterns: 900,000
pattern_meta_info: 700,000
</code>```

After the program is run and done, it takes about 15 seconds to release the memory. When I reduces the number of the dict sizes above by loading less data in initialization, the memory release is faster, so I judge it's due to these dict sizes that cause memory release slower. The total program takes about 8G memory. Also, after the dicts are built, all operations are lookup, no modifications.

Is there a way to use cython to optimize the 3 data structures above, especially in terms of memory usage? Is there a similar cython dictionary that can replaces the python dicts?

答:
It seems unlikely that a different dictionary or object type would change much. Destructor performance is dominated by the memory allocator. That will be roughly the same unless you switch to a different malloc implementation.

If this is only about object destruction at the end of your program, most languages (but not Python) would allow you to use call exit while keeping the KB object alive. The OS will release the memory much quicker when the process terminates. So why bother? Unfortunately that doesn't work with Python's sys.exit() since this merely raises an exception.

Everything else relies on changing the data structure or algorithm. Are your strings highly redundant? Maybe you can reuse string objects by interning them. Keep them in a shared set to use the same string in multiple places. A simple call to string = sys.intern(string) is enough. Unlike in earlier versions of Python, this will not keep the string object alive beyond its use so you don't run the risk of leaking memory in a long-running process.

You could also pool the strings in one large allocation. If access is relatively rare, you could change the class to use one large io.StringIO object for its contained strings and all dictionaries just deal with (offset, length) tuples into that buffer.

That still leaves many tuple and integer objects but those use specialized allocators that may be faster. Also, the length integer will come from the common pool of small integers and not allocate a new object.

A final thought: 8 GB of string data. You sure you don't want a small sqlite or dbm database? Could be a temporary file

Body:
I have a class which primarily contains the three dicts:

class KB(object):

  def __init__(self):

    # key:str value: list of str
    linear_patterns = defaultdict(list)

    # key:str value: list of str
    nonlinear_patterns = defaultdict(list)

    # key: str value: dict
    pattern_meta_info = {}
    ...
    self.__initialize()

def __initialize(self):
    # the 3 dicts are populated
    ...

The size of the 3 dicts are below:

linear_patterns: 100,000
non_linear_patterns: 900,000
pattern_meta_info: 700,000

After the program is run and done, it takes about 15 seconds to release the memory. When I reduces the number of the dict sizes above by loading less data in initialization, the memory release is faster, so I judge it's due to these dict sizes that cause memory release slower. The total program takes about 8G memory. Also, after the dicts are built, all operations are lookup, no modifications.

Is there a way to use cython to optimize the 3 data structures above, especially in terms of memory usage? Is there a similar cython dictionary that can replaces the python dicts?


问:
Filter multiple tables using query string with javascript
first I'm sorry if at some point I express myself badly, English is not my native language. I am developing an application in which the user sends 2 values through a form and in another page I use one of those data (string with comma separated options) to show a specific table and hide the others, and with the second data (Integer) I show one of the rows of that table.

What I already have:
I have the form and send the data through the Query String, I capture that data, I assign a variable to the integer and to the text string I separate it by commas and create an array.

URL Example: app.tables.example/?id=123&ops=option1%2c+option2

```<code>//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop)
});

//Assign integer to a variable
let num = param.id;

//Assign options to a variable
let op = param.ops;

//Separate string with commas
let opsplit = op.split(',');
</code>```

Up to here everything is perfect, I can print all the variables without any problem, now I need to compare the array with the id of each table, show the one that corresponds and hide the others. (The id of the tables is the same that user passes with the text string).

The tables look something like this:

```<code><div id="option1" class="table-1">
<table width="100%">
<thead>
<tr>
<th align="left">Option1</th>
<th align="left">Integer</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Number</td>
<td align="left">Info</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">textblock</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">textblock</td>
</tr>
</tbody>
</table>
</div>

//As you can see the id of each table corresponds to what the user chose
<div id="option2" class="table-1">
<table width="100%">
<thead>
<tr>
<th align="left">Option2</th>
<th align="left">Integer</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Number</td>
<td align="left">Info</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">textblock</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">textblock</td>
</tr>
</tbody>
</table>
</div>
</code>```

The problem:
I'm supposed to use the array elements in a "for" loop and compare them with the id of each table, then show that table and hide others, but I don't know exactly how to do it.

```<code>function myFunction() {
  var input, filter, table, tr, td, i, y, txtValue;
for (r = 0; r<opsplit.length; r++){
  input = opsplit[r];
  filter = function(x){
    return x.toUpperCase();
  };
  opsplit = opsplit.map(filter);
  }

//When I test this, it does not return any value,
//innerHTML error

  for(y = 0; y<opsplit.length; y++){
    table = document.getElementById(opsplit[y]).innerHTML;

//I use this section to test, it should show me the row,
//but since the previous loop failed, it does nothing.
// What I really need is to show the whole
// table where this data is located and hide the other tables.
  tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
}
myFunction();
</code>```

I am really stuck at the moment and would appreciate any help. What is the correct way to use the string array, and how can I hide the tables that the user does not need?

答:
Ok, thanks to those who took the time to write a comment, but I found the solution, I had to convert the form data to a string and an integer. Then I was able to compare that string to the classes id. I am writing the answer in case anyone finds it useful.

```<code>//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop)
});

//Assign number to a variable
let num = param.id;

//Convert to integer
let numint = parseInt(num);

//Assign options to a variable
let op = param.ops;

//Convert to String
let opstr = op.string();

//Separate string with commas
let opsplitstr = opstr.split(',');

//Assign class to a variable
tableclass = document.getElementsByClassName('table-1');

//Compare table class ids with string array
if (opsplitstr[0] == tableclass[0].id{
}
//We need a loop if we need compare all elements
</code>```

TLDR: The URL does not send information about the data type, so I had to read it and convert it according to my need.

Body:
first I'm sorry if at some point I express myself badly, English is not my native language. I am developing an application in which the user sends 2 values through a form and in another page I use one of those data (string with comma separated options) to show a specific table and hide the others, and with the second data (Integer) I show one of the rows of that table.

What I already have:
I have the form and send the data through the Query String, I capture that data, I assign a variable to the integer and to the text string I separate it by commas and create an array.

URL Example: app.tables.example/?id=123&ops=option1%2c+option2

//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop)
});

//Assign integer to a variable
let num = param.id;

//Assign options to a variable
let op = param.ops;

//Separate string with commas
let opsplit = op.split(',');

Up to here everything is perfect, I can print all the variables without any problem, now I need to compare the array with the id of each table, show the one that corresponds and hide the others. (The id of the tables is the same that user passes with the text string).

The tables look something like this:

Option1
Integer

Number
Info

1
textblock

2
textblock

//As you can see the id of each table corresponds to what the user chose

Option2
Integer

Number
Info

1
textblock

2
textblock

The problem:
I'm supposed to use the array elements in a "for" loop and compare them with the id of each table, then show that table and hide others, but I don't know exactly how to do it.

function myFunction() {
  var input, filter, table, tr, td, i, y, txtValue;
for (r = 0; r<opsplit.length; r++){
  input = opsplit[r];
  filter = function(x){
    return x.toUpperCase();
  };
  opsplit = opsplit.map(filter);
  }

//When I test this, it does not return any value,
//innerHTML error

  for(y = 0; y<opsplit.length; y++){
    table = document.getElementById(opsplit[y]).innerHTML;

//I use this section to test, it should show me the row,
//but since the previous loop failed, it does nothing.
// What I really need is to show the whole
// table where this data is located and hide the other tables.
  tr = table.getElementsByTagName("tr");

    for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
}
myFunction();

I am really stuck at the moment and would appreciate any help. What is the correct way to use the string array, and how can I hide the tables that the user does not need?

Body:
Ok, thanks to those who took the time to write a comment, but I found the solution, I had to convert the form data to a string and an integer. Then I was able to compare that string to the classes id. I am writing the answer in case anyone finds it useful.

//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop)
});

//Assign number to a variable
let num = param.id;

//Convert to integer
let numint = parseInt(num);

//Assign options to a variable
let op = param.ops;

//Convert to String
let opstr = op.string();

//Separate string with commas
let opsplitstr = opstr.split(',');

//Assign class to a variable
tableclass = document.getElementsByClassName('table-1');

//Compare table class ids with string array
if (opsplitstr[0] == tableclass[0].id{
}
//We need a loop if we need compare all elements

TLDR: The URL does not send information about the data type, so I had to read it and convert it according to my need.


问:
Understanding the Objective-C++ __block modifier
I need to do some maintenance on an Objective-C application (updating it to use a new API), and having never used the language before, I'm a bit confused.

I have an Objective-C++ class which implements an interface from my API, and this is used within a block, however whenever it is accessed within the block, it fails with an access violation error (EXC_BAD_ACCESS).

Furthrer investigation shows that none of the constructors for the object in question are being called. It is declared within the containing scope, and uses the __block modifier.

To try and understand this, I made a quick scratch application, and found the same thing happens there:

```<code>class Foo
{
public:
    Foo() : value(1) { printf("constructor"); }
    void addOne() { ++value; printf("value is %d", value); }
private:
    int value;
};

void Bar()
{
    Foo foo1; // prints "constructor"
    __block Foo foo2; // doesn't print anything

    foo1.addOne(); //prints "2"
    foo2.addOne(); //prints "1"
}
</code>```

Can anyone explain what is happening here? Why isn't my default constructor being called, and how can I access the object if it hasn't been properly constructed?

答:
As I understand it, your example there isn't using a block as such, but is declaring foo2 as to be used by a block.

This does funny things to the handling of foo2, which you can read more about here.

Hope that helps.

Body:
I need to do some maintenance on an Objective-C application (updating it to use a new API), and having never used the language before, I'm a bit confused.

I have an Objective-C++ class which implements an interface from my API, and this is used within a block, however whenever it is accessed within the block, it fails with an access violation error (EXC_BAD_ACCESS).

Furthrer investigation shows that none of the constructors for the object in question are being called. It is declared within the containing scope, and uses the __block modifier.

To try and understand this, I made a quick scratch application, and found the same thing happens there:

class Foo
{
public:
    Foo() : value(1) { printf("constructor"); }
    void addOne() { ++value; printf("value is %d", value); }
private:
    int value;
};

void Bar()
{
    Foo foo1; // prints "constructor"
    __block Foo foo2; // doesn't print anything

    foo1.addOne(); //prints "2"
    foo2.addOne(); //prints "1"
}

Can anyone explain what is happening here? Why isn't my default constructor being called, and how can I access the object if it hasn't been properly constructed?


问:
Restsharp 107 request fails with error "Request failed with status code Redirect"
I am in the process of updating some code to restharp 107. This specific code interfaces with a legacy website that does not have api's and essentially scrapes data from the user side.

The request I am making returns some data and redirects the user. in past versions of restsharp you would simply set FollowRedirects to false and you could read the response without redirecting. Upon upgrading to 107 it now throws an error and I can no longer read the response.

Here is the error

Exception Exception thrown: 'System.Net.Http.HttpRequestException' in
System.Private.CoreLib.dll ("Request failed with status code
Redirect")    System.Net.Http.HttpRequestException

Here is the code

```<code> var options = new RestClientOptions($"{data.BaseUrl}/Admin/EditEmployee.aspx")
            {
                ThrowOnAnyError = false,
                Timeout = 20000,
                CookieContainer = data.Cookies,
                UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0",
                FollowRedirects = false,
            };

            var client = new RestClient(options);
            var request = new RestRequest();
            request = request.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            request = request.AddHeader("Accept-Language", "en-US,en;q=0.5");
            request = request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request = request.AddHeader("Origin", $"{data.BaseUrl}");
            request = request.AddHeader("Connection", "keep-alive");
            request = request.AddHeader("Referer", $"{data.BaseUrl}/Admin/EditEmployee.aspx");
            request = request.AddHeader("Cookie", $"TBHFORMAUTH={tbhformauth.Value}; ASP.NET_SessionId={sessionId.Value}");
            request = request.AddHeader("Upgrade-Insecure-Requests", "1");
            request = request.AddHeader("Sec-Fetch-Dest", "document");
            request = request.AddHeader("Sec-Fetch-Mode", "navigate");
            request = request.AddHeader("Sec-Fetch-Site", "same-origin");
            request = request.AddHeader("Sec-Fetch-User", "?1");
            request = request.AddHeader("Pragma", "no-cache");
            request = request.AddHeader("Cache-Control", "no-cache");
            request = request.AddHeader("TE", "trailers");
            request = request.AddParameter("__EVENTTARGET", "");
            request = request.AddParameter("__EVENTARGUMENT", "");
            request = request.AddParameter("__VIEWSTATE", data.ViewState);
            request = request.AddParameter("__VIEWSTATEGENERATOR", "68248626");
            request = request.AddParameter("__EVENTVALIDATION", data.EventValidation);
            request = request.AddParameter("ctl00_ctl00_westZone_mainMenu_Collapsed", "false");
            request = request.AddParameter("ctl00_ctl00_westZone_mainMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_informationTablesMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_informationTablesMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_marketingMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_marketingMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_productsMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_productsMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_APIManagementMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_APIManagementMenu_SelIndex", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxFirstName", firstName);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxLastName", lastName);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxLogin", userName);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$ddlRoles", "0");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$ddlDepartment", "10");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$newPassword1", password);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$newPassword2", password);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$btnSave", "Save");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_PreventAutoCompleteUserName", "");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_PreventAutoCompletePassword", "");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_loginField", "");
            request = request.AddParameter("passwordField", "");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_gotoDashboard", "ctl00_ctl00_LoginBlock1_gotoDashboard");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$ddlCompany", "-1");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phoneExtension", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phone1", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phone2", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phoneExtension2", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxSignature", "");

            RestResponse response = await client.PostAsync(request);
</code>```

Is there something new that needs to be done in order to read the initial response in addition to setting redirects to false? Or is this a possible issue with the new RestSharp update?

答:
Looks like I figured it out shortly after...

By setting the method type in RestRequest and changing PostAsync to ExecuteAsync, it works as intended. Maybe someone could fill me in on why this behaves this way?

Body:
I am in the process of updating some code to restharp 107. This specific code interfaces with a legacy website that does not have api's and essentially scrapes data from the user side.

The request I am making returns some data and redirects the user. in past versions of restsharp you would simply set FollowRedirects to false and you could read the response without redirecting. Upon upgrading to 107 it now throws an error and I can no longer read the response.

Here is the error

Exception Exception thrown: 'System.Net.Http.HttpRequestException' in
System.Private.CoreLib.dll ("Request failed with status code
Redirect")    System.Net.Http.HttpRequestException

Here is the code

 var options = new RestClientOptions($"{data.BaseUrl}/Admin/EditEmployee.aspx")
            {
                ThrowOnAnyError = false,
                Timeout = 20000,
                CookieContainer = data.Cookies,
                UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0",
                FollowRedirects = false,
            };

            var client = new RestClient(options);
            var request = new RestRequest();
            request = request.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            request = request.AddHeader("Accept-Language", "en-US,en;q=0.5");
            request = request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request = request.AddHeader("Origin", $"{data.BaseUrl}");
            request = request.AddHeader("Connection", "keep-alive");
            request = request.AddHeader("Referer", $"{data.BaseUrl}/Admin/EditEmployee.aspx");
            request = request.AddHeader("Cookie", $"TBHFORMAUTH={tbhformauth.Value}; ASP.NET_SessionId={sessionId.Value}");
            request = request.AddHeader("Upgrade-Insecure-Requests", "1");
            request = request.AddHeader("Sec-Fetch-Dest", "document");
            request = request.AddHeader("Sec-Fetch-Mode", "navigate");
            request = request.AddHeader("Sec-Fetch-Site", "same-origin");
            request = request.AddHeader("Sec-Fetch-User", "?1");
            request = request.AddHeader("Pragma", "no-cache");
            request = request.AddHeader("Cache-Control", "no-cache");
            request = request.AddHeader("TE", "trailers");
            request = request.AddParameter("__EVENTTARGET", "");
            request = request.AddParameter("__EVENTARGUMENT", "");
            request = request.AddParameter("__VIEWSTATE", data.ViewState);
            request = request.AddParameter("__VIEWSTATEGENERATOR", "68248626");
            request = request.AddParameter("__EVENTVALIDATION", data.EventValidation);
            request = request.AddParameter("ctl00_ctl00_westZone_mainMenu_Collapsed", "false");
            request = request.AddParameter("ctl00_ctl00_westZone_mainMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_informationTablesMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_informationTablesMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_marketingMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_marketingMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_productsMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_productsMenu_SelIndex", "");
            request = request.AddParameter("ctl00_ctl00_westZone_APIManagementMenu_Collapsed", "true");
            request = request.AddParameter("ctl00_ctl00_westZone_APIManagementMenu_SelIndex", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxFirstName", firstName);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxLastName", lastName);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxLogin", userName);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$ddlRoles", "0");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$ddlDepartment", "10");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$newPassword1", password);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$newPassword2", password);
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$btnSave", "Save");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_PreventAutoCompleteUserName", "");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_PreventAutoCompletePassword", "");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_loginField", "");
            request = request.AddParameter("passwordField", "");
            request = request.AddParameter("ctl00_ctl00_LoginBlock1_gotoDashboard", "ctl00_ctl00_LoginBlock1_gotoDashboard");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$ddlCompany", "-1");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phoneExtension", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phone1", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phone2", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$phone$phoneExtension2", "");
            request = request.AddParameter("ctl00$ctl00$centerZone$ContentPlaceHolder1$tbxSignature", "");

            RestResponse response = await client.PostAsync(request);

Is there something new that needs to be done in order to read the initial response in addition to setting redirects to false? Or is this a possible issue with the new RestSharp update?


问:
Running Playwright .NET in Azure Function (Windows)
I am not able to run azure function which calls the playwright test after I publish it to the Azure cloud.

The exception is following

```<code>    Playwright Test or Playwright was just installed or updated.
║ ║ Please run the following command to download new browsers: ║ ║
║ ║ playwright install ║ ║
║ ║ <3 Playwright Team ║
</code>```

The issue is that I don't know how to run playwright install.

There is some remote build possibility, but the documentation does not contains details.

So I tried following

Copy chrome browser %USERPROFILE%\AppData\Local\ms-playwright\chrome-win into the project folder.

Attach chrome-win folder into the project.

Update .csproj so the chrome browser will be in output directory and output zip

```<code><ItemGroup>
  <Content Include="chrome-win\**">
     <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>
</code>```

Update executable path in playwright

```<code>await using var browser = await playwright.Chromium.LaunchAsync(new() { ExecutablePath = "chrome-win/chrome.exe"});
</code>```

Locally, it is working fine. Zip Deploy to Azure is also successful. But when the Azure function is triggered, it throws some unknown exception

```<code>Result: Failure Exception: System.AggregateException: One or more errors occurred. (spawn UNKNOWN =========================== logs =========================== <launching> chrome-win/chrome.exe --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --user-data-dir=C:\local\Temp\playwright_chromiumdev_profile-rw44Ph --remote-debugging-pipe --headless --hide-scrollbars --mute-audio --blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4 --no-sandbox --no-startup-window ============================================================) ---> Microsoft.Playwright.PlaywrightException: spawn UNKNOWN
</code>```

I just don't want to believe that I have to rewrite everything into JavaScript because of one line command in the terminal

Is it possible to switch to Linux OS with functions written in .NET and use browser installed via npm install playwright? The .NET is cross platform now, so it might work?

Has anyone managed to get this up and running?

答:
To run Playwright in a Windows-hosted Azure Function you have to make sure the browser is executed from the HOME_EXPANDED path instead of the default HOME environment variable path.

See Claire Novotny's blog for the details on the cause of this issue.

The HOME_EXPANDED environment variable points to a path like D:\DWASFiles\Sites\<FUNCTION_APP_NAME>\VirtualDirectory0\ which you can check in your Kudu environment which is hosted at https://<FUNCTION_APP_NAME>.scm.azurewebsites.net/Env.cshtml.

You will also need to make sure the .playwright directory is copied to the bin/ directory as described in Maurice Peters blog.

Manual browser download

You can either use the value of HOME_EXPANDED as a hardcoded path or retrieve the environment variable at runtime and pass it to the ExecutablePath property:

Environment.GetEnvironmentVariable("HOME_EXPANDED")

Automatic browser download

Instead you can also let Playwright download the browser binaries automatically for you.

Unfortunately there is no property which can be used but requires the PLAYWRIGHT_BROWSERS_PATH environment variable to be set to your preferred directory in the HOME_EXPANDED path location.

To download the binaries call the install command with any documented CLI arguments:

Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });

This will only download the binaries once so you can just call it before you create the Playwright browser instance.

Body:
I am not able to run azure function which calls the playwright test after I publish it to the Azure cloud.

The exception is following

    Playwright Test or Playwright was just installed or updated.
║ ║ Please run the following command to download new browsers: ║ ║
║ ║ playwright install ║ ║
║ ║ <3 Playwright Team ║

The issue is that I don't know how to run playwright install.

There is some remote build possibility, but the documentation does not contains details.

So I tried following

Copy chrome browser %USERPROFILE%\AppData\Local\ms-playwright\chrome-win into the project folder.

Attach chrome-win folder into the project.

Update .csproj so the chrome browser will be in output directory and output zip

<ItemGroup>
  <Content Include="chrome-win\**">
     <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>

Update executable path in playwright

await using var browser = await playwright.Chromium.LaunchAsync(new() { ExecutablePath = "chrome-win/chrome.exe"});

Locally, it is working fine. Zip Deploy to Azure is also successful. But when the Azure function is triggered, it throws some unknown exception

Result: Failure Exception: System.AggregateException: One or more errors occurred. (spawn UNKNOWN =========================== logs =========================== <launching> chrome-win/chrome.exe --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --user-data-dir=C:\local\Temp\playwright_chromiumdev_profile-rw44Ph --remote-debugging-pipe --headless --hide-scrollbars --mute-audio --blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4 --no-sandbox --no-startup-window ============================================================) ---> Microsoft.Playwright.PlaywrightException: spawn UNKNOWN

I just don't want to believe that I have to rewrite everything into JavaScript because of one line command in the terminal

Is it possible to switch to Linux OS with functions written in .NET and use browser installed via npm install playwright? The .NET is cross platform now, so it might work?

Has anyone managed to get this up and running?


问:
Any reason not to keep ViewModels in a separate, xaml-not-allowed assembly?
Just wondering if I am shooting myself in the foot if I put all my ViewModels into a separate assembly from the xaml of my silverlight application?  Do I lose any blendability?

It just seems more natural to me to have the ViewModels, which are (or should be) completely UI independent, in a separate assembly from the Xaml/views.

Do I lose anything in the area of blendability?

Im thinking it pretty much forces ease of unit testing, or am I missing something?

I found one post on this that agrees with my sentiment, but MVVMLights default project creation seems to put them together, so Im wondering if I am missing the point...

答:
It's not necessary, but it can be nice to do if you are striving for architectural purity. While VM library reuse is not common (as LBugnion said), it is quite common to retool your UI (or create a new one), in which case it can be very convenient to have a UI only assembly.

This also makes things simple if you are doing what i've heard talked about but never seen praticed in real life: having an independent UX designer work on the UI while the rest of the developers do the real code behind the scenes.

Following this practice will become more tiresome though if you have a larger project and are using something like Prism to manage modules - not only will you have several modules, each of those modules will have separate assemblies for UI and viewmodels/models, so you end up with many assemblies which can be difficult to manage or navigate.


问:
Spring API doesn't login and send infos (get&set) to React with JWT with same code
The title is self explanatory, I have this API made in Spring, and after JWT implementation I can login, but the gets doesn't work anymore.

But if I comment the the CorsConfigurationSource corsConfigurationSource() and the Lombok annotation @RequiredArgsConstructor in SecurityConfig, the login stop to work, but all the gets work beautifully.

I'll post the class SecurityConfig, AuthorizationFilter and the AuthenticationFilter respectively for you guys try to see whats going wrong.

```<code>import org.alterdata.shopback.app.security.AuthenticationFilter;
import org.alterdata.shopback.app.security.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import lombok.RequiredArgsConstructor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManagerBean());
        http.cors().and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/login").permitAll()
        .antMatchers("/cadastrar/**").hasAnyAuthority("ADMIN")
        .antMatchers("/cadastro/**").hasAnyAuthority("ADMIN")
        .anyRequest().authenticated();
        http.addFilter(authenticationFilter);
        http.addFilterBefore(new AuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager()throws Exception{
        return super.authenticationManager();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE","OPTIONS", "HEAD"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
            return source;
        }
}

</code>```
```<code>import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.auth0.jwt.exceptions.JWTVerificationException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.bytebuddy.implementation.bind.annotation.IgnoreForBinding.Verifier;

import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

@Slf4j
public class AuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if(request.getServletPath().equals("/login")) {
            filterChain.doFilter(request, response);
        }else {
            String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
            if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                String token = authorizationHeader.substring("Bearer ".length());
                Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
                JWTVerifier jwtVerifier = JWT.require(algorithm).build();
                DecodedJWT decodedJWT = jwtVerifier.verify(token);
                String user = decodedJWT.getSubject();
                String [] roles = decodedJWT.getClaim("roles").asArray(String.class);
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                Arrays.stream(roles).forEach(role ->{
                    authorities.add(new SimpleGrantedAuthority(role));
                });
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);

            }catch(Exception e){
                    log.error("erro ao realizar o login! {}", e.getMessage());
                    response.setHeader("erro", e.getMessage());
                    response.setStatus(401);
                    Map<String, String> error = new HashMap<>();
                    error.put("mensagem de erro", e.getMessage());
                    response.setContentType(APPLICATION_JSON_VALUE);
                    new ObjectMapper().writeValue(response.getOutputStream(), error);
                }
            }else {
                filterChain.doFilter(request, response);
            }
            }
        }
    }

</code>```
```<code>import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.bind.annotation.CrossOrigin;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@CrossOrigin(origins = {"*"})
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter (AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try{
            String nome = request.getParameter("nome");
            String senha = request.getParameter("senha");
            UsernamePasswordAuthenticationToken uspsToken = new UsernamePasswordAuthenticationToken(nome, senha);
            //response.setHeader("teste", String.valueOf(uspsToken));
            return authenticationManager.authenticate(uspsToken);
        }catch (Exception e){
            throw new  RuntimeException();
        }

    }

//  @Override
//  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
//          throws AuthenticationException {
//      try{
//  UserPasswordAuthRequest userPasswordAuthRequest = new ObjectMapper()
//              .readValue(request.getInputStream(), UserPasswordAuthRequest.class);
//
//          Authentication authentication = new UsernamePasswordAuthenticationToken(
//                  userPasswordAuthRequest.getNome(),
//                  userPasswordAuthRequest.getSenha()
//          );
//          return authenticationManager.authenticate(authentication);
//      }catch (IOException e){
//          throw new  RuntimeException();
//      }
//  }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
        User user = (User) authResult.getPrincipal();
        Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
        String tokenAcesso = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        String tokenRefresh = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        Map<String, String> tokens = new HashMap<>();
        tokens.put("tokenacesso", tokenAcesso);
        tokens.put("tokenrefresh", tokenRefresh);
        response.setContentType(APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getOutputStream(),tokens);
    }

}

</code>```

答:
I just fixed using this global cors</p>
```<code>@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
        }
</code>```

Body:
The title is self explanatory, I have this API made in Spring, and after JWT implementation I can login, but the gets doesn't work anymore.

But if I comment the the CorsConfigurationSource corsConfigurationSource() and the Lombok annotation @RequiredArgsConstructor in SecurityConfig, the login stop to work, but all the gets work beautifully.

I'll post the class SecurityConfig, AuthorizationFilter and the AuthenticationFilter respectively for you guys try to see whats going wrong.

import org.alterdata.shopback.app.security.AuthenticationFilter;
import org.alterdata.shopback.app.security.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import lombok.RequiredArgsConstructor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManagerBean());
        http.cors().and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/login").permitAll()
        .antMatchers("/cadastrar/**").hasAnyAuthority("ADMIN")
        .antMatchers("/cadastro/**").hasAnyAuthority("ADMIN")
        .anyRequest().authenticated();
        http.addFilter(authenticationFilter);
        http.addFilterBefore(new AuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager()throws Exception{
        return super.authenticationManager();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE","OPTIONS", "HEAD"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
            return source;
        }
}

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.auth0.jwt.exceptions.JWTVerificationException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.bytebuddy.implementation.bind.annotation.IgnoreForBinding.Verifier;

import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

@Slf4j
public class AuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if(request.getServletPath().equals("/login")) {
            filterChain.doFilter(request, response);
        }else {
            String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
            if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                String token = authorizationHeader.substring("Bearer ".length());
                Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
                JWTVerifier jwtVerifier = JWT.require(algorithm).build();
                DecodedJWT decodedJWT = jwtVerifier.verify(token);
                String user = decodedJWT.getSubject();
                String [] roles = decodedJWT.getClaim("roles").asArray(String.class);
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                Arrays.stream(roles).forEach(role ->{
                    authorities.add(new SimpleGrantedAuthority(role));
                });
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);

            }catch(Exception e){
                    log.error("erro ao realizar o login! {}", e.getMessage());
                    response.setHeader("erro", e.getMessage());
                    response.setStatus(401);
                    Map<String, String> error = new HashMap<>();
                    error.put("mensagem de erro", e.getMessage());
                    response.setContentType(APPLICATION_JSON_VALUE);
                    new ObjectMapper().writeValue(response.getOutputStream(), error);
                }
            }else {
                filterChain.doFilter(request, response);
            }
            }
        }
    }

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.bind.annotation.CrossOrigin;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@CrossOrigin(origins = {"*"})
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter (AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try{
            String nome = request.getParameter("nome");
            String senha = request.getParameter("senha");
            UsernamePasswordAuthenticationToken uspsToken = new UsernamePasswordAuthenticationToken(nome, senha);
            //response.setHeader("teste", String.valueOf(uspsToken));
            return authenticationManager.authenticate(uspsToken);
        }catch (Exception e){
            throw new  RuntimeException();
        }

    }

//  @Override
//  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
//          throws AuthenticationException {
//      try{
//  UserPasswordAuthRequest userPasswordAuthRequest = new ObjectMapper()
//              .readValue(request.getInputStream(), UserPasswordAuthRequest.class);
//
//          Authentication authentication = new UsernamePasswordAuthenticationToken(
//                  userPasswordAuthRequest.getNome(),
//                  userPasswordAuthRequest.getSenha()
//          );
//          return authenticationManager.authenticate(authentication);
//      }catch (IOException e){
//          throw new  RuntimeException();
//      }
//  }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
        User user = (User) authResult.getPrincipal();
        Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
        String tokenAcesso = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        String tokenRefresh = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        Map<String, String> tokens = new HashMap<>();
        tokens.put("tokenacesso", tokenAcesso);
        tokens.put("tokenrefresh", tokenRefresh);
        response.setContentType(APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getOutputStream(),tokens);
    }

}

Body:
I just fixed using this global cors

@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
        }


问:
create several lists with position
I have this super simple code to generate a list in python. I want to make several lists like this

```<code>0: [0, 2]
1: [2, 4]
2: [4, 6]
</code>```

it is possible . thanks

```<code>n = range(0,169,2)
num_list=list(n)
print (num_list)
</code>```

答:
```<code>>>> {n: [n*2, n*2+2] for n in range(3)}
{0: [0, 2], 1: [2, 4], 2: [4, 6]}
</code>```

Adjust the range(3) to produce however many lists you want.

If you want to be able to adjust the length of the individual lists:

```<code>>>> {n: list(range(n*2, n*2+4, 2)) for n in range(3)}
{0: [0, 2], 1: [2, 4], 2: [4, 6]}
</code>```

Title: create several lists with position

Body:
I have this super simple code to generate a list in python. I want to make several lists like this

0: [0, 2]
1: [2, 4]
2: [4, 6]

it is possible . thanks

n = range(0,169,2)
num_list=list(n)
print (num_list)

Body:
>>> {n: [n*2, n*2+2] for n in range(3)}
{0: [0, 2], 1: [2, 4], 2: [4, 6]}

Adjust the range(3) to produce however many lists you want.

If you want to be able to adjust the length of the individual lists:

>>> {n: list(range(n*2, n*2+4, 2)) for n in range(3)}
{0: [0, 2], 1: [2, 4], 2: [4, 6]}


问:
How to alternate order in flowchart?
How to alternate order in flowchart?

Imagine in the following flowchart,

"Want Fries" must be checked before checking "Want Drink". Now, I want to get an endpoint where, both of the conditions can be checked in any order. What should be the concise flowchart of it?

Update:

One possible diagram I made is the following but it looks not concise and also looks clumsy.

答: Please see the flowchart below:

Title: How to alternate order in flowchart?

Body: Please see the flowchart below:


问:
If I use a class more than once in an application, will it be compiled just once into the exe?
I'm evaluating the many possibilities for a trial protection system and came up with the following question:

If I use my "trial check" class more than once (scattered several times over the application), will it be compiled just once into the exe?

The reason why I'm asking is that if it's only compiled once into the exe, then patching this single class will invalidate all places where it is used.

If it's compiled just once, are there any viable alternatives to prevent this?

Thanks!

EDIT: I'm actually not trying to roll my own protection system, I'm looking at several existing solutions like OnGuard, mxProtector and TRegWare. It was while looking at the various solutions source-code, that I came up with this question.

答:
Yes, even if you create several instances of the class in different places there is only one copy of the methods (implementation), so if hacker patches the class all instances will be patched.

Do you really want to roll your own protection system? It ain't easy to come up with good system and there are several ready to use solutions around, if youre on budget then perhaps TurboPower OnGuard (which is open source now) will do.

BTW the general wisdom is that if they want to crack your app they will do it, no matter what, so one shouldn't waste too much resources on protection schemes. The only foolproof way is to exclude some of the (key) functionality from trial version, ie

```<code>{$IFDEF trial_version}
  ShowMessage('Sorry, this function is not available in trial version');
{$ELSE}
  // do the thing
{$END}
</code>```

but of course, if full version gets into wild then it will be cracked...

Body:
Yes, even if you create several instances of the class in different places there is only one copy of the methods (implementation), so if hacker patches the class all instances will be patched.

Do you really want to roll your own protection system? It ain't easy to come up with good system and there are several ready to use solutions around, if youre on budget then perhaps TurboPower OnGuard (which is open source now) will do.

BTW the general wisdom is that if they want to crack your app they will do it, no matter what, so one shouldn't waste too much resources on protection schemes. The only foolproof way is to exclude some of the (key) functionality from trial version, ie

{$IFDEF trial_version}
  ShowMessage('Sorry, this function is not available in trial version');
{$ELSE}
  // do the thing
{$END}

but of course, if full version gets into wild then it will be cracked...


问:
How to get the first string's from the right hand side
So I have this code that would get the first string's from the right hand side and stop whenever there is an integer but for some reason its not working with me.

Example input of fUnit is "CS_25x2u"

expected output of it after using unit is "u".

Real output is "undefined".

```<code>function buildUnit(fUnit){// wahts ginna be passed here is the gibirish unit and the output of this function is the clear unit
    fUnit = fUnit.toString;
    const regex = /[a-zA-Z]*$/;
    const unit = (x) => x.match(regex)[0];
    fUnit = unit(fUnit);

</code>```

If you need more info please let me know

Thank you

答:
Just in case.

function buildUnit(fUnit) {
  return fUnit.toString().match(/[A-z]*$/)[0];
}

console.log(buildUnit('CS_25x2u'));    // 'u'
console.log(buildUnit(''));            // ''
console.log(buildUnit(123));           // ''
console.log(buildUnit('aaa123'));      // ''
console.log(buildUnit('aaa 123 bbb')); // 'bbb'```

Body:
So I have this code that would get the first string's from the right hand side and stop whenever there is an integer but for some reason its not working with me.

Example input of fUnit is "CS_25x2u"

expected output of it after using unit is "u".

Real output is "undefined".

function buildUnit(fUnit){// wahts ginna be passed here is the gibirish unit and the output of this function is the clear unit
    fUnit = fUnit.toString;
    const regex = /[a-zA-Z]*$/;
    const unit = (x) => x.match(regex)[0];
    fUnit = unit(fUnit);

If you need more info please let me know

Thank you


问:
How to enable Performance logger in HCL Commerce 9.1
I want to generate trace for performance log but I don't find where enable the trace.

Checking this documentation page https://help.hcltechsw.com/commerce/9.1.0/admin/refs/rlsperflog_dup.html it's mention that we need to use the following string: com.ibm.commerce.performance=fine.

In Logging and Tracing settings we don't have this class path to enable finest log.

I tried to perform some run command in ts-app like:

```<code> run set-dynamic-trace-specification com.ibm.commerce.performance=fine
 run set-server-property com.ibm.commerce.performance fine
</code>```

Keep not seeing the trace file in: WAS_profiledir/logs/performanceTrace.json.

Some tip ?

Best Regards

答:
Document found:
https://help.hcltechsw.com/commerce/9.1.0/admin/tasks/tlslogging_txn.html

Basically, it's activated by PMT logs.

Body:
I want to generate trace for performance log but I don't find where enable the trace.

Checking this documentation page https://help.hcltechsw.com/commerce/9.1.0/admin/refs/rlsperflog_dup.html it's mention that we need to use the following string: com.ibm.commerce.performance=fine.

In Logging and Tracing settings we don't have this class path to enable finest log.

I tried to perform some run command in ts-app like:

 run set-dynamic-trace-specification com.ibm.commerce.performance=fine
 run set-server-property com.ibm.commerce.performance fine

Keep not seeing the trace file in: WAS_profiledir/logs/performanceTrace.json.

Some tip ?

Best Regards


问:
Docker: The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

```<code>It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.
</code>```

my docker

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]
</code>```

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <!--PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.14.0" /-->
    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>
</code>```

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:

答:
I believe I was able to resolve this by changing the final image to :</p>
```<code>FROM mcr.microsoft.com/dotnet/framework/sdk:4.8-windowsservercore-ltsc2019
</code>```

Body:
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.

my docker

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:

Body:
I believe I was able to resolve this by changing the final image to :

FROM mcr.microsoft.com/dotnet/framework/sdk:4.8-windowsservercore-ltsc2019


问:
What should be an transaction in Sentry for React application
The concept of transaction is explained briefly here in the Sentry documentation

And also here https://docs.sentry.io/product/performance/transaction-summary/

My question is: For a client side (React) application

Is It OK to make a transaction start at the time when a main/top-level component is created/rendered and end when it is destroyed, knowing that, the user may spend lots of time not interacting with the browser/component and no code is running? - Or that is not the designed purpose of transaction

答:
Hopefully it’s not too late, but might be interesting for others finding the question:

No, that’s not the designed purpose of a transaction. In another part of the Sentry documentation there’s a more detailed explanation with some examples (highlights are mine):

A trace represents the record of the entire operation you want to
measure or track - like page load, an instance of a user completing
some action in your application, or a cron job in your backend. When a
trace includes work in multiple services, such as those listed above,
it's called a distributed trace, because the trace is distributed
across those services.

Each trace consists of one or more tree-like structures called
transactions, the nodes of which are called spans. In most cases, each
transaction represents a single instance of a service being called,
and each span within that transaction represents that service
performing a single unit of work, whether calling a function within
that service or making a call to a different service.

In your client-side application you might be more interested in measuring e.g.  (in the case of React) the time it takes for a component being mounted until data is loaded and the first rendering is finished. Your transaction could be the rendering of the component, consisting of multiple spans (mounting, fetching data, rendering).

In theory you can do of course what you want to do and Sentry allows you to have these long running transactions, check e.g. the option maxTransactionDuration when setting up instrumentation (it’s 10min as default, so your example might work).

If you want to know how long people stay on one screen/in one widget/view and how they’re interacting with it, a classic tracking system where you can collect these events might be more what you want and need.


问:
System.out.printIn cannot find symbol
Whenever I try to compile this Java program in the command prompt I get an error about System.out.printIn saying that javac cannot find symbol. System.out.print works just fine but System.out.printIn refuses to cooperate. I've posted the program and the compiler message below. Thanks for the help.

```<code>    public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0) {

  if (beerNum == 1) {
    word = "bottle"; //singular, ONE bottle
}

System.out.printIn(beerNum + " " + word + "of beer on the wall");
System.out.printIn(beerNum + " " + word + "of beer.");
System.out.printIn("Take one down.");
System.out.printIn("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0) {
    System.out.printIn(beerNum + " " + word + " of beer on the wall");
}   else {
    System.out.printIn("No more bottles of beer on the wall");
} //end else
} //end while loop
} //end main method
} //end class
</code>```

```<code>C:\Users\Jesse\Desktop>javac BeerSong.java
BeerSong.java:12: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer on the wall");
              ^
BeerSong.java:13: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer.");
              ^
BeerSong.java:14: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Take one down.");
              ^
BeerSong.java:15: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Pass it around.");
              ^
BeerSong.java:19: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
        System.out.printIn(beerNum + " " + word + " of beer on the wall");
                  ^
BeerSong.java:21: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
            System.out.printIn("No more bottles of beer on the wall");
                      ^
6 errors
</code>```

答:
Typo:

printIn should be println

Title: System.out.printIn cannot find symbol

Body:
Whenever I try to compile this Java program in the command prompt I get an error about System.out.printIn saying that javac cannot find symbol. System.out.print works just fine but System.out.printIn refuses to cooperate. I've posted the program and the compiler message below. Thanks for the help.

    public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0) {

  if (beerNum == 1) {
    word = "bottle"; //singular, ONE bottle
}

System.out.printIn(beerNum + " " + word + "of beer on the wall");
System.out.printIn(beerNum + " " + word + "of beer.");
System.out.printIn("Take one down.");
System.out.printIn("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0) {
    System.out.printIn(beerNum + " " + word + " of beer on the wall");
}   else {
    System.out.printIn("No more bottles of beer on the wall");
} //end else
} //end while loop
} //end main method
} //end class

C:\Users\Jesse\Desktop>javac BeerSong.java
BeerSong.java:12: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer on the wall");
              ^
BeerSong.java:13: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer.");
              ^
BeerSong.java:14: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Take one down.");
              ^
BeerSong.java:15: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Pass it around.");
              ^
BeerSong.java:19: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
        System.out.printIn(beerNum + " " + word + " of beer on the wall");
                  ^
BeerSong.java:21: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
            System.out.printIn("No more bottles of beer on the wall");
                      ^
6 errors

Body:
Typo:

printIn should be println


问:
Laravel Trying to get property 'name' of non-object. Where problem?
I try to save in database information, which i received via API.

I try to save name, ratings and platforms in database, which comes in results array. Ratings received in array, platforms, how i understand received in double arrays.

I try to make something like this:

```<code>    $response = \Rawg::load('games')->setParams([
        'page' => 1,
        'page_size' => 40,
        'ordering' => '-rating',
    ])->get();

    foreach ($response as $result) {
        Games::insert(
            ['name' => $result->name, 'ratings' => $result->ratings->title, 'platforms' => $result->platforms->platform['name']]
        );
    }
</code>```

But i received error Trying to get property 'name' of non-object. Where can be my problem? I'll be glad to get help.

答:
This is an array not an object, and needs to change $response :

```<code>foreach ($response['results'] as $result) {
    Games::insert([
        'name' => $result['name'],
        'ratings' => $result['ratings'][0]['title'],
        'platforms' => $result['platforms'][0]['platform']['name']
    ]);
}
</code>```

Body:
I try to save in database information, which i received via API.

I try to save name, ratings and platforms in database, which comes in results array. Ratings received in array, platforms, how i understand received in double arrays.

I try to make something like this:

    $response = \Rawg::load('games')->setParams([
        'page' => 1,
        'page_size' => 40,
        'ordering' => '-rating',
    ])->get();

    foreach ($response as $result) {
        Games::insert(
            ['name' => $result->name, 'ratings' => $result->ratings->title, 'platforms' => $result->platforms->platform['name']]
        );
    }

But i received error Trying to get property 'name' of non-object. Where can be my problem? I'll be glad to get help.

Body:
This is an array not an object, and needs to change $response :

foreach ($response['results'] as $result) {
    Games::insert([
        'name' => $result['name'],
        'ratings' => $result['ratings'][0]['title'],
        'platforms' => $result['platforms'][0]['platform']['name']
    ]);
}


问:
NEAR Indexer and 2FA secured wallet transactions
In the Near, transactions signed by a 2FA-protected wallet are done in a special way (contract confirmation) and are not like regular transactions.
Signer and receiver id the same wallet.
Sample transaction:
https://explorer.near.org/transactions/9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY

How to work with them properly, where to find them in Indexer?
How do I get the data correctly, what contract and method the user signs?

答:
In addition to what @khorolets already mentioned, receipts table has originated_from_transaction_hash column which can help you to fetch all the receipts attributed to the transaction:

```<code>SELECT * FROM receipts WHERE originated_from_transaction_hash = '9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY';
</code>```
```<code>                  receipt_id                  |            included_in_block_hash            |            included_in_chunk_hash            | index_in_chunk | included_in_block_timestamp | predecessor_account_id | receiver_account_id | receipt_kind |       originated_from_transaction_hash
----------------------------------------------+----------------------------------------------+----------------------------------------------+----------------+-----------------------------+------------------------+---------------------+--------------+----------------------------------------------
 DiL4YA5iyKpsgkwdjdZkuiCatvKHmbVKPGAKpYJV1qS7 | AyX7umWGpR3RgQGnz4LAgTRnRGbF42krvAAjmXo4s4EV | 9VkhZdALu1EY6D2czKaKSV7qQZsLR6vxfAPXqBkgmAGg |              2 |         1644263681934508460 | system                 | shishkerin.near     | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3 | CyDT5XdZK8pKZM4VP559KxEXvUXTKaZbGVN3mVfoc5TX | FbfPdNLhYZEH3AncDiPa5qQZsaxCL8kfAtEaTV2geDi6 |              3 |         1644263680552610497 | system                 | shishkerin.near     | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU | CyDT5XdZK8pKZM4VP559KxEXvUXTKaZbGVN3mVfoc5TX | FbfPdNLhYZEH3AncDiPa5qQZsaxCL8kfAtEaTV2geDi6 |              2 |         1644263680552610497 | shishkerin.near        | gems.l2e.near       | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
 FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN | 5zvPFNeVytBNWfTzvmBaeCQtDrLuHfujKQqZ7qHhY4di | 4JngM4mhJnM9em6x8e7kJhyiSdPj1A9ZBzze9ZqJM8DP |              0 |         1644263679256841002 | shishkerin.near        | shishkerin.near     | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
(4 rows)
</code>```

Body:
In addition to what @khorolets already mentioned, receipts table has originated_from_transaction_hash column which can help you to fetch all the receipts attributed to the transaction:

SELECT * FROM receipts WHERE originated_from_transaction_hash = '9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY';

                  receipt_id                  |            included_in_block_hash            |            included_in_chunk_hash            | index_in_chunk | included_in_block_timestamp | predecessor_account_id | receiver_account_id | receipt_kind |       originated_from_transaction_hash
----------------------------------------------+----------------------------------------------+----------------------------------------------+----------------+-----------------------------+------------------------+---------------------+--------------+----------------------------------------------
 DiL4YA5iyKpsgkwdjdZkuiCatvKHmbVKPGAKpYJV1qS7 | AyX7umWGpR3RgQGnz4LAgTRnRGbF42krvAAjmXo4s4EV | 9VkhZdALu1EY6D2czKaKSV7qQZsLR6vxfAPXqBkgmAGg |              2 |         1644263681934508460 | system                 | shishkerin.near     | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3 | CyDT5XdZK8pKZM4VP559KxEXvUXTKaZbGVN3mVfoc5TX | FbfPdNLhYZEH3AncDiPa5qQZsaxCL8kfAtEaTV2geDi6 |              3 |         1644263680552610497 | system                 | shishkerin.near     | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU | CyDT5XdZK8pKZM4VP559KxEXvUXTKaZbGVN3mVfoc5TX | FbfPdNLhYZEH3AncDiPa5qQZsaxCL8kfAtEaTV2geDi6 |              2 |         1644263680552610497 | shishkerin.near        | gems.l2e.near       | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
 FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN | 5zvPFNeVytBNWfTzvmBaeCQtDrLuHfujKQqZ7qHhY4di | 4JngM4mhJnM9em6x8e7kJhyiSdPj1A9ZBzze9ZqJM8DP |              0 |         1644263679256841002 | shishkerin.near        | shishkerin.near     | ACTION       | 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY
(4 rows)