问:
How to work with NavigationBar in go_router? | Flutter
I am currently struggling refactoring my routing code with go_router.

I already got some simple routes like /signin & /signup, but the problem comes in when I try to make the routing work with a BottomNavigationBar that has multiple screens. I would like to have a separate route for each of them like /home, /events & /profile.

I figured out that I somehow have to return the same widget with a different parameter to prevent the whole screen to change whenever a BottomNavigationBarItem is pressed and instead only update the part above the BottomNavigationBar which would be the screen itself.

I came up with a pretty tricky solution:

```<code>GoRoute(
  path: '/:path',
  builder: (BuildContext context, GoRouterState state) {
    final String path = state.params['path']!;

    if (path == 'signin') {
      return const SignInScreen();
    }

    if (path == 'signup') {
      return const SignUpScreen();
    }

    if (path == 'forgot-password') {
      return const ForgotPasswordScreen();
    }

    // Otherwise it has to be the ScreenWithBottomBar

    final int index = getIndexFromPath(path);

    if (index != -1) {
      return MainScreen(selectedIndex: index);
    }

    return const ErrorScreen();
  }
)
</code>```

This does not look very good and it makes it impossible to add subroutes like /profile/settings/appearance or /events/:id.

I would like to have something easy understandable like this:

```<code>GoRoute(
  path: '/signin',
  builder: (BuildContext context, GoRouterState state) {
    return const SignInScreen();
  }
),
GoRoute(
  path: '/signup',
  builder: (BuildContext context, GoRouterState state) {
    return const SignUpScreen();
  }
),
GoRoute(
  path: '/home',
  builder: (BuildContext context, GoRouterState state) {
    return const ScreenWithNavBar(selectedScreen: 1);
  }
),
GoRoute(
  path: '/events',
  builder: (BuildContext context, GoRouterState state) {
    return const ScreenWithNavBar(selectedScreen: 2);
  },
  routes: <GoRoute>[
    GoRoute(
      path: ':id',
      builder: (BuildContext context, GoRouterState state) {
        return const EventScreen();
      }
    )
  ]
)
</code>```

Is there any way to achieve the behavior?

答: This is an outstanding feature request for go_router that I hope to resolve in the coming weeks. Stay tuned.</p>

Body:
I am currently struggling refactoring my routing code with go_router.

I already got some simple routes like /signin & /signup, but the problem comes in when I try to make the routing work with a BottomNavigationBar that has multiple screens. I would like to have a separate route for each of them like /home, /events & /profile.

I figured out that I somehow have to return the same widget with a different parameter to prevent the whole screen to change whenever a BottomNavigationBarItem is pressed and instead only update the part above the BottomNavigationBar which would be the screen itself.

I came up with a pretty tricky solution:

GoRoute(
  path: '/:path',
  builder: (BuildContext context, GoRouterState state) {
    final String path = state.params['path']!;

    if (path == 'signin') {
      return const SignInScreen();
    }

    if (path == 'signup') {
      return const SignUpScreen();
    }

    if (path == 'forgot-password') {
      return const ForgotPasswordScreen();
    }

    // Otherwise it has to be the ScreenWithBottomBar

    final int index = getIndexFromPath(path);

    if (index != -1) {
      return MainScreen(selectedIndex: index);
    }

    return const ErrorScreen();
  }
)

This does not look very good and it makes it impossible to add subroutes like /profile/settings/appearance or /events/:id.

I would like to have something easy understandable like this:

GoRoute(
  path: '/signin',
  builder: (BuildContext context, GoRouterState state) {
    return const SignInScreen();
  }
),
GoRoute(
  path: '/signup',
  builder: (BuildContext context, GoRouterState state) {
    return const SignUpScreen();
  }
),
GoRoute(
  path: '/home',
  builder: (BuildContext context, GoRouterState state) {
    return const ScreenWithNavBar(selectedScreen: 1);
  }
),
GoRoute(
  path: '/events',
  builder: (BuildContext context, GoRouterState state) {
    return const ScreenWithNavBar(selectedScreen: 2);
  },
  routes: <GoRoute>[
    GoRoute(
      path: ':id',
      builder: (BuildContext context, GoRouterState state) {
        return const EventScreen();
      }
    )
  ]
)

Is there any way to achieve the behavior?


来源: stackexchange

问:
inline style vs className in Componet context
Hello I try to understand when it's necessary to use inline style instead className in this case. I take a long time to solve my problem of translation. At the beginning I want to translate component by using classNameand that's don't work. it's very weird because in my point of view there is no reason that's happen. So I figure there is something wrong in my code, but what... I have not yet found. So I finish trying to translate by using a inline style. Miracle, that's work fine.

My question is why ?

Work well

export function Content() {
  return (

        <Test/>

)
}
```
<p>don't work</p>
<pre class="lang-js prettyprint-override"><code>export function Content() {
  return (
    <div className={container_content}>
        <Test/>
        <Footer />
        </div>
        )
}
</code>```

css

.container_content {
    transform: translateY(100px);
}

```
<p>Nota bene :
The problem is not from the method. To use className in my <code>jsx</code>
must be like that:</p>
<pre class="lang-js prettyprint-override"><code>import { container_content } from "./test.module.css";

</code>```

and next

```

So this part of code is good, the issue seems to come from elsewhere...

答:
What's happening is that when you use the inline style you are passing an object that includes the styling for that component. When you use the className you need to pass in a string for the class you want to use. Right now you are passing a variable name. Either of these works:

```<code><div className={"container_content"}>
</code>```

OR

```<code><div className="container_content">
</code>```

If you think about it in regular html you would do

```<code><div class="container_content">
</code>```

EDIT: Given your updated question, you should just import the css file with:

```<code>import "./test.module.css"
</code>```

and then use the solution I mentioned.

ContentLicense: CC BY-SA 4.0

Body:
Hello I try to understand when it's necessary to use inline style instead className in this case. I take a long time to solve my problem of translation. At the beginning I want to translate component by using classNameand that's don't work. it's very weird because in my point of view there is no reason that's happen. So I figure there is something wrong in my code, but what... I have not yet found. So I finish trying to translate by using a inline style. Miracle, that's work fine.

My question is why ?

Work well

export function Content() {
  return (

        <Test/>

)
}

don't work

export function Content() {
  return (

        <Test/>

        )
}

css

.container_content {
    transform: translateY(100px);
}

Nota bene :
The problem is not from the method. To use className in my jsx
must be like that:

import { container_content } from "./test.module.css";

and next

So this part of code is good, the issue seems to come from elsewhere...

Body:
What's happening is that when you use the inline style you are passing an object that includes the styling for that component. When you use the className you need to pass in a string for the class you want to use. Right now you are passing a variable name. Either of these works:

<div className={"container_content"}>

OR

<div className="container_content">

If you think about it in regular html you would do

<div class="container_content">

EDIT: Given your updated question, you should just import the css file with:

import "./test.module.css"

and then use the solution I mentioned.


问:
Convert each element in a dataframe which has comma separated values to list in R
I have a column in R dataframe , last column in the picture, it has comma separated values, it is char form. I want to convert it in a list.
For example , i want
df2$Elementsnew[1]=

```<code>[[1]]
[1]0000
[[2]]
[2]0010
</code>```

I have tried the following:

```<code>    for(i in 1:nrow(df2))
    {
    enter code here
df2$Elementsnew[i] <- as.list(df2$Elementsnew[i],sep=",")

    }
</code>```

But it does not work.
Please help

答:
Would this work?</p>
```<code>df <- data.frame(elementsnew = c("0000,0010", "1000,1001"))

my.l <- df$elementsnew |>
    stringr::str_split(pattern = ",") |>
    list()
</code>```

Body:
I have a column in R dataframe , last column in the picture, it has comma separated values, it is char form. I want to convert it in a list.
For example , i want
df2$Elementsnew[1]=

[[1]]
[1]0000
[[2]]
[2]0010

I have tried the following:

    for(i in 1:nrow(df2))
    {
    enter code here
df2$Elementsnew[i] <- as.list(df2$Elementsnew[i],sep=",")

    }

But it does not work.
Please help

Body:
Would this work?

df <- data.frame(elementsnew = c("0000,0010", "1000,1001"))

my.l <- df$elementsnew |>
    stringr::str_split(pattern = ",") |>
    list()


问:
javascript sum values from two different functions
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

```<code>      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }
</code>```

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

```<code>function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

</code>```

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

```<code>      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }
</code>```

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

```<code>function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }
</code>```

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

答:
This is NOT the answer you seek but your issues are too large to put in as a bunch of comments so I commented the code presented in the question:

```<code>// you never pass this any value in qty
// this does nothing so it is the same as: return qty;
function showHourlyRate(qty) {
    var oneFunc = qty
    console.log(oneFunc) //result is 5.00
    return oneFunc
  };
   // you never pass this any value
  function showMileageRate(qty) {
    var twoFunc = qty
    console.log(twoFunc) //result is 20.00
    return twoFunc
  };

  // you never pass values to your functions so no number is returned
  // This is the same as
  // var addTogether = undefined + undefined;
  function combinedTotal(){
    var addTogether = showHourlyRate() + showMileageRate();
    alert(addTogether); // gives NAN
    return addTogether;
  }
</code>```

console.log("What:", undefined + undefined); // NaN

function getHourlyRate() {
  const sheet = SpreadsheetApp
    .openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI")
    .getSheetByName("Working Hours");
  const data = sheet
    .getRange(2, 1, sheet.getLastRow() - 1, 8)
    .getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");
  // get into a habit of positive rather than negative conditions
  //let hasNoMatch = filteredData.length === 0;
  // force a boolean on length
  let hasMatch = !!filteredData.length;
  let fixedReduce = filteredData.reduce((subtotal, r) => subtotal + r[1], 0)
    .toFixed(2);

  // return hasNoMatch ? "No Match" : fixedReduce;
  return hasMatch ? fixedReduce : "No Match";
}

// never used, commented it out
// var arrayOfArrays;

function afterSidebarLoads() {
  // you seem to want to call the function?? how you don't consume the return is odd
  // you show it before you GET it? odd that these do that
  google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
  google.script.run.withSuccessHandler(showMileageRate).getMileageRate();
  // you call THIS "afterSidebarLoads" function by adding another event handler that calls this function?
  /// makes no sense to add an event handler inside the function the event handler uses
  document.addEventListener("DOMContentLoaded", afterSidebarLoads);

}
// this passes in "qty" but never uses it?
// as it stands "hourlyRate" is undefined
function showHourlyRate(qty) {
  var oneFunc = hourlyRate
  // var ghjJhg = oneFunc.toFixed(2)
  // console.log(oneFunc) //result is 0.55
  return oneFunc
};
// you just return what was passed in after assigning it to a variable?
// get into a habit of putting semi-colons on Example:
//  var twoFunc = mileageRate;
function showMileageRate(mileageRate) {
  var twoFunc = mileageRate
  // var ghjJhg = oneFunc.toFixed(2)
  // console.log(twoFunc) //result is 22.64
  return twoFunc
};

// does nothing and is not called here
function combinedTotal() {}```

Body:
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

Body:
This is NOT the answer you seek but your issues are too large to put in as a bunch of comments so I commented the code presented in the question:

// you never pass this any value in qty
// this does nothing so it is the same as: return qty;
function showHourlyRate(qty) {
    var oneFunc = qty
    console.log(oneFunc) //result is 5.00
    return oneFunc
  };
   // you never pass this any value
  function showMileageRate(qty) {
    var twoFunc = qty
    console.log(twoFunc) //result is 20.00
    return twoFunc
  };

  // you never pass values to your functions so no number is returned
  // This is the same as
  // var addTogether = undefined + undefined;
  function combinedTotal(){
    var addTogether = showHourlyRate() + showMileageRate();
    alert(addTogether); // gives NAN
    return addTogether;
  }

console.log("What:", undefined + undefined); // NaN

function getHourlyRate() {
  const sheet = SpreadsheetApp
    .openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI")
    .getSheetByName("Working Hours");
  const data = sheet
    .getRange(2, 1, sheet.getLastRow() - 1, 8)
    .getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");
  // get into a habit of positive rather than negative conditions
  //let hasNoMatch = filteredData.length === 0;
  // force a boolean on length
  let hasMatch = !!filteredData.length;
  let fixedReduce = filteredData.reduce((subtotal, r) => subtotal + r[1], 0)
    .toFixed(2);

  // return hasNoMatch ? "No Match" : fixedReduce;
  return hasMatch ? fixedReduce : "No Match";
}

// never used, commented it out
// var arrayOfArrays;

function afterSidebarLoads() {
  // you seem to want to call the function?? how you don't consume the return is odd
  // you show it before you GET it? odd that these do that
  google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
  google.script.run.withSuccessHandler(showMileageRate).getMileageRate();
  // you call THIS "afterSidebarLoads" function by adding another event handler that calls this function?
  /// makes no sense to add an event handler inside the function the event handler uses
  document.addEventListener("DOMContentLoaded", afterSidebarLoads);

}
// this passes in "qty" but never uses it?
// as it stands "hourlyRate" is undefined
function showHourlyRate(qty) {
  var oneFunc = hourlyRate
  // var ghjJhg = oneFunc.toFixed(2)
  // console.log(oneFunc) //result is 0.55
  return oneFunc
};
// you just return what was passed in after assigning it to a variable?
// get into a habit of putting semi-colons on Example:
//  var twoFunc = mileageRate;
function showMileageRate(mileageRate) {
  var twoFunc = mileageRate
  // var ghjJhg = oneFunc.toFixed(2)
  // console.log(twoFunc) //result is 22.64
  return twoFunc
};

// does nothing and is not called here
function combinedTotal() {}


问:
MVC3 Razor and Javascript - lots of syntax errors in green
I am starting to notice problems when I try and code my javascript and use functions that are in my viewmodel. Things like this:

```<code>    case 37:
        @if (Model.GoLeft)
        {
</code>```

Here I get a syntax error and the words "expected constant" for Model. Is there some solution to this? Do I need to upgrade something so it works?

I checked around on stackoverflow. Someone else suggested that I should separate my js but that doesn't help me as for example in this case where I want the keypress to do something if on a certain type of page where the Model allows it. If the js is in another file I can't code this way.

thanks

答: your approach is just wrong. Dont generate JS code in views by ifs. You defintely should keep your JS separetly (so that browser can efectively cache and reuse it). If you need to change behaviour of client-side code according to model values, do that by generation only some king of "flags" (JS have multiple ways to do that, i am not expert in JS - for example global variable works always, but there are more elegant and recommended ways) and in your client-side method test for their presence and fork your code by that.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am starting to notice problems when I try and code my javascript and use functions that are in my viewmodel. Things like this:

    case 37:
        @if (Model.GoLeft)
        {

Here I get a syntax error and the words "expected constant" for Model. Is there some solution to this? Do I need to upgrade something so it works?

I checked around on stackoverflow. Someone else suggested that I should separate my js but that doesn't help me as for example in this case where I want the keypress to do something if on a certain type of page where the Model allows it. If the js is in another file I can't code this way.

thanks


问:
How to include context variables in AWS API-EventBridge Integration Detail body
I have an ApiGatewayv2 EventBridge-PutEvents Integration running. The POST body is sent into event bridge as the event Detail.

The Integration request parameters are as below:

```<code>{
    'Source': 'com.me.api',
    'DetailType': 'ApiEvent',
    'Detail': $request.body,
    'EventBusName': BUS_NAME,
}
</code>```

If I post {"foo": "bar"} to the API endpoint, I end up with an event in my bus with {"foo": "bar"} as the Detail. So far, all straightforward.

I have also enabled an authorizer on the API GW and I want to pass the context from that authorizer into the event Detail as well.

I'm testing with an IAM authorizer for now, but would like to use Cognito.

I can update the request parameters to change the DetailType to $context.identity.caller and I get my Access Key in the DetailType of the Event.

This isn't what I want, but it shows that I can access these context variables in my integration.

What I want is for that to be in the Detail though - not the DetailType.

So, when I POST {"foo": "bar"} to my API GW I get an event with Detail:

```<code>{
    "body": {"foo":, "bar"},
    "auth": {"user": "AAA1111ACCESSKEY"}
}
</code>```

But, I can't use anything other than $request.body as the Detail value in the Integration's request parameters.

If I use a Detail like {"body": $request.body} I get an error on saving the integration - Invalid selection expression specified: Validation Result: warnings : [], errors : [Invalid source: {"body": $request.body} specified for destination: Detail]

And, I've tried that with stringified {"body": $request.body} as well.

How can I wrap the POST data in a key like "body" within the event's Detail, and add key/values from the context variables I get from the authorizer.

Or, some other way to inject the authorizer context into my Event. Should I just give up and use a lambda to access the ApiGw context and run PutEvent? Seems defeatist!

答:
This SAM template shows how to do what I wanted using an AWS REST API https://github.com/aws-samples/client-event-sample/blob/6d58777382da148a3ccc1314b0bdf21c46b6378f/template.yaml#L196

The rest api endpoint comes with the additional benefit that we can validate the inbound event json

Body:
I have an ApiGatewayv2 EventBridge-PutEvents Integration running. The POST body is sent into event bridge as the event Detail.

The Integration request parameters are as below:

{
    'Source': 'com.me.api',
    'DetailType': 'ApiEvent',
    'Detail': $request.body,
    'EventBusName': BUS_NAME,
}

If I post {"foo": "bar"} to the API endpoint, I end up with an event in my bus with {"foo": "bar"} as the Detail. So far, all straightforward.

I have also enabled an authorizer on the API GW and I want to pass the context from that authorizer into the event Detail as well.

I'm testing with an IAM authorizer for now, but would like to use Cognito.

I can update the request parameters to change the DetailType to $context.identity.caller and I get my Access Key in the DetailType of the Event.

This isn't what I want, but it shows that I can access these context variables in my integration.

What I want is for that to be in the Detail though - not the DetailType.

So, when I POST {"foo": "bar"} to my API GW I get an event with Detail:

{
    "body": {"foo":, "bar"},
    "auth": {"user": "AAA1111ACCESSKEY"}
}

But, I can't use anything other than $request.body as the Detail value in the Integration's request parameters.

If I use a Detail like {"body": $request.body} I get an error on saving the integration - Invalid selection expression specified: Validation Result: warnings : [], errors : [Invalid source: {"body": $request.body} specified for destination: Detail]

And, I've tried that with stringified {"body": $request.body} as well.

How can I wrap the POST data in a key like "body" within the event's Detail, and add key/values from the context variables I get from the authorizer.

Or, some other way to inject the authorizer context into my Event. Should I just give up and use a lambda to access the ApiGw context and run PutEvent? Seems defeatist!


问:
How to decode a property with type of JSON dictionary in Swift [45] decodable protocol
Let's say I have Customer data type which contains a metadata property that can contains any JSON dictionary in the customer object

```<code>struct Customer {
  let id: String
  let email: String
  let metadata: [String: Any]
}
</code>```

```<code>{
  "object": "customer",
  "id": "4yq6txdpfadhbaqnwp3",
  "email": "john.doe@example.com",
  "metadata": {
    "link_id": "linked-id",
    "buy_count": 4
  }
}
</code>```

The metadata property can be any arbitrary JSON map object.

Before I can cast the property from a deserialized JSON from NSJSONDeserialization but with the new Swift 4 Decodable protocol, I still can't think of a way to do that.

Do anyone know how to achieve this in Swift 4 with Decodable protocol?

答:
I used some of the answers on this topic to get the simplest solution possible for me. My problem is that I was receiving a [String: Any] type dictionary, but I could very well work with a [String: String] transforming every other Any value in String. So this is my solution:

```<code>struct MetadataType: Codable {
    let value: String?

    private init(_ value: String?) {
        self.value = value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        if let decodedValue = try? container.decode(Int.self) {
            self.init(String(decodedValue))
        } else if let decodedValue = try? container.decode(Double.self) {
            self.init(String(decodedValue))
        } else if let decodedValue = try? container.decode(Bool.self) {
            self.init(String(decodedValue))
        } else if let decodedValue = try? container.decode(String.self) {
            self.init(decodedValue)
        } else {
            self.init(nil)
        }
    }
}
</code>```

And when declaring my dictionary, I use

```<code>let userInfo: [String: MetadataType]
</code>```

Body:
Let's say I have Customer data type which contains a metadata property that can contains any JSON dictionary in the customer object

struct Customer {
  let id: String
  let email: String
  let metadata: [String: Any]
}

{
  "object": "customer",
  "id": "4yq6txdpfadhbaqnwp3",
  "email": "john.doe@example.com",
  "metadata": {
    "link_id": "linked-id",
    "buy_count": 4
  }
}

The metadata property can be any arbitrary JSON map object.

Before I can cast the property from a deserialized JSON from NSJSONDeserialization but with the new Swift 4 Decodable protocol, I still can't think of a way to do that.

Do anyone know how to achieve this in Swift 4 with Decodable protocol?

Body:
I used some of the answers on this topic to get the simplest solution possible for me. My problem is that I was receiving a [String: Any] type dictionary, but I could very well work with a [String: String] transforming every other Any value in String. So this is my solution:

struct MetadataType: Codable {
    let value: String?

    private init(_ value: String?) {
        self.value = value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        if let decodedValue = try? container.decode(Int.self) {
            self.init(String(decodedValue))
        } else if let decodedValue = try? container.decode(Double.self) {
            self.init(String(decodedValue))
        } else if let decodedValue = try? container.decode(Bool.self) {
            self.init(String(decodedValue))
        } else if let decodedValue = try? container.decode(String.self) {
            self.init(decodedValue)
        } else {
            self.init(nil)
        }
    }
}

And when declaring my dictionary, I use

let userInfo: [String: MetadataType]


问:
Open street map data - electoral wards
Im struggling to find the correct key and value to plot electoral wards in R's osmdata.

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

ward <- getbb("Sheffield United Kingdom") %>%
  opq() %>%
  add_osm_feature(boundary="political", political_division="ward") %>%
 osmdata_sf()
</code>```

key is specified as an input typically of the nature "highway" and value would in such case be motorway but the docs don't clarify what can be used in this use case.

答:
The issue is with passing the key and value to add_osm_feature() function

library(osmdata)
library(tidyverse)
library(sf)

ward <- getbb("Sheffield United Kingdom") %>%
  opq() %>%
  add_osm_feature(key = "boundary", value ="political") %>%
  add_osm_feature(key = "political_division", value ="ward") %>%
  osmdata_sf()

sheffield <- getbb("Sheffield United Kingdom") %>%
  opq() %>%
  add_osm_feature(key = "boundary", value ="administrative") %>%
  osmdata_sf()

d8 <- st_as_sf(sheffield$osm_multipolygons) |>
  filter(admin_level == 8 & name == "Sheffield") |>
  select(osm_id, name, geometry)

plot(d8$geometry, col = "gray")
```
<p>The objects returned with osmdata are long lists, consisting of <code>osm_points</code>, <code>osm_lines</code>, <code>osm_polygons</code> (created from closed lines) and <code>osm_multipolygons</code> (created from osm relations), therefore we can suspect wards in <code>osm_polygon</code> and <code>osm_multipolygon</code>. You can <code>st_cast()</code> multipolygons to polygons and then merge both features.</p>
```plot(st_as_sf(ward$osm_multipolygons$geometry), add=TRUE, col = "yellow")
plot(st_as_sf(ward$osm_polygons$geometry), add=TRUE, col = "lightyellow")
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Title: Open street map data - electoral wards

Body:
Im struggling to find the correct key and value to plot electoral wards in R's osmdata.

library(tidyverse)
library(osmdata)

ward <- getbb("Sheffield United Kingdom") %>%
  opq() %>%
  add_osm_feature(boundary="political", political_division="ward") %>%
 osmdata_sf()

key is specified as an input typically of the nature "highway" and value would in such case be motorway but the docs don't clarify what can be used in this use case.

Body:
The issue is with passing the key and value to add_osm_feature() function

library(osmdata)
library(tidyverse)
library(sf)

ward <- getbb("Sheffield United Kingdom") %>%
  opq() %>%
  add_osm_feature(key = "boundary", value ="political") %>%
  add_osm_feature(key = "political_division", value ="ward") %>%
  osmdata_sf()

sheffield <- getbb("Sheffield United Kingdom") %>%
  opq() %>%
  add_osm_feature(key = "boundary", value ="administrative") %>%
  osmdata_sf()

d8 <- st_as_sf(sheffield$osm_multipolygons) |>
  filter(admin_level == 8 & name == "Sheffield") |>
  select(osm_id, name, geometry)

plot(d8$geometry, col = "gray")

The objects returned with osmdata are long lists, consisting of osm_points, osm_lines, osm_polygons (created from closed lines) and osm_multipolygons (created from osm relations), therefore we can suspect wards in osm_polygon and osm_multipolygon. You can st_cast() multipolygons to polygons and then merge both features.

plot(st_as_sf(ward$osm_multipolygons$geometry), add=TRUE, col = "yellow")
plot(st_as_sf(ward$osm_polygons$geometry), add=TRUE, col = "lightyellow")

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
IntelliJ generates java test class in non-standard location
I have a Spring Boot app using maven as the build tool and I'm working from within IntelliJ IDEA. When I have IntelliJ generate a test from an existing class (Ctl+ Shift+ T), IntelliJ puts that test class into the corresponding package under directory src/test, followed by the package name, rather than the maven standard src/test/java.

The source class from which I’m asking IntelliJ to generate a test class is under src/main/java, the standard maven source directory. So I would expect the generated test to end up by default under the corresponding src/test/java location, since that’s the standard maven test directory.

It seems strange to me that IntelliJ would put tests directly under src/test rather than the standard src/test/java. Is there some setting in IntelliJ to specify where the generated classes go?

答:
I ran some tests and it seems the problem arises when you don't already have that test directory location, src/test/java, in your project layout.

If you don't have it already you can create it via the IntelliJ Project Structure panel (Ctrl+Alt+Shift+S, then click Modules).

I do notice that if you open an existing maven project into IntelliJ (File > Open) that already has that standard test library directory in its layout structure, IntelliJ does actually seem to know to put its generated test classes into that directory.


问:
issue in using dynamic grid link button for scriptManager.RegisterPostBackControl (control) as this has to be declared at page_load
I was trying to download csv file on grid's dynamically created link button.
I was facing issue while downloading csv in asp.net.
Exception : Sys.WebForms.PageRequestManagerParserErrorException
This Exception is resolved by using code:

```<code>ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.grouplnkbutton);
</code>```

at page_load event,but this.grouplnkbutton (dynamically created link button i.e. grouplnkbutton control is not available at page_load event).

how can i use linkbutton with scriptmanager at page_load event.

Code:

```<code>  protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        scriptManager.RegisterPostBackControl(this.grouplnkbutton);
        //codes
     }

 protected void hlGroupName_Click(object sender, EventArgs e)
    {
        try`enter code here`
        {
            Response.ClearHeaders();
            Response.ClearContent();
            grouplnkbutton = sender as LinkButton;
            string linkBtnValue = grouplnkbutton.CommandArgument;
            GridDataItem item = grouplnkbutton.NamingContainer as GridDataItem;
            ExportToCSV exportToCSV = new ExportToCSV();
            StringBuilder csv = new StringBuilder();

            DataSet gridData = new DataSet();

            int scheduleId = Convert.ToInt32(((HiddenField)item.FindControl("hidID")).Value);
            csv = exportToCSV.ExportScheduleDataToCSV(scheduleId);

            Response.Buffer = true;

            Response.Clear();
            Response.ContentType = "text/csv";
            Response.AddHeader("content-disposition", "attachment;filename=perfscheduleReport.csv");
            //Response.Charset = "";
            Response.Output.Write(csv.ToString());
            //Response.Write(csv.ToString());
            Response.Flush();
            //Response.End();

        }
</code>```

Thanks for solution.
markup code

```<code> <telerik:RadGrid ID="PerfGrid" GridLines="None" runat="server" CssClass="BorderGrid" OnItemDataBound="PerfGrid_ItemDataBound" OnItemCommand ="PerfGrid_ItemCommand"
                                                                                Skin="Default" Width="100%" PageSize="100" PagerStyle-PageSizeLabelText="Records Per Page" AllowFilteringByColumn="true" OnNeedDataSource="PerfGrid_NeedDataSource" OnPageIndexChanged="PerfGrid_PageIndexChanged">

                                                                                <ClientSettings EnableRowHoverStyle="true">
                                                                                <Resizing AllowColumnResize="True" AllowRowResize="false" ResizeGridOnColumnResize="false"
                                                                                ClipCellContentOnResize="true" EnableRealTimeResize="false" AllowResizeToFit="true" />
                                                                                </ClientSettings>
                                                                                <MasterTableView CommandItemDisplay="None" HorizontalAlign="NotSet" AllowPaging="false" AutoGenerateColumns="False" AllowSorting="true" AllowFilteringByColumn="True">

                                                                                <HeaderStyle CssClass="GridHeader" Font-Bold="true"></HeaderStyle>
                                                                                <ItemStyle BackColor="White" CssClass="text2" HorizontalAlign="Left" />
                                                                                <AlternatingItemStyle BackColor="#E6EEF8" CssClass="text2" HorizontalAlign="Left" />
                                                                                <%--<PagerStyle AlwaysVisible="true" Mode="NextPrevAndNumeric" />--%>
                                                                                <Columns>
                                                                                <telerik:GridBoundColumn DataField="ScheduleId" Display="false" ReadOnly="true" HeaderText="ID" AllowFiltering="false" HeaderStyle-Width="10px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridTemplateColumn HeaderText="Select" HeaderStyle-Width="15px" AllowFiltering="false">
                                                                                <ItemTemplate>
                                                                                <asp:CheckBox ID="CheckSelect" runat="server"></asp:CheckBox>
                                                                                </ItemTemplate>
                                                                                </telerik:GridTemplateColumn>
                                                                                <telerik:GridTemplateColumn DataField="GroupingName" ReadOnly="true" HeaderText="Group Name" SortExpression="GroupName" HeaderStyle-Width="20px">
                                                                                <ItemTemplate>

                                                                                <asp:LinkButton ID="hlGroupName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "GroupingName") %>' OnClick="hlGroupName_Click"></asp:LinkButton>  <%--CommandName="Export"--%>

                                                                                <%--<asp:HyperLink ID="hlTestCase" CommandName="Edit1" runat="server" Text='<%# Container.DataItem("TestDescription") %>'--%>
                                                                                Target="_self"></asp:HyperLink>--%>
                                                                                <asp:HiddenField ID="hidID" runat="server" Value='<%# CheckNull(DataBinder.Eval(Container.DataItem, "ScheduleId") , false)%>' />
                                                                                <%--Value='<%# Container.DataItem("Id") %>' Value='<%# DataBinder.Eval(Container.DataItem, "Id") %>--%>
                                                                                </ItemTemplate>
                                                                                </telerik:GridTemplateColumn>
                                                                                <telerik:GridBoundColumn SortExpression="TestDescription" DataField="TestDescription" ReadOnly="true" HeaderText="Test Cases" HeaderStyle-Width="30px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="ServerIP" DataField="ServerIP" ReadOnly="true" HeaderText="Server IP" HeaderStyle-Width="20px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="LoadNoOfUsersTobeSimulated" DataField="LoadNoOfUsersTobeSimulated" HeaderText="Users Load" ReadOnly="true" HeaderStyle-Width="12px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="StartTime" DataField="StartTime" HeaderText="Start Time" ReadOnly="true" HeaderStyle-Width="25px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="EndTime" DataField="EndTime" HeaderText="End Time" ReadOnly="true" HeaderStyle-Width="25px">
                                                                                </telerik:GridBoundColumn>
                                                                                </Columns>
                                                                                </MasterTableView>
                                                                                </telerik:RadGrid>
</code>```

in this lnkbtn - ID -"hlGroupname" onclick event i want to downalod csv
But getting Exception:Sys.WebForms.PageRequestManagerParserErrorException
resolved Exception using :

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        ScriptManager.RegisterPostBackControl(this.PerfGrid);
//codes
}
</code>```

I am using Scriptmanager as my grid is under updatepanel.
Here PerfGrid is telerikGrid control. Instead of grid control i want to use dynamically created grid link button. And onclick event of lnkbutton i want to download csv.

答:
Hum, your code looks fine, but why the need for the register script?

dump that code you have in the load event, I don't see a need for it??

You not posted your markup, but say a grid like this:

```<code>        <asp:GridView ID="GridView1" runat="server" CssClass="table" AutoGenerateColumns="False" DataKeyNames="ID">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"  />
                <asp:BoundField DataField="ProjectName" HeaderText="ProjectName" />
                <asp:BoundField DataField="ProjectDate" HeaderText="ProjectDate"  />

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton runat="server" OnClick="LinkButton1_Click">My Link</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
</code>```

Your button code then as you have looks fine.

I don't (so far) on what you posted see why any need for register script or that button event needs that code. You can just wire up the click event as you have, nothing more need be done.

So, in above, the linkbutton should be just fine. Check and REMOVE the post-back URL setting for that link button - that might be your issue (but, you not posted at least the markup you have for the LinkButton.

It should only require the click even code you have - no other settings such as post-back URL is required for that button click event to work. In fact, it not at all clear why you using a LinkButton as opposed to say a button? (I see no need for a link button ).

So, no real reason for the register script stuff - remove it.

And note how I don't have to include the PK row "ID" in the markup, or even a hidden field. The datakeys setting is just for that reason (and it nice from a secuirty point of view - I don't have to render the PK row ID has hiddefield or anything.

Hence this code can get the PK id

```<code>    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        LinkButton lBtn = sender as LinkButton;
        GridViewRow gRow = lBtn.NamingContainer as GridViewRow;
        // get row click index with gRow.RowIndex
        int? pkID = GridView1.DataKeys[gRow.RowIndex]["ID"] as int?;
</code>```

And my code to fill the gv was this:

```<code>using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Project"L, conn))
{
conn.Open();

GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
</code>```

Now, of course if you using the row data bound for ANY thing at all? Then don't bind the GV to the reader, but use this:

```<code>conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader();
GridView1.DataSource = rstData;
GridView1.DataBind();
</code>```

Body:
I was trying to download csv file on grid's dynamically created link button.
I was facing issue while downloading csv in asp.net.
Exception : Sys.WebForms.PageRequestManagerParserErrorException
This Exception is resolved by using code:

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.grouplnkbutton);

at page_load event,but this.grouplnkbutton (dynamically created link button i.e. grouplnkbutton control is not available at page_load event).

how can i use linkbutton with scriptmanager at page_load event.

Code:

  protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        scriptManager.RegisterPostBackControl(this.grouplnkbutton);
        //codes
     }

 protected void hlGroupName_Click(object sender, EventArgs e)
    {
        try`enter code here`
        {
            Response.ClearHeaders();
            Response.ClearContent();
            grouplnkbutton = sender as LinkButton;
            string linkBtnValue = grouplnkbutton.CommandArgument;
            GridDataItem item = grouplnkbutton.NamingContainer as GridDataItem;
            ExportToCSV exportToCSV = new ExportToCSV();
            StringBuilder csv = new StringBuilder();

            DataSet gridData = new DataSet();

            int scheduleId = Convert.ToInt32(((HiddenField)item.FindControl("hidID")).Value);
            csv = exportToCSV.ExportScheduleDataToCSV(scheduleId);

            Response.Buffer = true;

            Response.Clear();
            Response.ContentType = "text/csv";
            Response.AddHeader("content-disposition", "attachment;filename=perfscheduleReport.csv");
            //Response.Charset = "";
            Response.Output.Write(csv.ToString());
            //Response.Write(csv.ToString());
            Response.Flush();
            //Response.End();

        }

Thanks for solution.
markup code

 <telerik:RadGrid ID="PerfGrid" GridLines="None" runat="server" CssClass="BorderGrid" OnItemDataBound="PerfGrid_ItemDataBound" OnItemCommand ="PerfGrid_ItemCommand"
                                                                                Skin="Default" Width="100%" PageSize="100" PagerStyle-PageSizeLabelText="Records Per Page" AllowFilteringByColumn="true" OnNeedDataSource="PerfGrid_NeedDataSource" OnPageIndexChanged="PerfGrid_PageIndexChanged">

                                                                                <ClientSettings EnableRowHoverStyle="true">
                                                                                <Resizing AllowColumnResize="True" AllowRowResize="false" ResizeGridOnColumnResize="false"
                                                                                ClipCellContentOnResize="true" EnableRealTimeResize="false" AllowResizeToFit="true" />
                                                                                </ClientSettings>
                                                                                <MasterTableView CommandItemDisplay="None" HorizontalAlign="NotSet" AllowPaging="false" AutoGenerateColumns="False" AllowSorting="true" AllowFilteringByColumn="True">

                                                                                <HeaderStyle CssClass="GridHeader" Font-Bold="true"></HeaderStyle>
                                                                                <ItemStyle BackColor="White" CssClass="text2" HorizontalAlign="Left" />
                                                                                <AlternatingItemStyle BackColor="#E6EEF8" CssClass="text2" HorizontalAlign="Left" />
                                                                                <%--<PagerStyle AlwaysVisible="true" Mode="NextPrevAndNumeric" />--%>
                                                                                <Columns>
                                                                                <telerik:GridBoundColumn DataField="ScheduleId" Display="false" ReadOnly="true" HeaderText="ID" AllowFiltering="false" HeaderStyle-Width="10px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridTemplateColumn HeaderText="Select" HeaderStyle-Width="15px" AllowFiltering="false">
                                                                                <ItemTemplate>
                                                                                <asp:CheckBox ID="CheckSelect" runat="server"></asp:CheckBox>
                                                                                </ItemTemplate>
                                                                                </telerik:GridTemplateColumn>
                                                                                <telerik:GridTemplateColumn DataField="GroupingName" ReadOnly="true" HeaderText="Group Name" SortExpression="GroupName" HeaderStyle-Width="20px">
                                                                                <ItemTemplate>

                                                                                <asp:LinkButton ID="hlGroupName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "GroupingName") %>' OnClick="hlGroupName_Click"></asp:LinkButton>  <%--CommandName="Export"--%>

                                                                                <%--<asp:HyperLink ID="hlTestCase" CommandName="Edit1" runat="server" Text='<%# Container.DataItem("TestDescription") %>'--%>
                                                                                Target="_self"></asp:HyperLink>--%>
                                                                                <asp:HiddenField ID="hidID" runat="server" Value='<%# CheckNull(DataBinder.Eval(Container.DataItem, "ScheduleId") , false)%>' />
                                                                                <%--Value='<%# Container.DataItem("Id") %>' Value='<%# DataBinder.Eval(Container.DataItem, "Id") %>--%>
                                                                                </ItemTemplate>
                                                                                </telerik:GridTemplateColumn>
                                                                                <telerik:GridBoundColumn SortExpression="TestDescription" DataField="TestDescription" ReadOnly="true" HeaderText="Test Cases" HeaderStyle-Width="30px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="ServerIP" DataField="ServerIP" ReadOnly="true" HeaderText="Server IP" HeaderStyle-Width="20px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="LoadNoOfUsersTobeSimulated" DataField="LoadNoOfUsersTobeSimulated" HeaderText="Users Load" ReadOnly="true" HeaderStyle-Width="12px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="StartTime" DataField="StartTime" HeaderText="Start Time" ReadOnly="true" HeaderStyle-Width="25px">
                                                                                </telerik:GridBoundColumn>
                                                                                <telerik:GridBoundColumn SortExpression="EndTime" DataField="EndTime" HeaderText="End Time" ReadOnly="true" HeaderStyle-Width="25px">
                                                                                </telerik:GridBoundColumn>
                                                                                </Columns>
                                                                                </MasterTableView>
                                                                                </telerik:RadGrid>

in this lnkbtn - ID -"hlGroupname" onclick event i want to downalod csv
But getting Exception:Sys.WebForms.PageRequestManagerParserErrorException
resolved Exception using :

protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        ScriptManager.RegisterPostBackControl(this.PerfGrid);
//codes
}

I am using Scriptmanager as my grid is under updatepanel.
Here PerfGrid is telerikGrid control. Instead of grid control i want to use dynamically created grid link button. And onclick event of lnkbutton i want to download csv.

Body:
Hum, your code looks fine, but why the need for the register script?

dump that code you have in the load event, I don't see a need for it??

You not posted your markup, but say a grid like this:

        <asp:GridView ID="GridView1" runat="server" CssClass="table" AutoGenerateColumns="False" DataKeyNames="ID">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"  />
                <asp:BoundField DataField="ProjectName" HeaderText="ProjectName" />
                <asp:BoundField DataField="ProjectDate" HeaderText="ProjectDate"  />

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton runat="server" OnClick="LinkButton1_Click">My Link</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Your button code then as you have looks fine.

I don't (so far) on what you posted see why any need for register script or that button event needs that code. You can just wire up the click event as you have, nothing more need be done.

So, in above, the linkbutton should be just fine. Check and REMOVE the post-back URL setting for that link button - that might be your issue (but, you not posted at least the markup you have for the LinkButton.

It should only require the click even code you have - no other settings such as post-back URL is required for that button click event to work. In fact, it not at all clear why you using a LinkButton as opposed to say a button? (I see no need for a link button ).

So, no real reason for the register script stuff - remove it.

And note how I don't have to include the PK row "ID" in the markup, or even a hidden field. The datakeys setting is just for that reason (and it nice from a secuirty point of view - I don't have to render the PK row ID has hiddefield or anything.

Hence this code can get the PK id

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        LinkButton lBtn = sender as LinkButton;
        GridViewRow gRow = lBtn.NamingContainer as GridViewRow;
        // get row click index with gRow.RowIndex
        int? pkID = GridView1.DataKeys[gRow.RowIndex]["ID"] as int?;

And my code to fill the gv was this:

using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Project"L, conn))
{
conn.Open();

GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}

Now, of course if you using the row data bound for ANY thing at all? Then don't bind the GV to the reader, but use this:

conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader();
GridView1.DataSource = rstData;
GridView1.DataBind();


问:
SwiftUI MVVM With ObservedObject
UPDATE (2/10/22 @ 11:30am CST):

I rewrote the workflow so that my viewModel conforms to the ObservableObject protocol and no longer conforms to the CreateUser class. Now my variables are updating properly (tested via print("\(viewModel.loadingStatus)") both before and after the loadingState value is set.

However, my view that uses a switch statement to show the current state of the view (i.e. switches on loadingState) does not update, even though the value of loadingState in the viewModel is being set correctly and I'm able to use that print statement to show that it's being set, in the view itself.

I even tried setting changing the viewModel's @Published var loadingState to read as:

```<code>@Published var loadingState: LoadingState = .loading {
    willSet {
        objectwillchange.send()
    }
}
</code>```

Of course, according to Apple's docs, that's exactly the same behavior as @Published by itself, and it did nothing to solve the issue.

It seems as though everything else is working properly, except for the view switch case not updating when loadingState changes in the viewModel.

Original Post:

I have a multi-page form where all of the views of the form share the same ObservableObject(s). What I would like to do is split up each individual view into an MVVM workflow so that the UI stuff is in the view and the data stuff is in the viewModel.

The issue is that since all of these views share the same ObservableObject(s), and the functions in each of the views make heavy use of these ObservableObjects (storing variables, using other functions, etc.), the viewModel can't just be an ObservableObject of its own, because I would need to write a custom intializer for everything (and there are a lot of variables). This also means that in my NavigationLink as well as the view's preview, I would have to call to every single one of those individually initialized vars.

CreateUser (the shared ObservableObject that has all of the form variables as @Published vars) is where I am setting all of the form variables as the user moves through the pages. The best I came up with was to conform my viewModel to CreateUser instead of simply ObservableObject. That seemed to work and after quite a bit of recoding, there were no more errors and my app built. That being said, as it's not working, I have a feeling that this is not the correct way to do it.

Unfortunately, it seems that the viewModel is not updating any of the CreateUser variables, nor is it accurately referencing the CreateUser variables that are being set. I tested this by using page 3 of the form (where the username is entered) as the test for the MVVM architecture, and asked it to print the variable from page 2. It returned the default value instead of what was actually set.

This means my data is not being passed through properly and my variables are not being referenced the way they should, so page 3 (the MVVM view) is stuck showing the loading state, even though it should show the loaded state once the json fetch is finished.

What is the proper procedure for instituting an MVVM workflow when you have multiple other ObservedObjects being utilized in each view? This is for the latest SwiftUI/XCode for iOS 15+.

Here's a bit of code to further explain (obviously very stripped down for this post, but you get the idea if you read my explanation above):

Main View:

```<code>import Combine
import SwiftUI

struct UsernameView: View {

@StateObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List {
                switch viewModel.loadingState {
                    case .loading:
                        Section {
                            Text("I am loading")
                        }

                    case .loaded:
                        Section {
                            Text("I am loaded")
                        }

                    case .failed:
                        Section {
                            Text("Something went wrong")
                        }
                }
            }
        }
        .task {
            viewModel.userActivity = Date.now
            jsonFetch.sink (receiveCompletion: { completion in
                switch completion {
                    case .failure:
                        viewModel.loadingState = .failed
                    case .finished:
                        viewModel.loadingState = .loaded
                    }
                },
                receiveValue: { loadedData in
                    viewModel.userData = loadedData
                }).store(in: &viewModel.dataTransfer.requests)
        }
    }
}
</code>```

View Model:

```<code>import Combine
import SwiftUI

extension UsernameView {
    class ViewModel: CreateUser {

        @ObservedObject var textBindingManager = TextBindingManager(limit: 15)

        @Published var loadingState: LoadingState = .loading
        @Published var userData: [Usernames] = []
        @Published var usernameExists: [UsernameExists] = []

        func editingChanged(_ value: String) {
            username = String(value.prefix(textBindingManager.characterLimit))

            let jsonFetchUserExistsURL = URL(string: "https://api.foo.com/userselect?user=\(user)")
            let jsonFetchUserExistsTask = dataTransfer.jsonFetch(jsonFetchUserExistsURL, defaultValue: [UsernameExists]())

            if username.count >= 8 {
                guard network.isNetworkActive else { loadingAlert = true; return }
                Task {
                    status = .loading
                    usernameExists.removeAll()
                    jsonFetchUserExistsTask.sink (receiveCompletion: { completion in
                        switch completion {
                        case .failure:
                            self.loadingState = .failed
                        case .finished:
                            return
                        }
                    },
                    receiveValue: { loadedUserExists in
                        self.usernameExists = loadedUserExists
                    }).store(in: &dataTransfer.requests)
                }
            }
        }

extension UsernameView.ViewModel {
    enum LoadingState {
        case loading, loaded, failed
    }
}
</code>```

CreateUser:

```<code>import Combine
import SwiftUI

class CreateUser: ObservableObject {

    @ObservedObject var dataTransfer = NetworkTransfer()
    let network: NetworkMonitor

    init(network: NetworkMonitor) {
        self.network = network
    }

    @Published var userActivity = Date.now
    @Published var userActivityAlert = false
    @Published var birthday = Date()
    @Published var username = ""
}
</code>```

答:
I ended up forgetting about trying to use an MVVM workflow. Unfortunately, though I recoded everything and got it pretty close to working, the nested ObservedObjects do not update the view. After quite a bit of research I found several articles stating the same.

Instead, I decided to follow malhal's suggestion of breaking everything up into separate views, structs, and classes. It's a serious pain the ass, but hopefully it'll make the code a bit easier to work with as things progress.

I appreciate everyone's input.

Title: SwiftUI MVVM With ObservedObject

Body:
UPDATE (2/10/22 @ 11:30am CST):

I rewrote the workflow so that my viewModel conforms to the ObservableObject protocol and no longer conforms to the CreateUser class. Now my variables are updating properly (tested via print("\(viewModel.loadingStatus)") both before and after the loadingState value is set.

However, my view that uses a switch statement to show the current state of the view (i.e. switches on loadingState) does not update, even though the value of loadingState in the viewModel is being set correctly and I'm able to use that print statement to show that it's being set, in the view itself.

I even tried setting changing the viewModel's @Published var loadingState to read as:

@Published var loadingState: LoadingState = .loading {
    willSet {
        objectwillchange.send()
    }
}

Of course, according to Apple's docs, that's exactly the same behavior as @Published by itself, and it did nothing to solve the issue.

It seems as though everything else is working properly, except for the view switch case not updating when loadingState changes in the viewModel.

Original Post:

I have a multi-page form where all of the views of the form share the same ObservableObject(s). What I would like to do is split up each individual view into an MVVM workflow so that the UI stuff is in the view and the data stuff is in the viewModel.

The issue is that since all of these views share the same ObservableObject(s), and the functions in each of the views make heavy use of these ObservableObjects (storing variables, using other functions, etc.), the viewModel can't just be an ObservableObject of its own, because I would need to write a custom intializer for everything (and there are a lot of variables). This also means that in my NavigationLink as well as the view's preview, I would have to call to every single one of those individually initialized vars.

CreateUser (the shared ObservableObject that has all of the form variables as @Published vars) is where I am setting all of the form variables as the user moves through the pages. The best I came up with was to conform my viewModel to CreateUser instead of simply ObservableObject. That seemed to work and after quite a bit of recoding, there were no more errors and my app built. That being said, as it's not working, I have a feeling that this is not the correct way to do it.

Unfortunately, it seems that the viewModel is not updating any of the CreateUser variables, nor is it accurately referencing the CreateUser variables that are being set. I tested this by using page 3 of the form (where the username is entered) as the test for the MVVM architecture, and asked it to print the variable from page 2. It returned the default value instead of what was actually set.

This means my data is not being passed through properly and my variables are not being referenced the way they should, so page 3 (the MVVM view) is stuck showing the loading state, even though it should show the loaded state once the json fetch is finished.

What is the proper procedure for instituting an MVVM workflow when you have multiple other ObservedObjects being utilized in each view? This is for the latest SwiftUI/XCode for iOS 15+.

Here's a bit of code to further explain (obviously very stripped down for this post, but you get the idea if you read my explanation above):

Main View:

import Combine
import SwiftUI

struct UsernameView: View {

@StateObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List {
                switch viewModel.loadingState {
                    case .loading:
                        Section {
                            Text("I am loading")
                        }

                    case .loaded:
                        Section {
                            Text("I am loaded")
                        }

                    case .failed:
                        Section {
                            Text("Something went wrong")
                        }
                }
            }
        }
        .task {
            viewModel.userActivity = Date.now
            jsonFetch.sink (receiveCompletion: { completion in
                switch completion {
                    case .failure:
                        viewModel.loadingState = .failed
                    case .finished:
                        viewModel.loadingState = .loaded
                    }
                },
                receiveValue: { loadedData in
                    viewModel.userData = loadedData
                }).store(in: &viewModel.dataTransfer.requests)
        }
    }
}

View Model:

import Combine
import SwiftUI

extension UsernameView {
    class ViewModel: CreateUser {

        @ObservedObject var textBindingManager = TextBindingManager(limit: 15)

        @Published var loadingState: LoadingState = .loading
        @Published var userData: [Usernames] = []
        @Published var usernameExists: [UsernameExists] = []

        func editingChanged(_ value: String) {
            username = String(value.prefix(textBindingManager.characterLimit))

            let jsonFetchUserExistsURL = URL(string: "https://api.foo.com/userselect?user=\(user)")
            let jsonFetchUserExistsTask = dataTransfer.jsonFetch(jsonFetchUserExistsURL, defaultValue: [UsernameExists]())

            if username.count >= 8 {
                guard network.isNetworkActive else { loadingAlert = true; return }
                Task {
                    status = .loading
                    usernameExists.removeAll()
                    jsonFetchUserExistsTask.sink (receiveCompletion: { completion in
                        switch completion {
                        case .failure:
                            self.loadingState = .failed
                        case .finished:
                            return
                        }
                    },
                    receiveValue: { loadedUserExists in
                        self.usernameExists = loadedUserExists
                    }).store(in: &dataTransfer.requests)
                }
            }
        }

extension UsernameView.ViewModel {
    enum LoadingState {
        case loading, loaded, failed
    }
}

CreateUser:

import Combine
import SwiftUI

class CreateUser: ObservableObject {

    @ObservedObject var dataTransfer = NetworkTransfer()
    let network: NetworkMonitor

    init(network: NetworkMonitor) {
        self.network = network
    }

    @Published var userActivity = Date.now
    @Published var userActivityAlert = false
    @Published var birthday = Date()
    @Published var username = ""
}


问:
How to join adjacent elements in a list with a string in between?
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

and the output needs to be:

```<code>1-2
3-4
5-6
7-8
</code>```

Now I have gotten as far as this, but have no idea what to do next:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))
</code>```

And this only gives me this as result:

```<code>[(1, 2), (3, 4), (5, 6), (7, 8)]
</code>```

I feel like I am close and just missing one tiny step.

答:
Yep, very close indeed.

You can use a generator expression to form the pair strings without the intermediate variables, then "\n".join to make a single string out of the formatted pairs.

```<code>>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> print("\n".join(f"{a}-{b}" for (a, b) in zip(numbers[::2], numbers[1::2])))
1-2
3-4
5-6
7-8
</code>```

The more procedural version (that's functionally equivalent, but doesn't form a list, but just prints each pair) would be

```<code>for (a, b) in zip(numbers[::2], numbers[1::2]):
    print(f"{a}-{b}")
</code>```

Body:
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

a = [1, 2, 3, 4, 5, 6, 7, 8]

and the output needs to be:

1-2
3-4
5-6
7-8

Now I have gotten as far as this, but have no idea what to do next:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))

And this only gives me this as result:

[(1, 2), (3, 4), (5, 6), (7, 8)]

I feel like I am close and just missing one tiny step.

Body:
Yep, very close indeed.

You can use a generator expression to form the pair strings without the intermediate variables, then "\n".join to make a single string out of the formatted pairs.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> print("\n".join(f"{a}-{b}" for (a, b) in zip(numbers[::2], numbers[1::2])))
1-2
3-4
5-6
7-8

The more procedural version (that's functionally equivalent, but doesn't form a list, but just prints each pair) would be

for (a, b) in zip(numbers[::2], numbers[1::2]):
    print(f"{a}-{b}")


问:
Split row into multiple rows to limit length of array in column (spark / scala)
I have a dataframe that looks like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, .... x, y, z]|
+--------------+--------------------+
|             1|[q, z, .... x, b, 5]|
+--------------+--------------------+
|             2|[q, z, .... x, b, 5]|
+--------------+--------------------+
```
<p>I want to split the rows so that the array in the <code>items</code> column is at most length 20. If an array has length greater than 20, I would want to make new rows and split the array up so that each array is of length 20 or less. So for the first row in my example dataframe, if we assume the length is 10 and I want at most length 3 for each row, I would like for it to be split like this:</p>
<pre class="lang-none prettyprint-override"><code>+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, c]           |
+--------------+--------------------+
|             1|[z, y, z]           |
+--------------+--------------------+
|             1|[e, f, g]           |
+--------------+--------------------+
|             1|[q]                 |
+--------------+--------------------+
</code>```

Ideally, all rows should be of length 3 except the last row if the length of the array is not evenly divisible by the max desired length. Note - the id column is not unique

答:
You could try this:

```<code>import pandas as pd

max_item_length = 3

df = pd.DataFrame(
    {"fake_index": [1, 2, 3],
     "items": [["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "j"], ["k", "l"]]}
)

df2 = pd.DataFrame({"fake_index": [], "items": []})

for i in df.index:
    try:
        df2 = df2.append({"fake_index": int(df.iloc[i, 0]), "items": df.iloc[i, 1][:max_item_length]},
                         ignore_index=True)
        df2 = df2.append({"fake_index": int(df.iloc[i, 0]), "items": df.iloc[i, 1][max_item_length:]},
                         ignore_index=True)
    except:
        df2 = df2.append({"fake_index": int(df.iloc[i, 0]), "items": df.iloc[i, 1]}, ignore_index=True)

df = df2

print(df)
</code>```

Input:

```<code>   fake_index            items
0           1  [a, b, c, d, e]
1           2  [f, g, h, i, j]
2           3           [k, l]
</code>```

Output:

```<code>   fake_index      items
0           1  [a, b, c]
1           1     [d, e]
2           2  [f, g, h]
3           2     [i, j]
4           3     [k, l]
</code>```

Body:
I have a dataframe that looks like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, .... x, y, z]|
+--------------+--------------------+
|             1|[q, z, .... x, b, 5]|
+--------------+--------------------+
|             2|[q, z, .... x, b, 5]|
+--------------+--------------------+

I want to split the rows so that the array in the items column is at most length 20. If an array has length greater than 20, I would want to make new rows and split the array up so that each array is of length 20 or less. So for the first row in my example dataframe, if we assume the length is 10 and I want at most length 3 for each row, I would like for it to be split like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, c]           |
+--------------+--------------------+
|             1|[z, y, z]           |
+--------------+--------------------+
|             1|[e, f, g]           |
+--------------+--------------------+
|             1|[q]                 |
+--------------+--------------------+

Ideally, all rows should be of length 3 except the last row if the length of the array is not evenly divisible by the max desired length. Note - the id column is not unique

Body:
You could try this:

import pandas as pd

max_item_length = 3

df = pd.DataFrame(
    {"fake_index": [1, 2, 3],
     "items": [["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "j"], ["k", "l"]]}
)

df2 = pd.DataFrame({"fake_index": [], "items": []})

for i in df.index:
    try:
        df2 = df2.append({"fake_index": int(df.iloc[i, 0]), "items": df.iloc[i, 1][:max_item_length]},
                         ignore_index=True)
        df2 = df2.append({"fake_index": int(df.iloc[i, 0]), "items": df.iloc[i, 1][max_item_length:]},
                         ignore_index=True)
    except:
        df2 = df2.append({"fake_index": int(df.iloc[i, 0]), "items": df.iloc[i, 1]}, ignore_index=True)

df = df2

print(df)

Input:

   fake_index            items
0           1  [a, b, c, d, e]
1           2  [f, g, h, i, j]
2           3           [k, l]

Output:

   fake_index      items
0           1  [a, b, c]
1           1     [d, e]
2           2  [f, g, h]
3           2     [i, j]
4           3     [k, l]


问:
Wanted to Update Title and Image in Angular after component load
Wanted to update Dom elements like Image and Text after loading component in Angular. Note: Both of them does not have ID but have Class Name.

I used following code:

@ViewChild('.appnametitle') el: ElementRef;
  constructor(
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document,
    @Inject(ONEPLACE_JS_URI) private oneplaceJsUri,
    public cookieConfig: CookieConfig
  ) { }

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'innerHTML', 'Test Title Change');
  }```

but it shows following error:
Cannot read properties of undefined (reading 'nativeElement')

Could you help me where I am doing it wrong?

答:
ViewChild has not a classname as selector (a directive yes). So you can create a directive with the selector of the class and use ViewChild asking about the directive

```<code>@Directive({
  selector: '.appnametitle'
})
export class SelectDirective {

  constructor(public el:ElementRef) { }

}
</code>```

And in Component:

```<code>@ViewChild(SelectDirective) selectDirective:SelectDirective

ngAfterViewInit(): void {
    this.renderer.setAttribute(this.selectDirective.el.nativeElement,
              'innerHTML', 'Test Title Change');
  }
</code>```

But this is used if you has not access to the component (because was on third persons, e.g.), else you should rethinking the problem in a more angular way

Body:
Wanted to update Dom elements like Image and Text after loading component in Angular. Note: Both of them does not have ID but have Class Name.

I used following code:

@ViewChild('.appnametitle') el: ElementRef;
  constructor(
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document,
    @Inject(ONEPLACE_JS_URI) private oneplaceJsUri,
    public cookieConfig: CookieConfig
  ) { }

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'innerHTML', 'Test Title Change');
  }

but it shows following error:
Cannot read properties of undefined (reading 'nativeElement')

Could you help me where I am doing it wrong?

Body:
ViewChild has not a classname as selector (a directive yes). So you can create a directive with the selector of the class and use ViewChild asking about the directive

@Directive({
  selector: '.appnametitle'
})
export class SelectDirective {

  constructor(public el:ElementRef) { }

}

And in Component:

@ViewChild(SelectDirective) selectDirective:SelectDirective

ngAfterViewInit(): void {
    this.renderer.setAttribute(this.selectDirective.el.nativeElement,
              'innerHTML', 'Test Title Change');
  }

But this is used if you has not access to the component (because was on third persons, e.g.), else you should rethinking the problem in a more angular way


问:
Domain Driven Design - How do I model a Company and Employee use case?
I've been digging into DDD for the first time the last few weeks. I'm developing an HR application and am really struggling with the idea of Aggregate Roots.

So the current entities would be:

Company

Employee

Now given the lifecycle of an Employee, it makes sense at first to include it as a child entity on Company. An Employee can be added to a Company (new hire or existing) and then that Employee could resign or be fired - at which point that Employee record would likely be updated with some kind of status, so it can be differentiated from active Employees.

In regards to domain logic, every Employee at a Company must have a unique email. So if a Company always contained a list of all its Employees, I imagined that could be modeled as:

company.AddEmployee(employee) - This method would contain logic that makes sure the email is unique. In addition, it would update the size property of the Company, based on how many Employees they have. (<100 is small, <500 is medium, etc)

Now the biggest issue I have seen people discuss is concerning large Aggregates. I think this use case would fall under that concern, as a Company could have 10k+ Employees in this HR application. If I'm adding a single Employee at a time, it seems really wasteful to gather all 10k+, even if it's just their emails.

Am I doing the right thing here by making the Company the Aggregate Root, or is there a better way?

答:
Modeling aggregates is not so much about parent-child hierarchies. As already been stated it is about transaction boundaries. Also, consider aggregates provide the public APIs for performing transactions to your domain model.

It is easier to set aside parent-child hierarchy thinking and, at first also performance considerations. But rather to think:

Are there use cases to perform transactions (changes) on this entity without the need to apply domain rules that can only be adhered by some encapsulating root entity? That means, can this entity contain all domain logic (business rules) on its own to perform transactions on it?

Applying this kind of thinking in your case could have the following reasoning:

There are use cases where I want to modify an Employee entity where it does not make sense for the Company to check business invariants. Like, the main phone number contact information of an employee must never be empty or have invalid format.

This is of course an artificial example but it shows that by that reasoning such a transaction does not require business invariants that would be rather located in the Company entity. By that logic it can make sense to make Employee an aggregate on its own.

Also, for me, one crucial key learning from tactical DDD (or basically also from object-oriented programming) is to put the logic where the data is. If employee has all the data to execute logic that is required to keep transactional consistency without the need to ask Company, it can be a good candidate for an aggregate on its own.

Note: Of course, making an entity which is part of an aggregate an aggregate on its own can also make sense based on performance requirements (in case child entity collections would get too large). But I would not start modeling aggregates based on performance requirements, but rather ask yourself the questions outlined above.

Now to the topic of checking for e-mail uniqueness.

Where is the data for that? You could say if the Company knows about all the employees it would also know about all the emails of employees in that company so far. But just making the Employee a child of the Company does not seem to be the right reason.

If you model an Employee as an aggregate on its own, there is usually a special domain service that maintains collections of employee aggregates and provides access capabilities for retrieval and modification of such aggregates that make sense in the domain of your business - the aggregate repository.

This is also a good place to put logic for questioning, is there already an employee with that email address? Because the repository has the data to provide that logic.

The remaining question would of course be what code/component should than call this logic on the repository?. You could, e.g. have a special employee service that orchestrates employee creation. But depending on the situation that might also not be suitable. To help with this kind of decisions it is good to understand the implications of  the DDD trilemma.

To get further hints concerning such decisions you can have a look at this Q&A on stackoverflow which also discusses domain services for a similar problem.


问:
C signal: segmentation fault (core dumped)
I am learning C, and I am facing this error.
Why I cannot pass a pointer to the funcion as change(&p_x); and only change(&x); works? Thanks

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

void change(int *p_xa) // GET ERROR HERE signal: segmentation fault (core dumped)
{
    *p_xa = 999;
}

int main()
{
    int x = 1;
    int * p_x = &x;

    *p_x = 2;

    change(&p_x); // cannot do this

    printf("x is: %d \n", *p_x);

    return 0;
}
</code>```

答:
change has a parameter of type int *.

The call passes &p_x. The type of p_x is int *. The type of &p_x is int **. That is the wrong type for the parameter. Passing &p_x passes the address of p_x, but you want to pass the address of x.

Pass p_x, not &p_x. The value of p_x is the address of x.

Enable warnings in your compiler and elevate them to errors. With Clang, start with -Wmost -Werror. With GCC, start with -Wall -Werror. With MSVC, start with /W3 /WX. When you do this, the compiler will warn you when an argument is an incorrect type for a declared parameter.

Body:
I am learning C, and I am facing this error.
Why I cannot pass a pointer to the funcion as change(&p_x); and only change(&x); works? Thanks

#include <stdio.h>

void change(int *p_xa) // GET ERROR HERE signal: segmentation fault (core dumped)
{
    *p_xa = 999;
}

int main()
{
    int x = 1;
    int * p_x = &x;

    *p_x = 2;

    change(&p_x); // cannot do this

    printf("x is: %d \n", *p_x);

    return 0;
}


问:
Insert existing element an just created one
If I have: Some Code Here, can I create a new div element and move the span element inside just created div?

The new element must be in same place where span element was before

I'd like to use pure javascript code

答:
HTML:

```<code><span id="the_id">Some code...</span>
</code>```

JS:

```<code>var the_div = document.getElementById('the_id');
var foobar = document.createElement('div');
foobar.appendChild(the_id);
the_id.parentNode.replaceChild(foobar, the_id);
</code>```

Body:
HTML:

<span id="the_id">Some code...</span>

JS:

var the_div = document.getElementById('the_id');
var foobar = document.createElement('div');
foobar.appendChild(the_id);
the_id.parentNode.replaceChild(foobar, the_id);


问:
R eats up all RAM, then all swap, and the suddenly closes
I am using the mediation package to run a mediation analysis.

But when I call the mediate function, R eats up all RAM, then it eats up all swap, and then RStudio suddenly closes.

The same happens if I call Rscript from the terminal, and the terminal suddenly closes.

Here is measures for RAM and swap. Notice the peaks:

This happens both with the R 4.0.5 version that comes with the Fedora repository (which uses Open BLAS), both with a custom R 4.1.0 version I compiled from source against Intel MKL.

What is the cause of this, and how I can debug?

Here is my current sessionInfo():

```<code>> sessionInfo()
R version 4.1.0 (2021-05-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Fedora 34 (Workstation Edition)

Matrix products: default
BLAS/LAPACK: /opt/intel/oneapi/mkl/2021.2.0/lib/intel64/libmkl_gf_lp64.so.1

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_GB.UTF-8
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.1.0 tools_4.1.0
</code>```

答:
If the application needs all RAM and all virtual RAM you definitely hit the hard limit of your computer. If the application now requests more RAM from the OS, that request has to fail. How do you expect the application to deal with it?

As we do not know why more RAM was requested (it could be a memory leak, it could be that the algorithm just requires that much) we cannot distinguish bug or feature, but we can try things around that.

One quite cheap thing to try is to increase virtual memory size. Execution will get slower (disk access is measured in ms as opposed to RAM access times measured in ns), but maybe you find a value that the application can complete the task with.

If you cannot find any limit on virtual memory and the application always crashes due to the out-of-memory situation, you are likely facing a bug.

In any case you may want to talk to the vendor about this perception.

Body:
I am using the mediation package to run a mediation analysis.

But when I call the mediate function, R eats up all RAM, then it eats up all swap, and then RStudio suddenly closes.

The same happens if I call Rscript from the terminal, and the terminal suddenly closes.

Here is measures for RAM and swap. Notice the peaks:

This happens both with the R 4.0.5 version that comes with the Fedora repository (which uses Open BLAS), both with a custom R 4.1.0 version I compiled from source against Intel MKL.

What is the cause of this, and how I can debug?

Here is my current sessionInfo():

> sessionInfo()
R version 4.1.0 (2021-05-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Fedora 34 (Workstation Edition)

Matrix products: default
BLAS/LAPACK: /opt/intel/oneapi/mkl/2021.2.0/lib/intel64/libmkl_gf_lp64.so.1

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_GB.UTF-8
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.1.0 tools_4.1.0


问:
Visual Studio 2022 Git context menu does not appear anymore
All,

In the previous version of VS (19) was a lovely source files context menu that could provide basic git operations like "blame", "compare with unmodified", "commit", etc. But in new VS 22 version git context menu completely disappeared.

I have feeling it was deleted.
Does anyone know the good replacement of this feature? Any extension that provides a git hub context menu?

答:
As you can see it does not appear in my screenshot above.
However, after I installed a plugin:

Context menu started to appear:

when I disabled the plugging, git context menu continue to appear:

probably plugin installation reset settings of the context menu.

@jessehouwing, thanks anyway.