问:
Why a PHP warning appearing in Chrome but not in any other browser?
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

```<code>class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '<p><strong>ERROR 404</strong></p>';
            echo '<p>The resource you requested could not be located.</p>';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}
</code>```

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).

答:
Most likely it's this:

```<code>$_SESSION[$this->name][$varname] = $value;
</code>```

if $_SESSION[$this->name] was not defined as an array earlier, you'll get the "can't use scalar as array" error. e.g. if you do

```<code>$_SESSION[$this->name] = 42;
$_SESSION[$this->name][$varname] = 'will not work';
</code>```

the error is triggered.

Body:
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '
ERROR 404
';
            echo '
The resource you requested could not be located.
';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).

Body:
Most likely it's this:

$_SESSION[$this->name][$varname] = $value;

if $_SESSION[$this->name] was not defined as an array earlier, you'll get the "can't use scalar as array" error. e.g. if you do

$_SESSION[$this->name] = 42;
$_SESSION[$this->name][$varname] = 'will not work';

the error is triggered.


来源: stackexchange

问:
Selenium python Chrome not working as intended
Even if we use :

```<code>options=Options()
options.add_argument(r"user-data-dir=orginal chrome path")
driver = webdriver.Chrome(options=options)
</code>```

This above code need chromedriver. exe in to be in the current path where the file is even though it uses normal chrome so it this question is not duplicate and if we change the source code to use normal chrome.exe and it opens and the chrome is being controlled by automated testing software popup is closed but it can't do any further than that any solution
Thanks my os is windows 7 python3. 8.8 and selenium was installed by pip and chrome version is 96. Something any solu thanks also this question is related to this please answer both if you know question is I was using selenium python to login you can ask for further info

答: Found that it won't work as selenium need chromedriver to work</p>

ContentLicense: CC BY-SA 4.0

Body:
Even if we use :

options=Options()
options.add_argument(r"user-data-dir=orginal chrome path")
driver = webdriver.Chrome(options=options)

This above code need chromedriver. exe in to be in the current path where the file is even though it uses normal chrome so it this question is not duplicate and if we change the source code to use normal chrome.exe and it opens and the chrome is being controlled by automated testing software popup is closed but it can't do any further than that any solution
Thanks my os is windows 7 python3. 8.8 and selenium was installed by pip and chrome version is 96. Something any solu thanks also this question is related to this please answer both if you know question is I was using selenium python to login you can ask for further info


问:
How to convert an array of string integers to an array of integers? Ruby
I have an array:

```<code>all_ages = ["11", "9", "10", "8", "9"]
</code>```

and I want to convert it to an array of integers to hopefully make it easier to add them all together.
Any help greatly appreciated, looking for level one solutions.

答:
Enumerable#sum can be called with a block telling Ruby how to sum the elements of the array, in this case, to call String#to_i on element first.

```<code>all_ages = ["11", "9", "10", "8", "9"]
all_ages.sum(&:to_i)
#=> 47

</code>```

Body:
I have an array:

all_ages = ["11", "9", "10", "8", "9"]

and I want to convert it to an array of integers to hopefully make it easier to add them all together.
Any help greatly appreciated, looking for level one solutions.

Body:
Enumerable#sum can be called with a block telling Ruby how to sum the elements of the array, in this case, to call String#to_i on element first.

all_ages = ["11", "9", "10", "8", "9"]
all_ages.sum(&:to_i)
#=> 47


问:
How to change stroke weight / thickness of a Google Icon?
I've been trying to figure this one out for a few days, the material icons are a bit too thick, so I downloaded one and have been trying to change the stroke weight / thickness.  But just using the stroke-width property doesn't change anything, and if I add a 'stroke' it also adds a border around the element.

For example, here is the 'public' icon from google / material icons

<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
<path d="M0 0h24v24H0V0z" fill="none"/>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-.61.08-1.21.21-1.78L8.99 15v1c0 1.1.9 2 2 2v1.93C7.06 19.43 4 16.07 4 12zm13.89 5.4c-.26-.81-1-1.4-1.9-1.4h-1v-3c0-.55-.45-1-1-1h-6v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41C17.92 5.77 20 8.65 20 12c0 2.08-.81 3.98-2.11 5.4z"/>
</svg>```

How would I go about making this thinner or thicker?  Is there a minimum font weight?   ( I want some pretty thin strokes for this)

答:
The design of the icon is your problem

Paste the path in https://yqnn.github.io/svg-path-editor/

If you want more detail you need to edit the (filled) path.

Body:
I've been trying to figure this one out for a few days, the material icons are a bit too thick, so I downloaded one and have been trying to change the stroke weight / thickness.  But just using the stroke-width property doesn't change anything, and if I add a 'stroke' it also adds a border around the element.

For example, here is the 'public' icon from google / material icons

<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
<path d="M0 0h24v24H0V0z" fill="none"/>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-.61.08-1.21.21-1.78L8.99 15v1c0 1.1.9 2 2 2v1.93C7.06 19.43 4 16.07 4 12zm13.89 5.4c-.26-.81-1-1.4-1.9-1.4h-1v-3c0-.55-.45-1-1-1h-6v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41C17.92 5.77 20 8.65 20 12c0 2.08-.81 3.98-2.11 5.4z"/>
</svg>

How would I go about making this thinner or thicker?  Is there a minimum font weight?   ( I want some pretty thin strokes for this)


问:
GWT request factory: Please help explain a complete  end-to-end WriteOperation.DELETE scenario?
Been looking at a lot of gwt request factory examples lately but still can't quite find the complete picture:

GWT request factory's sweet spot is CRUD (create/read/update/delete). Having said that:

Even in the "update" case, it is not clear to me who is responsible for firing a EntityProxyChange (Event)

I read somewhere (forget where) that the client side request factory keeps a local cache of EntityProxy that it has 'seen', and, if it 'sees' a new one then it fires a EntityProxyChange (Event)

does that mean that, if my "updatePerson()" method returns a (newly updated) PersonProxy, then does the local client side request factory infrastructure 'see' this newly updated person (i.e., by virtue of its updated versionId) and then does it automatically fire a EntityProxyChange (Event) ?

In the "delete" case, say I create a function called "deletePerson()" in my request context, I understand how the request arrives at the server and one might do, e.g., a SQL DELETE to delete the entity, but, who is responsible for firing a EntityProxyChange (Event) w/WriteOperation=DELETE ? do these events get fired at the server side? the client side?

I've had a look at the listwidget example (http://code.google.com/p/listwidget), but, on a 'itemlist' delete, it kinda 'cheats' by just doing a brute force refresh of the entire list (though I do understand that that detail is not necessarily what listwidget is trying to illustrate in the first place); I would have expected to see a EntityProxyChange (Event) handler that listens for WriteOperation.DELETE events and then would just remove just that entity from the ListDataProvider.

Does ServiceLayer/ServiceLayerDecorator.isLive() factor into any of this?

答:
See http://code.google.com/p/google-web-toolkit/wiki/RequestFactoryMovingParts#Flow

The client-side doesn't keep a cache (that was probably the case in the early iterations a year ago though, but has never been the case in non-milestones releases), and the server-side is responsible for "firing" the events (you'll see them in the JSON response payload).

When the wiki page referenced above says:

Entities that can be no longer retrieved ...

What it really means is that isLive has returned false, and isLive's implementation defaults to doing a get by the ID and checking for a non-null result.

ContentLicense: CC BY-SA 3.0


问:
Defining and using a key-value list of generics
I'm sure I'm missing a key concept here but here's what I'm trying to do.

These are the definitions:

```<code>export interface ActionError {
  message: string;
}

export interface Request<Payload> {
  payload: Payload;
}

export interface Response<Payload> {
  send: (response?: Payload) => void;
  error: (error?: ActionError) => void;
}

export interface Action<RequestPayload, ResponsePayload> {
  (request: Request<RequestPayload>, response: Response<ResponsePayload>): void;
}

export interface Actions {
  [key: string]: Action<unknown, unknown>;
}
</code>```

Basically, I'm trying to create a key-value list of Actions that can work with any type that can be passed to a function like below:

```<code>const processActions = (actions: Actions) => {
  // Removed for brevity
};
</code>```

Then I create a key-value object of actions:

```<code>const sampleActions = {
  'hello-world': async (
    request: Request<{ input: string }>,
    response: Response<{ output: number }>
  ) => {
    response.send({ output: 10 });
  },
};
</code>```

And when I call processActions with sampleActions:

processActions(sampleActions) I get this error:

```<code>Argument of type '{ "hello-world": (request: Request<{    input: string;}>, response: Response<{    output: number;}>) => Promise<void>; }' is not assignable to parameter of type 'Actions'.
  Property '"hello-world"' is incompatible with index signature.
    Type '(request: Request<{    input: string;}>, response: Response<{    output: number;}>) => Promise<void>' is not assignable to type 'Action<unknown, unknown>'.
      Types of parameters 'request' and 'request' are incompatible.
        Type 'Request<unknown>' is not assignable to type 'Request<{ input: string; }>'.
          Type 'unknown' is not assignable to type '{ input: string; }'
</code>```

So what am I doing wrong and how can I make this work with any generic type parameter?

答:
My understanding is that the error is simply due to function parameter bivariance. You can satisfy the compiler (and potentially infer a narrowed return type from the processing function) by using a generic for the actions parameter, constrained by a type that uses any for the payloads instead of unknown, as shown in the example below.

Whether any or unknown is used, you still won't have information about the actual types required by the actions' payloads within the processing function. This is simply the nature of the pattern you're using.

TS Playground

export interface ActionError {
  message: string;
}

export interface ActionRequest<Payload> {
  payload: Payload;
}

export interface ActionResponse<Payload> {
  send: (response?: Payload) => void;
  error: (error?: ActionError) => void;
}

export interface Action<ReqPayload, ResPayload> {
  (request: ActionRequest<ReqPayload>, response: ActionResponse<ResPayload>): void;
}

function processActions <Actions extends Record<string, Action<any, any>>>(actions: Actions) {
  // Removed for brevity
}

const sampleActions = {
  'hello-world': async (
    request: ActionRequest<{ input: string }>,
    response: ActionResponse<{ output: number }>,
  ) => {
    response.send({ output: 10 });
  },
};

processActions(sampleActions); // ok, hover in playground link to see inferred generics

```

Body:
I'm sure I'm missing a key concept here but here's what I'm trying to do.

These are the definitions:

export interface ActionError {
  message: string;
}

export interface Request<Payload> {
  payload: Payload;
}

export interface Response<Payload> {
  send: (response?: Payload) => void;
  error: (error?: ActionError) => void;
}

export interface Action<RequestPayload, ResponsePayload> {
  (request: Request<RequestPayload>, response: Response<ResponsePayload>): void;
}

export interface Actions {
  [key: string]: Action<unknown, unknown>;
}

Basically, I'm trying to create a key-value list of Actions that can work with any type that can be passed to a function like below:

const processActions = (actions: Actions) => {
  // Removed for brevity
};

Then I create a key-value object of actions:

const sampleActions = {
  'hello-world': async (
    request: Request<{ input: string }>,
    response: Response<{ output: number }>
  ) => {
    response.send({ output: 10 });
  },
};

And when I call processActions with sampleActions:

processActions(sampleActions) I get this error:

Argument of type '{ "hello-world": (request: Request<{    input: string;}>, response: Response<{    output: number;}>) => Promise<void>; }' is not assignable to parameter of type 'Actions'.
  Property '"hello-world"' is incompatible with index signature.
    Type '(request: Request<{    input: string;}>, response: Response<{    output: number;}>) => Promise<void>' is not assignable to type 'Action<unknown, unknown>'.
      Types of parameters 'request' and 'request' are incompatible.
        Type 'Request<unknown>' is not assignable to type 'Request<{ input: string; }>'.
          Type 'unknown' is not assignable to type '{ input: string; }'

So what am I doing wrong and how can I make this work with any generic type parameter?

Body:
My understanding is that the error is simply due to function parameter bivariance. You can satisfy the compiler (and potentially infer a narrowed return type from the processing function) by using a generic for the actions parameter, constrained by a type that uses any for the payloads instead of unknown, as shown in the example below.

Whether any or unknown is used, you still won't have information about the actual types required by the actions' payloads within the processing function. This is simply the nature of the pattern you're using.

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgQWxgQiQFEopo4BvAWACg44BbYAZ3cwHNgAuOOxhRk3ANyMAvo0ahIsRCjRZcBIiSQAlYAEcArhxgAeAAqYAngBsImACYA+Wo2ZgL1uwLNWbtiQ2kMsuDQ8MioGDh4hMSk2uyQSOzApm4+jvRMgsBItgIAFFAcCUkA-J6pdgCUcAC8jgBuEAi+znBoVFD57dBlajHklNDVdXCNzX4BQfKhShGq0RpG2jpe7rYANHBxq2lOmQW6BkICC7GHhku6O3b2m4XxpEkn6mcPicnbFQ6VAmMt-jIGOg9EgXkg4GAqLhOKdEnAjLD2G0QKgckjtNhoLYjEIREhuJtYUZMEhzJsSeZ7FS8jh+uxnnTqhlmAB6FlbYAsCD1YC2ODoagAI0K9QQMHMUkBmMS8C4LDAlmAiNqe2YAHIABbASzWAC0AHdoJZbGqBJh2OZQXA8q1mIV9IYGRplkdjDRFGA9DABLjRHBJLdbXB7sV+H1nUVHsl3RAvZ7vXAkHoWIK0P7A5lhukgyGowA6JI5PIxuNegQARgADP7Kn5mJJ1lI-IxIRBoexEXk5QqlWD2LW4Gy4BAANaMIA" rel="nofollow noreferrer">TS Playground

export interface ActionError {
  message: string;
}

export interface ActionRequest<Payload> {
  payload: Payload;
}

export interface ActionResponse<Payload> {
  send: (response?: Payload) => void;
  error: (error?: ActionError) => void;
}

export interface Action<ReqPayload, ResPayload> {
  (request: ActionRequest<ReqPayload>, response: ActionResponse<ResPayload>): void;
}

function processActions <Actions extends Record<string, Action<any, any>>>(actions: Actions) {
  // Removed for brevity
}

const sampleActions = {
  'hello-world': async (
    request: ActionRequest<{ input: string }>,
    response: ActionResponse<{ output: number }>,
  ) => {
    response.send({ output: 10 });
  },
};

processActions(sampleActions); // ok, hover in playground link to see inferred generics


问:
CSS3 Transition Fill Mode
Is there any way / trick to have transition keeping its state just like animation-fill-mode?

```<code><style>
    #firstdiv {
        width: 100px;
        height: 100px;
        background: red;
        animation: firstdivframe 2s;
        animation-play-state: paused;
        animation-fill-mode: forwards;
    }

    #firstdiv:hover {
        animation-play-state: running
    }

    @keyframes firstdivframe {
        from { background: red; }
        to { background: yellow; }
    }

    #seconddiv {
        width: 100px;
        height: 100px;
        background: red;
        transition: background 2s;
    }

    #seconddiv:hover {
        background: yellow;
    }
</style>

<div id="firstdiv"></div>
<br />
<div id="seconddiv"></div>
</code>```

jsbin

Based on above code, I want the seconddiv to behave just like firstdiv without using any javascript code. The firstdiv will keep its state when the mouse stops hovering or the animation ends, while the seconddiv will always go back to its original state.

答: Yes, of course! Think about setTimeout! You can use setTimeout with the same duration as you have in transition! And the call-back function of setTimeout should set the back the style that you want to keep it!</p>

Title: CSS3 Transition Fill Mode

Body:
Is there any way / trick to have transition keeping its state just like animation-fill-mode?

jsbin

Based on above code, I want the seconddiv to behave just like firstdiv without using any javascript code. The firstdiv will keep its state when the mouse stops hovering or the animation ends, while the seconddiv will always go back to its original state.


问:
SVC classifier taking too much time for training
I am using SVC classifier with Linear kernel to train my model.
Train data: 42000 records

```<code>    model = SVC(probability=True)
    model.fit(self.features_train, self.labels_train)
    y_pred = model.predict(self.features_test)
    train_accuracy = model.score(self.features_train,self.labels_train)
    test_accuracy = model.score(self.features_test, self.labels_test)
</code>```

It takes more than 2 hours to train my model.
Am I doing something wrong?
Also, what can be done to improve the time

Thanks in advance

答:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

For SVM you for sure would be able to get higher compute efficiency.

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Body:
I am using SVC classifier with Linear kernel to train my model.
Train data: 42000 records

    model = SVC(probability=True)
    model.fit(self.features_train, self.labels_train)
    y_pred = model.predict(self.features_test)
    train_accuracy = model.score(self.features_train,self.labels_train)
    test_accuracy = model.score(self.features_test, self.labels_test)

It takes more than 2 hours to train my model.
Am I doing something wrong?
Also, what can be done to improve the time

Thanks in advance

Body:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

For SVM you for sure would be able to get higher compute efficiency.

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


答:
The user is also unknown for the day without sales. To solve this, you can do something like this:

```<code>SELECT
  calendar.date AS date,
  su.user_id AS user_id,
  COALESCE( sales.quantity,0) AS quantity
FROM calendar
CROSS JOIN (SELECT DISTINCT user_id FROM sales) su
LEFT JOIN sales
  ON calendar.date = sales.date AND sales.user_id=su.user_id
ORDER BY 2,1
</code>```

see fiddle

Title: MySQL (SQL) | LEFT JOIN DOES NOT RETURN ALL ROWS (NO FILTER APPLIED)

Body:
I would like to left join a calendar table with a sales table and return all sales by user by day (inclusive of all days without sales). For some reason, however, I only get the days with sales. As you can see below, there are no filters applied. What am I doing wrong here?

Below my SQL code, all tables and the wished final result.

MySQL Query

SELECT
  calendar.date AS date,
  sales.user_id AS user_id,
  CASE
    WHEN sales.date = calendar.date THEN sales.quantity
    ELSE 0
  END AS quantity
FROM calendar
LEFT JOIN sales
  ON calendar.date = sales.date

DATE table (from 2020-01-01 to 2020-01-31)

date

2020-01-01

2020-01-02

...

2020-01-31

SALES table

date
user_id
quantity

2020-01-03
1
10

2020-01-12
1
12

2020-01-20
1
2

2020-01-01
2
13

2020-01-29
2
8

WISHED RESULT

date
user_id
quantity

2020-01-01
1
0

2020-01-02
1
0

2020-01-03
1
10

2020-01-04
1
0

2020-01-05
1
0

2020-01-06
1
0

2020-01-07
1
0

2020-01-08
1
0

2020-01-09
1
0

2020-01-10
1
0

2020-01-11
1
0

2020-01-12
1
12

2020-01-13
1
0

2020-01-14
1
0

2020-01-15
1
0

2020-01-16
1
0

2020-01-17
1
0

2020-01-18
1
0

2020-01-19
1
0

2020-01-20
1
2

2020-01-21
1
0

2020-01-21
1
0

2020-01-22
1
0

2020-01-23
1
0

2020-01-24
1
0

2020-01-25
1
0

2020-01-26
1
0

2020-01-27
1
0

2020-01-28
1
0

2020-01-29
1
0

2020-01-30
1
0

2020-01-31
1
0

2020-01-01
2
13

2020-01-02
2
0

2020-01-03
2
0

2020-01-04
2
0

2020-01-05
2
0

2020-01-06
2
0

2020-01-07
2
0

2020-01-08
2
0

2020-01-09
2
0

2020-01-10
2
0

2020-01-11
2
0

2020-01-12
2
0

2020-01-13
2
0

2020-01-14
2
0

2020-01-15
2
0

2020-01-16
2
0

2020-01-17
2
0

2020-01-18
2
0

2020-01-19
2
0

2020-01-20
2
0

2020-01-21
2
0

2020-01-21
2
0

2020-01-22
2
0

2020-01-23
2
0

2020-01-24
2
0

2020-01-25
2
0

2020-01-26
2
0

2020-01-27
2
0

2020-01-28
2
0

2020-01-29
2
8

2020-01-30
2
0

2020-01-31
2
0

Body:
The user is also unknown for the day without sales. To solve this, you can do something like this:

SELECT
  calendar.date AS date,
  su.user_id AS user_id,
  COALESCE( sales.quantity,0) AS quantity
FROM calendar
CROSS JOIN (SELECT DISTINCT user_id FROM sales) su
LEFT JOIN sales
  ON calendar.date = sales.date AND sales.user_id=su.user_id
ORDER BY 2,1

see fiddle


问:
Usage of Dictionary along with KeyPairValue
I have a dictionary declared as follows:

```<code>public:
     static Dictionary<String ^, List<String ^>^> ^ language_string_table;
</code>```

so by using for each loop key and values are loaded into that (which is written by someone else). Now I need by using the same for each loop I am able to access "key" of the Dictionary alone, please help me out how to access "value" of the Dictionary.

答:
You are asking the very basic usage of IEnumerator interface.

Your answer is :

```<code>Dictionary<String ^, List<String ^>^> ^ language_string_table;

Dictionary<String ^, List<String ^>^>::Enumerator etor = language_string_table->GetEnumerator();
while(etor.MoveNext())
{
    String^ ss = etor.Current.Key;
    List<String ^>^> ^ list = etor.Current.Value;
}
//if you just want to get keys or values only
Dictionary<String ^, List<String ^>^>::KeyCollection::Enumerator keytor = language_string_table->Keys->GetEnumerator();

while(etor.MoveNext())
{
    String^ ss = keytor.Current;
}
</code>```

But I strongly recommend you learn the iterator concept.

Also here is the for each usage in C++/CLI.

Body:
I have a dictionary declared as follows:

public:
     static Dictionary<String ^, List<String ^>^> ^ language_string_table;

so by using for each loop key and values are loaded into that (which is written by someone else). Now I need by using the same for each loop I am able to access "key" of the Dictionary alone, please help me out how to access "value" of the Dictionary.

Body:
You are asking the very basic usage of IEnumerator interface.

Your answer is :

Dictionary<String ^, List<String ^>^> ^ language_string_table;

Dictionary<String ^, List<String ^>^>::Enumerator etor = language_string_table->GetEnumerator();
while(etor.MoveNext())
{
    String^ ss = etor.Current.Key;
    List<String ^>^> ^ list = etor.Current.Value;
}
//if you just want to get keys or values only
Dictionary<String ^, List<String ^>^>::KeyCollection::Enumerator keytor = language_string_table->Keys->GetEnumerator();

while(etor.MoveNext())
{
    String^ ss = keytor.Current;
}

But I strongly recommend you learn the iterator concept.

Also here is the for each usage in C++/CLI.


问:
Button hover does not work after I change button color using JS
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}</code>```

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>```

After I click the button event occurs and the color changes to dark blue and the hover do not work.

答:
Inline styling (applied via style attribute) takes precedence over CSS applied styling (applied via class attribute).

Before click there was no background-color defined via style, after click there is which is overruling your CSS .button1:hover background-color. See documentation on CSS Specificity for more details on this topic.

To see the hover effect after clicking the button, try updating your .button1:hover to the following:

.button1:hover {
  background-color: red !important;
  color: black;
  border: 2px solid #4caf50;
}
```

Note the use of !important which instructs the browser to give precedence over the inline styling.

⚠ Using !important is generally not good practice therefore don't consider this to be a solution rather a topic to look into.

Body:
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}

.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>

After I click the button event occurs and the color changes to dark blue and the hover do not work.

Body:
Inline styling (applied via style attribute) takes precedence over CSS applied styling (applied via class attribute).

Before click there was no background-color defined via style, after click there is which is overruling your CSS .button1:hover background-color. See documentation on CSS Specificity for more details on this topic.

To see the hover effect after clicking the button, try updating your .button1:hover to the following:

.button1:hover {
  background-color: red !important;
  color: black;
  border: 2px solid #4caf50;
}

Note the use of !important which instructs the browser to give precedence over the inline styling.

⚠ Using !important is generally not good practice therefore don't consider this to be a solution rather a topic to look into.


问:
How do I solve error: Tensor object has not atrribute 'fold'
I have a method that divides an image into patches and change the colour of a specified patch. I tried merging the patches together  after the manipulation and I got the error: AttributeError: 'Tensor' object has no attribute 'fold'

```<code>def perturb_patch(img, patch_idx, patch_size, stride):
    img = img.unsqueeze(0)
    patches = img.unfold(2, patch_size, stride).unfold(3, patch_size, stride)
    patches = patches.reshape(1, 3, -1, patch_size, patch_size)
    patches = patches.squeeze(0).permute(1, 0, 2, 3)
    patches[patch_idx][0, :, :] = 0.09803922
    patches[patch_idx][1,:, :] = 0.21333333
    patches[patch_idx][2,:, :] = 0.61176471

    merged_patches = patches.fold(img.shape[-2:], kernel_size=16, stride=16, padding=0)
    return merged_patches
</code>```

When I tried returning patches instead of merged_patches with  new_img = perturb_patch(img, 6, 16, 16), I could visualize the patches and the manipulated patch was noticeable. How do I merge this patches together to form the original image which of size (3, 224, 224)?

答:
So, I was able to find an alternative to merge the patches together with the pytorch's view method here.

updated code:

```<code>def perturb_patch(img, patch_idx, patch_size, stride):

    img = img.unsqueeze(0)
    patches = img.unfold(2, patch_size, stride).unfold(3, patch_size, stride)
    patches = patches.reshape(1, 3, -1, patch_size, patch_size)
    patches = patches.squeeze(0).permute(1, 0, 2, 3)

    patches[patch_idx][0, :, :] = 0.09803922
    patches[patch_idx][1,:, :] = 0.21333333
    patches[patch_idx][2,:, :] = 0.61176471

    unsqueezed_patch = patches.unsqueeze(0)
    grid_size = (14, 14)
    batch_size, num_patches, c, height, width = unsqueezed_patch.size()
    image = unsqueezed_patch.view(batch_size, grid_size[0], grid_size[1], c, height, width)
    output_height = grid_size[0] * height
    output_width = grid_size[1] * width

    image = image.permute(0, 3, 1, 4, 2, 5).contiguous()
    image = image.view(batch_size, c, output_height, output_width)

    return image
</code>```

Body:
I have a method that divides an image into patches and change the colour of a specified patch. I tried merging the patches together  after the manipulation and I got the error: AttributeError: 'Tensor' object has no attribute 'fold'

def perturb_patch(img, patch_idx, patch_size, stride):
    img = img.unsqueeze(0)
    patches = img.unfold(2, patch_size, stride).unfold(3, patch_size, stride)
    patches = patches.reshape(1, 3, -1, patch_size, patch_size)
    patches = patches.squeeze(0).permute(1, 0, 2, 3)
    patches[patch_idx][0, :, :] = 0.09803922
    patches[patch_idx][1,:, :] = 0.21333333
    patches[patch_idx][2,:, :] = 0.61176471

    merged_patches = patches.fold(img.shape[-2:], kernel_size=16, stride=16, padding=0)
    return merged_patches

When I tried returning patches instead of merged_patches with  new_img = perturb_patch(img, 6, 16, 16), I could visualize the patches and the manipulated patch was noticeable. How do I merge this patches together to form the original image which of size (3, 224, 224)?

Body:
So, I was able to find an alternative to merge the patches together with the pytorch's view method here.

updated code:

def perturb_patch(img, patch_idx, patch_size, stride):

    img = img.unsqueeze(0)
    patches = img.unfold(2, patch_size, stride).unfold(3, patch_size, stride)
    patches = patches.reshape(1, 3, -1, patch_size, patch_size)
    patches = patches.squeeze(0).permute(1, 0, 2, 3)

    patches[patch_idx][0, :, :] = 0.09803922
    patches[patch_idx][1,:, :] = 0.21333333
    patches[patch_idx][2,:, :] = 0.61176471

    unsqueezed_patch = patches.unsqueeze(0)
    grid_size = (14, 14)
    batch_size, num_patches, c, height, width = unsqueezed_patch.size()
    image = unsqueezed_patch.view(batch_size, grid_size[0], grid_size[1], c, height, width)
    output_height = grid_size[0] * height
    output_width = grid_size[1] * width

    image = image.permute(0, 3, 1, 4, 2, 5).contiguous()
    image = image.view(batch_size, c, output_height, output_width)

    return image


问:
c++ linking error when doing __inline__ on class member function: symbol not found
I'm trying to force inline a member function and I get the error:

```<code>"a_class::mem_func()", referenced from:
func(a_class&)    in func.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
</code>```

here is the distilled error-producing code

```<code>a_class.h
    #ifndef A_CLASS_H  #define A_CLASS_H
    class a_class {public: __inline__ void mem_func(); };
    #endif

a_class.cpp
    #include "a_class.h"
    __inline__ void a_class::mem_func() {}

func.h
    #ifndef FUNC_H  #define FUNC_H  #include"a_class.h"
    void func(a_class & obj);
    #endif

func.cpp
    #include "func.h"
    void func(a_class & obj) {obj.mem_func();}

main.cpp
    #include <iostream>  #include "func.h"  #include "a_class.h"
    int main () {a_class obj; func(obj);}
</code>```

I'm using Xcode / gcc

答:
If you want to make sure your function is inlined, move the definition in the header:</p>

```<code>a_class.h
    #ifndef A_CLASS_H  #define A_CLASS_H
    class a_class {public: __inline__ void mem_func() {} /*<-definition*/; };
    #endif
</code>```

Body:
I'm trying to force inline a member function and I get the error:

"a_class::mem_func()", referenced from:
func(a_class&)    in func.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

here is the distilled error-producing code

a_class.h
    #ifndef A_CLASS_H  #define A_CLASS_H
    class a_class {public: __inline__ void mem_func(); };
    #endif

a_class.cpp
    #include "a_class.h"
    __inline__ void a_class::mem_func() {}

func.h
    #ifndef FUNC_H  #define FUNC_H  #include"a_class.h"
    void func(a_class & obj);
    #endif

func.cpp
    #include "func.h"
    void func(a_class & obj) {obj.mem_func();}

main.cpp
    #include <iostream>  #include "func.h"  #include "a_class.h"
    int main () {a_class obj; func(obj);}

I'm using Xcode / gcc

Body:
If you want to make sure your function is inlined, move the definition in the header:

a_class.h
    #ifndef A_CLASS_H  #define A_CLASS_H
    class a_class {public: __inline__ void mem_func() {} /*<-definition*/; };
    #endif


问:
how to add dynamic dictionary in jinja template?
I have the below jinja template and i want to achieve the following:

jinja template for json:

```<code>{
  "spark_conf": {
  {% if cluster_mode == "single" %}
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
  {% endif %}
  {% if cluster_mode == "concurrent" %}
        "spark.databricks.cluster.profile":"serverless",
        "spark.databricks.repl.allowedLanguages":"sql,python,r",
  {% endif %}
  {{ spark_conf }}
  },
  "spark_env_vars": {{ spark_env_vars }}}
</code>```

I am passing spark_env_vars as parameter and want to add more spark_conf dynamically, so the input to this j2 template is:

```<code>spark_env_vars = {
    "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
}
spark_conf = {"test": "abc", "test124": "def"}
cluster_mode = "single"
</code>```

Post jinja i am expecting output as :

```<code>{ "spark_conf" : {
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
        "test": "abc",
        "test123": "def"},
  "spark_env_vars": {
        "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
    }
}
</code>```

please could you advise how to handle that in jinja template to get the desired output.

答:
Use the for loop for dynamic variables:

```<code>{
    "spark_conf": {
    {%- if cluster_mode == "single" %}
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
    {%- endif %}
    {%- if cluster_mode == "concurrent" %}
        "spark.databricks.cluster.profile":"serverless",
        "spark.databricks.repl.allowedLanguages":"sql,python,r",
    {%- endif %}
    {%- for key,value in spark_conf.items() %}
        "{{ key }}": "{{ value }}"{% if not loop.last %},{% endif %}
    {%- endfor %}
    },
    "spark_env_vars": {
    {%- for key,value in spark_env_vars.items() %}
        "{{ key }}": "{{ value }}"{% if not loop.last %},{% endif %}
    {%- endfor %}
    }
}
</code>```

Output:

```<code>{
    "spark_conf": {
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
        "test": "abc",
        "test124": "def"
    },
    "spark_env_vars": {
        "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
    }
}
</code>```

With loop.last special variable we can check whether the current element is the last one, and skip putting a comma at the end.

Body:
I have the below jinja template and i want to achieve the following:

jinja template for json:

{
  "spark_conf": {
  {% if cluster_mode == "single" %}
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
  {% endif %}
  {% if cluster_mode == "concurrent" %}
        "spark.databricks.cluster.profile":"serverless",
        "spark.databricks.repl.allowedLanguages":"sql,python,r",
  {% endif %}
  {{ spark_conf }}
  },
  "spark_env_vars": {{ spark_env_vars }}}

I am passing spark_env_vars as parameter and want to add more spark_conf dynamically, so the input to this j2 template is:

spark_env_vars = {
    "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
}
spark_conf = {"test": "abc", "test124": "def"}
cluster_mode = "single"

Post jinja i am expecting output as :

{ "spark_conf" : {
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
        "test": "abc",
        "test123": "def"},
  "spark_env_vars": {
        "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
    }
}

please could you advise how to handle that in jinja template to get the desired output.

Body:
Use the for loop for dynamic variables:

{
    "spark_conf": {
    {%- if cluster_mode == "single" %}
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
    {%- endif %}
    {%- if cluster_mode == "concurrent" %}
        "spark.databricks.cluster.profile":"serverless",
        "spark.databricks.repl.allowedLanguages":"sql,python,r",
    {%- endif %}
    {%- for key,value in spark_conf.items() %}
        "{{ key }}": "{{ value }}"{% if not loop.last %},{% endif %}
    {%- endfor %}
    },
    "spark_env_vars": {
    {%- for key,value in spark_env_vars.items() %}
        "{{ key }}": "{{ value }}"{% if not loop.last %},{% endif %}
    {%- endfor %}
    }
}

Output:

{
    "spark_conf": {
        "spark.databricks.cluster.profile": "singleNode",
        "spark.master": "local[*]",
        "test": "abc",
        "test124": "def"
    },
    "spark_env_vars": {
        "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
    }
}

With loop.last special variable we can check whether the current element is the last one, and skip putting a comma at the end.


问:
Data structure that requires a search function in c++
this is our tasks and I don't know what command should I use to put a search function .
it should use a search function to search for the Employee ID No. If found, display the details.
Otherwise, tell the user that record not found. these are the requirements the user inputs 6 employee records with the corresponding data structure fields:
a. ID No
b. Name
c. Age
d. Gender (M/F)
e. Address
f. Salary</p>
```<code>#include<iostream>
#include<string>
#include<sstream>
using namespace std;

struct Info {
    string Id;
    string Name;
    string Age;
    string Gender;
    string Address;
    string Salary;

}i1, i2, i3, i4, i5, i6;

void printdata(Info data);
//storing data
int main() {

    string staff1;
    cout << "ID Number: ";
    getline(cin, staff1);
    cout << "Name: ";
    getline(cin, i1.Name);
    cout << "Age: ";
    getline(cin, i1.Age);
    cout << "Gender(M/F): ";
    getline(cin, i1.Gender);
    cout << "Address: ";
    getline(cin, i1.Address);
    cout << "Salary: ";
    getline(cin, i1.Salary);
    cout << "\n";

    string staff2;
    cout << "ID Number: ";
    getline(cin, staff2);
    cout << "Name: ";
    getline(cin, i2.Name);
    cout << "Age: ";
    getline(cin, i2.Age);
    cout << "Gender(M/F): ";
    getline(cin, i2.Gender);
    cout << "Address: ";
    getline(cin, i2.Address);
    cout << "Salary: ";
    getline(cin, i2.Salary);
    cout << "\n";

    string staff3;
    cout << "ID Number: ";
    getline(cin, staff3);
    cout << "Name: ";
    getline(cin, i3.Name);
    cout << "Age: ";
    getline(cin, i3.Age);
    cout << "Gender(M/F): ";
    getline(cin, i3.Gender);
    cout << "Address: ";
    getline(cin, i3.Address);
    cout << "Salary: ";
    getline(cin, i3.Salary);
    cout << "\n";

    string staff4;
    cout << "ID Number: ";
    getline(cin, staff4);
    cout << "Name: ";
    getline(cin, i4.Name);
    cout << "Age: ";
    getline(cin, i4.Age);
    cout << "Gender(M/F): ";
    getline(cin, i4.Gender);
    cout << "Address: ";
    getline(cin, i4.Address);
    cout << "Salary: ";
    getline(cin, i4.Salary);
    cout << "\n";

    string staff5;
    cout << "ID Number: ";
    getline(cin, staff5);
    cout << "Name: ";
    getline(cin, i5.Name);
    cout << "Age: ";
    getline(cin, i5.Age);
    cout << "Gender(M/F): ";
    getline(cin, i5.Gender);
    cout << "Address: ";
    getline(cin, i5.Address);
    cout << "Salary: ";
    getline(cin, i5.Salary);
    cout << "\n";

    string staff6;
    cout << "ID Number: ";
    getline(cin, staff6);
    cout << "Name: ";
    getline(cin, i6.Name);
    cout << "Age: ";
    getline(cin, i6.Age);
    cout << "Gender(M/F): ";
    getline(cin, i6.Gender);
    cout << "Address: ";
    getline(cin, i6.Address);
    cout << "Salary: ";
    getline(cin, i6.Salary);
    cout << "\n";

    string a;
    cout << "\nEnter Employees ID Number: ";
    getline(cin, a);

    if (a == staff1) {
        printdata(i1);
    }
    else if (a == staff2) {
        printdata(i2);
    }
    else if (a == staff3) {
        printdata(i3);
    }
    else if (a == staff4) {
        printdata(i4);
    }
    else if (a == staff5) {
        printdata(i5);
    }
    else if (a == staff6) {
        printdata(i6);
    }
    return 0;
    }
//layout of data output
void printdata(Info data)
{
    cout << "\n\n";
    cout << "Name: " << data.Name << endl;
    cout << "Age: " << data.Age << endl;
    cout << "Gender: " << data.Gender << endl;
    cout << "Address: " << data.Address << endl;
    cout << "Salary: " << data.Salary << endl;
}
</code>```

答:
You mention the term function. The task is to write a search function.

And you know functions, because you have written one: printdata.

What is not a good implementation, is to create 6 different sets of variables and then reading them step by step. This is not good.

Also here you must use a function. What would you have done, if the teacher would have said: Use 100 Info data?

So, first step is to write a function for the input. For you important to know is, how to return values from a function. There are basically 3 possibilites.

Pass an Info ass pointer

Pass an info as reference

Return the Info from the function

I will select number 3 to give you an example.

```<code>Info getInfo() {

    Info result;

    cout << "ID Number: ";
    getline(cin, result.Id);
    cout << "Name: ";
    getline(cin, result.Name);
    cout << "Age: ";
    getline(cin, result.Age);
    cout << "Gender(M/F): ";
    getline(cin, result.Gender);
    cout << "Address: ";
    getline(cin, result.Address);
    cout << "Salary: ";
    getline(cin, result.Salary);
    cout << "\n";

    return result;
}
</code>```

With that your program can already be shortened very much and look better. We eliminated much code repetition by using a function.

The next version of your code would then look like this:

```<code>#include<iostream>
#include<string>
#include<sstream>
using namespace std;

struct Info {
    string Id;
    string Name;
    string Age;
    string Gender;
    string Address;
    string Salary;

}i1, i2, i3, i4, i5, i6;

Info getInfo() {

    Info result;

    cout << "ID Number: ";
    getline(cin, result.Id);
    cout << "Name: ";
    getline(cin, result.Name);
    cout << "Age: ";
    getline(cin, result.Age);
    cout << "Gender(M/F): ";
    getline(cin, result.Gender);
    cout << "Address: ";
    getline(cin, result.Address);
    cout << "Salary: ";
    getline(cin, result.Salary);
    cout << "\n";

    return result;
}

void printdata(Info data);
//storing data
int main() {

    i1 = getInfo();
    i2 = getInfo();
    i3 = getInfo();
    i4 = getInfo();
    i5 = getInfo();
    i6 = getInfo();

    string a;
    cout << "\nEnter Employees ID Number: ";
    getline(cin, a);

    if (a == i1.Id) {
        printdata(i1);
    }
    else if (a == i2.Id) {
        printdata(i2);
    }
    else if (a == i3.Id) {
        printdata(i3);
    }
    else if (a == i4.Id) {
        printdata(i4);
    }
    else if (a == i5.Id) {
        printdata(i5);
    }
    else if (a == i6.Id) {
        printdata(i6);
    }
    return 0;
    }
//layout of data output
void printdata(Info data)
{
    cout << "\n\n";
    cout << "Name: " << data.Name << endl;
    cout << "Age: " << data.Age << endl;
    cout << "Gender: " << data.Gender << endl;
    cout << "Address: " << data.Address << endl;
    cout << "Salary: " << data.Salary << endl;
}

</code>```

Bu this is of course still not good. Therefore the next important information is that we can use so a called "arrays". In arrays you can store 1 or many instances of the same data type.

And in your example you have to store 6 instances of the same type "Info".

How can this be done. In C++ we would always uses a std::vector or a std::array. You may read here and here about those.

But most probably you did not learn about them yet. But, no worries, C++ understands some legacy code from C and so we can use C-Style arrays. Please read here about them. I guess, you saw it already.

Now, if you want to have a data structure for 6 Info's. You can write:

```<code>Info data[6];
</code>```

And then you can store 6 instances of info in data. Using the index operator [].

And to avoid redundant writing we can use for loop. Please read here about for loops.

Additionally we will add a function for searching.

This will lead us to the nearly final implementation:

```<code>#include<iostream>
#include<string>
#include<sstream>
using namespace std;

struct Info {
    string Id;
    string Name;
    string Age;
    string Gender;
    string Address;
    string Salary;

};

Info getInfo() {

    Info result;

    cout << "ID Number: ";
    getline(cin, result.Id);
    cout << "Name: ";
    getline(cin, result.Name);
    cout << "Age: ";
    getline(cin, result.Age);
    cout << "Gender(M/F): ";
    getline(cin, result.Gender);
    cout << "Address: ";
    getline(cin, result.Address);
    cout << "Salary: ";
    getline(cin, result.Salary);
    cout << "\n";

    return result;
}

void printdata(Info data);

void searchAndPrint(Info data[6]) {
    string a;
    cout << "\nEnter Employees ID Number: ";
    getline(cin, a);

    for (int i = 0; i < 6; ++i) {
        if (a == data[i].Id)
            printdata(data[i]);
    }
}

//storing data
int main() {

    Info data[6];

    for (int i = 0; i < 6; ++i) {
        data[i] = getInfo();
    }
    searchAndPrint(data);

    return 0;
}
//layout of data output
void printdata(Info data)
{
    cout << "\n\n";
    cout << "Name: " << data.Name << endl;
    cout << "Age: " << data.Age << endl;
    cout << "Gender: " << data.Gender << endl;
    cout << "Address: " << data.Address << endl;
    cout << "Salary: " << data.Salary << endl;
}
</code>```

And alittle bit more advanced, using more C++ elements:

```<code>#include<iostream>
#include<string>

struct Info;                          // Forward declaration
constexpr size_t NumberOfInfo = 6u;   // We want to use 6 Info structs
using InfoData = Info[NumberOfInfo];  // Define the type of the array

struct Info {                         // Structure to store info abaout a person
    std::string Id;
    std::string Name;
    std::string Age;
    std::string Gender;
    std::string Address;
    std::string Salary;
};

// Get info data from user
void getInfo(InfoData &data) {

    for (size_t i = 0u; i < NumberOfInfo; ++i) {

        std::cout << "ID Number: ";
        std::getline(std::cin, data[i].Id);
        std::cout << "Name: ";
        std::getline(std::cin, data[i].Name);
        std::cout << "Age: ";
        std::getline(std::cin, data[i].Age);
        std::cout << "Gender(M/F): ";
        std::getline(std::cin, data[i].Gender);
        std::cout << "Address: ";
        std::getline(std::cin, data[i].Address);
        std::cout << "Salary: ";
        std::getline(std::cin, data[i].Salary);
        std::cout << "\n";
    }
}

// Print one Info data to std::cout
void printdata(Info &data)
{
    std::cout << "\n\nName: " << data.Name << '\n'
        << "Age: " << data.Age << '\n'
        << "Gender: " << data.Gender << '\n'
        << "Address: " << data.Address << '\n'
        << "Salary: " << data.Salary << '\n';
}

// Search and ID and, if found, show the Info
void searchAndPrint(InfoData &data) {

    std::string a;
    std::cout << "\nEnter Employees ID Number: ";
    std::getline(std::cin, a);

    for (int i = 0; i < NumberOfInfo; ++i) {
        if (a == data[i].Id)
            printdata(data[i]);
    }
}

// Main function
int main() {

    InfoData data;

    getInfo(data);
    searchAndPrint(data);

    return 0;
}

</code>```

The intersting point in the last solution is:

If you really want to use full C++ and with that std::array, then the only difference is

to inlcude <array> and

to replace the line using InfoData = Info[NumberOfInfo]; with using InfoData = std::array<Info,NumberOfInfo>;

Body:
this is our tasks and I don't know what command should I use to put a search function .
it should use a search function to search for the Employee ID No. If found, display the details.
Otherwise, tell the user that record not found. these are the requirements the user inputs 6 employee records with the corresponding data structure fields:
a. ID No
b. Name
c. Age
d. Gender (M/F)
e. Address
f. Salary

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

struct Info {
    string Id;
    string Name;
    string Age;
    string Gender;
    string Address;
    string Salary;

}i1, i2, i3, i4, i5, i6;

void printdata(Info data);
//storing data
int main() {

    string staff1;
    cout << "ID Number: ";
    getline(cin, staff1);
    cout << "Name: ";
    getline(cin, i1.Name);
    cout << "Age: ";
    getline(cin, i1.Age);
    cout << "Gender(M/F): ";
    getline(cin, i1.Gender);
    cout << "Address: ";
    getline(cin, i1.Address);
    cout << "Salary: ";
    getline(cin, i1.Salary);
    cout << "\n";

    string staff2;
    cout << "ID Number: ";
    getline(cin, staff2);
    cout << "Name: ";
    getline(cin, i2.Name);
    cout << "Age: ";
    getline(cin, i2.Age);
    cout << "Gender(M/F): ";
    getline(cin, i2.Gender);
    cout << "Address: ";
    getline(cin, i2.Address);
    cout << "Salary: ";
    getline(cin, i2.Salary);
    cout << "\n";

    string staff3;
    cout << "ID Number: ";
    getline(cin, staff3);
    cout << "Name: ";
    getline(cin, i3.Name);
    cout << "Age: ";
    getline(cin, i3.Age);
    cout << "Gender(M/F): ";
    getline(cin, i3.Gender);
    cout << "Address: ";
    getline(cin, i3.Address);
    cout << "Salary: ";
    getline(cin, i3.Salary);
    cout << "\n";

    string staff4;
    cout << "ID Number: ";
    getline(cin, staff4);
    cout << "Name: ";
    getline(cin, i4.Name);
    cout << "Age: ";
    getline(cin, i4.Age);
    cout << "Gender(M/F): ";
    getline(cin, i4.Gender);
    cout << "Address: ";
    getline(cin, i4.Address);
    cout << "Salary: ";
    getline(cin, i4.Salary);
    cout << "\n";

    string staff5;
    cout << "ID Number: ";
    getline(cin, staff5);
    cout << "Name: ";
    getline(cin, i5.Name);
    cout << "Age: ";
    getline(cin, i5.Age);
    cout << "Gender(M/F): ";
    getline(cin, i5.Gender);
    cout << "Address: ";
    getline(cin, i5.Address);
    cout << "Salary: ";
    getline(cin, i5.Salary);
    cout << "\n";

    string staff6;
    cout << "ID Number: ";
    getline(cin, staff6);
    cout << "Name: ";
    getline(cin, i6.Name);
    cout << "Age: ";
    getline(cin, i6.Age);
    cout << "Gender(M/F): ";
    getline(cin, i6.Gender);
    cout << "Address: ";
    getline(cin, i6.Address);
    cout << "Salary: ";
    getline(cin, i6.Salary);
    cout << "\n";

    string a;
    cout << "\nEnter Employees ID Number: ";
    getline(cin, a);

    if (a == staff1) {
        printdata(i1);
    }
    else if (a == staff2) {
        printdata(i2);
    }
    else if (a == staff3) {
        printdata(i3);
    }
    else if (a == staff4) {
        printdata(i4);
    }
    else if (a == staff5) {
        printdata(i5);
    }
    else if (a == staff6) {
        printdata(i6);
    }
    return 0;
    }
//layout of data output
void printdata(Info data)
{
    cout << "\n\n";
    cout << "Name: " << data.Name << endl;
    cout << "Age: " << data.Age << endl;
    cout << "Gender: " << data.Gender << endl;
    cout << "Address: " << data.Address << endl;
    cout << "Salary: " << data.Salary << endl;
}

Body:
You mention the term function. The task is to write a search function.

And you know functions, because you have written one: printdata.

What is not a good implementation, is to create 6 different sets of variables and then reading them step by step. This is not good.

Also here you must use a function. What would you have done, if the teacher would have said: Use 100 Info data?

So, first step is to write a function for the input. For you important to know is, how to return values from a function. There are basically 3 possibilites.

Pass an Info ass pointer

Pass an info as reference

Return the Info from the function

I will select number 3 to give you an example.

Info getInfo() {

    Info result;

    cout << "ID Number: ";
    getline(cin, result.Id);
    cout << "Name: ";
    getline(cin, result.Name);
    cout << "Age: ";
    getline(cin, result.Age);
    cout << "Gender(M/F): ";
    getline(cin, result.Gender);
    cout << "Address: ";
    getline(cin, result.Address);
    cout << "Salary: ";
    getline(cin, result.Salary);
    cout << "\n";

    return result;
}

With that your program can already be shortened very much and look better. We eliminated much code repetition by using a function.

The next version of your code would then look like this:

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

struct Info {
    string Id;
    string Name;
    string Age;
    string Gender;
    string Address;
    string Salary;

}i1, i2, i3, i4, i5, i6;

Info getInfo() {

    Info result;

    cout << "ID Number: ";
    getline(cin, result.Id);
    cout << "Name: ";
    getline(cin, result.Name);
    cout << "Age: ";
    getline(cin, result.Age);
    cout << "Gender(M/F): ";
    getline(cin, result.Gender);
    cout << "Address: ";
    getline(cin, result.Address);
    cout << "Salary: ";
    getline(cin, result.Salary);
    cout << "\n";

    return result;
}

void printdata(Info data);
//storing data
int main() {

    i1 = getInfo();
    i2 = getInfo();
    i3 = getInfo();
    i4 = getInfo();
    i5 = getInfo();
    i6 = getInfo();

    string a;
    cout << "\nEnter Employees ID Number: ";
    getline(cin, a);

    if (a == i1.Id) {
        printdata(i1);
    }
    else if (a == i2.Id) {
        printdata(i2);
    }
    else if (a == i3.Id) {
        printdata(i3);
    }
    else if (a == i4.Id) {
        printdata(i4);
    }
    else if (a == i5.Id) {
        printdata(i5);
    }
    else if (a == i6.Id) {
        printdata(i6);
    }
    return 0;
    }
//layout of data output
void printdata(Info data)
{
    cout << "\n\n";
    cout << "Name: " << data.Name << endl;
    cout << "Age: " << data.Age << endl;
    cout << "Gender: " << data.Gender << endl;
    cout << "Address: " << data.Address << endl;
    cout << "Salary: " << data.Salary << endl;
}

Bu this is of course still not good. Therefore the next important information is that we can use so a called "arrays". In arrays you can store 1 or many instances of the same data type.

And in your example you have to store 6 instances of the same type "Info".

How can this be done. In C++ we would always uses a std::vector or a std::array. You may read here and here about those.

But most probably you did not learn about them yet. But, no worries, C++ understands some legacy code from C and so we can use C-Style arrays. Please read here about them. I guess, you saw it already.

Now, if you want to have a data structure for 6 Info's. You can write:

Info data[6];

And then you can store 6 instances of info in data. Using the index operator [].

And to avoid redundant writing we can use for loop. Please read here about for loops.

Additionally we will add a function for searching.

This will lead us to the nearly final implementation:

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

struct Info {
    string Id;
    string Name;
    string Age;
    string Gender;
    string Address;
    string Salary;

};

Info getInfo() {

    Info result;

    cout << "ID Number: ";
    getline(cin, result.Id);
    cout << "Name: ";
    getline(cin, result.Name);
    cout << "Age: ";
    getline(cin, result.Age);
    cout << "Gender(M/F): ";
    getline(cin, result.Gender);
    cout << "Address: ";
    getline(cin, result.Address);
    cout << "Salary: ";
    getline(cin, result.Salary);
    cout << "\n";

    return result;
}

void printdata(Info data);

void searchAndPrint(Info data[6]) {
    string a;
    cout << "\nEnter Employees ID Number: ";
    getline(cin, a);

    for (int i = 0; i < 6; ++i) {
        if (a == data[i].Id)
            printdata(data[i]);
    }
}

//storing data
int main() {

    Info data[6];

    for (int i = 0; i < 6; ++i) {
        data[i] = getInfo();
    }
    searchAndPrint(data);

    return 0;
}
//layout of data output
void printdata(Info data)
{
    cout << "\n\n";
    cout << "Name: " << data.Name << endl;
    cout << "Age: " << data.Age << endl;
    cout << "Gender: " << data.Gender << endl;
    cout << "Address: " << data.Address << endl;
    cout << "Salary: " << data.Salary << endl;
}

And alittle bit more advanced, using more C++ elements:

#include<iostream>
#include<string>

struct Info;                          // Forward declaration
constexpr size_t NumberOfInfo = 6u;   // We want to use 6 Info structs
using InfoData = Info[NumberOfInfo];  // Define the type of the array

struct Info {                         // Structure to store info abaout a person
    std::string Id;
    std::string Name;
    std::string Age;
    std::string Gender;
    std::string Address;
    std::string Salary;
};

// Get info data from user
void getInfo(InfoData &data) {

    for (size_t i = 0u; i < NumberOfInfo; ++i) {

        std::cout << "ID Number: ";
        std::getline(std::cin, data[i].Id);
        std::cout << "Name: ";
        std::getline(std::cin, data[i].Name);
        std::cout << "Age: ";
        std::getline(std::cin, data[i].Age);
        std::cout << "Gender(M/F): ";
        std::getline(std::cin, data[i].Gender);
        std::cout << "Address: ";
        std::getline(std::cin, data[i].Address);
        std::cout << "Salary: ";
        std::getline(std::cin, data[i].Salary);
        std::cout << "\n";
    }
}

// Print one Info data to std::cout
void printdata(Info &data)
{
    std::cout << "\n\nName: " << data.Name << '\n'
        << "Age: " << data.Age << '\n'
        << "Gender: " << data.Gender << '\n'
        << "Address: " << data.Address << '\n'
        << "Salary: " << data.Salary << '\n';
}

// Search and ID and, if found, show the Info
void searchAndPrint(InfoData &data) {

    std::string a;
    std::cout << "\nEnter Employees ID Number: ";
    std::getline(std::cin, a);

    for (int i = 0; i < NumberOfInfo; ++i) {
        if (a == data[i].Id)
            printdata(data[i]);
    }
}

// Main function
int main() {

    InfoData data;

    getInfo(data);
    searchAndPrint(data);

    return 0;
}

The intersting point in the last solution is:

If you really want to use full C++ and with that std::array, then the only difference is

to inlcude <array> and

to replace the line using InfoData = Info[NumberOfInfo]; with using InfoData = std::array<Info,NumberOfInfo>;


问:
Why use the `go` keyword when calling a function?
I was going through an example of a TCP server. They defined a function and called it with:

```<code>go handleRequest(conn)
</code>```

I thought it was weird seeing the go keyword, so I tried it without:

```<code>handleRequest(conn)
</code>```

To my surprise, this worked!

If both work the same way, why use the go keyword at all?

If they work differently, what is the difference?

Is there a certain style guideline to use, or should you just use personal preference?

答:
Concurrency is not well documented in the go spec and it is one of the most powerful features of the language, the go keyword is the starting point when you are building concurrent software and not procedural software in go.

You need to look at channels as well to better understand this concept.

When you removed the go keyword, you made the function call procedural.

Check out the talk by Rob Pike (Creator of Go) on concurrency in golang.
https://www.youtube.com/watch?v=f6kdp27TYZs&t=1198s&ab_channel=GoogleDevelopers

Body:
I was going through an example of a TCP server. They defined a function and called it with:

go handleRequest(conn)

I thought it was weird seeing the go keyword, so I tried it without:

handleRequest(conn)

To my surprise, this worked!

If both work the same way, why use the go keyword at all?

If they work differently, what is the difference?

Is there a certain style guideline to use, or should you just use personal preference?


问:
Generic Data Access Layer in an Multi-Layer Arcitechture
I need to create an generic data access layer to use in my final assignment in Software Engineering, but my data access layer that I have currently created can automatically generate CRUD(Create, Read, Update and Delete) SQL Statement. I still need to define every table in my database and every time I change my database I need to define the changes in my data access layer.

Please look at the sample of my code and tell me how to change my code to improve my access layer:

```<code>class sqlConn
{
    //Local
    private String strConn = @"Data Source=.\SQLEXPRESS;" +
        @"AttachDbFilename='D:\JP Stuff\BELGIUM CAMPUS\3de Jaar\SOFTWARE ENGINEERING\ASSIGNMENT\Premier Service Solutions\Premier Service Solutions\DB\db_PSS_1.0.mdf';" +
        @"Integrated Security=True;" +
        @"User Instance=True";
    private SqlConnection conn;

    //Properties
    public SqlConnection Conn
    {
        get { return this.conn = new SqlConnection(this.strConn); }
    }

    //Constructor
    public sqlConn()
    {

    }
}

class sqlFactory : sqlConn
{
    //Constructor
    public sqlFactory()
        : base()
    {

    }

    //Insert Record into database
    public void Create(String[] dbData, List<String> strRow)
    {
        using (SqlConnection sqlCon = this.Conn)
        using (SqlCommand com = new SqlCommand("SELECT * FROM " + dbData[0], sqlCon))
        {
            SqlDataAdapter da = new SqlDataAdapter(com);
            SqlCommandBuilder sqlbuilder = new SqlCommandBuilder(da);

            DataSet ds = new DataSet();
            da.Fill(ds, dbData[0]);

            DataRow dr = ds.Tables[dbData[0]].NewRow();

            for (int i = 0; i < dbData.Count() - 2; i++)
            {
                dr[i + 1] = strRow[i];
            }

            ds.Tables[dbData[0]].Rows.Add(dr);
            da.Update(ds, dbData[0]);
        }
    }
}

 class dbDefinitions : sqlFactory
 {
    public static Dictionary<String, String[]> columns;

    static dbDefinitions()
    {
        columns = new Dictionary<String,String[]>();

        //tblCall Definition
        #region call
        String[] data = new String[]
        {
            "tblCall", "call_ID_PK", "call_emp_ID_FK",
            "call_Description", "call_Notes", "call_Start_Time",
            "call_End_Time", "call_Job_FK"
        };
        columns.Add("call", data);
        #endregion
    }
}
</code>```

答: Your DAO should have backing classes that act as models to the tables.  These models should all have a common interface.  Your DAO should then have instances of the Model interface with XML configuration pointing to the proper tables for the model.  This will prevent you from having to define your tables in your code.  Your data access layer is the layer that accesses your data, not the layer that defines your data.  Your models should define the data.

Body:
I need to create an generic data access layer to use in my final assignment in Software Engineering, but my data access layer that I have currently created can automatically generate CRUD(Create, Read, Update and Delete) SQL Statement. I still need to define every table in my database and every time I change my database I need to define the changes in my data access layer.

Please look at the sample of my code and tell me how to change my code to improve my access layer:

class sqlConn
{
    //Local
    private String strConn = @"Data Source=.\SQLEXPRESS;" +
        @"AttachDbFilename='D:\JP Stuff\BELGIUM CAMPUS\3de Jaar\SOFTWARE ENGINEERING\ASSIGNMENT\Premier Service Solutions\Premier Service Solutions\DB\db_PSS_1.0.mdf';" +
        @"Integrated Security=True;" +
        @"User Instance=True";
    private SqlConnection conn;

    //Properties
    public SqlConnection Conn
    {
        get { return this.conn = new SqlConnection(this.strConn); }
    }

    //Constructor
    public sqlConn()
    {

    }
}

class sqlFactory : sqlConn
{
    //Constructor
    public sqlFactory()
        : base()
    {

    }

    //Insert Record into database
    public void Create(String[] dbData, List<String> strRow)
    {
        using (SqlConnection sqlCon = this.Conn)
        using (SqlCommand com = new SqlCommand("SELECT * FROM " + dbData[0], sqlCon))
        {
            SqlDataAdapter da = new SqlDataAdapter(com);
            SqlCommandBuilder sqlbuilder = new SqlCommandBuilder(da);

            DataSet ds = new DataSet();
            da.Fill(ds, dbData[0]);

            DataRow dr = ds.Tables[dbData[0]].NewRow();

            for (int i = 0; i < dbData.Count() - 2; i++)
            {
                dr[i + 1] = strRow[i];
            }

            ds.Tables[dbData[0]].Rows.Add(dr);
            da.Update(ds, dbData[0]);
        }
    }
}

 class dbDefinitions : sqlFactory
 {
    public static Dictionary<String, String[]> columns;

    static dbDefinitions()
    {
        columns = new Dictionary<String,String[]>();

        //tblCall Definition
        #region call
        String[] data = new String[]
        {
            "tblCall", "call_ID_PK", "call_emp_ID_FK",
            "call_Description", "call_Notes", "call_Start_Time",
            "call_End_Time", "call_Job_FK"
        };
        columns.Add("call", data);
        #endregion
    }
}


问:
Pandas: find column min and max ranges by group
I have a data frame like so:

```<code>df = pd.DataFrame({
    'A':np.random.random(20),
    'B':np.random.random(20),
    'Gen': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]
})
</code>```

Is there a simple way with pandas to find the range (min and max values) in each column by group 'Gen'? In real life, I can have lots of columns A, B, ... (>20). The result could look something like:

```<code>Var   Gen    Min   Max
A     1      x     x
B     1      x     x
A     2      x     x
...
</code>```

答:
You can melt to reshape, then groupby+agg to aggregate per group:

```<code>(df.melt(id_vars='Gen', var_name='Var')
   .groupby(['Var', 'Gen'])['value']
   .agg(['min', 'max'])
   #.reset_index()  # uncomment to have Gen/Var as columns
)
</code>```

Alternatively, aggregate first, then stack:

```<code>df.groupby('Gen').agg(['min', 'max']).stack(level=0)
</code>```

output:

```<code>              min       max
Var Gen
A   1    0.009241  0.813241
    2    0.142218  0.751106
    3    0.005829  0.991914
    4    0.033108  0.579354
B   1    0.241094  0.990492
    2    0.030335  0.848735
    3    0.209076  0.785530
    4    0.277970  0.962307
</code>```

Body:
I have a data frame like so:

df = pd.DataFrame({
    'A':np.random.random(20),
    'B':np.random.random(20),
    'Gen': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]
})

Is there a simple way with pandas to find the range (min and max values) in each column by group 'Gen'? In real life, I can have lots of columns A, B, ... (>20). The result could look something like:

Var   Gen    Min   Max
A     1      x     x
B     1      x     x
A     2      x     x
...

Body:
You can melt to reshape, then groupby+agg to aggregate per group:

(df.melt(id_vars='Gen', var_name='Var')
   .groupby(['Var', 'Gen'])['value']
   .agg(['min', 'max'])
   #.reset_index()  # uncomment to have Gen/Var as columns
)

Alternatively, aggregate first, then stack:

df.groupby('Gen').agg(['min', 'max']).stack(level=0)

output:

              min       max
Var Gen
A   1    0.009241  0.813241
    2    0.142218  0.751106
    3    0.005829  0.991914
    4    0.033108  0.579354
B   1    0.241094  0.990492
    2    0.030335  0.848735
    3    0.209076  0.785530
    4    0.277970  0.962307


问:
Drop pandas rows by index name
I have a dataframe of let say 1000 rows. I want to drop the row store in variable breakval and also next 10 rows.

```<code>breakval=[10,100,500]
for i in breakval:
    df=df.drop(df.index[i:i+10])
</code>```

But after first iteration in which row 10-20 are dropped. I want row 100-110 by index name, not by row number. Because row number is reduced by 10, but row index name remain the same.
I am looking for a way to get index by its name. For example if i do df.index[12] it will return me the value, though i dropped it. For this purpose i used df.loc[22].name, but it worked for a single value

答:
One solution can be sorting breakval decreasingly. So breakval = [500, 100, 10] and doing the same dropping but 500 first, then 100 and then 10.

It will also obviously drop the rows and the indices will be updated. But at first, it will drop from index 500 to 510 so the indices of the laters will be updated, the previous indices are not changed.

Then dropping from 100 to 110 will also change the later indices not the previous indices before 100 and same for 10 to 20.

Title: Drop pandas rows by index name

Body:
I have a dataframe of let say 1000 rows. I want to drop the row store in variable breakval and also next 10 rows.

breakval=[10,100,500]
for i in breakval:
    df=df.drop(df.index[i:i+10])

But after first iteration in which row 10-20 are dropped. I want row 100-110 by index name, not by row number. Because row number is reduced by 10, but row index name remain the same.
I am looking for a way to get index by its name. For example if i do df.index[12] it will return me the value, though i dropped it. For this purpose i used df.loc[22].name, but it worked for a single value


问:
How to combine array in php to dynamically?
I have code like this

```<code>$a =[
      [1,2],
      [4,6],
      [10,24]
    ];
</code>```

i want a output like this

```<code>    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )
</code>```

and i use code like this

```<code>print_r(array_merge($a[0],$a[1],$a[2]));
</code>```

if a have code like this and have more data

```<code>    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )
</code>```

writing like this is not good

```<code>print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));
</code>```

how to use array_merge in dinamic in there?

答:
```<code>$result = array_reduce($a, fn($carry, $item) => array_merge($carry, $item), []);
</code>```

Body:
I have code like this

$a =[
      [1,2],
      [4,6],
      [10,24]
    ];

i want a output like this

    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )

and i use code like this

print_r(array_merge($a[0],$a[1],$a[2]));

if a have code like this and have more data

    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )

writing like this is not good

print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));

how to use array_merge in dinamic in there?


问:
How do I use nginx to rewrite all links start with www.example.com/page to www.example.com/new-page
I want to redirect all request to

www.example.com/page

to

```<code>www.example.com/new-page
</code>```

That means to replace www.example.com/page with the new one, for instance:

```<code>www.example.com/page
301 > www.example.com/new-page

www.example.com/page/1
301 >www.example.com/new-page/1

www.example.com/page/1.png
301 >www.example.com/new-page/1.png?1

www.example.com/page/common/1.png
301 >www.example.com/new-page/common/1.png?1

www.example.com/page123
301 >www.example.com/new-page123
</code>```

How could I do that?

答:
Use rewrite with a redirect param like

location /page/ {
        rewrite ^/page/(.*)$ /new-page/$1 permanent;
    }
```
<p>My Testing</p>
<pre class="lang-sh prettyprint-override"><code>127.0.0.1 - - [12/Feb/2022:10:20:42 +0000] "GET /page/test/123 HTTP/1.1" 301 169 "-" "curl/7.74.0" "-"
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.21.6
< Date: Sat, 12 Feb 2022 10:20:42 GMT
< Content-Type: text/html
< Content-Length: 169
< Location: http://127.1/new-page/test/123
< Connection: keep-alive
<
* Ignoring the response-body
* Connection #0 to host 127.1 left intact
* Issue another request to this URL: 'http://127.1/new-page/test/123'
* Found bundle for host 127.1: 0x561d293f5970 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#0) with host 127.1
* Connected to 127.1 (127.0.0.1) port 80 (#0)
> GET /new-page/test/123 HTTP/1.1
> Host: 127.1
> User-Agent: curl/7.74.0
> Accept: */*
>127.0.0.1 - - [12/Feb/2022:10:20:42 +0000] "GET /new-page/test/123 HTTP/1.1" 200 3 "-" "curl/7.74.0" "-"

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.21.6
< Date: Sat, 12 Feb 2022 10:20:42 GMT
< Content-Type: application/octet-stream
< Content-Length: 3
< Connection: keep-alive
<
OK
</code>```

Body:
I want to redirect all request to

www.example.com/page

to

www.example.com/new-page

That means to replace www.example.com/page with the new one, for instance:

www.example.com/page
301 > www.example.com/new-page

www.example.com/page/1
301 >www.example.com/new-page/1

www.example.com/page/1.png
301 >www.example.com/new-page/1.png?1

www.example.com/page/common/1.png
301 >www.example.com/new-page/common/1.png?1

www.example.com/page123
301 >www.example.com/new-page123

How could I do that?

Body:
Use rewrite with a redirect param like

location /page/ {
        rewrite ^/page/(.*)$ /new-page/$1 permanent;
    }

My Testing

127.0.0.1 - - [12/Feb/2022:10:20:42 +0000] "GET /page/test/123 HTTP/1.1" 301 169 "-" "curl/7.74.0" "-"
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.21.6
< Date: Sat, 12 Feb 2022 10:20:42 GMT
< Content-Type: text/html
< Content-Length: 169
< Location: http://127.1/new-page/test/123
< Connection: keep-alive
<
* Ignoring the response-body
* Connection #0 to host 127.1 left intact
* Issue another request to this URL: 'http://127.1/new-page/test/123'
* Found bundle for host 127.1: 0x561d293f5970 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#0) with host 127.1
* Connected to 127.1 (127.0.0.1) port 80 (#0)
> GET /new-page/test/123 HTTP/1.1
> Host: 127.1
> User-Agent: curl/7.74.0
> Accept: */*
>127.0.0.1 - - [12/Feb/2022:10:20:42 +0000] "GET /new-page/test/123 HTTP/1.1" 200 3 "-" "curl/7.74.0" "-"

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.21.6
< Date: Sat, 12 Feb 2022 10:20:42 GMT
< Content-Type: application/octet-stream
< Content-Length: 3
< Connection: keep-alive
<
OK


问:
qunit test error with equal and deepEqual
I'm Trying to understand qunit testing

Why is this test failing? If I compare every property, are the same ...

```<code>    test("Get model equal", function () {

        function getModel() {

            function myModel() {
                this.name = "";
                this.address = "";
                this.phone = "";
            }

            return new myModel();
        }

        var model1 = getModel();
        var model2 = getModel();

        equal(model1, model2);

    });

    test("Get model deepEqual", function () {

        function getModel() {

            function myModel() {
                this.name = "";
                this.address = "";
                this.phone = "";
            }

            return new myModel();
        }

        var model1 = getModel();
        var model2 = getModel();

        deepEqual(model1, model2);

    });
</code>```

答: The equality test is failing right? That's because they are two different instances, even though they contain the same data. For example, look at the examples on the QUnit documentation here.</p>

Body:
I'm Trying to understand qunit testing

Why is this test failing? If I compare every property, are the same ...

    test("Get model equal", function () {

        function getModel() {

            function myModel() {
                this.name = "";
                this.address = "";
                this.phone = "";
            }

            return new myModel();
        }

        var model1 = getModel();
        var model2 = getModel();

        equal(model1, model2);

    });

    test("Get model deepEqual", function () {

        function getModel() {

            function myModel() {
                this.name = "";
                this.address = "";
                this.phone = "";
            }

            return new myModel();
        }

        var model1 = getModel();
        var model2 = getModel();

        deepEqual(model1, model2);

    });


问:
SQL - Multiple records into one line with conditions
I have two tables that look like this

Account Table

```<code>| Account Number | Account Name   |
| -------------- | -------------- |
| 12345          | Bob Jones      |
| 12346          | Jenny Smith    |
| 12347          | Mary Frederick |
</code>```

Email Table

```<code>| Account Number         | Email Type    |Email                  | IsPrimary       |
| ---------------------- | --------------|-----------------------|-----------------|
| 12345                  | WORK          | BOBSMITH@STACK.COM    | 0               |
| 12345                  | HOME          | BOBSMITH@GMAIL.COM    | 0               |
| 12345                  | WORK          | BOBSMITH@APPLE.COM    | 1               |
| 12345                  | HOME          | BOBSMITH@HOTMAIL.COM  | 0               |
| 12346                  | HOME          | JMSMITH@GMAIL.COM     | 1               |
| 12346                  | WORK          | JMSMITH@DISNEY.COM    | 0               |
| 12346                  | HOME          | JMSMITH@HOTMAIL.COM   | 0               |
| 12347                  | HOME          | MFRED@HOTMAIL.COM     | 0               |
</code>```

I need to end up with results like this:

```<code>| Account Number           | Account Name      | Home Email         | Work Email         | Alternate Email      |
| ------------------------ | ----------------- |--------------------|--------------------|----------------------|
| 12345                    | Bob Jones         | BOBSMITH@GMAIL.COM | BOBSMITH@APPLE.COM | BOBSMITH@HOTMAIL.COM |
| 12346                    | Jenny Smith       | JMSMITH@GMAIL.COM  | JMSMITH@DISNEY.COM | JMSMITH@HOTMAIL.COM  |
| 12347                    | Mary Frederick    | MFRED@HOTMAIL.COM  |                    |                      |
</code>```

I have all possible combinations of emails such as multiple work and no home, no primaries at all, multiple primaries... etc.

I need the logic to be:

Home Email: When type is Home. If there is a primary, choose the first one. If there is no primary, choose the first non-primary home email. Otherwise make it blank

Work Email: Same as above but for work

Alternate Email: Any third email on the list. If there are more than 3, choose home over work.

I have tried a ton of things and nothing has worked well. Here is my top attempt -two things don't work about it. The 'top 1' returns a lot of nulls and the code for alternates isn't always mutually exclusive to the home and work email, especially for people that have no primary checked:

```<code>select distinct
A01.AccountNumber,
A01.FirstName,
A01.LastName,
(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'HOME' and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'HOME')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as HomeEmail
,(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'WORK'  and A07.EmailType is not null)--and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'WORK')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as WorkEmail
,(
    select top 1 (A07.EmailAddress)
    from A07_AccountEmails A07
    where A07.AccountNumber = A01.AccountNumber
    and A07.Active = 1 and A07.UseAsPrimary = 0
) as AlternateEmailMulti
from A01_AccountMaster A01
left outer join A07_AccountEmails A07 on A07.AccountNumber = A01.AccountNumber
where
A01.[Status] = 'A'
</code>```

答:
Here is an alternative approach which list all e-mails, primaries first.
We use group_,concat to show all matching entries, order by primary prim inversed by desc and finally a newline separator \n to make a vertical list.
NB : It doesn't print correctly in the terminal because of the newlines.</p>
```<code>USE test;
CREATE TABLE user (
        acc INT,
        nam CHAR(10)
        );
INSERT INTO user VALUES ( 1, 'Andrew');
INSERT INTO user VALUES ( 2, 'Bernard');
INSERT INTO user VALUES ( 3, 'Charles');
CREATE TABLE telMail (
        acc INT,
        email CHAR(25),
        type CHAR(5),
        prim INT
        );
INSERT INTO telMail VALUES(1,'a@w0','Work',0);
INSERT INTO telMail VALUES(1,'a@w1','Work',0);
INSERT INTO telMail VALUES(1,'ap@w2','Work',1);
INSERT INTO telMail VALUES(1,'a@w3','Work',0);
INSERT INTO telMail VALUES(1,'a@h1','Home',0);
INSERT INTO telMail VALUES(1,'a@h2','Home',0);
INSERT INTO telMail VALUES(2,'b@h1','Home',0);
INSERT INTO telMail VALUES(2,'b@w1','Work',0);
INSERT INTO telMail VALUES(2,'b@w2','Work',0);
INSERT INTO telMail VALUES(3,'c@h1','Home',0);
INSERT INTO telMail VALUES(3,'cp@h1','Home',1);
INSERT INTO telMail VALUES(3,'c@w1','Work',0);

SELECT
        u.acc 'Account',
        u.nam 'Name',
        GROUP_CONCAT(DISTINCT w.email ORDER BY w.prim DESC SEPARATOR '\n' ) work_mail,
        GROUP_CONCAT(DISTINCT h.email ORDER BY h.prim DESC SEPARATOR '\n' ) home_mail

FROM
        (SELECT acc,email,prim FROM telMail WHERE type ='Home') h
JOIN
        user u on u.acc=h.acc
JOIN
        (SELECT acc,email,prim FROM telMail WHERE type ='Work') w ON u.acc = w.acc
GROUP BY u.acc, u.nam
ORDER BY u.acc;
DROP TABLE user;
DROP TABLE telMail;
</code>```

Body:
I have two tables that look like this

Account Table

| Account Number | Account Name   |
| -------------- | -------------- |
| 12345          | Bob Jones      |
| 12346          | Jenny Smith    |
| 12347          | Mary Frederick |

Email Table

| Account Number         | Email Type    |Email                  | IsPrimary       |
| ---------------------- | --------------|-----------------------|-----------------|
| 12345                  | WORK          | BOBSMITH@STACK.COM    | 0               |
| 12345                  | HOME          | BOBSMITH@GMAIL.COM    | 0               |
| 12345                  | WORK          | BOBSMITH@APPLE.COM    | 1               |
| 12345                  | HOME          | BOBSMITH@HOTMAIL.COM  | 0               |
| 12346                  | HOME          | JMSMITH@GMAIL.COM     | 1               |
| 12346                  | WORK          | JMSMITH@DISNEY.COM    | 0               |
| 12346                  | HOME          | JMSMITH@HOTMAIL.COM   | 0               |
| 12347                  | HOME          | MFRED@HOTMAIL.COM     | 0               |

I need to end up with results like this:

| Account Number           | Account Name      | Home Email         | Work Email         | Alternate Email      |
| ------------------------ | ----------------- |--------------------|--------------------|----------------------|
| 12345                    | Bob Jones         | BOBSMITH@GMAIL.COM | BOBSMITH@APPLE.COM | BOBSMITH@HOTMAIL.COM |
| 12346                    | Jenny Smith       | JMSMITH@GMAIL.COM  | JMSMITH@DISNEY.COM | JMSMITH@HOTMAIL.COM  |
| 12347                    | Mary Frederick    | MFRED@HOTMAIL.COM  |                    |                      |

I have all possible combinations of emails such as multiple work and no home, no primaries at all, multiple primaries... etc.

I need the logic to be:

Home Email: When type is Home. If there is a primary, choose the first one. If there is no primary, choose the first non-primary home email. Otherwise make it blank

Work Email: Same as above but for work

Alternate Email: Any third email on the list. If there are more than 3, choose home over work.

I have tried a ton of things and nothing has worked well. Here is my top attempt -two things don't work about it. The 'top 1' returns a lot of nulls and the code for alternates isn't always mutually exclusive to the home and work email, especially for people that have no primary checked:

select distinct
A01.AccountNumber,
A01.FirstName,
A01.LastName,
(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'HOME' and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'HOME')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as HomeEmail
,(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'WORK'  and A07.EmailType is not null)--and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'WORK')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as WorkEmail
,(
    select top 1 (A07.EmailAddress)
    from A07_AccountEmails A07
    where A07.AccountNumber = A01.AccountNumber
    and A07.Active = 1 and A07.UseAsPrimary = 0
) as AlternateEmailMulti
from A01_AccountMaster A01
left outer join A07_AccountEmails A07 on A07.AccountNumber = A01.AccountNumber
where
A01.[Status] = 'A'

Body:
Here is an alternative approach which list all e-mails, primaries first.
We use group_,concat to show all matching entries, order by primary prim inversed by desc and finally a newline separator \n to make a vertical list.
NB : It doesn't print correctly in the terminal because of the newlines.

USE test;
CREATE TABLE user (
        acc INT,
        nam CHAR(10)
        );
INSERT INTO user VALUES ( 1, 'Andrew');
INSERT INTO user VALUES ( 2, 'Bernard');
INSERT INTO user VALUES ( 3, 'Charles');
CREATE TABLE telMail (
        acc INT,
        email CHAR(25),
        type CHAR(5),
        prim INT
        );
INSERT INTO telMail VALUES(1,'a@w0','Work',0);
INSERT INTO telMail VALUES(1,'a@w1','Work',0);
INSERT INTO telMail VALUES(1,'ap@w2','Work',1);
INSERT INTO telMail VALUES(1,'a@w3','Work',0);
INSERT INTO telMail VALUES(1,'a@h1','Home',0);
INSERT INTO telMail VALUES(1,'a@h2','Home',0);
INSERT INTO telMail VALUES(2,'b@h1','Home',0);
INSERT INTO telMail VALUES(2,'b@w1','Work',0);
INSERT INTO telMail VALUES(2,'b@w2','Work',0);
INSERT INTO telMail VALUES(3,'c@h1','Home',0);
INSERT INTO telMail VALUES(3,'cp@h1','Home',1);
INSERT INTO telMail VALUES(3,'c@w1','Work',0);

SELECT
        u.acc 'Account',
        u.nam 'Name',
        GROUP_CONCAT(DISTINCT w.email ORDER BY w.prim DESC SEPARATOR '\n' ) work_mail,
        GROUP_CONCAT(DISTINCT h.email ORDER BY h.prim DESC SEPARATOR '\n' ) home_mail

FROM
        (SELECT acc,email,prim FROM telMail WHERE type ='Home') h
JOIN
        user u on u.acc=h.acc
JOIN
        (SELECT acc,email,prim FROM telMail WHERE type ='Work') w ON u.acc = w.acc
GROUP BY u.acc, u.nam
ORDER BY u.acc;
DROP TABLE user;
DROP TABLE telMail;