问:
Function-wide exception handling in c++ - is it a bad style?
There is a try-catch thing about functions, which I think sometimes may be quite useful:

```<code>bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}
</code>```

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

```<code>bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
</code>```

after:

```<code>bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}
</code>```

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

答:
Just to be clear: rethrowing and repackaging exceptions isn't poor practice, it's a Good Thing since it minimizes exposure of external dependencies. </p>

<p>However, function-level try-catch is intended for constructor initialization. Saving a couple of horizontal spaces in your code isn't worth using a relatively obscure language feature for. Better to refactor the nested code if you really are indenting that far! </p>

ContentLicense: CC BY-SA 2.5

Body:
There is a try-catch thing about functions, which I think sometimes may be quite useful:

bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}

after:

bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

Body:
Just to be clear: rethrowing and repackaging exceptions isn't poor practice, it's a Good Thing since it minimizes exposure of external dependencies.

However, function-level try-catch is intended for constructor initialization. Saving a couple of horizontal spaces in your code isn't worth using a relatively obscure language feature for. Better to refactor the nested code if you really are indenting that far!

OwnerDisplayName: Pontus Gagge


来源: stackexchange

问:
Python grep and cut
In Linux, it's easy to get certain string by using tools such as grep, cut, or awk.

This show version sample is taken from https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst9300/software/release/16-6/configuration_guide/sys_mgmt/b_166_sys_mgmt_9300_cg/b_166_sys_mgmt_9300_cg_chapter_01.html

```<code>wolf@linux:~$ cat shver
cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S

wolf@linux:~$
</code>```

grep and cut

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2
 C9300-48P
 C9300-48P
wolf@linux:~$
</code>```

Remove extra space (If there's better solution, let me know)

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2
C9300-48P
C9300-48P
wolf@linux:~$
</code>```

Select the 1st output

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2 | head -1
C9300-48P
wolf@linux:~$
</code>```

That was in Linux. I was planning to write similar code in Python.

My attempt which still didn't work at the moment.

Define shver string

```<code>>>> shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
... Processor board ID FCW2049G03S
... 2048K bytes of non-volatile configuration memory.
... 8388608K bytes of physical memory.
... 1638400K bytes of Crash Files at crashinfo:.
... 11264000K bytes of Flash at flash:.
... 0K bytes of WebUI ODM Files at webui:.
... Model Number                       : C9300-48P
...
... Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
... Motherboard Assembly Number        : 73-17956-04
... Motherboard Serial Number          : FOC20465ABU
... Model Revision Number              : P4B
... Motherboard Revision Number        : 04
... Model Number                       : C9300-48P
... System Serial Number               : FCW2049G03S
... '''
>>>
</code>```

verify it

```<code>>>> shver
'cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.\nProcessor board ID FCW2049G03S\n2048K bytes of non-volatile configuration memory.\n8388608K bytes of physical memory.\n1638400K bytes of Crash Files at crashinfo:.\n11264000K bytes of Flash at flash:.\n0K bytes of WebUI ODM Files at webui:.\nModel Number                       : C9300-48P\n\nBase Ethernet MAC Address          : 04:6c:9d:01:3b:80\nMotherboard Assembly Number        : 73-17956-04\nMotherboard Serial Number          : FOC20465ABU\nModel Revision Number              : P4B\nMotherboard Revision Number        : 04\nModel Number                       : C9300-48P\nSystem Serial Number               : FCW2049G03S\n'
>>>
</code>```

create a list

```<code>>>> shver_list = shver.splitlines()
>>> shver_list
['cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.', 'Processor board ID FCW2049G03S', '2048K bytes of non-volatile configuration memory.', '8388608K bytes of physical memory.', '1638400K bytes of Crash Files at crashinfo:.', '11264000K bytes of Flash at flash:.', '0K bytes of WebUI ODM Files at webui:.', 'Model Number                       : C9300-48P', '', 'Base Ethernet MAC Address          : 04:6c:9d:01:3b:80', 'Motherboard Assembly Number        : 73-17956-04', 'Motherboard Serial Number          : FOC20465ABU', 'Model Revision Number              : P4B', 'Motherboard Revision Number        : 04', 'Model Number                       : C9300-48P', 'System Serial Number               : FCW2049G03S']
>>>
</code>```

Next step is to find out if string 'Model Number' is there or not and print out that line

```<code>>>> if 'Model Number' in shver_list:
...     'yes'
... else:
...     'no'
...
'no'
>>>
</code>```

How do I print out the line contains 'Model Number'?

```<code>>>> for i in shver_list:
...     if 'Model Number' in shver_list:
...             i
...
>>>
</code>```

Desired Output

```<code>C9300-48P
</code>```

答:
From your shver_list step, you can do this:

```<code>for item in shver_list:
    if "Model Number" in item:
        break
</code>```

So once it finds a match, it will break out the loop and look what we have in item:

```<code>>>> item
'Model Number                       : C9300-48P'
</code>```

Now we can split this on : (note the spaces around) and get:

```<code>>>> items.split(" : ")
['Model Number                      ', 'C9300-48P']
</code>```

So the desired element lies in the 1st positon in this list.

All in all:

```<code>for item in shver_list:
    if "Model Number" in item:
        break
desired = item.split(" : ")[1]
</code>```

Another way of doing is with regular expressions. This time we take it from shver string:

```<code>import re
matches_gen = re.finditer(r"Model Number\s+:\s*(.+)", shver)
desired = next(matches_gen).group(1)
</code>```

We use finditer for lazy evaluation and because we want the first occurence, we use one next on it and take the matching group to get the desired result of C9300-48P.

ContentLicense: CC BY-SA 4.0

Title: Python grep and cut

Body:
In Linux, it's easy to get certain string by using tools such as grep, cut, or awk.

This show version sample is taken from https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst9300/software/release/16-6/configuration_guide/sys_mgmt/b_166_sys_mgmt_9300_cg/b_166_sys_mgmt_9300_cg_chapter_01.html

wolf@linux:~$ cat shver
cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S

wolf@linux:~$

grep and cut

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2
 C9300-48P
 C9300-48P
wolf@linux:~$

Remove extra space (If there's better solution, let me know)

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2
C9300-48P
C9300-48P
wolf@linux:~$

Select the 1st output

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2 | head -1
C9300-48P
wolf@linux:~$

That was in Linux. I was planning to write similar code in Python.

My attempt which still didn't work at the moment.

Define shver string

>>> shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
... Processor board ID FCW2049G03S
... 2048K bytes of non-volatile configuration memory.
... 8388608K bytes of physical memory.
... 1638400K bytes of Crash Files at crashinfo:.
... 11264000K bytes of Flash at flash:.
... 0K bytes of WebUI ODM Files at webui:.
... Model Number                       : C9300-48P
...
... Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
... Motherboard Assembly Number        : 73-17956-04
... Motherboard Serial Number          : FOC20465ABU
... Model Revision Number              : P4B
... Motherboard Revision Number        : 04
... Model Number                       : C9300-48P
... System Serial Number               : FCW2049G03S
... '''
>>>

verify it

>>> shver
'cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.\nProcessor board ID FCW2049G03S\n2048K bytes of non-volatile configuration memory.\n8388608K bytes of physical memory.\n1638400K bytes of Crash Files at crashinfo:.\n11264000K bytes of Flash at flash:.\n0K bytes of WebUI ODM Files at webui:.\nModel Number                       : C9300-48P\n\nBase Ethernet MAC Address          : 04:6c:9d:01:3b:80\nMotherboard Assembly Number        : 73-17956-04\nMotherboard Serial Number          : FOC20465ABU\nModel Revision Number              : P4B\nMotherboard Revision Number        : 04\nModel Number                       : C9300-48P\nSystem Serial Number               : FCW2049G03S\n'
>>>

create a list

>>> shver_list = shver.splitlines()
>>> shver_list
['cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.', 'Processor board ID FCW2049G03S', '2048K bytes of non-volatile configuration memory.', '8388608K bytes of physical memory.', '1638400K bytes of Crash Files at crashinfo:.', '11264000K bytes of Flash at flash:.', '0K bytes of WebUI ODM Files at webui:.', 'Model Number                       : C9300-48P', '', 'Base Ethernet MAC Address          : 04:6c:9d:01:3b:80', 'Motherboard Assembly Number        : 73-17956-04', 'Motherboard Serial Number          : FOC20465ABU', 'Model Revision Number              : P4B', 'Motherboard Revision Number        : 04', 'Model Number                       : C9300-48P', 'System Serial Number               : FCW2049G03S']
>>>

Next step is to find out if string 'Model Number' is there or not and print out that line

>>> if 'Model Number' in shver_list:
...     'yes'
... else:
...     'no'
...
'no'
>>>

How do I print out the line contains 'Model Number'?

>>> for i in shver_list:
...     if 'Model Number' in shver_list:
...             i
...
>>>

Desired Output

C9300-48P

Body:
From your shver_list step, you can do this:

for item in shver_list:
    if "Model Number" in item:
        break

So once it finds a match, it will break out the loop and look what we have in item:

>>> item
'Model Number                       : C9300-48P'

Now we can split this on : (note the spaces around) and get:

>>> items.split(" : ")
['Model Number                      ', 'C9300-48P']

So the desired element lies in the 1st positon in this list.

All in all:

for item in shver_list:
    if "Model Number" in item:
        break
desired = item.split(" : ")[1]

Another way of doing is with regular expressions. This time we take it from shver string:

import re
matches_gen = re.finditer(r"Model Number\s+:\s*(.+)", shver)
desired = next(matches_gen).group(1)

We use finditer for lazy evaluation and because we want the first occurence, we use one next on it and take the matching group to get the desired result of C9300-48P.


问:
How to run Bokeh app in Jupyter notebook?
I'd like to create and run bokeh application in Jupyter notebook. To try it I downloaded code from bokeh tutorial

```<code>from bokeh.io import output_notebook, show
output_notebook()
from bokeh.layouts import column
from bokeh.models import TextInput, Button, Paragraph

def modify_doc(doc):

    # create some widgets
    button = Button(label="Say HI")
    input = TextInput(value="Bokeh")
    output = Paragraph()

    # add a callback to a widget
    def update():
        output.text = "Hello, " + input.value
    button.on_click(update)

    # create a layout for everything
    layout = column(button, input, output)

    # add the layout to curdoc
    doc.add_root(layout)

# In the notebook, just pass the function that defines the app to show
# You may need to supply notebook_url, e.g notebook_url="http://localhost:8889"
show(modify_doc, notebook_url="http://localhost:8888")
</code>```

When I run it in Jupyter notebook, I get error message below:

ERROR:tornado.application:Uncaught exception in /ws
  Traceback (most recent call last):
    File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\websocket.py", line 494, in _run_callback
      result = callback(*args, **kwargs)
    File "C:\Users\123058850\AppData\Roaming\Python\Python36\site-packages\bokeh\server\views\ws.py", line 121, in open
      if self.selected_subprotocol != 'bokeh':
  AttributeError: 'WSHandler' object has no attribute 'selected_subprotocol'

Can you please help me understand what is wrong?

答: If seems like in your environment, you have some old Tornado version installed somehow. tornado.websocket.WebSocketHandler.selected_subprotocol has appeared in Tornado 5.1.

Body:
I'd like to create and run bokeh application in Jupyter notebook. To try it I downloaded code from bokeh tutorial

from bokeh.io import output_notebook, show
output_notebook()
from bokeh.layouts import column
from bokeh.models import TextInput, Button, Paragraph

def modify_doc(doc):

    # create some widgets
    button = Button(label="Say HI")
    input = TextInput(value="Bokeh")
    output = Paragraph()

    # add a callback to a widget
    def update():
        output.text = "Hello, " + input.value
    button.on_click(update)

    # create a layout for everything
    layout = column(button, input, output)

    # add the layout to curdoc
    doc.add_root(layout)

# In the notebook, just pass the function that defines the app to show
# You may need to supply notebook_url, e.g notebook_url="http://localhost:8889"
show(modify_doc, notebook_url="http://localhost:8888")

When I run it in Jupyter notebook, I get error message below:

ERROR:tornado.application:Uncaught exception in /ws
  Traceback (most recent call last):
    File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\websocket.py", line 494, in _run_callback
      result = callback(*args, **kwargs)
    File "C:\Users\123058850\AppData\Roaming\Python\Python36\site-packages\bokeh\server\views\ws.py", line 121, in open
      if self.selected_subprotocol != 'bokeh':
  AttributeError: 'WSHandler' object has no attribute 'selected_subprotocol'

Can you please help me understand what is wrong?


问:
Locate the Keys with same values in JSON
I have below json

```<code>[{
    "workType": "NDB To Nice",
    "priority": 5
},
{
    "workType": "PDAD",
    "priority": 0
}, {
    "workType": "PPACA",
    "priority": 0
}, {
    "workType": "Retrigger",
    "priority": "5"
}, {
    "workType": "Special Intake Request Intake",
    "priority": "7"
}]
</code>```

I need to call out all the "worktype" which have same "priority" , iff the priority is NOT EQUAL TO 0.

Means for above example i should get keys = ["NDB To Nice","Retrigger"] since they both have priority 5.

I have tried below code

```<code>  function(array, k) {
  return array.reduce(function(acc, cur) {
    (acc[cur[k]] = acc[cur[k]] || []).push(cur);
    return acc;
  }, {});
};
</code>```

But i am not able to achieve the output.

答:
You could try the following

var input = [{ "workType": "NDB To Nice", "priority": 5 }, { "workType": "PDAD", "priority": 0 }, { "workType": "PPACA", "priority": 0 }, { "workType": "Retrigger", "priority": "5" }, { "workType": "Special Intake Request Intake", "priority": "7" }];

var output = input.reduce((r, a) => {
  r[a.priority] = r[a.priority] || [];
  if (!r[a.priority].includes(a.workType)) {       // <-- ignore duplicates
    r[a.priority].push(a.workType);
  }
  return r;
}, Object.create(null));

console.log(output);        // <-- all priorities
console.log(output['5']);   // <-- priority '5'```

Body:
I have below json

[{
    "workType": "NDB To Nice",
    "priority": 5
},
{
    "workType": "PDAD",
    "priority": 0
}, {
    "workType": "PPACA",
    "priority": 0
}, {
    "workType": "Retrigger",
    "priority": "5"
}, {
    "workType": "Special Intake Request Intake",
    "priority": "7"
}]

I need to call out all the "worktype" which have same "priority" , iff the priority is NOT EQUAL TO 0.

Means for above example i should get keys = ["NDB To Nice","Retrigger"] since they both have priority 5.

I have tried below code

  function(array, k) {
  return array.reduce(function(acc, cur) {
    (acc[cur[k]] = acc[cur[k]] || []).push(cur);
    return acc;
  }, {});
};

But i am not able to achieve the output.


问:
Logistic Regression sklearn with categorical Output
i have to train a model with logistic Regression in sklearn. I saw everywhere that the outcome has to be binary but my label is good, bad or normal. I have 12 features and i don't know how can i deal with three Labels ? I am very thankful for every answer</p>

答:
It's called as one-vs-all Classification or Multi class classification.

From sklearn.linear_model.LogisticRegression:

In the multiclass case, the training algorithm uses the one-vs-rest (OvR) scheme if the ‘multi_class’ option is set to ‘ovr’, and uses the cross-entropy loss if the ‘multi_class’ option is set to ‘multinomial’. (Currently the ‘multinomial’ option is supported only by the ‘lbfgs’, ‘sag’, ‘saga’ and ‘newton-cg’ solvers.)

Code example:

# Authors: Tom Dupre la Tour <tom.dupre-la-tour@m4x.org>
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression

# make 3-class dataset for classification
centers = [[-5, 0], [0, 1.5], [5, -1]]
X, y = make_blobs(n_samples=1000, centers=centers, random_state=40)
transformation = [[0.4, 0.2], [-0.4, 1.2]]
X = np.dot(X, transformation)

for multi_class in ('multinomial', 'ovr'):
    clf = LogisticRegression(solver='sag', max_iter=100, random_state=42,
                             multi_class=multi_class).fit(X, y)

    # print the training scores
    print("training score : %.3f (%s)" % (clf.score(X, y), multi_class))
```

Check for full code example: Plot multinomial and One-vs-Rest Logistic Regression

Body:
It's called as one-vs-all Classification or Multi class classification.

From sklearn.linear_model.LogisticRegression:

In the multiclass case, the training algorithm uses the one-vs-rest (OvR) scheme if the ‘multi_class’ option is set to ‘ovr’, and uses the cross-entropy loss if the ‘multi_class’ option is set to ‘multinomial’. (Currently the ‘multinomial’ option is supported only by the ‘lbfgs’, ‘sag’, ‘saga’ and ‘newton-cg’ solvers.)

Code example:

# Authors: Tom Dupre la Tour <tom.dupre-la-tour@m4x.org>
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression

# make 3-class dataset for classification
centers = [[-5, 0], [0, 1.5], [5, -1]]
X, y = make_blobs(n_samples=1000, centers=centers, random_state=40)
transformation = [[0.4, 0.2], [-0.4, 1.2]]
X = np.dot(X, transformation)

for multi_class in ('multinomial', 'ovr'):
    clf = LogisticRegression(solver='sag', max_iter=100, random_state=42,
                             multi_class=multi_class).fit(X, y)

    # print the training scores
    print("training score : %.3f (%s)" % (clf.score(X, y), multi_class))

Check for full code example: Plot multinomial and One-vs-Rest Logistic Regression


问:
Localized routes in koa
I'm developing a site with multiple languages. Some routes will therefore also have to be localized and I'm not sure how to do this properly.

I'm using @koa/router for routing.

For this example it's only English and Swedish but the site will handle more languages.

I can setup routes to match words in different languages like

```<code>router.get('/(create-account|skapa-konto)/', (ctx, next) => {
  ctx.body = translate('signup_welcome');
  await next();
});
</code>```

But, I want the English site to only respond to '/sign-up' and send 404 for '/skapa-konto' (and vice versa).

In the real world the route would point to some controller function. So if I set up individual routes for each language I would have to change all localized routes manually should the controller function change in the future. That's something I would like to avoid ;)

Any suggestions?

答:
This problem interested me so I created a small github repo with some code. I'll try to explain here:

I created an array with some options:

```<code>const localeConfig = [
  {
    locale: "en",
    routes: [
      {
        path: "/sign-up",
        controllers: [enController],
        method: "GET",
      },
    ],
    prefix: false,
  },
  {
    locale: "se",
    routes: [
      {
        path: "/skapa-konto",
        controllers: [seController],
        method: "GET",
      },
    ],
    prefix: false,
  },
];
</code>```

I then pass this object to a setupRoutes function that basically iterates the array, generating all the routes according to those options.

```<code>const setupRoutes = (localeConfig) => {
  // Have some check to prevent duplicate routes
  localeConfig.forEach((opt) => {
    // Adding prefix according to option
    const localePrefix = opt.prefix ? `/${opt.locale}` : "";
    opt.routes.forEach((route) => {
      const path = `${localePrefix}${route.path}`;
      router[route.method.toLowerCase()].apply(router, [
        path,
        ...route.controllers,
      ]);
    });
  });
};
</code>```

So, for instance, if you were to change any of the controllers in either language you would only need to update the specific locale object.route.controllers. I imagine you could even have each different locale in a different file to have some modularity.

The github repo is here and I would really like to have you contribute to it if you have any idea on how to improve this.

Cheers!

Title: Localized routes in koa

Body:
I'm developing a site with multiple languages. Some routes will therefore also have to be localized and I'm not sure how to do this properly.

I'm using @koa/router for routing.

For this example it's only English and Swedish but the site will handle more languages.

I can setup routes to match words in different languages like

router.get('/(create-account|skapa-konto)/', (ctx, next) => {
  ctx.body = translate('signup_welcome');
  await next();
});

But, I want the English site to only respond to '/sign-up' and send 404 for '/skapa-konto' (and vice versa).

In the real world the route would point to some controller function. So if I set up individual routes for each language I would have to change all localized routes manually should the controller function change in the future. That's something I would like to avoid ;)

Any suggestions?

Body:
This problem interested me so I created a small github repo with some code. I'll try to explain here:

I created an array with some options:

const localeConfig = [
  {
    locale: "en",
    routes: [
      {
        path: "/sign-up",
        controllers: [enController],
        method: "GET",
      },
    ],
    prefix: false,
  },
  {
    locale: "se",
    routes: [
      {
        path: "/skapa-konto",
        controllers: [seController],
        method: "GET",
      },
    ],
    prefix: false,
  },
];

I then pass this object to a setupRoutes function that basically iterates the array, generating all the routes according to those options.

const setupRoutes = (localeConfig) => {
  // Have some check to prevent duplicate routes
  localeConfig.forEach((opt) => {
    // Adding prefix according to option
    const localePrefix = opt.prefix ? `/${opt.locale}` : "";
    opt.routes.forEach((route) => {
      const path = `${localePrefix}${route.path}`;
      router[route.method.toLowerCase()].apply(router, [
        path,
        ...route.controllers,
      ]);
    });
  });
};

So, for instance, if you were to change any of the controllers in either language you would only need to update the specific locale object.route.controllers. I imagine you could even have each different locale in a different file to have some modularity.

The github repo is here and I would really like to have you contribute to it if you have any idea on how to improve this.

Cheers!


问:
Projecting points onto 3D terrain surface in UWP MapControl
I'm creating a windows desktop app using the UWP Map control (MapControl) and inking based on this blog post.

I have the basics working. can draw ink on the canvas and convert them to map locations, but I can't get the points to correctly project onto the map 3D surface.

I'm using mapControl.GetLocationFromOffset to transform the control-space offset to map position but no matter what AltitudeReferenceSystem I use the points are offset above or below the 3D mesh.  I'm basically trying to emulate how inking works in the built in windows Maps app.  But since there's a pause after drawing each stroke I'm thinking it's doing some ray casting onto the 3D mesh. Lat/Long are correct but altitude has an offset.

```<code>Geopoint GeopointFromPoint(Point point)
{
   Geopoint geoPoint = null;
   this.map.GetLocationFromOffset(point, AltitudeReferenceSystem.Geoid, out geoPoint); // Tried all alt ref systems here
   return (geoPoint);
}
...
BasicGeoposition curP;
foreach (var segment in firstStroke.GetRenderingSegments())
{
   curP = GeopointFromPoint(segment.Position).Position;
   geoPoints.Add(curP);
}
...
</code>```

This is my inking around a patch of grass in the Maps App which determines correct altitude:

And the same area using the Map control + GetLocationFromOffset, blue ink is annotation showing altitude offset:

How can I project screen/control space coordinates onto the 3D mesh in the UWP Map control and get the correct altitude?

Edit: And the answer is I'm an idiot, have been thinking in meters from center of earth too long, ie I thought altitude was the altitude above sea level of the map location, but it's not, it's the points altitude above the map.  So just setting altitude to zero works.

答:
First problem was I wasn't passing a AltitudeReferenceSystem to the Geopath constructor while translating ink strokes to map polygons.  Once you do this you can pass the result of TryGetLocationFromOffset directly to the polygons.

Second is a possible bug with the map control.  If the map control does not take up the entire height of the main window you see a pixel offset between what TryGetLocationFromOffset and where the ink stroke was drawn.

Body:
I'm creating a windows desktop app using the UWP Map control (MapControl) and inking based on this blog post.

I have the basics working. can draw ink on the canvas and convert them to map locations, but I can't get the points to correctly project onto the map 3D surface.

I'm using mapControl.GetLocationFromOffset to transform the control-space offset to map position but no matter what AltitudeReferenceSystem I use the points are offset above or below the 3D mesh.  I'm basically trying to emulate how inking works in the built in windows Maps app.  But since there's a pause after drawing each stroke I'm thinking it's doing some ray casting onto the 3D mesh. Lat/Long are correct but altitude has an offset.

Geopoint GeopointFromPoint(Point point)
{
   Geopoint geoPoint = null;
   this.map.GetLocationFromOffset(point, AltitudeReferenceSystem.Geoid, out geoPoint); // Tried all alt ref systems here
   return (geoPoint);
}
...
BasicGeoposition curP;
foreach (var segment in firstStroke.GetRenderingSegments())
{
   curP = GeopointFromPoint(segment.Position).Position;
   geoPoints.Add(curP);
}
...

This is my inking around a patch of grass in the Maps App which determines correct altitude:

And the same area using the Map control + GetLocationFromOffset, blue ink is annotation showing altitude offset:

How can I project screen/control space coordinates onto the 3D mesh in the UWP Map control and get the correct altitude?

Edit: And the answer is I'm an idiot, have been thinking in meters from center of earth too long, ie I thought altitude was the altitude above sea level of the map location, but it's not, it's the points altitude above the map.  So just setting altitude to zero works.


问:
ColdFusion CFHTTP I/O Exception: peer not authenticated - even after adding certs to Keystore
I'm currently working with a payment processor. I can browse to the payment URL from our server, so it's not a firewall issue, but when I try to use CFHTTP I get a I/O Exception: peer not authenticated. I've downloaded and installed their latest security cert into cacerts keystore and restarted CF and am still getting the same error. Not only have I installed the providers cert, but also the 2 other Verisign certificate authority certs in the certificate chain. The cert is one of the newer Class 3 Extended Validation certs.

Has anybody come across this before and found a solution?

答:
What I just found out was referenced at this article: http://kb2.adobe.com/cps/400/kb400977.html and a few other places after a lot of digging.

If you are looking at this article you have most likely inserted your "server.crt" certificate in the proper root locations and you have probably inserted it into the cacerts file in /ColdFusion9/runtime/jre/lib/security using the command

\ColdFusion9\runtime\jre\bin\keytool -import -v -alias someServer-cert -file someServerCertFile.crt -keystore cacerts -storepass changeit

(if you haven't done this, do it now).
The thing I was running into was that I am setting up ssl on my localhost so after doing these steps I was still getting the same error.

As it turns out, you need to also insert your "server.crt" into the "trustStore" file commonly located in /ColdFusion9/runtime/jre/lib using the command

```<code>\ColdFusion9\runtime\jre\bin\keytool -import -v -alias someServer-cert -file someServerCertFile.cer -keystore trustStore -storepass changeit
</code>```

Hopefully this will save someone time.

ContentLicense: CC BY-SA 3.0

Body:
What I just found out was referenced at this article: http://kb2.adobe.com/cps/400/kb400977.html and a few other places after a lot of digging.

If you are looking at this article you have most likely inserted your "server.crt" certificate in the proper root locations and you have probably inserted it into the cacerts file in /ColdFusion9/runtime/jre/lib/security using the command

\ColdFusion9\runtime\jre\bin\keytool -import -v -alias someServer-cert -file someServerCertFile.crt -keystore cacerts -storepass changeit

(if you haven't done this, do it now).
The thing I was running into was that I am setting up ssl on my localhost so after doing these steps I was still getting the same error.

As it turns out, you need to also insert your "server.crt" into the "trustStore" file commonly located in /ColdFusion9/runtime/jre/lib using the command

\ColdFusion9\runtime\jre\bin\keytool -import -v -alias someServer-cert -file someServerCertFile.cer -keystore trustStore -storepass changeit

Hopefully this will save someone time.


问:
Search a value in a main-entity's child property of type List<T> in another List<T> and return main entity
I'm running into a LINQ2Sql problem where Visual Studio suggest a potential fix but that doesn't work.
Imagine following:

I need to return an entity of type IEnumerable
QmmProductionOrderInteruptCardCollection contains a List this again contains a List every Note has a property "Reviewed" of type boolean.

I now want to look for this property in each note where Reviewed is false but return the top entity
IEnumerable

Now this is my LINQ-Statement which would return IEnumerable without casting instead:

```<code>return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();
</code>```

Visual studio suggests a casting into type IEnumerable like so:

```<code>return (IEnumerable<QmmProductionOrderInteruptCardCollection>)await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();
</code>```

But when test I get an InvalidCastException

Unable to cast object of type 'System.Collections.Generic.List1[BIP_Models.Domain.Qmm.QmmNote]' to type 'System.Collections.Generic.IEnumerable1[BIP_Models.Domain.Qmm.QmmProductionOrderInteruptCardCollection]'.

Do you have any thoughts how to solve this?

For a better understanding, this would be the sql statement I'd like to transfer:

```<code>SELECT
*
FROM QmmProductionOrderInteruptCardCollections pic
JOIN QmmProductionOrders p ON p.Id = pic.ProductionOrderId
JOIN QmmNotes n ON n.ProductionOrderId = p.Id
WHERE
n.IsReviewed = 0;
</code>```

Thanks and best regards.
Patrick

答:
Try:

```<code>return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
        .Where(x => x.ProductionOrder.Notes.Any(n => !n.IsReviewed))
        .ToListAsync();
</code>```

This should return you Qmm_ProductionOrderInteruptCardCollection's which have at least one unreviewed note.

Body:
I'm running into a LINQ2Sql problem where Visual Studio suggest a potential fix but that doesn't work.
Imagine following:

I need to return an entity of type IEnumerable
QmmProductionOrderInteruptCardCollection contains a List this again contains a List every Note has a property "Reviewed" of type boolean.

I now want to look for this property in each note where Reviewed is false but return the top entity
IEnumerable

Now this is my LINQ-Statement which would return IEnumerable without casting instead:

return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();

Visual studio suggests a casting into type IEnumerable like so:

return (IEnumerable<QmmProductionOrderInteruptCardCollection>)await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();

But when test I get an InvalidCastException

Unable to cast object of type 'System.Collections.Generic.List1[BIP_Models.Domain.Qmm.QmmNote]' to type 'System.Collections.Generic.IEnumerable1[BIP_Models.Domain.Qmm.QmmProductionOrderInteruptCardCollection]'.

Do you have any thoughts how to solve this?

For a better understanding, this would be the sql statement I'd like to transfer:

SELECT
*
FROM QmmProductionOrderInteruptCardCollections pic
JOIN QmmProductionOrders p ON p.Id = pic.ProductionOrderId
JOIN QmmNotes n ON n.ProductionOrderId = p.Id
WHERE
n.IsReviewed = 0;

Thanks and best regards.
Patrick

Body:
Try:

return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
        .Where(x => x.ProductionOrder.Notes.Any(n => !n.IsReviewed))
        .ToListAsync();

This should return you Qmm_ProductionOrderInteruptCardCollection's which have at least one unreviewed note.


问:
Ajax operation running later than javascript function
I am building a django project which is a website sending form to server and server responds with the queryset just registered by the form and a message string "Create new event successful.".

This is code for it:

listevent is another javascript function which shows the queryset the server just received to "sidebar" div. After that, by document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );, appends the message above the result.

Javascript

```<code>function makeEvent(event){
            event.preventDefault();
            var year = event.target.childNodes[3].children[0].value.slice(0,4);
            var month = event.target.childNodes[3].children[0].value.slice(5,7);
            var day = event.target.childNodes[3].children[0].value.slice(8,10);
            var form = $("#makeEventForm");
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                success: function(response){
                    console.log(response);
                    listevent(year, month, day);
                    document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );
                },
                error: function(request,status,error){
                    if (request.status == 599) {
                        listevent(year, month, day);
                        document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Error : time overlaps with another event" );
                    } else {
                        alert("code:"+request.status+"\n"+"message:"+status+"\n"+"error:"+error);
                    }
                },
            });
        }
</code>```

The problem is, when this makeEventfunction ran and ajax operation successfully done, second line of success function(listevent(year, month, day);) seems to run later than third line. As a result, "Create new event successful" does not displayed, because listevent function overwrites all contents in sidebar div.

So I tried using setTimeout on the third line, but it seems like does not work at all time. It'll work if I set the time value sufficiently big, but It looks so bad.

So, my question is:

1. Second line of success function looks like running later than third line, is that right?

2. If so, to third line run after second line ended running, what should I do?

Edit

listevent function

```<code>function listevent(year, month, day){
            $.ajax({
                type: "POST",
                url: "{% url 'listevent' %}",
                data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                dataType: "json",
                success: function(response){
                    $("#sidebar").attr('year', year);
                    $("#sidebar").attr('month', month);
                    $("#sidebar").attr('day', day);
                    events = JSON.parse(response.events)
                    var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"
                    if(events.length > 0){
                         events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));
                    } else {
                        str += "No events currently."
                    }
                    $("#sidebar").html(str);
                    var btn = $("<button></button>").html("New event");
                    btn.click(function(){
                        makeEventClick(day);
                    });
                    $("#sidebar").append(btn);
                },
                error: function(request,status,error){
                       console.log(error);
                },
            });
        }
</code>```

答:
Seems to be case of AJAX working out asynchroniosuly. listevent is successfully run, but since its AJAX operation the code won't wait until the response is received, that is left of the success/failure callbacks.

So listevent is called and AJAX call started and instead of waiting for it to complete, it moves to next line which is document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );

So my suggestion would be to move this nside listevent at the end of the success callback.

Body:
I am building a django project which is a website sending form to server and server responds with the queryset just registered by the form and a message string "Create new event successful.".

This is code for it:

listevent is another javascript function which shows the queryset the server just received to "sidebar" div. After that, by document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );, appends the message above the result.

Javascript

function makeEvent(event){
            event.preventDefault();
            var year = event.target.childNodes[3].children[0].value.slice(0,4);
            var month = event.target.childNodes[3].children[0].value.slice(5,7);
            var day = event.target.childNodes[3].children[0].value.slice(8,10);
            var form = $("#makeEventForm");
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                success: function(response){
                    console.log(response);
                    listevent(year, month, day);
                    document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );
                },
                error: function(request,status,error){
                    if (request.status == 599) {
                        listevent(year, month, day);
                        document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Error : time overlaps with another event" );
                    } else {
                        alert("code:"+request.status+"\n"+"message:"+status+"\n"+"error:"+error);
                    }
                },
            });
        }

The problem is, when this makeEventfunction ran and ajax operation successfully done, second line of success function(listevent(year, month, day);) seems to run later than third line. As a result, "Create new event successful" does not displayed, because listevent function overwrites all contents in sidebar div.

So I tried using setTimeout on the third line, but it seems like does not work at all time. It'll work if I set the time value sufficiently big, but It looks so bad.

So, my question is:

1. Second line of success function looks like running later than third line, is that right?

2. If so, to third line run after second line ended running, what should I do?

Edit

listevent function

function listevent(year, month, day){
            $.ajax({
                type: "POST",
                url: "{% url 'listevent' %}",
                data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                dataType: "json",
                success: function(response){
                    $("#sidebar").attr('year', year);
                    $("#sidebar").attr('month', month);
                    $("#sidebar").attr('day', day);
                    events = JSON.parse(response.events)
                    var str = "
"+year+"/"+month+"/"+day+"

"
                    if(events.length > 0){
                         events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"
"));
                    } else {
                        str += "No events currently."
                    }
                    $("#sidebar").html(str);
                    var btn = $("<button></button>").html("New event");
                    btn.click(function(){
                        makeEventClick(day);
                    });
                    $("#sidebar").append(btn);
                },
                error: function(request,status,error){
                       console.log(error);
                },
            });
        }


问:
Pandas write data to seperate csv files
I got a dataframe that looks like this

```<code>  Name      Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
4   Orange  New York  20200501  15:30:00  5.50  5.85  5.45   5.70    1500  5.73      95
5   Orange  New York  20200501  17:00:00  5.65  5.70  5.50   5.60    1600  5.65      54
6   Orange  New York  20200501  20:00:00  5.80  5.85  5.45   5.81    1700  5.73      41
0    Apple  Minsk     20200504  15:30:00  3.70  3.97  3.65   3.75    1000  3.60      55
1    Apple  Minsk     20200504  17:00:00  3.65  3.95  3.50   3.80    1200  3.65      68
2    Apple  Minsk     20200504  20:00:00  3.50  3.83  3.44   3.60    1300  3.73      71
</code>```

How do I write each row to a different file based on the 'Name' and 'Location' column?

Desired output:

Location: "Entities\New York\Orange\TwoHours.csv"

```<code>    Name    Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
4   Orange  New York  20200501  15:30:00  5.50  5.85  5.45   5.70    1500  5.73      95
5   Orange  New York  20200501  17:00:00  5.65  5.70  5.50   5.60    1600  5.65      54
6   Orange  New York  20200501  20:00:00  5.80  5.85  5.45   5.81    1700  5.73      41
</code>```

Location: "Entities\Minsk\Apple\TwoHours.csv"

```<code>     Name      Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
0    Apple  Minsk     20200504  15:30:00  3.70  3.97  3.65   3.75    1000  3.60      55
1    Apple  Minsk     20200504  17:00:00  3.65  3.95  3.50   3.80    1200  3.65      68
2    Apple  Minsk     20200504  20:00:00  3.50  3.83  3.44   3.60    1300  3.73      71
</code>```

Could anyone help me out? the current code that I am using writes the entire dataframe to each file rather than just the specific rows:

```<code>for idx, rows in Dataframe.iterrows():
dest_dir = os.path.join('Entities', rows.Location, rows.Name)
csv_file = os.path.join(dest_dir, 'TwoHours.csv')
if not os.path.exists(csv_file):
    os.makedirs(dest_dir)
    print("Writing .csv's " + str(idx))
    df1.to_csv(csv_file, sep=";", index=False)
</code>```

答:
Here is possible loop by DataFrame.groupby object with unpack name and loc from tuple and if necessary create folders, last write groups to files:

```<code>for (name, loc), g in Dataframe.groupby(['Name','Location']):

    dest_dir = os.path.join('Entities', loc, name)
    csv_file = os.path.join(dest_dir, 'TwoHours.csv')

    if not os.path.exists(csv_file):
        os.makedirs(dest_dir)

    g.to_csv(csv_file, sep=";", index=False)
</code>```

Title: Pandas write data to seperate csv files

Body:
I got a dataframe that looks like this

  Name      Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
4   Orange  New York  20200501  15:30:00  5.50  5.85  5.45   5.70    1500  5.73      95
5   Orange  New York  20200501  17:00:00  5.65  5.70  5.50   5.60    1600  5.65      54
6   Orange  New York  20200501  20:00:00  5.80  5.85  5.45   5.81    1700  5.73      41
0    Apple  Minsk     20200504  15:30:00  3.70  3.97  3.65   3.75    1000  3.60      55
1    Apple  Minsk     20200504  17:00:00  3.65  3.95  3.50   3.80    1200  3.65      68
2    Apple  Minsk     20200504  20:00:00  3.50  3.83  3.44   3.60    1300  3.73      71

How do I write each row to a different file based on the 'Name' and 'Location' column?

Desired output:

Location: "Entities\New York\Orange\TwoHours.csv"

    Name    Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
4   Orange  New York  20200501  15:30:00  5.50  5.85  5.45   5.70    1500  5.73      95
5   Orange  New York  20200501  17:00:00  5.65  5.70  5.50   5.60    1600  5.65      54
6   Orange  New York  20200501  20:00:00  5.80  5.85  5.45   5.81    1700  5.73      41

Location: "Entities\Minsk\Apple\TwoHours.csv"

     Name      Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
0    Apple  Minsk     20200504  15:30:00  3.70  3.97  3.65   3.75    1000  3.60      55
1    Apple  Minsk     20200504  17:00:00  3.65  3.95  3.50   3.80    1200  3.65      68
2    Apple  Minsk     20200504  20:00:00  3.50  3.83  3.44   3.60    1300  3.73      71

Could anyone help me out? the current code that I am using writes the entire dataframe to each file rather than just the specific rows:

for idx, rows in Dataframe.iterrows():
dest_dir = os.path.join('Entities', rows.Location, rows.Name)
csv_file = os.path.join(dest_dir, 'TwoHours.csv')
if not os.path.exists(csv_file):
    os.makedirs(dest_dir)
    print("Writing .csv's " + str(idx))
    df1.to_csv(csv_file, sep=";", index=False)

Body:
Here is possible loop by DataFrame.groupby object with unpack name and loc from tuple and if necessary create folders, last write groups to files:

for (name, loc), g in Dataframe.groupby(['Name','Location']):

    dest_dir = os.path.join('Entities', loc, name)
    csv_file = os.path.join(dest_dir, 'TwoHours.csv')

    if not os.path.exists(csv_file):
        os.makedirs(dest_dir)

    g.to_csv(csv_file, sep=";", index=False)


问:
Is it possibile to access ( not copy ) files in my remote from my local machine?
I want to access a random forest estimator that I trained and saved on the remote machine. The pickled estimator is 2.4 gigs and my local machine is low on space so i can't use scp to download the file in my local. Is it possible that python can access (read) the file kept in the remote and load it in its RAM ?

答:
Would a RAM disk be an option? It is not python specific, but on the os level, but in case there is no better solution, it might be helpful.
(Sadly i don't have the necessary reputation to comment, therefore i'll add this as an anwser.)</p>


问:
Perl: match against a large array
Say I have $sentence = "The quick brown fox jumps over the lazy dog" and an array @targets = qw(brown red black lazy quick);.

The goal is to find out all words in @targets that contains in the $sentence, in this case, it's this three words: brown lazy quick.

Note: The @targets array could be very large, like there could be 10,000 elements in it. And there could be 10,000 $sentences to deal with.

Is there an efficient and elegant way to do it?

答:
See if this logic helps you:

```<code>#!/usr/bin/perl

use strict;
use warnings;

my $sentence = "The quick brown fox jumps over the lazy dog";

my @targets = qw/brown red black lazy quick/;
my %targets = map { $_ => 1 } @targets;

my @words = split(' ', $sentence);

foreach my $each_word ( @words ){
    print $each_word."\n" if $targets{$each_word};
}
</code>```

Output:

```<code>quick
brown
lazy
</code>```

Title: Perl: match against a large array

Body:
See if this logic helps you:

#!/usr/bin/perl

use strict;
use warnings;

my $sentence = "The quick brown fox jumps over the lazy dog";

my @targets = qw/brown red black lazy quick/;
my %targets = map { $_ => 1 } @targets;

my @words = split(' ', $sentence);

foreach my $each_word ( @words ){
    print $each_word."\n" if $targets{$each_word};
}

Output:

quick
brown
lazy


问:
Issue with cancelling the selection of txt file
I want to import a txt file to excel using a button.
I have a dialog box to pick a folder name and display the name of the folder that the user selects.

If the user selects cancel an error occure because of type mismatch. I have declared variables as VARIANT

Have a look in the code:

```<code>Sub ImportTXTFiles()
    Dim fso As Object
    Dim xlsheet As Worksheet
    Dim qt As QueryTable
    Dim txtfilesToOpen As Variant, txtfile As Variant

    Application.ScreenUpdating = False
    Set fso = CreateObject("Scripting.FileSystemObject")

    txtfilesToOpen = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt", _
                  MultiSelect:=True, Title:="Text Files to Open")
    If txtfilesToOpen = "False" Then
            Exit Sub
    End If
        For Each txtfile In txtfilesToOpen
                ' FINDS EXISTING WORKSHEET
                For Each xlsheet In ThisWorkbook.Worksheets
                    If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
                        xlsheet.Activate
                        GoTo ImportData
                    End If
                Next xlsheet

                ' CREATES NEW WORKSHEET IF NOT FOUND
                Set xlsheet = ThisWorkbook.Worksheets.Add( _
                                     After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
                xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
                xlsheet.Activate
                GoTo ImportData
</code>```

My question is how can I handle this exception here

```<code>If txtfilesToOpen = "False" Then
            Exit Sub
    End If
</code>```

if the user cancels the selection, while variables are declared as variant.

Thanks in advance.

答:
Maybe using this auxiliar function will help you out:

```<code>Option Explicit
Sub Test()

    Dim txtfilesToOpen As String
    txtfilesToOpen = GetFile

End Sub
Private Function GetFile() As String
    Dim fldr As FileDialog
    Set fldr = Application.FileDialog(msoFileDialogFilePicker)
    With fldr
        .Title = "Text Files to Open"
        .AllowMultiSelect = False
        If .Show <> -1 Then
            MsgBox "No file was picked. Please run the macro again."
            End
        End If
        GetFile = .SelectedItems(1)
    End With
End Function
</code>```

If the user doesn't pick a file, a MsgBox will pop up warning the user and then finishing the whole procedure. Note that this procedure works for only one selected item at a time. If you need to pick more than one, consider using the folder picker.

Body:
I want to import a txt file to excel using a button.
I have a dialog box to pick a folder name and display the name of the folder that the user selects.

If the user selects cancel an error occure because of type mismatch. I have declared variables as VARIANT

Have a look in the code:

Sub ImportTXTFiles()
    Dim fso As Object
    Dim xlsheet As Worksheet
    Dim qt As QueryTable
    Dim txtfilesToOpen As Variant, txtfile As Variant

    Application.ScreenUpdating = False
    Set fso = CreateObject("Scripting.FileSystemObject")

    txtfilesToOpen = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt", _
                  MultiSelect:=True, Title:="Text Files to Open")
    If txtfilesToOpen = "False" Then
            Exit Sub
    End If
        For Each txtfile In txtfilesToOpen
                ' FINDS EXISTING WORKSHEET
                For Each xlsheet In ThisWorkbook.Worksheets
                    If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
                        xlsheet.Activate
                        GoTo ImportData
                    End If
                Next xlsheet

                ' CREATES NEW WORKSHEET IF NOT FOUND
                Set xlsheet = ThisWorkbook.Worksheets.Add( _
                                     After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
                xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
                xlsheet.Activate
                GoTo ImportData

My question is how can I handle this exception here

If txtfilesToOpen = "False" Then
            Exit Sub
    End If

if the user cancels the selection, while variables are declared as variant.

Thanks in advance.

Body:
Maybe using this auxiliar function will help you out:

Option Explicit
Sub Test()

    Dim txtfilesToOpen As String
    txtfilesToOpen = GetFile

End Sub
Private Function GetFile() As String
    Dim fldr As FileDialog
    Set fldr = Application.FileDialog(msoFileDialogFilePicker)
    With fldr
        .Title = "Text Files to Open"
        .AllowMultiSelect = False
        If .Show <> -1 Then
            MsgBox "No file was picked. Please run the macro again."
            End
        End If
        GetFile = .SelectedItems(1)
    End With
End Function

If the user doesn't pick a file, a MsgBox will pop up warning the user and then finishing the whole procedure. Note that this procedure works for only one selected item at a time. If you need to pick more than one, consider using the folder picker.


问:
How to do both client side and server side validation?
I was creating a HTML form in which I was doing both client side and server side validation.I used the below code.

```<code><form action='logic.php' method='post' id='login'>
    <input type='text' placeholder='Enter name' name='name'>
    <input type='submit'>
</form>

// Jquery
$(document).ready(function(){

    function validate_name(input_id,error_id,msg="Name"){
        const x = document.getElementById(input_id).value;
        const y = document.getElementById(error_id);
        const pattern = /^[a-zA-Z]+$/
        if(x!==""){
            if(pattern.test(x) ){
                if(x.length<3 || x.length>10){
                    y.innerHTML = msg+' should be between 3 and 10 characters.'
                    return false;
                }
                else{
                    y.innerHTML = '';
                    return true;
                }
            }
            else{
                y.innerHTML = 'Should contain only alphabets.'
                return false;
            }
        }
        else{
            y.innerHTML = "Please Enter Your "+msg;
            return false;
        }
    }

    $('#login').submit(function(e){
        e.preventDefault();
        let name = validate_name('rollno','rerror');
        let subject_name = validate_select('subject_dropdown','serror');
        if(name === true & subject_name === true){
            window.location = 'controller/indexPage_logic.php';
        }
    })
});
</code>```

I may able to do client side validation but if the form is properly validated I can't able to access the input value using $_POST['name'] in server side PHP.I think this is due to window.location.Is there any better way to do both side validation?

答:
You have to send your data to the server, the probleme was window.location didn't sent any request to the server
to be able to accomplice that use </p>

```<code>$.post('url to the server', { data1 : "Your data", data2 : yourvar }, function(res) {
   console.log(res)
});
</code>```

Body:
I was creating a HTML form in which I was doing both client side and server side validation.I used the below code.

<form action='logic.php' method='post' id='login'>
    <input type='text' placeholder='Enter name' name='name'>
    <input type='submit'>
</form>

// Jquery
$(document).ready(function(){

    function validate_name(input_id,error_id,msg="Name"){
        const x = document.getElementById(input_id).value;
        const y = document.getElementById(error_id);
        const pattern = /^[a-zA-Z]+$/
        if(x!==""){
            if(pattern.test(x) ){
                if(x.length<3 || x.length>10){
                    y.innerHTML = msg+' should be between 3 and 10 characters.'
                    return false;
                }
                else{
                    y.innerHTML = '';
                    return true;
                }
            }
            else{
                y.innerHTML = 'Should contain only alphabets.'
                return false;
            }
        }
        else{
            y.innerHTML = "Please Enter Your "+msg;
            return false;
        }
    }

    $('#login').submit(function(e){
        e.preventDefault();
        let name = validate_name('rollno','rerror');
        let subject_name = validate_select('subject_dropdown','serror');
        if(name === true & subject_name === true){
            window.location = 'controller/indexPage_logic.php';
        }
    })
});

I may able to do client side validation but if the form is properly validated I can't able to access the input value using $_POST['name'] in server side PHP.I think this is due to window.location.Is there any better way to do both side validation?

Body:
You have to send your data to the server, the probleme was window.location didn't sent any request to the server
to be able to accomplice that use

$.post('url to the server', { data1 : "Your data", data2 : yourvar }, function(res) {
   console.log(res)
});


问:
how do make this show/hide more concise?
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

```<code>jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});
</code>```

Each show/hide uses its own ID, so I simply group ids like so:

```<code>jQuery('#show-hide1, #show-hide2').hide();
</code>```

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

```<code>jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});
</code>```

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

答:
Made a little example of how you could do it: http://jsfiddle.net/ytx2J/

HTML:

```<code><a href="#" class="toggleLink" data-id="1">1</a>
<a href="#" class="toggleLink" data-id="2">2</a>
<a href="#" class="toggleLink" data-id="3">3</a>
<a href="#" class="toggleLink" data-id="4">4</a>

<div id="show-hide1">div 1</div>
<div id="show-hide2">div 2</div>
<div id="show-hide3">div 3</div>
<div id="show-hide4">div 4</div>
</code>```

JS:

```<code>$(function(){
    $('.toggleLink').click(function(ev){
       $('#show-hide'+$(this).data('id')).toggle(400);
       ev.preventDefault();
    });
});
</code>```

Body:
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});

Each show/hide uses its own ID, so I simply group ids like so:

jQuery('#show-hide1, #show-hide2').hide();

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

Body:
Made a little example of how you could do it: http://jsfiddle.net/ytx2J/

HTML:

<a href="#" class="toggleLink" data-id="1">1</a>
<a href="#" class="toggleLink" data-id="2">2</a>
<a href="#" class="toggleLink" data-id="3">3</a>
<a href="#" class="toggleLink" data-id="4">4</a>

<div id="show-hide1">div 1</div>
<div id="show-hide2">div 2</div>
<div id="show-hide3">div 3</div>
<div id="show-hide4">div 4</div>

JS:

$(function(){
    $('.toggleLink').click(function(ev){
       $('#show-hide'+$(this).data('id')).toggle(400);
       ev.preventDefault();
    });
});


问:
Click on ion-label to toggle the ion-toggle
I am creating a page with ionic 5.

I am making a 'remember me' button with use of <ion-toggle>.

<ion-item>
    <ion-label>remember me</ion-label>
    <ion-toggle class="button"></ion-toggle>
</ion-item>
```

The Ion-toggle is working fine, but I can't toggle it by clicking on the label next to it.

I have tried many solutions.

The link for the API documentation is: https://ionicframework.com/docs/api/toggle

Is there any way to make both the ion toggle and the text clickable?

I'm using ionic angular

Thanks in advance

答:
This is how you can do:

add a Ionic id to the toggle with for example #mytoggle

use the id in the (click) of the label to toggle the .checked property

code:

```<code><ion-item>
    <ion-label (click)="mytoggle.checked = !mytoggle.checked">remember me</ion-label>
    <ion-toggle #mytoggle class="button"></ion-toggle>
</ion-item>
</code>```

Try it in stackblitz

Body:
I am creating a page with ionic 5.

I am making a 'remember me' button with use of <ion-toggle>.

<ion-item>
    <ion-label>remember me</ion-label>
    <ion-toggle class="button"></ion-toggle>
</ion-item>

The Ion-toggle is working fine, but I can't toggle it by clicking on the label next to it.

I have tried many solutions.

The link for the API documentation is: https://ionicframework.com/docs/api/toggle

Is there any way to make both the ion toggle and the text clickable?

I'm using ionic angular

Thanks in advance

Body:
This is how you can do:

add a Ionic id to the toggle with for example #mytoggle

use the id in the (click) of the label to toggle the .checked property

code:

<ion-item>
    <ion-label (click)="mytoggle.checked = !mytoggle.checked">remember me</ion-label>
    <ion-toggle #mytoggle class="button"></ion-toggle>
</ion-item>

Try it in stackblitz


问:
Different types of React Routers and their purposes?
On one of my interviews I was asked:

Name different types of React Routers and their purposes?

I know and use only react-router-dom in my projects. It uses to bind DOM elements to specific route in browser without sending request to server.

So, Guy is there other routers types and purpose?

答:
There are different routers provided by react-router-dom lib:-

Browser Router
A  that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL.

Hash Router
A  that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

Memory Router
A  that keeps the history of your “URL” in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.

Reference: https://reacttraining.com/react-router/web/api/BrowserRouter


问:
AWS SAM local API cannot access Systems Management parameters
I have an C# AWS Lambda function created using AWS SAM. The function tries to get parameters from Systems Management using this code:

```<code>public async Task<string> GetConfiguration(string parameterName)
{
    var request = new GetParameterRequest
    {
        Name = $"/project-name/{parameterName}",
        WithDecryption = true
    };

    using (var client = new AmazonSimpleSystemsManagementClient(RegionEndpoint.EUWest1))
    {
        var response = await client.GetParameterAsync(request);
        return response.Parameter.Value;
    }
}
</code>```

The SAM template specifies the function runs as an IAM user with ssm:GetParameter* permissions. When I  deploy the function to AWS, this code works exactly as expected. If I hit run in Visual Studio, the API is also able to access the parameters.

However, when I run the code locally with:
sam local start-api

I get this exception:

[Error] Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction:
  Unknown error responding to request:
  AmazonSimpleSystemsManagementException:
  Amazon.SimpleSystemsManagement.AmazonSimpleSystemsManagementException:
  The security token included in the request is invalid
  ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type Amazon.Runtime.Internal.HttpErrorResponseException was thrown. at
  Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken
  cancellationToken) at
  Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext
  executionContext)
  --- End of inner exception stack trace --- at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext
  executionContext, HttpErrorResponseException exception) at
  Amazon.Runtime.Internal.ExceptionHandler1.Handle(IExecutionContext
  executionContext, Exception exception) at
  Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext
  executionContext, Exception exception) at
  Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext
  executionContext)

I'm struggling to work out why or how to get it working.

答:
I think that your local machine is not yet configured to call AWS API.

While you're running code using AWS on your local machine, you have to confirm you configured your environment with client credentials.

To confirm that, please verify you have generated access key for your IAM user. Here you'll find a detailed answer about how to find your access keys and how to generate a new one: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_CreateAccessKey

The next step is to configure your local environment. You have to store access key and secret on your local machine. You have two options:

use security profiles file

use environment variables

If you choose the first option, run from your CLI (terminal) command aws configure. Then, you will be asked to put your credentials and set default region and output for default profile. This profile is used by all code calls (including your SDK).
You can check all available profiles in file ~/.aws/credentials (on Windows it's in C:/Users/<your-username>/.aws/credentials. It may be the case that you already configured the profile with a non-default name. Then, your C# code needs to call this profile explicitly - the same applies to CLI calls, just like Marcin pointed in a comment below your question.

If you choose the second option, then you need to set your environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Details about environment variables are available here: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html

Body:
I have an C# AWS Lambda function created using AWS SAM. The function tries to get parameters from Systems Management using this code:

public async Task<string> GetConfiguration(string parameterName)
{
    var request = new GetParameterRequest
    {
        Name = $"/project-name/{parameterName}",
        WithDecryption = true
    };

    using (var client = new AmazonSimpleSystemsManagementClient(RegionEndpoint.EUWest1))
    {
        var response = await client.GetParameterAsync(request);
        return response.Parameter.Value;
    }
}

The SAM template specifies the function runs as an IAM user with ssm:GetParameter* permissions. When I  deploy the function to AWS, this code works exactly as expected. If I hit run in Visual Studio, the API is also able to access the parameters.

However, when I run the code locally with:
sam local start-api

I get this exception:

[Error] Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction:
  Unknown error responding to request:
  AmazonSimpleSystemsManagementException:
  Amazon.SimpleSystemsManagement.AmazonSimpleSystemsManagementException:
  The security token included in the request is invalid
  ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type Amazon.Runtime.Internal.HttpErrorResponseException was thrown. at
  Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken
  cancellationToken) at
  Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext
  executionContext)
  --- End of inner exception stack trace --- at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext
  executionContext, HttpErrorResponseException exception) at
  Amazon.Runtime.Internal.ExceptionHandler1.Handle(IExecutionContext
  executionContext, Exception exception) at
  Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext
  executionContext, Exception exception) at
  Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext
  executionContext) at
  Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext
  executionContext)

I'm struggling to work out why or how to get it working.


问:
Encountering error for keras when implementing neural network with multiple outputs
I am implementing a chess AI in which the output is the position and the piece to be moved. However, when I follow the multi-output tutorial on the keras API documentation, It returns the error

```<code>Failed to find data adapter that can handle input:(<class 'list'> containing values of types {'(<class \'list\'> containing values of types {\'(<class \\\'list\\\'> containing values of types {\\\'(<class \\\\\\\'list\\\\\\\'> containing values of types {"<class \\\\\\\'int\\\\\\\'>"})\\\'})\'})'}), (<class 'dict'> containing {"<class 'str'>"} keys and {"<class 'numpy.ndarray'>"} values)
</code>```

Sorry if the copied section is too long, I just wanted to make sure that it could be easier to find what went wrong.

Reproducible section of code below:

```<code>import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

board_inputs = keras.Input(shape=(8, 8, 12))

conv1= layers.Conv2D(10, 3, activation='relu')
conv2 = layers.Conv2D(10, 3, activation='relu')
pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = keras.layers.Flatten(data_format=None)

x = conv1(board_inputs)
x = pooling1(x)
x = conv2(x)
x = flatten(x)
piece_output = layers.Dense(12,name = 'piece')(x)
alpha_output = layers.Dense(7,name = 'alpha')(x)
numbers_output = layers.Dense(7,name = 'number')(x)

model = keras.Model(inputs=board_inputs, outputs=[piece_output,alpha_output,numbers_output], name="chess_ai_v3")
model.compile(
    loss=keras.losses.mse,
    optimizer=keras.optimizers.Adam(),
    metrics=None,
)

keras.utils.plot_model(model, "multi_input_and_output_model.png", show_shapes=True)
history = model.fit(
    trans_data[:len(trans_data)],
    {"piece": pieces[:len(trans_data)], "alpha": alphas[:len(trans_data)],"number": numbers[:len(trans_data)]},
    epochs=2,
    batch_size=32,
)
# history = model.fit(trans_data[:len(trans_data)],batch_size=64, epochs=1000,verbosity = 2)
</code>```

Update:
I am still having problems with the network, I tested each of the arrays of values set for the answer. They all function normally when executed individually, does anyone know of any problem that could cause this?

答:
it seems that your data are in a strange format. look at this

I have no problem running this example

```<code>import numpy as np
from tensorflow.keras import layers, models

board_inputs = layers.Input(shape=(8, 8, 12))
conv1= layers.Conv2D(10, 3, activation='relu')
conv2 = layers.Conv2D(10, 3, activation='relu')
pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = layers.Flatten(data_format=None)

x = conv1(board_inputs)
x = pooling1(x)
x = conv2(x)
x = flatten(x)
piece_output = layers.Dense(12,name = 'piece')(x)
alpha_output = layers.Dense(7,name = 'alpha')(x)
numbers_output = layers.Dense(7,name = 'number')(x)

model = models.Model(inputs=board_inputs, outputs=[piece_output,alpha_output,numbers_output], name="chess_ai_v3")
model.compile(loss='mse', optimizer='adam')
model.summary()

X = np.random.uniform(0,1, (100,8,8,12))
y = {"piece": np.random.uniform(0,1,(100,12)),
     "alpha": np.random.uniform(0,1,(100,7)),
     "number": np.random.uniform(0,1,(100,7))}

history = model.fit(X,y, epochs=2, batch_size=32)
</code>```

Body:
I am implementing a chess AI in which the output is the position and the piece to be moved. However, when I follow the multi-output tutorial on the keras API documentation, It returns the error

Failed to find data adapter that can handle input:(<class 'list'> containing values of types {'(<class \'list\'> containing values of types {\'(<class \\\'list\\\'> containing values of types {\\\'(<class \\\\\\\'list\\\\\\\'> containing values of types {"<class \\\\\\\'int\\\\\\\'>"})\\\'})\'})'}), (<class 'dict'> containing {"<class 'str'>"} keys and {"<class 'numpy.ndarray'>"} values)

Sorry if the copied section is too long, I just wanted to make sure that it could be easier to find what went wrong.

Reproducible section of code below:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

board_inputs = keras.Input(shape=(8, 8, 12))

conv1= layers.Conv2D(10, 3, activation='relu')
conv2 = layers.Conv2D(10, 3, activation='relu')
pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = keras.layers.Flatten(data_format=None)

x = conv1(board_inputs)
x = pooling1(x)
x = conv2(x)
x = flatten(x)
piece_output = layers.Dense(12,name = 'piece')(x)
alpha_output = layers.Dense(7,name = 'alpha')(x)
numbers_output = layers.Dense(7,name = 'number')(x)

model = keras.Model(inputs=board_inputs, outputs=[piece_output,alpha_output,numbers_output], name="chess_ai_v3")
model.compile(
    loss=keras.losses.mse,
    optimizer=keras.optimizers.Adam(),
    metrics=None,
)

keras.utils.plot_model(model, "multi_input_and_output_model.png", show_shapes=True)
history = model.fit(
    trans_data[:len(trans_data)],
    {"piece": pieces[:len(trans_data)], "alpha": alphas[:len(trans_data)],"number": numbers[:len(trans_data)]},
    epochs=2,
    batch_size=32,
)
# history = model.fit(trans_data[:len(trans_data)],batch_size=64, epochs=1000,verbosity = 2)

Update:
I am still having problems with the network, I tested each of the arrays of values set for the answer. They all function normally when executed individually, does anyone know of any problem that could cause this?

Body:
it seems that your data are in a strange format. look at this

I have no problem running this example

import numpy as np
from tensorflow.keras import layers, models

board_inputs = layers.Input(shape=(8, 8, 12))
conv1= layers.Conv2D(10, 3, activation='relu')
conv2 = layers.Conv2D(10, 3, activation='relu')
pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)
flatten = layers.Flatten(data_format=None)

x = conv1(board_inputs)
x = pooling1(x)
x = conv2(x)
x = flatten(x)
piece_output = layers.Dense(12,name = 'piece')(x)
alpha_output = layers.Dense(7,name = 'alpha')(x)
numbers_output = layers.Dense(7,name = 'number')(x)

model = models.Model(inputs=board_inputs, outputs=[piece_output,alpha_output,numbers_output], name="chess_ai_v3")
model.compile(loss='mse', optimizer='adam')
model.summary()

X = np.random.uniform(0,1, (100,8,8,12))
y = {"piece": np.random.uniform(0,1,(100,12)),
     "alpha": np.random.uniform(0,1,(100,7)),
     "number": np.random.uniform(0,1,(100,7))}

history = model.fit(X,y, epochs=2, batch_size=32)