问:
Get form coordinates of a custom control
In Winforms, I have implemented a custom object with a draw method, which is called by Form_Paint. I now want to be able to get the coordinates of this object after being drawn to the form, for the sake of a Move procedure in the works. I have tried using object.Location, object.Left, and object.Top, but these just give 0,0. I then tried object.Size to test, and it gave me the size of the form.

How can I get the location of my runtime object on the form? Thanks

答:
Try using</p>

```<code>Point objLocation= cusObject.FindForm().PointToClient(
cusObject.Parent.PointToScreen(cusObject.Location));
</code>```

Body:
Try using

Point objLocation= cusObject.FindForm().PointToClient(
cusObject.Parent.PointToScreen(cusObject.Location));


来源: stackexchange

问:
Put specific cells on top of the tableView
How can i put specific cells to show on top of the tableView? , For example I have 10 cells which 5 of them have red color and other 5 have green and I want to show the top 5 ones with the green colors on top and the other 5 with red below them?

I didn't find any resources so I decided to get advise from the dear SO community.

Code:

```<code>extension MonitorimiViewController: UITableViewDelegate, UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return listOfVechicle.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "monitorimiCell", for: indexPath) as? MyCustomCell1 else {return UITableViewCell()}
    let currentVechicle = listOfVechicle[indexPath.row]

    cell.veturaOutlet.text = currentVechicle.Plate
    cell.shpejtsiaAktualeOutlet.text = currentVechicle.Speed!
    cell.perditsuarOutlet.text = "\(currentVechicle.LastCommunicationDate!.convertToDisplayForm())"
    cell.pasagjereOutlet.text = "\(currentVechicle.Passengers!) Person/a"
    cell.vozitesiOutlet.text = "\(currentVechicle.Driver!)"

    switch currentVechicle.Status {
    case 1:
        cell.colorsImageView.backgroundColor = .green
    case 2:
        cell.colorsImageView.backgroundColor = .red
    case 3:
        cell.colorsImageView.backgroundColor = .black
    case 4:
        cell.colorsImageView.backgroundColor = .orange
    default: break
    }

    return cell
</code>```

So from the currentVechicle.Status I need the case 1 to show on top then the rest.

My data structure coming from the API:

```<code>struct Vehicles: Codable {

var  IDVehicle: Int?
var  Title: String?
var  RegistrationDate: String?
var  ExpireDate: String?
var  Department: String?
var  Identification: String?
var  Speed: String?
var  Latitude: Double?
var  Longitude: Double?
var  Angle: Int?
var  Status: Int?
var  InputValue: Int?
var  Plate: String?
var  LastCommunicationDate: String?
var  Passengers: Int?
var  Driver: String?

}
</code>```

data coming from api in form of json:

```<code>{
 "IDVehicle": 0,
 "Title": "Truck",
 "RegistrationDate": "2017-10-26T17:23:20.677",
 "ExpireDate": "2022-10-28T00:00:00",
 "Department": "Transport",
 "Identification": "863286023094252",
 "Speed": "0",
 "Latitude": 80.8769778,
 "Longitude": 70.9877813,
 "Angle": 265,
 "Status": 1,          // I want the cells sorted based on the Status, If status 1 show cells with 1 on top etc.
 "InputValue": 0,
 "Plate": "09 09 KO",
 "LastCommunicationDate": "2021-10-28T13:53:23",
 "Passengers": 0,
 "Driver": "Empty"
}
</code>```

答:
struct Vehicles: Codable {
    var Title: String
    var Status: Int // I'm assuming this will never be null in your JSON. Remove all your question marks except for keys that might not have values.
}

var data = [Vehicles(Title: "Honda", Status: 2), Vehicles(Title: "Mazda", Status: 1), Vehicles(Title: "Subaru", Status: 1)]
// You surely keep your data in an Array like this, right? You will need it formatted like this to be able to index it using `IndexPath.row`

data.sort{$0.Status < $1.Status}
// Call this when you're done populating your data.
```

The key thing here is in the .map {} part. $0 means THIS element in the list, much like how name in for name in names {} would mean the current name in the list. and $1 means the next element in the list. When using .sort(), you're comparing one value to the next value repeatedly. In this case, we using the < sign because we want the higher values to be further down the list.

ContentLicense: CC BY-SA 4.0

Body:
How can i put specific cells to show on top of the tableView? , For example I have 10 cells which 5 of them have red color and other 5 have green and I want to show the top 5 ones with the green colors on top and the other 5 with red below them?

I didn't find any resources so I decided to get advise from the dear SO community.

Code:

extension MonitorimiViewController: UITableViewDelegate, UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return listOfVechicle.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "monitorimiCell", for: indexPath) as? MyCustomCell1 else {return UITableViewCell()}
    let currentVechicle = listOfVechicle[indexPath.row]

    cell.veturaOutlet.text = currentVechicle.Plate
    cell.shpejtsiaAktualeOutlet.text = currentVechicle.Speed!
    cell.perditsuarOutlet.text = "\(currentVechicle.LastCommunicationDate!.convertToDisplayForm())"
    cell.pasagjereOutlet.text = "\(currentVechicle.Passengers!) Person/a"
    cell.vozitesiOutlet.text = "\(currentVechicle.Driver!)"

    switch currentVechicle.Status {
    case 1:
        cell.colorsImageView.backgroundColor = .green
    case 2:
        cell.colorsImageView.backgroundColor = .red
    case 3:
        cell.colorsImageView.backgroundColor = .black
    case 4:
        cell.colorsImageView.backgroundColor = .orange
    default: break
    }

    return cell

So from the currentVechicle.Status I need the case 1 to show on top then the rest.

My data structure coming from the API:

struct Vehicles: Codable {

var  IDVehicle: Int?
var  Title: String?
var  RegistrationDate: String?
var  ExpireDate: String?
var  Department: String?
var  Identification: String?
var  Speed: String?
var  Latitude: Double?
var  Longitude: Double?
var  Angle: Int?
var  Status: Int?
var  InputValue: Int?
var  Plate: String?
var  LastCommunicationDate: String?
var  Passengers: Int?
var  Driver: String?

}

data coming from api in form of json:

{
 "IDVehicle": 0,
 "Title": "Truck",
 "RegistrationDate": "2017-10-26T17:23:20.677",
 "ExpireDate": "2022-10-28T00:00:00",
 "Department": "Transport",
 "Identification": "863286023094252",
 "Speed": "0",
 "Latitude": 80.8769778,
 "Longitude": 70.9877813,
 "Angle": 265,
 "Status": 1,          // I want the cells sorted based on the Status, If status 1 show cells with 1 on top etc.
 "InputValue": 0,
 "Plate": "09 09 KO",
 "LastCommunicationDate": "2021-10-28T13:53:23",
 "Passengers": 0,
 "Driver": "Empty"
}

Body:
struct Vehicles: Codable {
    var Title: String
    var Status: Int // I'm assuming this will never be null in your JSON. Remove all your question marks except for keys that might not have values.
}

var data = [Vehicles(Title: "Honda", Status: 2), Vehicles(Title: "Mazda", Status: 1), Vehicles(Title: "Subaru", Status: 1)]
// You surely keep your data in an Array like this, right? You will need it formatted like this to be able to index it using `IndexPath.row`

data.sort{$0.Status < $1.Status}
// Call this when you're done populating your data.

The key thing here is in the .map {} part. $0 means THIS element in the list, much like how name in for name in names {} would mean the current name in the list. and $1 means the next element in the list. When using .sort(), you're comparing one value to the next value repeatedly. In this case, we using the < sign because we want the higher values to be further down the list.


问:
Tradingview test the strategy with the given start date
I want to test a strategy. However, no matter how I drag the chart, the start date of the test cannot earlier than 2020 Sep 01. I want to test it use earlier data. Is there a way to select the date range for Strategy Tester?

My scripts:

```<code>//@version=3
strategy("My Strategy", overlay=true)

longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

plotshape(longCondition, color = blue)

shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

plotshape(shortCondition, color = red)
</code>```

I am using 15 minutes chart with ES as the trading target.

Is there a statement that can let the Backtesting be done with more data?

Thanks

答:
You can write the condition in script</p>
```<code>//@version=4
date = input(title="Date", type=input.time, defval=timestamp("2020-09-01T00:00+03:00"))
if (time_close >= date)
</code>```

Body:
I want to test a strategy. However, no matter how I drag the chart, the start date of the test cannot earlier than 2020 Sep 01. I want to test it use earlier data. Is there a way to select the date range for Strategy Tester?

My scripts:

//@version=3
strategy("My Strategy", overlay=true)

longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

plotshape(longCondition, color = blue)

shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

plotshape(shortCondition, color = red)

I am using 15 minutes chart with ES as the trading target.

Is there a statement that can let the Backtesting be done with more data?

Thanks

Body:
You can write the condition in script

//@version=4
date = input(title="Date", type=input.time, defval=timestamp("2020-09-01T00:00+03:00"))
if (time_close >= date)


问:
howt to use mBagOfTags in ViewModel android?
I have object that implement Closeable interface and want to close() method called when my ViewModel is clear. I know to implement onCleared method of ViewModel but I want to use mBagOfTags in ViewModel. mBagOfTags handle closeable object (call close method in clear method) and don't want create new map object in ViewModel . How can I use mBagOfTags of ViewModel ??

mBagOfTags and their member functions  in ViewModel are package Private access modifer.

this is the ViewModel class that android team is developed.

```<code>package androidx.lifecycle;

public abstract class ViewModel {
// Can't use ConcurrentHashMap, because it can lose values on old apis (see b/37042460)
@Nullable
private final Map<String, Object> mBagOfTags = new HashMap<>();
private volatile boolean mCleared = false;

/**
 * This method will be called when this ViewModel is no longer used and will be destroyed.
 * <p>
 * It is useful when ViewModel observes some data and you need to clear this subscription to
 * prevent a leak of this ViewModel.
 */
@SuppressWarnings("WeakerAccess")
protected void onCleared() {
}

@MainThread
final void clear() {
    mCleared = true;
    // Since clear() is final, this method is still called on mock objects
    // and in those cases, mBagOfTags is null. It'll always be empty though
    // because setTagIfAbsent and getTag are not final so we can skip
    // clearing it
    if (mBagOfTags != null) {
        synchronized (mBagOfTags) {
            for (Object value : mBagOfTags.values()) {
                // see comment for the similar call in setTagIfAbsent
                closeWithRuntimeException(value);
            }
        }
    }
    onCleared();
}

/**
 * Sets a tag associated with this viewmodel and a key.
 * If the given {@code newValue} is {@link Closeable},
 * it will be closed once {@link #clear()}.
 * <p>
 * If a value was already set for the given key, this call does nothing and
 * returns currently associated value, the given {@code newValue} would be ignored
 * <p>
 * If the ViewModel was already cleared then close() would be called on the returned object if
 * it implements {@link Closeable}. The same object may receive multiple close calls, so method
 * should be idempotent.
 */
@SuppressWarnings("unchecked")
<T> T setTagIfAbsent(String key, T newValue) {
    T previous;
    synchronized (mBagOfTags) {
        previous = (T) mBagOfTags.get(key);
        if (previous == null) {
            mBagOfTags.put(key, newValue);
        }
    }
    T result = previous == null ? newValue : previous;
    if (mCleared) {
        // It is possible that we'll call close() multiple times on the same object, but
        // Closeable interface requires close method to be idempotent:
        // "if the stream is already closed then invoking this method has no effect." (c)
        closeWithRuntimeException(result);
    }
    return result;
}

/**
 * Returns the tag associated with this viewmodel and the specified key.
 */
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
<T> T getTag(String key) {
    if (mBagOfTags == null) {
        return null;
    }
    synchronized (mBagOfTags) {
        return (T) mBagOfTags.get(key);
    }
}

private static void closeWithRuntimeException(Object obj) {
    if (obj instanceof Closeable) {
        try {
            ((Closeable) obj).close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
}
</code>```

my ViewModel is in another package.

答: You can set package of your file same as ViewModel package. Write first line of a file: "package androidx.lifecycle"</p>

Body:
I have object that implement Closeable interface and want to close() method called when my ViewModel is clear. I know to implement onCleared method of ViewModel but I want to use mBagOfTags in ViewModel. mBagOfTags handle closeable object (call close method in clear method) and don't want create new map object in ViewModel . How can I use mBagOfTags of ViewModel ??

mBagOfTags and their member functions  in ViewModel are package Private access modifer.

this is the ViewModel class that android team is developed.

package androidx.lifecycle;

public abstract class ViewModel {
// Can't use ConcurrentHashMap, because it can lose values on old apis (see b/37042460)
@Nullable
private final Map<String, Object> mBagOfTags = new HashMap<>();
private volatile boolean mCleared = false;

/**
 * This method will be called when this ViewModel is no longer used and will be destroyed.
 *

 * It is useful when ViewModel observes some data and you need to clear this subscription to
 * prevent a leak of this ViewModel.
 */
@SuppressWarnings("WeakerAccess")
protected void onCleared() {
}

@MainThread
final void clear() {
    mCleared = true;
    // Since clear() is final, this method is still called on mock objects
    // and in those cases, mBagOfTags is null. It'll always be empty though
    // because setTagIfAbsent and getTag are not final so we can skip
    // clearing it
    if (mBagOfTags != null) {
        synchronized (mBagOfTags) {
            for (Object value : mBagOfTags.values()) {
                // see comment for the similar call in setTagIfAbsent
                closeWithRuntimeException(value);
            }
        }
    }
    onCleared();
}

/**
 * Sets a tag associated with this viewmodel and a key.
 * If the given {@code newValue} is {@link Closeable},
 * it will be closed once {@link #clear()}.
 *

 * If a value was already set for the given key, this call does nothing and
 * returns currently associated value, the given {@code newValue} would be ignored
 *

 * If the ViewModel was already cleared then close() would be called on the returned object if
 * it implements {@link Closeable}. The same object may receive multiple close calls, so method
 * should be idempotent.
 */
@SuppressWarnings("unchecked")
<T> T setTagIfAbsent(String key, T newValue) {
    T previous;
    synchronized (mBagOfTags) {
        previous = (T) mBagOfTags.get(key);
        if (previous == null) {
            mBagOfTags.put(key, newValue);
        }
    }
    T result = previous == null ? newValue : previous;
    if (mCleared) {
        // It is possible that we'll call close() multiple times on the same object, but
        // Closeable interface requires close method to be idempotent:
        // "if the stream is already closed then invoking this method has no effect." (c)
        closeWithRuntimeException(result);
    }
    return result;
}

/**
 * Returns the tag associated with this viewmodel and the specified key.
 */
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
<T> T getTag(String key) {
    if (mBagOfTags == null) {
        return null;
    }
    synchronized (mBagOfTags) {
        return (T) mBagOfTags.get(key);
    }
}

private static void closeWithRuntimeException(Object obj) {
    if (obj instanceof Closeable) {
        try {
            ((Closeable) obj).close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
}

my ViewModel is in another package.


问:
reset a vuetify stepper
I'm looking for a function who can resetting my stepper made with vuetify.

the e1 is set as 0 but if I make a function who reset this value to 0, it doesn't work and the stepper set as the same screen.

答:
A simpler approach at resetting your stepper is by using the key prop assigning to it a value and then in the function increasing this value. Something like this:

<template>
  <v-stepper
    :key="stepperKey"
    v-model="e1"
  >
    ...
  </v-stepper>
</template>

```

The key prop or attribute is a build in Vue.js feature. Even if you don't see it it's been used on the back. Changing the key will trigger a re render.

If you have doubt about the key attribute/prop here is a nice article about it

Title: reset a vuetify stepper

Body:
A simpler approach at resetting your stepper is by using the key prop assigning to it a value and then in the function increasing this value. Something like this:

<template>
  <v-stepper
    :key="stepperKey"
    v-model="e1"
  >
    ...
  </v-stepper>
</template>
<script>
  export default {
    data () {
      return {
        e1: 1,
        stepperKey: 0
      }
    },
    methods: {
      increaseKey () { this.stepperKey++ }
    }
  }
</script>

The key prop or attribute is a build in Vue.js feature. Even if you don't see it it's been used on the back. Changing the key will trigger a re render.

If you have doubt about the key attribute/prop here is a nice article about it


问:
Flaky cypress test with Svelte: Button is sometimes clicked, sometimes not
I am testing my SvelteKit site with Cypress. I sometimes experience flaky tests, similar to what has been described here: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/. In short, Cypress sometimes finds and clicks a button before the event listeners are attached - as a result, the click goes nowhere. The proposed solution is to simply re-try clicking until the appropriate listeners have been attached. That works in my case as well. However, though I do understand why this can be an issue in the example given in the blog post (it's a large calendar modal), I find it hard to justify that this issue arises when using a simple Svelte button.

Here is a simple example of a button that reveals some content when clicked:

<button
  on:click={() => {
    console.log('clicked');
    hide = false;
  }}>
  Show
</button>

Content

```
<p>The corresponding test sometimes passes, sometimes fails:</p>
<pre class="lang-js prettyprint-override"><code>it('reveals content on click', () => {
  cy.contains('Show').click();
  cy.contains('Content').should('be.visible');
});
</code>```

Again, I am aware this can be fixed by re-trying to click the button. And if this is what it takes to make Cypress work with Svelte/SvelteKit, then that's fine with me. But I am wondering: Why would this even be an issue?

Minimal reproduction repo: https://github.com/sophiamersmann/test-svelte-kit-cypress

答:
I think the problem lies with Vite, which uses ES modules to load the page and it's components.

Adding an intercept before the cy.visit() seems to give consistent results.
(Note the URL to intercept may vary, you can get it from the last entry in devtools Network).

beforeEach(() => {
  cy.intercept('index.svelte?svelte&type=style&lang.css').as('svelte')
  cy.visit('/');
  cy.wait('@svelte')
});
```
<p>Using cypress-grep to burn-test</p>
<pre class="lang-js prettyprint-override"><code>npx cypress run --env burn=100
</code>```

With intercept

Without intercept

Why is it not hydration?

If you create an equivalent Svelte app with hydratable set to true, it will pass the burn test - IMO because it uses rollup instead of vite to deliver the app to the browser.

Body:
I am testing my SvelteKit site with Cypress. I sometimes experience flaky tests, similar to what has been described here: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/. In short, Cypress sometimes finds and clicks a button before the event listeners are attached - as a result, the click goes nowhere. The proposed solution is to simply re-try clicking until the appropriate listeners have been attached. That works in my case as well. However, though I do understand why this can be an issue in the example given in the blog post (it's a large calendar modal), I find it hard to justify that this issue arises when using a simple Svelte button.

Here is a simple example of a button that reveals some content when clicked:

<button
  on:click={() => {
    console.log('clicked');
    hide = false;
  }}>
  Show
</button>

Content

The corresponding test sometimes passes, sometimes fails:

it('reveals content on click', () => {
  cy.contains('Show').click();
  cy.contains('Content').should('be.visible');
});

Again, I am aware this can be fixed by re-trying to click the button. And if this is what it takes to make Cypress work with Svelte/SvelteKit, then that's fine with me. But I am wondering: Why would this even be an issue?

Minimal reproduction repo: https://github.com/sophiamersmann/test-svelte-kit-cypress

Body:
I think the problem lies with Vite, which uses ES modules to load the page and it's components.

Adding an intercept before the cy.visit() seems to give consistent results.
(Note the URL to intercept may vary, you can get it from the last entry in devtools Network).

beforeEach(() => {
  cy.intercept('index.svelte?svelte&type=style&lang.css').as('svelte')
  cy.visit('/');
  cy.wait('@svelte')
});

Using cypress-grep to burn-test

npx cypress run --env burn=100

With intercept

Without intercept

Why is it not hydration?

If you create an equivalent Svelte app with hydratable set to true, it will pass the burn test - IMO because it uses rollup instead of vite to deliver the app to the browser.


问:
Can't run multiple ngrok tunnels using config file
I would like to run multiple Ngrok subdomains

I have created an ngrok.yml file

```<code>tunnels:
  teams:
    proto: http
    addr: 8000
    subdomain: expl
  jira:
    proto: http
    addr: 8080
    subdomain: expl2
</code>```

Then I run ./ngrok start teams -config=ngrok.yml

I have a Basic plan I have already registres my authtoken.

But I get this message

Only paid plans may bind custom subdomains.

Failed to bind the custom subdomain 'explore' for an
unauthenticated client. Sign up at: https://dashboard.ngrok.com/signup

If you have already signed up, make sure your authtoken is installed.
Your authtoken is available on your dashboard:
https://dashboard.ngrok.com/get-started/your-authtoken

ERR_NGROK_305

But I'm able to run a single subdomain tunnel using command :
./ngrok http -hostname=exple 3000, it works

答: Can you double check that you have included your authtoken: <TOKEN> at the top of your new config? That would explain why the single command works (because it is using the original config with the authtoken) but the command pointing to a new config does not.

Body:
I would like to run multiple Ngrok subdomains

I have created an ngrok.yml file

tunnels:
  teams:
    proto: http
    addr: 8000
    subdomain: expl
  jira:
    proto: http
    addr: 8080
    subdomain: expl2

Then I run ./ngrok start teams -config=ngrok.yml

I have a Basic plan I have already registres my authtoken.

But I get this message

Only paid plans may bind custom subdomains.

Failed to bind the custom subdomain 'explore' for an
unauthenticated client. Sign up at: https://dashboard.ngrok.com/signup

If you have already signed up, make sure your authtoken is installed.
Your authtoken is available on your dashboard:
https://dashboard.ngrok.com/get-started/your-authtoken

ERR_NGROK_305

But I'm able to run a single subdomain tunnel using command :
./ngrok http -hostname=exple 3000, it works


问:
Javascript to open default email client doesn't work
I need to perform following tasks;

on click of link (could be link button,  or Hyperlink) the default email program at client machine should open up.

Javascript for the same has been written as below:

string adminemail= "xyz@abc.com";    //fetches admin email address; display in To Field

ScriptManager.RegisterStartupScript(this.updatePanel1, typeof (string), "defaultemail", "window.open('mailto:" + adminemail+ " ');", true);

But, using the link button is not correct option, as it triggers postback. Hence i thought of using the  tag, but i am not sure how to link that with the javascript.

How to execute the JS with the help of  tag? OR Suggest some possible solution for the same.

Please guide!

Thanks!!

答:
An anchor or link button with href/src set to mailto: protocol will do fine, e.g:

```<code><a href="mailto:[email address]">Mail me</a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
An anchor or link button with href/src set to mailto: protocol will do fine, e.g:

<a href="mailto:[email address]">Mail me</a>


问:
How to deserialize enum with Jackson (2.13.1)
I want to deserialize an enum with Jackson 2.13.1.

I found the following solution.

```<code>public enum Type {
    TYPEONE("Type1");

    private static Map<String, Type> typesMap = new HashMap<>(1);

    static {
        typesMap.put("type1", TYPEONE);
    }

    @JsonCreator
    public static Type forValue(String value) {
        return typesMap.get(value.toLowerCase());
    }

    private final String label;

    Type(String label) {
        this.label = label;
    }

    @JsonValue
    public String getLabel() {
        return label;
    }
}
</code>```

Still getting the following error:

```<code>java.lang.IllegalArgumentException: No enum constant com.cas.cascrt.certificate.model.enums.Type.Type1
at java.base/java.lang.Enum.valueOf(Enum.java:266) ~[na:na]
</code>```

答:
Looks like your error is caused by a typo:

Instead of typesMap.put("type1", TYPEONE);

it should be typesMap.put("Type1", TYPEONE); to match the TYPEONE("Type1");.

But anyway: Using a @JsonCreator, @JsonValueand a Map
for deserializing/serializing an enum from/to customized strings
is kind of overkill.

You can do it much simpler just by using @JsonProperty on the enum constants.

```<code>public enum Type {
    @JsonProperty("Type1")
    TYPEONE,

    @JsonProperty("Type2")
    TYPETWO,

    @JsonProperty("Type3")
    TYPETHREE;
}
</code>```

Body:
I want to deserialize an enum with Jackson 2.13.1.

I found the following solution.

public enum Type {
    TYPEONE("Type1");

    private static Map<String, Type> typesMap = new HashMap<>(1);

    static {
        typesMap.put("type1", TYPEONE);
    }

    @JsonCreator
    public static Type forValue(String value) {
        return typesMap.get(value.toLowerCase());
    }

    private final String label;

    Type(String label) {
        this.label = label;
    }

    @JsonValue
    public String getLabel() {
        return label;
    }
}

Still getting the following error:

java.lang.IllegalArgumentException: No enum constant com.cas.cascrt.certificate.model.enums.Type.Type1
at java.base/java.lang.Enum.valueOf(Enum.java:266) ~[na:na]

Body:
Looks like your error is caused by a typo:

Instead of typesMap.put("type1", TYPEONE);

it should be typesMap.put("Type1", TYPEONE); to match the TYPEONE("Type1");.

But anyway: Using a @JsonCreator, @JsonValueand a Map
for deserializing/serializing an enum from/to customized strings
is kind of overkill.

You can do it much simpler just by using @JsonProperty on the enum constants.

public enum Type {
    @JsonProperty("Type1")
    TYPEONE,

    @JsonProperty("Type2")
    TYPETWO,

    @JsonProperty("Type3")
    TYPETHREE;
}


问:
T-SQL Exclude scenarios where two or more records have two or more fields with the same value but one is different
Given the table below:

```<code>DECLARE @Data TABLE
              (
                   Id INT,
                   Branch VARCHAR(50),
                   Color VARCHAR(50),
                   Name VARCHAR(50),
                   Model VARCHAR(50)
               )

INSERT INTO @Data
VALUES (1, 'London', 'Red', 'Mazda 3', '2015'),
       (2, 'London', NULL, 'Mazda 3', '2015'),
       (3, 'London', 'Red', 'Mazda 2', '2014'),
       (4, 'London', 'Red', 'Fiesta', '2020'),
       (5, 'London', 'Yellow', 'Focus', '2010'),
       (6, 'London', NULL, 'Fiesta', '2020')
</code>```

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

2
London
null
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Red
Fiesta
2020

5
London
Yellow
Focus
2010

6
London
null
Fiesta
2020

I am aiming to exclude those records where the Branch, Name and Model are the same, but one of the rows has a specific Color value and the second row is null.

So, I would be only returning the id's below as the desired result, so Id's 1,2,4 and 6 should be excluded.:

Id
Branch
Color
Name
Model

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

I have tried the query below:

```<code>SELECT Data1.*
FROM @Data Data1
INNER JOIN @Data Data2 ON Data1.Branch = Data2.Branch
                       AND Data1.Name = Data2.Name
                       AND Data1.Model = Data2.Model
                       AND Data1.Color = Data2.Color
</code>```

But I still get the ones where the Color is not null as shown below.

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

Any guidance will be really appreciated !

答:
Schema and insert statements:

```<code> DECLARE @Data TABLE
               (
                    Id INT,
                    Branch VARCHAR(50),
                    Color VARCHAR(50),
                    Name VARCHAR(50),
                    Model VARCHAR(50)
                )

 INSERT INTO @Data
 VALUES (1, 'London', 'Red', 'Mazda 3', '2015'),
        (2, 'London', NULL, 'Mazda 3', '2015'),
        (3, 'London', 'Red', 'Mazda 2', '2014'),
        (4, 'London', 'Red', 'Fiesta', '2020'),
        (5, 'London', 'Yellow', 'Focus', '2010'),
        (6, 'London', NULL, 'Fiesta', '2020')

</code>```

Query:

```<code> Select * from @Data Data0
 where not exists(
                    select * from @Data Data1
                    inner join @Data Data2
                    on Data1.Branch=Data2.Branch and data1.Model=data2.Model and data1.id<>data2.Id
                    where Data1.color is not null
                    and Data2.color is null and (data0.id =data1.id or data0.id=data2.Id)
                )
</code>```

Output:

Id
Branch
Color
Name
Model

3
London
Red
Mazda 2
2014

5
London
Yellow
Focus
2010

db<>fiddle here

Body:
Given the table below:

DECLARE @Data TABLE
              (
                   Id INT,
                   Branch VARCHAR(50),
                   Color VARCHAR(50),
                   Name VARCHAR(50),
                   Model VARCHAR(50)
               )

INSERT INTO @Data
VALUES (1, 'London', 'Red', 'Mazda 3', '2015'),
       (2, 'London', NULL, 'Mazda 3', '2015'),
       (3, 'London', 'Red', 'Mazda 2', '2014'),
       (4, 'London', 'Red', 'Fiesta', '2020'),
       (5, 'London', 'Yellow', 'Focus', '2010'),
       (6, 'London', NULL, 'Fiesta', '2020')

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

2
London
null
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Red
Fiesta
2020

5
London
Yellow
Focus
2010

6
London
null
Fiesta
2020

I am aiming to exclude those records where the Branch, Name and Model are the same, but one of the rows has a specific Color value and the second row is null.

So, I would be only returning the id's below as the desired result, so Id's 1,2,4 and 6 should be excluded.:

Id
Branch
Color
Name
Model

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

I have tried the query below:

SELECT Data1.*
FROM @Data Data1
INNER JOIN @Data Data2 ON Data1.Branch = Data2.Branch
                       AND Data1.Name = Data2.Name
                       AND Data1.Model = Data2.Model
                       AND Data1.Color = Data2.Color

But I still get the ones where the Color is not null as shown below.

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

Any guidance will be really appreciated !

Body:
Schema and insert statements:

 DECLARE @Data TABLE
               (
                    Id INT,
                    Branch VARCHAR(50),
                    Color VARCHAR(50),
                    Name VARCHAR(50),
                    Model VARCHAR(50)
                )

 INSERT INTO @Data
 VALUES (1, 'London', 'Red', 'Mazda 3', '2015'),
        (2, 'London', NULL, 'Mazda 3', '2015'),
        (3, 'London', 'Red', 'Mazda 2', '2014'),
        (4, 'London', 'Red', 'Fiesta', '2020'),
        (5, 'London', 'Yellow', 'Focus', '2010'),
        (6, 'London', NULL, 'Fiesta', '2020')

Query:

 Select * from @Data Data0
 where not exists(
                    select * from @Data Data1
                    inner join @Data Data2
                    on Data1.Branch=Data2.Branch and data1.Model=data2.Model and data1.id<>data2.Id
                    where Data1.color is not null
                    and Data2.color is null and (data0.id =data1.id or data0.id=data2.Id)
                )

Output:

Id
Branch
Color
Name
Model

3
London
Red
Mazda 2
2014

5
London
Yellow
Focus
2010

db<>fiddle here


问:
Regex replacement for URI in vrl (vector.dev)
I need a regex that replaces the pieces of a URI that would create a high cardinality situation.

Basically if the segment of a URI contains any non a-zA-Z characters (other than /), replace it with an *

Example:

```<code>$ replace("/first/12ab34/B1a234/12B3a/1234/second/A789B-89d", r'(?i)[a-z]*\d+(?i)[a-z]*',"*")
</code>```

results in: "/first/**/**/**/*/second/*-*"

That's close, but I need "/first/*/*/*/*/second/*"

Multiple replaces are acceptable. Any regex masters out there willing to help?
This is for vrl (vector.dev) written in Rust. VRL does not support look-around of any kind.

答:
For the example data, you might use

```<code>(?i)[a-z]*\d[\da-z]*(?:-[\da-z]+)*
</code>```

(?i) Inline modifier for case insensitive

[a-z]* Match optional chars a-z

\d Match a single digit

[\da-z]* Match optional digits or chars a-z

(?:-[\da-z]+)* optionally repeat a - and 1+ times either a digit or a-z

Regex demo

Body:
I need a regex that replaces the pieces of a URI that would create a high cardinality situation.

Basically if the segment of a URI contains any non a-zA-Z characters (other than /), replace it with an *

Example:

$ replace("/first/12ab34/B1a234/12B3a/1234/second/A789B-89d", r'(?i)[a-z]*\d+(?i)[a-z]*',"*")

results in: "/first/**/**/**/*/second/*-*"

That's close, but I need "/first/*/*/*/*/second/*"

Multiple replaces are acceptable. Any regex masters out there willing to help?
This is for vrl (vector.dev) written in Rust. VRL does not support look-around of any kind.

Body:
For the example data, you might use

(?i)[a-z]*\d[\da-z]*(?:-[\da-z]+)*

(?i) Inline modifier for case insensitive

[a-z]* Match optional chars a-z

\d Match a single digit

[\da-z]* Match optional digits or chars a-z

(?:-[\da-z]+)* optionally repeat a - and 1+ times either a digit or a-z

Regex demo


问:
How to npm audit global packages
As stated in the official npm documentation you can manually run npm audit on locally installed packages, which must have both package.json and package-lock.json files.

Globally installed packages doesn't have package-lock.json, if you run an audit it will trow an error: npm ERR! code EAUDITNOLOCK

How can I run npm audit on all globally installed packages?

答:
Well, there is another interesting way to audit global packages without using some third party packages. After all, we don't want to violate security principles by using them on such a sensitive data ;).

You might need to run terminal (bash or similar on Unix-like system or cmd on Windows) with administrative priviledges to get proper results.

Use this command to figure out the path and the list of globally installed packages:

```<code>npm i
</code>```

You should get something like this:

```<code>C:\Program Files\nodejs -> .\
├── gulp-cli@2.3.0
├── nodemon@2.0.15
├── npm@8.4.1
└── ts-node@10.5.0
</code>```

Go to that path using your terminal. Keep in mind that this path might by a link (or symlink) to another folder.

Create a package.json file in that folder with the contents reflecting global packages list and exact versions you've got in step 1 like this:

{
  "name": "-",
  "version": "0.0.1",
  "dependencies": {
    "gulp-cli": "2.3.0",
    "nodemon": "2.0.15",
    "npm": "8.4.1",
    "ts-node": "10.5.0"
  }
}
```
<p>Pay attention that npm itself is included as well.</p>
<ol start="4">
<li>Create a <code>package-lock.json</code> file there using this cli command:</li>
</ol>
```npm i --package-lock-only
```
<ol start="5">
<li>Run audit with</li>
</ol>
```npm audit
```

It worked for me on my Windows 8.1 system at least, running node v.16.13.2, npm v.8.4.1.

Interesting that I've got a moderate severity vulnerability for npm itself in my report.

I would appreciate it if you'll share your experience with the way I suggested to solve the problem.

Title: How to npm audit global packages

Body:
Well, there is another interesting way to audit global packages without using some third party packages. After all, we don't want to violate security principles by using them on such a sensitive data ;).

You might need to run terminal (bash or similar on Unix-like system or cmd on Windows) with administrative priviledges to get proper results.

Use this command to figure out the path and the list of globally installed packages:

npm i

You should get something like this:

C:\Program Files\nodejs -> .\
├── gulp-cli@2.3.0
├── nodemon@2.0.15
├── npm@8.4.1
└── ts-node@10.5.0

Go to that path using your terminal. Keep in mind that this path might by a link (or symlink) to another folder.

Create a package.json file in that folder with the contents reflecting global packages list and exact versions you've got in step 1 like this:

{
  "name": "-",
  "version": "0.0.1",
  "dependencies": {
    "gulp-cli": "2.3.0",
    "nodemon": "2.0.15",
    "npm": "8.4.1",
    "ts-node": "10.5.0"
  }
}

Pay attention that npm itself is included as well.

Create a package-lock.json file there using this cli command:

npm i --package-lock-only

Run audit with

npm audit

It worked for me on my Windows 8.1 system at least, running node v.16.13.2, npm v.8.4.1.

Interesting that I've got a moderate severity vulnerability for npm itself in my report.

I would appreciate it if you'll share your experience with the way I suggested to solve the problem.


问:
Why am I getting a "No signature of method"" error when running the closure recursion example in the Groovy shell?
I'm trying to experiment with the Groovy closure recursion example from http://groovy.codehaus.org/JN2515-Closures .

I saved the snippet in a file called recursionTest.groovy and loaded it in the shell, but I'm getting a "No signature of method error":

```<code>// recursionTest.groovy

def results = [];
{ a, b ->
  results << a
  a<10 && call(b, a+b)
}(1,1)

assert results == [1, 1, 2, 3, 5, 8, 13]

groovy:000> load recursionTest.groovy
===> []
ERROR groovy.lang.MissingMethodException:
No signature of method: java.lang.Boolean.call() is applicable for argument types: (groovysh_evaluate$_run_closure1) values: [groovysh_evaluate$_run_closure1@6b7599cc]
Possible solutions: wait(), any(), wait(long), and(java.lang.Boolean), each(groovy.lang.Closure), any(groovy.lang.Closure)
        at groovysh_evaluate.run (groovysh_evaluate:1)
        ...
groovy:003>
</code>```

What's going on?

答:
I don't have a perfect answer for you, but it looks like GroovySH has some hacks that can screw it up when working with certain Groovy features.

The example code you have works perfectly in groovyConsole (which is a graphical editor, and much easier to play around in), as well as running it using groovy recursionTest.groovy.

I haven't found a solution that works correctly in the groovy shell, but I wouldn't really recommend using that for learning, anyway.

Body:
I'm trying to experiment with the Groovy closure recursion example from http://groovy.codehaus.org/JN2515-Closures .

I saved the snippet in a file called recursionTest.groovy and loaded it in the shell, but I'm getting a "No signature of method error":

// recursionTest.groovy

def results = [];
{ a, b ->
  results << a
  a<10 && call(b, a+b)
}(1,1)

assert results == [1, 1, 2, 3, 5, 8, 13]

groovy:000> load recursionTest.groovy
===> []
ERROR groovy.lang.MissingMethodException:
No signature of method: java.lang.Boolean.call() is applicable for argument types: (groovysh_evaluate$_run_closure1) values: [groovysh_evaluate$_run_closure1@6b7599cc]
Possible solutions: wait(), any(), wait(long), and(java.lang.Boolean), each(groovy.lang.Closure), any(groovy.lang.Closure)
        at groovysh_evaluate.run (groovysh_evaluate:1)
        ...
groovy:003>

What's going on?


问:
Array reversal in C language using while loop
I made this program to reverse an array but it only works when I put in an odd number of digits in the array. If I put in even number of digits it doesn't print anything.
For example: If I put {1,2,3,4,5} the program will print {5,4,3,2,1} but if the input is {1,2,3,4} it doesn't print anything.

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

int main()
{
    int num, *arr, i, count;
    count = 0;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
        count++;
    }

    int l_Count, h_Count, temp;
    temp = 0;
    h_Count = count - 1;
    l_Count = 0;
    while (l_Count != h_Count) {
        temp = *(arr + l_Count);
        *(arr + l_Count) = *(arr + h_Count);
        *(arr + h_Count) = temp;
        h_Count--;
        l_Count++;
    }

    for (i = 0; i < num; i++) {
        printf("%d ", *(arr + i));
    }
    return 0;
}
</code>```

答:
Generic array reversal:

```<code>void *reverseArray(void *array, const size_t nelemets, const size_t elemsize)
{
    if(array && nelemets && elemsize)
    {
        unsigned char *last = (nelemets - 1) * elemsize + array;
        unsigned char *first = array;
        while(first + elemsize < last)
        {
            unsigned char temp[elemsize];
            memcpy(temp, first, elemsize);
            memcpy(first, last, elemsize);
            memcpy(last, temp, elemsize);
            first += elemsize;
            last -= elemsize;
        }
    }
    return array;
}
</code>```

Example usage:

```<code>int main(void)
{
    int a[5] = {1,2,3,4,5};

    reverseArray(a, 5, sizeof(a[0]));

    for(size_t i = 0; i < 5; i++) printf("%d\n", a[i]);
}
</code>```

Body:
I made this program to reverse an array but it only works when I put in an odd number of digits in the array. If I put in even number of digits it doesn't print anything.
For example: If I put {1,2,3,4,5} the program will print {5,4,3,2,1} but if the input is {1,2,3,4} it doesn't print anything.

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

int main()
{
    int num, *arr, i, count;
    count = 0;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
        count++;
    }

    int l_Count, h_Count, temp;
    temp = 0;
    h_Count = count - 1;
    l_Count = 0;
    while (l_Count != h_Count) {
        temp = *(arr + l_Count);
        *(arr + l_Count) = *(arr + h_Count);
        *(arr + h_Count) = temp;
        h_Count--;
        l_Count++;
    }

    for (i = 0; i < num; i++) {
        printf("%d ", *(arr + i));
    }
    return 0;
}

Body:
Generic array reversal:

void *reverseArray(void *array, const size_t nelemets, const size_t elemsize)
{
    if(array && nelemets && elemsize)
    {
        unsigned char *last = (nelemets - 1) * elemsize + array;
        unsigned char *first = array;
        while(first + elemsize < last)
        {
            unsigned char temp[elemsize];
            memcpy(temp, first, elemsize);
            memcpy(first, last, elemsize);
            memcpy(last, temp, elemsize);
            first += elemsize;
            last -= elemsize;
        }
    }
    return array;
}

Example usage:

int main(void)
{
    int a[5] = {1,2,3,4,5};

    reverseArray(a, 5, sizeof(a[0]));

    for(size_t i = 0; i < 5; i++) printf("%d\n", a[i]);
}


问:
Get value of another field in Field level Validation in DRF
I am using Field level Validation in my serializer and I have situation where I need value of first field while validating second field. I know in object level validation I can have access to that but my serailzer have many=True and in object level validation  I cannot tell client side which iteration have raised the error.

Serailzer :

```<code>class Keys_Serializer(serializers.Serializer):
    """
    """
    key_id = serializers.IntegerField(required=True)
    key_name = serializers.CharField(required=True)
    value_id = serializers.IntegerField(required=False)

    def validate_key_id(self, value):
        """
        validate key id
        """
         *** validate key_id here ***
        return value

    def validate_value_id(self, value):
        """
        validate value_id w.r.t key_id
        """
         *** I need key_id of current iteration here so that I can validate value_id. ***
        return value
</code>```

Is there any way of accessing the value of key_id in value_id validation.

答:
I had a similar problem where I just needed other values for the output, not for validation but this could probably be a good starting point. It is based on https://www.django-rest-framework.org/api-guide/fields/#examples.

You need to override the get_attribute function to return the object instead of  the attribute. From the docs:

```<code>class ClassNameField(serializers.Field):
def get_attribute(self, instance):
    # We pass the object instance onto `to_representation`,
    # not just the field attribute.
    return instance
</code>```

Then I was able to do stuff like

```<code>def to_representation(self, instance):  # pylint: disable=arguments-renamed
    return instance.my_function()
    or
    return f"{instance.attribute_1}, {instance.attribute_2}"
</code>```

Body:
I am using Field level Validation in my serializer and I have situation where I need value of first field while validating second field. I know in object level validation I can have access to that but my serailzer have many=True and in object level validation  I cannot tell client side which iteration have raised the error.

Serailzer :

class Keys_Serializer(serializers.Serializer):
    """
    """
    key_id = serializers.IntegerField(required=True)
    key_name = serializers.CharField(required=True)
    value_id = serializers.IntegerField(required=False)

    def validate_key_id(self, value):
        """
        validate key id
        """
         *** validate key_id here ***
        return value

    def validate_value_id(self, value):
        """
        validate value_id w.r.t key_id
        """
         *** I need key_id of current iteration here so that I can validate value_id. ***
        return value

Is there any way of accessing the value of key_id in value_id validation.

Body:
I had a similar problem where I just needed other values for the output, not for validation but this could probably be a good starting point. It is based on https://www.django-rest-framework.org/api-guide/fields/#examples.

You need to override the get_attribute function to return the object instead of  the attribute. From the docs:

class ClassNameField(serializers.Field):
def get_attribute(self, instance):
    # We pass the object instance onto `to_representation`,
    # not just the field attribute.
    return instance

Then I was able to do stuff like

def to_representation(self, instance):  # pylint: disable=arguments-renamed
    return instance.my_function()
    or
    return f"{instance.attribute_1}, {instance.attribute_2}"


问:
how to create an autorelease object
Is this method create an autorelease object?

```<code>- (instancetype)autoreleasePerson {
    return [[Person alloc] init];
}
</code>```

I created an Command Line Tool Project to test this:

```<code>int main(int argc, const char * argv[]) {
    @autoreleasepool {
        {
            [Person autoreleasePerson];

        }
        NSLog(@"did out scope");

        NSLog(@"will out autoreleasepool");
    }
    NSLog(@"did out autoreleasepool");
    return 0;
}
</code>```

And the output is:

```<code>2022-02-04 23:22:23.224298+0800 MyTest[8921:4007144] did out scope
2022-02-04 23:22:23.224771+0800 MyTest[8921:4007144] will out autoreleasepool
2022-02-04 23:22:23.224876+0800 MyTest[8921:4007144] -[Person dealloc]
2022-02-04 23:22:23.224948+0800 MyTest[8921:4007144] did out autoreleasepool
</code>```

The person instance will dealloc when the autoreleasepool drains!

But when I use the same Person class in my iOS APP project:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    {
        [Person autoreleasePerson];
    }
    NSLog(@"out scope");
}
</code>```

The output is:

```<code>2022-02-04 23:28:13.992969+0800 MyAppTest[9023:4011490] -[Person dealloc] <Person: 0x600001fe8ff0>
2022-02-04 23:28:13.993075+0800 MyAppTest[9023:4011490] out scope
</code>```

The person instance released once out of scope!

Why is this so?

答:
It looks like on macOS the default behaviour is to autorelease return values, except for cases where the method name starts with "new", "init" or "copy":

```<code>+ (Person *)createPerson {
    return [Person new]; // autorelease & return
}
+ (Person *)newPerson {
    return [Person new]; // direct return
}
</code>```

To control this behaviour apply a compiler attribute:

```<code>+ (Person *)createPerson __attribute__((ns_returns_retained)) {
    return [Person new]; // direct return
}
+ (Person *)newPerson __attribute__((ns_returns_not_retained)) {
    return [Person new]; // autorelease & return
}
</code>```

To check whether a call to objc_autoreleaseReturnValue was added by the compiler, enable Debug -> Debug Workflow -> Always Show Disassembly,
and put a breakpoint inside these methods on return lines. A call to objc_autoreleaseReturnValue should be visible then:

See ARC reference - Retained return values

Title: how to create an autorelease object

Body:
Is this method create an autorelease object?

- (instancetype)autoreleasePerson {
    return [[Person alloc] init];
}

I created an Command Line Tool Project to test this:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        {
            [Person autoreleasePerson];

        }
        NSLog(@"did out scope");

        NSLog(@"will out autoreleasepool");
    }
    NSLog(@"did out autoreleasepool");
    return 0;
}

And the output is:

2022-02-04 23:22:23.224298+0800 MyTest[8921:4007144] did out scope
2022-02-04 23:22:23.224771+0800 MyTest[8921:4007144] will out autoreleasepool
2022-02-04 23:22:23.224876+0800 MyTest[8921:4007144] -[Person dealloc]
2022-02-04 23:22:23.224948+0800 MyTest[8921:4007144] did out autoreleasepool

The person instance will dealloc when the autoreleasepool drains!

But when I use the same Person class in my iOS APP project:

- (void)viewDidLoad {
    [super viewDidLoad];
    {
        [Person autoreleasePerson];
    }
    NSLog(@"out scope");
}

The output is:

2022-02-04 23:28:13.992969+0800 MyAppTest[9023:4011490] -[Person dealloc] <Person: 0x600001fe8ff0>
2022-02-04 23:28:13.993075+0800 MyAppTest[9023:4011490] out scope

The person instance released once out of scope!

Why is this so?

Body:
It looks like on macOS the default behaviour is to autorelease return values, except for cases where the method name starts with "new", "init" or "copy":

+ (Person *)createPerson {
    return [Person new]; // autorelease & return
}
+ (Person *)newPerson {
    return [Person new]; // direct return
}

To control this behaviour apply a compiler attribute:

+ (Person *)createPerson __attribute__((ns_returns_retained)) {
    return [Person new]; // direct return
}
+ (Person *)newPerson __attribute__((ns_returns_not_retained)) {
    return [Person new]; // autorelease & return
}

To check whether a call to objc_autoreleaseReturnValue was added by the compiler, enable Debug -> Debug Workflow -> Always Show Disassembly,
and put a breakpoint inside these methods on return lines. A call to objc_autoreleaseReturnValue should be visible then:

See ARC reference - Retained return values


问:
How to extract R code from a Markdown file (*.md)?
I tried the following R commands in order to generate an R file:

```<code>library(knitr)
purl("/Readme.md")
</code>```

But I get an R empty file.

答:
Quick function for parsing only the code chunks out from a .md file and then writing them to a local temp file:

library(dplyr)
library(stringr)

subset_even <- function(x) x[!seq_along(x) %% 2]

extract_code_md <- function(file_path){

  lines <- readr::read_file(file_path) %>%
    stringr::str_split("```.*", simplify = TRUE) %>%
    subset_even() %>%
    stringr::str_flatten("\n## new chunk \n")

  file_output <- tempfile(fileext = ".R")
  writeLines(lines, file_output)
  file_output

}
</code>```

Let's use this function on the "README.md" file from dplyr's github page.

readr::read_file(extract_code_md('https://raw.githubusercontent.com/tidyverse/dplyr/main/README.md')) %>%
  writeLines()
#>
#> # The easiest way to get dplyr is to install the whole tidyverse:
#> install.packages("tidyverse")
#>
#> # Alternatively, install just dplyr:
#> install.packages("dplyr")
#>
#> ## new chunk
#>
#> # install.packages("devtools")
#> devtools::install_github("tidyverse/dplyr")
#>
#> ## new chunk
#>
#> library(dplyr)
#>
#> starwars %>%
#>   filter(species == "Droid")
#> #> # A tibble: 6 <d7> 14
#> #>   name   height  mass hair_color skin_color  eye_color birth_year sex   gender
#> #>   <chr>   <int> <dbl> <chr>      <chr>       <chr>          <dbl> <chr> <chr>
#> #> 1 C-3PO     167    75 <NA>       gold        yellow           112 none  masculi
#> #> 2 R2-D2      96    32 <NA>       white, blue red               33 none  masculi
#> #> 3 R5-D4      97    32 <NA>       white, red  red               NA none  masculi
#> #> 4 IG-88     200   140 none       metal       red               15 none  masculi
#> #> 5 R4-P17     96    NA none       silver, red red, blue         NA none  feminine
#> #> #  with 1 more row, and 5 more variables: homeworld <chr>, species <chr>,
#> #> #   films <list>, vehicles <list>, starships <list>
#>
#> starwars %>%
#>   select(name, ends_with("color"))
#> #> # A tibble: 87 <d7> 4
#> #>   name           hair_color skin_color  eye_color
#> #>   <chr>          <chr>      <chr>       <chr>
#> #> 1 Luke Skywalker blond      fair        blue
#> #> 2 C-3PO          <NA>       gold        yellow
#> #> 3 R2-D2          <NA>       white, blue red
#> #> 4 Darth Vader    none       white       yellow
#> #> 5 Leia Organa    brown      light       brown
#> #> #  with 82 more rows
#>
#> starwars %>%
#>   mutate(name, bmi = mass / ((height / 100)  ^ 2)) %>%
#>   select(name:mass, bmi)
#> #> # A tibble: 87 <d7> 4
#> #>   name           height  mass   bmi
#> #>   <chr>           <int> <dbl> <dbl>
#> #> 1 Luke Skywalker    172    77  26.0
#> #> 2 C-3PO             167    75  26.9
#> #> 3 R2-D2              96    32  34.7
#> #> 4 Darth Vader       202   136  33.3
#> #> 5 Leia Organa       150    49  21.8
#> #> #  with 82 more rows
#>
#> starwars %>%
#>   arrange(desc(mass))
#> #> # A tibble: 87 <d7> 14
#> #>   name      height  mass hair_color skin_color eye_color birth_year sex   gender
#> #>   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr>
#> #> 1 Jabba De    175  1358 <NA>       green-tan orange         600   herm mascu
#> #> 2 Grievous     216   159 none       brown, wh green, y       NA   male  mascu
#> #> 3 IG-88        200   140 none       metal      red             15   none  mascu
#> #> 4 Darth Va    202   136 none       white      yellow          41.9 male  mascu
#> #> 5 Tarfful      234   136 brown      brown      blue            NA   male  mascu
#> #> #  with 82 more rows, and 5 more variables: homeworld <chr>, species <chr>,
#> #> #   films <list>, vehicles <list>, starships <list>
#>
#> starwars %>%
#>   group_by(species) %>%
#>   summarise(
#>     n = n(),
#>     mass = mean(mass, na.rm = TRUE)
#>   ) %>%
#>   filter(
#>     n > 1,
#>     mass > 50
#>   )
#> #> # A tibble: 8 <d7> 3
#> #>   species      n  mass
#> #>   <chr>    <int> <dbl>
#> #> 1 Droid        6  69.8
#> #> 2 Gungan       3  74
#> #> 3 Human       35  82.8
#> #> 4 Kaminoan     2  88
#> #> 5 Mirialan     2  53.1
#> #> #  with 3 more rows
#>
```

Function is rough and subject to the assumption that three backticks are only used to make code chunks (e.g. if they show-up in a quoted character string or something, will break code).

Body:
I tried the following R commands in order to generate an R file:

library(knitr)
purl("/Readme.md")

But I get an R empty file.

Body:
Quick function for parsing only the code chunks out from a .md file and then writing them to a local temp file:

library(dplyr)
library(stringr)

subset_even <- function(x) x[!seq_along(x) %% 2]

extract_code_md <- function(file_path){

  lines <- readr::read_file(file_path) %>%
    stringr::str_split("```.*", simplify = TRUE) %>%
    subset_even() %>%
    stringr::str_flatten("\n## new chunk \n")

  file_output <- tempfile(fileext = ".R")
  writeLines(lines, file_output)
  file_output

}

Let's use this function on the "README.md" file from dplyr's github page.

readr::read_file(extract_code_md('https://raw.githubusercontent.com/tidyverse/dplyr/main/README.md')) %>%
  writeLines()
#>
#> # The easiest way to get dplyr is to install the whole tidyverse:
#> install.packages("tidyverse")
#>
#> # Alternatively, install just dplyr:
#> install.packages("dplyr")
#>
#> ## new chunk
#>
#> # install.packages("devtools")
#> devtools::install_github("tidyverse/dplyr")
#>
#> ## new chunk
#>
#> library(dplyr)
#>
#> starwars %>%
#>   filter(species == "Droid")
#> #> # A tibble: 6 <d7> 14
#> #>   name   height  mass hair_color skin_color  eye_color birth_year sex   gender
#> #>   <chr>   <int> <dbl> <chr>      <chr>       <chr>          <dbl> <chr> <chr>
#> #> 1 C-3PO     167    75 <NA>       gold        yellow           112 none  masculi<U+0085>
#> #> 2 R2-D2      96    32 <NA>       white, blue red               33 none  masculi<U+0085>
#> #> 3 R5-D4      97    32 <NA>       white, red  red               NA none  masculi<U+0085>
#> #> 4 IG-88     200   140 none       metal       red               15 none  masculi<U+0085>
#> #> 5 R4-P17     96    NA none       silver, red red, blue         NA none  feminine
#> #> # <U+0085> with 1 more row, and 5 more variables: homeworld <chr>, species <chr>,
#> #> #   films <list>, vehicles <list>, starships <list>
#>
#> starwars %>%
#>   select(name, ends_with("color"))
#> #> # A tibble: 87 <d7> 4
#> #>   name           hair_color skin_color  eye_color
#> #>   <chr>          <chr>      <chr>       <chr>
#> #> 1 Luke Skywalker blond      fair        blue
#> #> 2 C-3PO          <NA>       gold        yellow
#> #> 3 R2-D2          <NA>       white, blue red
#> #> 4 Darth Vader    none       white       yellow
#> #> 5 Leia Organa    brown      light       brown
#> #> # <U+0085> with 82 more rows
#>
#> starwars %>%
#>   mutate(name, bmi = mass / ((height / 100)  ^ 2)) %>%
#>   select(name:mass, bmi)
#> #> # A tibble: 87 <d7> 4
#> #>   name           height  mass   bmi
#> #>   <chr>           <int> <dbl> <dbl>
#> #> 1 Luke Skywalker    172    77  26.0
#> #> 2 C-3PO             167    75  26.9
#> #> 3 R2-D2              96    32  34.7
#> #> 4 Darth Vader       202   136  33.3
#> #> 5 Leia Organa       150    49  21.8
#> #> # <U+0085> with 82 more rows
#>
#> starwars %>%
#>   arrange(desc(mass))
#> #> # A tibble: 87 <d7> 14
#> #>   name      height  mass hair_color skin_color eye_color birth_year sex   gender
#> #>   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr>
#> #> 1 Jabba De<U+0085>    175  1358 <NA>       green-tan<U+0085> orange         600   herm<U+0085> mascu<U+0085>
#> #> 2 Grievous     216   159 none       brown, wh<U+0085> green, y<U+0085>       NA   male  mascu<U+0085>
#> #> 3 IG-88        200   140 none       metal      red             15   none  mascu<U+0085>
#> #> 4 Darth Va<U+0085>    202   136 none       white      yellow          41.9 male  mascu<U+0085>
#> #> 5 Tarfful      234   136 brown      brown      blue            NA   male  mascu<U+0085>
#> #> # <U+0085> with 82 more rows, and 5 more variables: homeworld <chr>, species <chr>,
#> #> #   films <list>, vehicles <list>, starships <list>
#>
#> starwars %>%
#>   group_by(species) %>%
#>   summarise(
#>     n = n(),
#>     mass = mean(mass, na.rm = TRUE)
#>   ) %>%
#>   filter(
#>     n > 1,
#>     mass > 50
#>   )
#> #> # A tibble: 8 <d7> 3
#> #>   species      n  mass
#> #>   <chr>    <int> <dbl>
#> #> 1 Droid        6  69.8
#> #> 2 Gungan       3  74
#> #> 3 Human       35  82.8
#> #> 4 Kaminoan     2  88
#> #> 5 Mirialan     2  53.1
#> #> # <U+0085> with 3 more rows
#>

Function is rough and subject to the assumption that three backticks are only used to make code chunks (e.g. if they show-up in a quoted character string or something, will break code).


Title: Regex replacement for URI in vrl (vector.dev)

Body:
Use

[^/\d]*\d[^/]*

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  [^/\d]*                  any character except: '/', digits (0-9) (0
                           or more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \d                       digits (0-9)
--------------------------------------------------------------------------------
  [^/]*                    any character except: '/' (0 or more times
                           (matching the most amount possible))


问:
Problem with Authentification in Blazor Webassembly project which hosted on ASP.NET Core project
I have two projects:

Notes.Server - ASP.NET Core project,

Notes.Client - Blazor WASM project

My Note App contain Client.cshtml page which have:

<component type="typeof(PrettyNotes.Web.Client.App)" render-mode="WebAssemblyPrerendered"/>

It's preprenderes Blazor WASM. I implementing oidc authentification in this prerendered project.

Notes.Server's Startup.cs file:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PrettyNotes.Web.Server.Models;
using PrettyNotes.Web.Server.Models.Data;

namespace Notes.Web.Server
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRazorPages().AddRazorRuntimeCompilation();
            services.AddDbContext<PrettyNotesApplicationDBContext>(options =>
            {
                options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ProjectDB;Trusted_Connection=True;");
            });

            services.AddIdentity<PNUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = true;
            }).AddEntityFrameworkStores<PrettyNotesApplicationDBContext>();
            services.AddAuthentication().AddIdentityServerJwt();

            services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme,
                opt =>
                {
                    opt.LoginPath = "/auth/login";
                    opt.LogoutPath = "/auth/logout";
                });

            services.AddIdentityServer()
                .AddInMemoryApiResources(new ApiResource[] { new ApiResource("API", "ServerAPI") }).AddInMemoryClients(
                    new[]
                    {
                        new IdentityServer4.Models.Client
                        {
                            ClientId = "PrettyNotesClient",
                            AllowedGrantTypes = GrantTypes.Code,
                            RequirePkce = true,
                            RequireClientSecret = false,
                            AllowedCorsOrigins = { "https://localhost:5001" },
                            AllowedScopes = { "openid", "profile", "email" },
                            RedirectUris = { "https://localhost:5001/client/security/auth/login-callback" },
                            PostLogoutRedirectUris = { "http://localhost:5001/client" },
                            Enabled = true
                        }
                    })
                .AddInMemoryIdentityResources(
                    new IdentityResource[]
                    {
                        new IdentityResources.Address(),
                        new IdentityResources.Profile(),
                        new IdentityResources.Email(),
                        new IdentityResources.OpenId()
                    }).AddInMemoryApiScopes(new[] { new ApiScope("API") }).AddAspNetIdentity<PNUser>()
                .AddDeveloperSigningCredential();
            services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>().AddScoped<SignOutSessionStateManager>();
            services.AddRemoteAuthentication<RemoteAuthenticationState, RemoteUserAccount, OidcProviderOptions>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseStaticFiles();
            app.UseBlazorFrameworkFiles();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseIdentityServer();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
                endpoints.MapFallbackToController("/client/{**segment}", "Index", "Client");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
</code>```

My Blazor WASM Project is prerendered in server. When I trying to reach Blazor WASM Project page that prerenders Blazor, I get next error:

```<code>fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IRemoteAuthenticationService`1[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState]'.

</code>```

How to resolve this problem?
Can you suggest some resources, repos about Authentification in Prerendered Blazor Webassembly?

答:
The documentation here should help already a lot: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-6.0#support-prerendering-with-authentication

although they seem to ignore the fact that the callback-login url stays stuck on "loading" as you need to disable the div override for prerendering, still figuring that on out

Body:
I have two projects:

Notes.Server - ASP.NET Core project,

Notes.Client - Blazor WASM project

My Note App contain Client.cshtml page which have:

<component type="typeof(PrettyNotes.Web.Client.App)" render-mode="WebAssemblyPrerendered"/>

It's preprenderes Blazor WASM. I implementing oidc authentification in this prerendered project.

Notes.Server's Startup.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PrettyNotes.Web.Server.Models;
using PrettyNotes.Web.Server.Models.Data;

namespace Notes.Web.Server
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRazorPages().AddRazorRuntimeCompilation();
            services.AddDbContext<PrettyNotesApplicationDBContext>(options =>
            {
                options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ProjectDB;Trusted_Connection=True;");
            });

            services.AddIdentity<PNUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = true;
            }).AddEntityFrameworkStores<PrettyNotesApplicationDBContext>();
            services.AddAuthentication().AddIdentityServerJwt();

            services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme,
                opt =>
                {
                    opt.LoginPath = "/auth/login";
                    opt.LogoutPath = "/auth/logout";
                });

            services.AddIdentityServer()
                .AddInMemoryApiResources(new ApiResource[] { new ApiResource("API", "ServerAPI") }).AddInMemoryClients(
                    new[]
                    {
                        new IdentityServer4.Models.Client
                        {
                            ClientId = "PrettyNotesClient",
                            AllowedGrantTypes = GrantTypes.Code,
                            RequirePkce = true,
                            RequireClientSecret = false,
                            AllowedCorsOrigins = { "https://localhost:5001" },
                            AllowedScopes = { "openid", "profile", "email" },
                            RedirectUris = { "https://localhost:5001/client/security/auth/login-callback" },
                            PostLogoutRedirectUris = { "http://localhost:5001/client" },
                            Enabled = true
                        }
                    })
                .AddInMemoryIdentityResources(
                    new IdentityResource[]
                    {
                        new IdentityResources.Address(),
                        new IdentityResources.Profile(),
                        new IdentityResources.Email(),
                        new IdentityResources.OpenId()
                    }).AddInMemoryApiScopes(new[] { new ApiScope("API") }).AddAspNetIdentity<PNUser>()
                .AddDeveloperSigningCredential();
            services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>().AddScoped<SignOutSessionStateManager>();
            services.AddRemoteAuthentication<RemoteAuthenticationState, RemoteUserAccount, OidcProviderOptions>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseStaticFiles();
            app.UseBlazorFrameworkFiles();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseIdentityServer();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
                endpoints.MapFallbackToController("/client/{**segment}", "Index", "Client");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

My Blazor WASM Project is prerendered in server. When I trying to reach Blazor WASM Project page that prerenders Blazor, I get next error:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IRemoteAuthenticationService`1[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState]'.

How to resolve this problem?
Can you suggest some resources, repos about Authentification in Prerendered Blazor Webassembly?


问:
Error: Element type is invalid next.js when running dev server
I keep getting this error when running npm run dev

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
```
<p>However, when I do <code>npm run build</code> and then <code>npm run start</code> the site loads fine. It is just on the dev server that it gives that error. The site also deploys to Vercel fine without any issues.</p>
<p>Any idea why I am getting this on the dev server and not production?</p>
<p>Also, I tried deleting the <code>.next</code> folder, also deleted <code>node_modules</code>, and installed all packages again, still gives an error. Deployed to different Vercel sites and all of them were fine.</p>
<p>Here is the full error:</p>
```Server Error

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
ReactDOMServerRenderer.render
[project]/node_modules/react-dom/cjs/react-dom-server.node.development.js (4053:17)
ReactDOMServerRenderer.read
[project]/node_modules/react-dom/cjs/react-dom-server.node.development.js (3690:29)
Object.renderToString
[project]/node_modules/react-dom/cjs/react-dom-server.node.development.js (4298:27)
Object.renderPage
[project]/node_modules/next/dist/server/render.js (596:45)
Function.getInitialProps
node_modules/next/dist/pages/_document.js (150:43)
Object.loadGetInitialProps
[project]/node_modules/next/dist/shared/lib/utils.js (69:29)
renderDocument
[project]/node_modules/next/dist/server/render.js (609:48)
Object.renderToHTML
[project]/node_modules/next/dist/server/render.js (647:34)
runMicrotasks
<anonymous>
processTicksAndRejections
internal/process/task_queues.js (97:5)
```

答:
⛳ You can find the bug step by step if you fail on one step then go to the next one:

Try to comment out the getInitialProps section.

Components in page folder should be exported as export default ComponentName.

Check all imported components, some of them may be undefined.

Check all environment variables you use.

Make production build npm run build rename .next folder to .next-prod, then npm run dev, compare those 2 folders.

Body:
I keep getting this error when running npm run dev

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
This error happened while generating the page. Any console logs will be displayed in the terminal window.

However, when I do npm run build and then npm run start the site loads fine. It is just on the dev server that it gives that error. The site also deploys to Vercel fine without any issues.

Any idea why I am getting this on the dev server and not production?

Also, I tried deleting the .next folder, also deleted node_modules, and installed all packages again, still gives an error. Deployed to different Vercel sites and all of them were fine.

Here is the full error:

Server Error

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
ReactDOMServerRenderer.render
[project]/node_modules/react-dom/cjs/react-dom-server.node.development.js (4053:17)
ReactDOMServerRenderer.read
[project]/node_modules/react-dom/cjs/react-dom-server.node.development.js (3690:29)
Object.renderToString
[project]/node_modules/react-dom/cjs/react-dom-server.node.development.js (4298:27)
Object.renderPage
[project]/node_modules/next/dist/server/render.js (596:45)
Function.getInitialProps
node_modules/next/dist/pages/_document.js (150:43)
Object.loadGetInitialProps
[project]/node_modules/next/dist/shared/lib/utils.js (69:29)
renderDocument
[project]/node_modules/next/dist/server/render.js (609:48)
Object.renderToHTML
[project]/node_modules/next/dist/server/render.js (647:34)
runMicrotasks
<anonymous>
processTicksAndRejections
internal/process/task_queues.js (97:5)


问:
Code standard (not style) enforcer for Eclipse
Is there some coding standard enforcer for use with Eclipse (a plugin or something)? I know I can use "Window > Preferences > [Language] > Code Style" to suggest conventions, but these are not enforced.

In other words, I want Coding standard violations to be marked as "Errors" and Coding style violations as "Warnings".

Thanks and regards,
Karthick S.

答: Eclipse checkstyle plugin should do this :)</p>


问:
Union type (a -> b | IO b) in Haskell?
I need to define a Union Type which the set of the type includes

a -> b OR a -> IO b

a -> b || a -> IO b

or

a -> b | IO b

foo :: (a -> b | IO b) -> IO (R a) -> IO (R b)

I tried data unionType b = b | IO b that does not work.

```<code>Not a data constructor: ‘b’parser
No quick fixes available
</code>```

Is it possible in Haskell?

答:
In Haskell, a sum type (the standard term for a disjoint union type) requires explicit "constructors" for its components, so you need to write something like:

```<code>data BarType b = BarPure b | BarIO (IO b)
</code>```

This defines a type BarType, and it also defines constructors BarPure and BarIO for use in constructing values of this type:

```<code>val1, val2 :: BarType String
val1 = BarPure "pure"
val2 = BarIO getLine
</code>```

and consuming values of this type via case-matching:

```<code>runBar :: BarType b -> IO b
runBar barb = case barb of
  BarPure s -> pure s
  BarIO act -> act
</code>```

Title: Union type (a -> b | IO b) in Haskell?

Body:
I need to define a Union Type which the set of the type includes

a -> b OR a -> IO b

a -> b || a -> IO b

or

a -> b | IO b

foo :: (a -> b | IO b) -> IO (R a) -> IO (R b)

I tried data unionType b = b | IO b that does not work.

Not a data constructor: ‘b’parser
No quick fixes available

Is it possible in Haskell?

Body:
In Haskell, a sum type (the standard term for a disjoint union type) requires explicit "constructors" for its components, so you need to write something like:

data BarType b = BarPure b | BarIO (IO b)

This defines a type BarType, and it also defines constructors BarPure and BarIO for use in constructing values of this type:

val1, val2 :: BarType String
val1 = BarPure "pure"
val2 = BarIO getLine

and consuming values of this type via case-matching:

runBar :: BarType b -> IO b
runBar barb = case barb of
  BarPure s -> pure s
  BarIO act -> act


问:
Cast, pointers, unsigned, output
 float f = 010; unsigned *pi = (unsigned *) &f; printf("%x", *pi);
I don't understand why is output 41000000.

答:
lets break this down into individual steps.

```<code> float f = 010;
</code>```

this sets f to 8.0 (!) because 010 is in octal.

lets see what gets stored in memory, using my vs debugger I see

Why, well this is how 8.0 is stored in binary floating point. See https://www.h-schmidt.net/FloatConverter/IEEE754.html for a tool which will show you the binary representation of any float. Look here for a definition of the format https://en.wikipedia.org/wiki/Single-precision_floating-point_format.

next you say

```<code>float *pf = &f;
</code>```

ok take the address of f

```<code> unsigned* pi = (unsigned*)pf;
</code>```

now treat the pointer to a float as though it were a pointer to an int. Nothing gets changed in f, we just get a pointer that thinks its pointing at an unsigned (32 bit) integer

```<code> unsigned i = *pi;
</code>```

deference that pointer. i gets loaded with the four bytes in f.

```<code>printf("%x", i);
</code>```

print that , in hex, treating those bytes as an int.

so you get 41000000 cos thats what those bytes contain.

check out this for an interesting video that shows this trick in action https://www.youtube.com/watch?v=p8u_k2LIZyo

Title: Cast, pointers, unsigned, output

Body:
lets break this down into individual steps.

 float f = 010;

this sets f to 8.0 (!) because 010 is in octal.

lets see what gets stored in memory, using my vs debugger I see

Why, well this is how 8.0 is stored in binary floating point. See https://www.h-schmidt.net/FloatConverter/IEEE754.html for a tool which will show you the binary representation of any float. Look here for a definition of the format https://en.wikipedia.org/wiki/Single-precision_floating-point_format.

next you say

float *pf = &f;

ok take the address of f

 unsigned* pi = (unsigned*)pf;

now treat the pointer to a float as though it were a pointer to an int. Nothing gets changed in f, we just get a pointer that thinks its pointing at an unsigned (32 bit) integer

 unsigned i = *pi;

deference that pointer. i gets loaded with the four bytes in f.

printf("%x", i);

print that , in hex, treating those bytes as an int.

so you get 41000000 cos thats what those bytes contain.

check out this for an interesting video that shows this trick in action https://www.youtube.com/watch?v=p8u_k2LIZyo


问:
What's wrong with Hello World in scala?
I am learning scala from docs.scala-lang.org. There is an example

```<code>object HelloYou extends App {
    if (args.size == 0)
        println("Hello, you")
    else
        println("Hello, " + args(0))
}
</code>```

After compiling with scalac I run scala HelloYou Al and get

java.lang.NullPointerException

followed by

```<code>    at java.lang.reflect.Array.getLength(Native Method)
    at scala.collection.ArrayOps$.size$extension(ArrayOps.scala:197)
    at HelloYou$.<clinit>(HelloYou.scala:2)
    at HelloYou.main(HelloYou.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code>```

What's wrong? It's my first experience of a language where Hello, World is not working...

Details

```<code>scala -version
Scala code runner version 3.1.1 -- Copyright 2002-2022, LAMP/EPFL

java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)
</code>```

答:
Accessing the command-line arguments like that is no longer supported in Scala 3:

https://docs.scala-lang.org/scala3/reference/dropped-features/delayed-init.html

Title: What's wrong with Hello World in scala?

Body:
I am learning scala from docs.scala-lang.org. There is an example

object HelloYou extends App {
    if (args.size == 0)
        println("Hello, you")
    else
        println("Hello, " + args(0))
}

After compiling with scalac I run scala HelloYou Al and get

java.lang.NullPointerException

followed by

    at java.lang.reflect.Array.getLength(Native Method)
    at scala.collection.ArrayOps$.size$extension(ArrayOps.scala:197)
    at HelloYou$.<clinit>(HelloYou.scala:2)
    at HelloYou.main(HelloYou.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

What's wrong? It's my first experience of a language where Hello, World is not working...

Details

scala -version
Scala code runner version 3.1.1 -- Copyright 2002-2022, LAMP/EPFL

java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)


答:
There are two issues: On the one hand your type must be upper-case, that is UnionType. Second, you need to define type constructors to be able to create a value of said data type. So the closest would be e.g.

```<code>data UnionType b = Left b | Right (IO b)
</code>```

Here I chose the arbitrary names Left and Right for the constructors, but you can use any you like.

If the Left/Right constructors seem familiar to you, that is because Either uses these by default, and can do exactly the same with a slightly "cheaper" type synonym:

```<code>type UnionType b = Either b (IO b)
</code>```

Of course in both cases we have to deconstruct  the type to get to the actual values of b and IO b.

EDIT: As @leftroundabout mentioned, it is not very convenient to define a data type with type constructors called Left and Right, as these constructors are already used with the built in Either.

Title: Union type (a -> b | IO b) in Haskell?

Body:
There are two issues: On the one hand your type must be upper-case, that is UnionType. Second, you need to define type constructors to be able to create a value of said data type. So the closest would be e.g.

data UnionType b = Left b | Right (IO b)

Here I chose the arbitrary names Left and Right for the constructors, but you can use any you like.

If the Left/Right constructors seem familiar to you, that is because Either uses these by default, and can do exactly the same with a slightly "cheaper" type synonym:

type UnionType b = Either b (IO b)

Of course in both cases we have to deconstruct  the type to get to the actual values of b and IO b.

EDIT: As @leftroundabout mentioned, it is not very convenient to define a data type with type constructors called Left and Right, as these constructors are already used with the built in Either.


问:
how to return an array of objects from a number?
You must create a function called arrayOfObjects that receives a number as a parameter and returns an array of objects that have a property called value that contains the value of the number and its predecessors.

example

```<code>ArrayOfObjects(3)
</code>```

should return:

```<code>[{value: 1}, {value: 2}, {value: 3}]
</code>```

my code

```<code>function arrObj(number){
  let newArray = [];
  for(let i = 0;i<number; i++){
    newArray.push(number.object)
  }
  console.log(newArray)
}

arrObj(5)
</code>```

I'm new with objects, can someone help me?

答:
To insert into newArray you need to add an object with a key of value and value of the incremental index. Here is a snippet that would do that.

function arrObj(number){
  let newArray = [];
  for(let i = 0;i<number; i++){
    // Push {value:number}
    newArray.push({value:i+1})
  }
  console.log(newArray)
}

arrObj(5)```

Body:
You must create a function called arrayOfObjects that receives a number as a parameter and returns an array of objects that have a property called value that contains the value of the number and its predecessors.

example

ArrayOfObjects(3)

should return:

[{value: 1}, {value: 2}, {value: 3}]

my code

function arrObj(number){
  let newArray = [];
  for(let i = 0;i<number; i++){
    newArray.push(number.object)
  }
  console.log(newArray)
}

arrObj(5)

I'm new with objects, can someone help me?


问:
Pulling EventLogs using powershell from a certain time period
I am trying to run a powershell script that will pull application event logs from between 2 certain times. I have the following code:

```<code>$Begin = Get-Date -Date '2/04/2022 14:36:00'
$End = Get-Date -Date '2/04/2022 14:40:00'
Get-EventLog –LogName Application -After $Begin -Before $End
</code>```

I keep receiving the following error.

```<code>Get-Date : Cannot bind parameter because parameter 'Date' is specified more
than once. To provide multiple values to parameters that can accept multiple
values, use the array syntax. For example, "-parameter value1,value2,value3".
</code>```

Does anyone know what I am doing wrong?

答:
Get-Eventlog itself is depreciated.

You can use Get-Winevent like js2010 is suggesting.
-filterhashtable is (I believe) the only way to specify a time period.

```<code>    $EventLogFilter = @{
        Logname = 'System'
        StartTime = [datetime]::Today.AddHours(-$Hours)
        EndTime = [datetime]::Today
    }
</code>```

This would give you everything that happened in the last number of $hours you specify.

This is a list of key-value pairs.

Body:
I am trying to run a powershell script that will pull application event logs from between 2 certain times. I have the following code:

$Begin = Get-Date -Date '2/04/2022 14:36:00'
$End = Get-Date -Date '2/04/2022 14:40:00'
Get-EventLog –LogName Application -After $Begin -Before $End

I keep receiving the following error.

Get-Date : Cannot bind parameter because parameter 'Date' is specified more
than once. To provide multiple values to parameters that can accept multiple
values, use the array syntax. For example, "-parameter value1,value2,value3".

Does anyone know what I am doing wrong?

Body:
Get-Eventlog itself is depreciated.

You can use Get-Winevent like js2010 is suggesting.
-filterhashtable is (I believe) the only way to specify a time period.

    $EventLogFilter = @{
        Logname = 'System'
        StartTime = [datetime]::Today.AddHours(-$Hours)
        EndTime = [datetime]::Today
    }

This would give you everything that happened in the last number of $hours you specify.

This is a list of key-value pairs.


问:
Access session variables across all controllers in .net core 5.0
I have been researching this for a minute but nothing seems to work. I want to be able to set multiple session variables at different points in time and access them across all controllers.

I have tried the below:

I created a base controller and set a public string of the variable I want to access.

```<code> public class BaseController : Controller
    {
       public string UserToken
        {
            get
            {
                string token = HttpContext.Session.GetString("SessionUserToken");
                return token == null ? null : token.ToString();
            }
            set
            {
                HttpContext.Session.SetString("SessionUserToken", value);
            }
        }
    }
</code>```

then I inherited from the base controller into my home controller

```<code> public class HomeController : BaseController
 {
    public async Task<IActionResult> Index()
    {
            string userToken = HttpContext.Session.GetString("SessionUserToken"); ;
            if (userToken == null)
              //do something
            else
             //do something else
    }

 }
</code>```

And in another controller as well

```<code> public class ProfileController: BaseController
 {
    public async Task<IActionResult> Login(LoginModel login)
    {
       Login account = await _Repository.Login(login);
          if(account.succeeded)
           {
               UserToken = account.data;
           }else{
              redirectToAction("Index", "Home");
           }

    }

 }
</code>```

Does anyone know how I can accomplish this?

答:
Looks like your re-creating the authentication system in ASP.NET

I would very much suggest that you consider using the Cookie Authentication system that's already build in. This does NOT require you to use ASP.NET Identity.

See https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0

In your startup file you would have to set

```<code>services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });
</code>```

Then in your ProfileController you can run the below code to set the authentication cookie.

```<code>var claimsIdentity = new ClaimsIdentity(new List<Claim>
{
    new Claim("SessionUserToken", account.data)
}, CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties());
</code>```

Then you can validate access either using the classic attributes like [Authorize] or you can check User.Identity.IsAuthenicated and when you need the SessionUserToken you can access User.FindFirstValue("SessionUserToken")

Body:
I have been researching this for a minute but nothing seems to work. I want to be able to set multiple session variables at different points in time and access them across all controllers.

I have tried the below:

I created a base controller and set a public string of the variable I want to access.

 public class BaseController : Controller
    {
       public string UserToken
        {
            get
            {
                string token = HttpContext.Session.GetString("SessionUserToken");
                return token == null ? null : token.ToString();
            }
            set
            {
                HttpContext.Session.SetString("SessionUserToken", value);
            }
        }
    }

then I inherited from the base controller into my home controller

 public class HomeController : BaseController
 {
    public async Task<IActionResult> Index()
    {
            string userToken = HttpContext.Session.GetString("SessionUserToken"); ;
            if (userToken == null)
              //do something
            else
             //do something else
    }

 }

And in another controller as well

 public class ProfileController: BaseController
 {
    public async Task<IActionResult> Login(LoginModel login)
    {
       Login account = await _Repository.Login(login);
          if(account.succeeded)
           {
               UserToken = account.data;
           }else{
              redirectToAction("Index", "Home");
           }

    }

 }

Does anyone know how I can accomplish this?

Body:
Looks like your re-creating the authentication system in ASP.NET

I would very much suggest that you consider using the Cookie Authentication system that's already build in. This does NOT require you to use ASP.NET Identity.

See https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0

In your startup file you would have to set

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });

Then in your ProfileController you can run the below code to set the authentication cookie.

var claimsIdentity = new ClaimsIdentity(new List<Claim>
{
    new Claim("SessionUserToken", account.data)
}, CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties());

Then you can validate access either using the classic attributes like [Authorize] or you can check User.Identity.IsAuthenicated and when you need the SessionUserToken you can access User.FindFirstValue("SessionUserToken")