问:
svelte CSS file isn't generate on run
I'm following this tutorial trying to create a svelte frontend.

I don't get any errors but when I run npm run dev i get:

which I'm supposed to see the new extra.css file created in the public folder. and so the page displayed is without any CSS and just plain li items instead of having materialize-css attributes.

my files:

rollup.config.js

```<code>import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            // enable run-time checks when not in production
            dev: !production,
            // we'll extract any component CSS out into
            // a separate file - better for performance
            css: css => {
                css.write('public/build/bundle.css');
            }
        }),
        css({ output: 'public\extra.css'}),
...
...
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Svelte app</title>

    <link rel='icon' type='image/png' href='/favicon.png'>
    <link rel='stylesheet' href='extra.css'>
    <link rel='stylesheet' href='global.css'>
    <link rel='stylesheet' href='build/bundle.css'>

    <script defer src='/build/bundle.js'></script>
</head>

<body>
</body>
</html>
</code>```

App.svelte

```<code><script>
    import '..\node_modules\materialize-css\dist\css\materialize.min.css';
    import '..\node_modules\materialize-css\dist\js\materialize.min.js';

    import { Router, Route } from 'svelte-routing';

    import Navbar from './layout/Navbar.svelte';
    import Home from './pages/Home.svelte';
    import About from './pages/About.svelte';
</script>

<style>
</style>

<Router>
    <Navbar>
        <div class="container">
            <Route path="/" component={Home} />
            <Route path="/about" component={About} />
        </div>
    </Navbar>
</Router>
</code>```

Navbar.svelte

```<code><script>
    import { Link } from 'svelte-routing';
</script>

<nav>
    <div class="nav-wrapper">
        <Link to="/" class="brand-logo">svelte app</Link>
      <ul id="nav-mobile" class="right hide-on-med-and-down">
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </div>
</nav>
</code>```

and i also found this question/answer on SO that seem to say that the tutorial is ok and working for people so i'm confused.

答:
I have a similiar setup and it works for me. I only noticed that I import materialize.css instead of materialize.min.css and that I have no matierialize.min.css in my node_modules/materialize-css/dist/css/ folder.

Maybe that's the solution to that riddle: you may try importing a non-existing css file.

Title: svelte CSS file isn't generate on run

Body:
I'm following this tutorial trying to create a svelte frontend.

I don't get any errors but when I run npm run dev i get:

which I'm supposed to see the new extra.css file created in the public folder. and so the page displayed is without any CSS and just plain li items instead of having materialize-css attributes.

my files:

rollup.config.js

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            // enable run-time checks when not in production
            dev: !production,
            // we'll extract any component CSS out into
            // a separate file - better for performance
            css: css => {
                css.write('public/build/bundle.css');
            }
        }),
        css({ output: 'public\extra.css'}),
...
...

index.html

<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Svelte app</title>

    <link rel='icon' type='image/png' href='/favicon.png'>
    <link rel='stylesheet' href='extra.css'>
    <link rel='stylesheet' href='global.css'>
    <link rel='stylesheet' href='build/bundle.css'>

App.svelte

<Router>
    <Navbar>

            <Route path="/" component={Home} />
            <Route path="/about" component={About} />

    </Navbar>
</Router>

Navbar.svelte

        <Link to="/" class="brand-logo">svelte app</Link>

          <Link to="/">Home</Link>

          <Link to="/about">About</Link>

and i also found this question/answer on SO that seem to say that the tutorial is ok and working for people so i'm confused.


来源: stackexchange

问:
regex : match dot with no space after
I would like to search for all punctuations in a string except /, #, $ and dot with no space after (.net for example)

I have done this so far.

```<code>?!['\/#$])\p{P}
</code>```

Now I need to handle the dot with no space after.

If anyone has an idea...

I am using Java.

For example I need to replace all punctuations by "" (empty character)  except for dot with no space after:

.net, asp.net hello. world, c#

becomes

.net asp.net hello world c#

答:
I would use the following :

```<code>[\]!"%&'()*+,:;<=>?@[\\^_`{|}~-]|\.(?![a-zA-Z0-9])
</code>```

The character class [!"%&'()*+,:;<=>?@[\]^_`{|}~-] matches any symbol of \p{P} except /, #, $ and ., and the other alternative matches a dot that is not followed by a letter nor a digit.

Note that it's alluring to use \b but that it's a bad idea as \w includes _ in addition to [a-zA-Z0-9].

If you want to keep using \p{P}, you could use the following, but expect lesser performances :

```<code>(?![/#$]|\.[a-zA-Z0-9])\p{P}
</code>```

The following would also work and might be as efficient as my first answer, but it's based on lesser known syntax which if I'm not mistaken is specific to Java regexs :

```<code>[\p{P}&&[^/#$.]]|\.(?![a-zA-Z0-9])
</code>```

ContentLicense: CC BY-SA 4.0

Title: regex : match dot with no space after

Body:
I would like to search for all punctuations in a string except /, #, $ and dot with no space after (.net for example)

I have done this so far.

?!['\/#$])\p{P}

Now I need to handle the dot with no space after.

If anyone has an idea...

I am using Java.

For example I need to replace all punctuations by "" (empty character)  except for dot with no space after:

.net, asp.net hello. world, c#

becomes

.net asp.net hello world c#

Body:
I would use the following :

[\]!"%&'()*+,:;<=>?@[\\^_`{|}~-]|\.(?![a-zA-Z0-9])

The character class [!"%&'()*+,:;<=>?@[\]^_`{|}~-] matches any symbol of \p{P} except /, #, $ and ., and the other alternative matches a dot that is not followed by a letter nor a digit.

Note that it's alluring to use \b but that it's a bad idea as \w includes _ in addition to [a-zA-Z0-9].

If you want to keep using \p{P}, you could use the following, but expect lesser performances :

(?![/#$]|\.[a-zA-Z0-9])\p{P}

The following would also work and might be as efficient as my first answer, but it's based on lesser known syntax which if I'm not mistaken is specific to Java regexs :

[\p{P}&&[^/#$.]]|\.(?![a-zA-Z0-9])


问:
Is it possible to change domparser element to string?
I have some HTML string. Use domparser to update some values, now i need back to HTML string format with updated values... Bcoz document.write accept only string.

Checkout the Sample patch,

```<code>const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Please do not refresh this page...</h1></center><form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form></body></html>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

// now i need to replace current update data entire screen
document.write(parsedHtml)
</code>```

Thanks,

Gopal.R

答:
Bcoz document.write accept only string.

Using document.write is almost always poor practice.

But, if for some reason you really need to, what you get back from parseFromString is a Document object. It has a single documentElement, which you can get the innerHTML or outerHTML of:

```<code>document.write(parsedHtml.documentElement.innerHTML);
// or
document.write(parsedHtml.documentElement.outerHTML);
</code>```

Live Example:

const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<title>Merchant Checkout Page</title>
Please do not refresh this page...
<form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

// now i need to replace current update data entire screen
document.write(parsedHtml.documentElement.innerHTML);```
</div>
</div>
</p>

<p><strong>But</strong>, again, probably better to just append to the page, e.g.</p>

```document.body.appendChild(parsedHtml.documentElement);
```

<p>Live Example:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Please do not refresh this page...</h1></center><form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form></body></html>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

document.body.appendChild(parsedHtml.documentElement);</code>```

Or loop through it and append its children:

```<code>let child = parsedHtml.documentElement.firstChild;
while (child) {
    let next = child.nextSibling;
    document.documentElement.appendChild(child);
    child = next;
}
</code>```

Live Example:

const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<title>Merchant Checkout Page</title>
Please do not refresh this page...
<form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

let child = parsedHtml.documentElement.firstChild;
while (child) {
    let next = child.nextSibling;
    document.documentElement.appendChild(child);
    child = next;
}```

Body:
I have some HTML string. Use domparser to update some values, now i need back to HTML string format with updated values... Bcoz document.write accept only string.

Checkout the Sample patch,

const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<title>Merchant Checkout Page</title>
Please do not refresh this page...
<form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

// now i need to replace current update data entire screen
document.write(parsedHtml)

Thanks,

Gopal.R

Body:
Bcoz document.write accept only string.

Using document.write is almost always poor practice.

But, if for some reason you really need to, what you get back from parseFromString is a Document object. It has a single documentElement, which you can get the innerHTML or outerHTML of:

document.write(parsedHtml.documentElement.innerHTML);
// or
document.write(parsedHtml.documentElement.outerHTML);

Live Example:

const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Please do not refresh this page...</h1></center><form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form></body></html>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

// now i need to replace current update data entire screen
document.write(parsedHtml.documentElement.innerHTML);

But, again, probably better to just append to the page, e.g.

document.body.appendChild(parsedHtml.documentElement);

Live Example:

const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Please do not refresh this page...</h1></center><form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form></body></html>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

document.body.appendChild(parsedHtml.documentElement);

Or loop through it and append its children:

let child = parsedHtml.documentElement.firstChild;
while (child) {
    let next = child.nextSibling;
    document.documentElement.appendChild(child);
    child = next;
}

Live Example:

const domName = 'MOBILE_NO';
// Below dom was getting from api.
const dom =  '<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Please do not refresh this page...</h1></center><form method="post"  name="paytm_form"><input type="hidden" name="MOBILE_NO" value="xxxxxxxx"></form></body></html>';
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(dom, 'text/html');
parsedHtml.getElementsByName(domName)[0].setAttribute('value', '1234567890');

let child = parsedHtml.documentElement.firstChild;
while (child) {
    let next = child.nextSibling;
    document.documentElement.appendChild(child);
    child = next;
}


问:
Get username in magnolia
I am using the following command to get the username in a custom magnolia class:String userName = MgnlContext.getInstance().getJCRSession("website").getUserID();
Instead of getting the name of the user who is signed on in magnolia when the command was triggered I am getting admin for the value. How can I get the real user name - the one who signed on to magnolia?

答:
You can inject info.magnolia.cms.security.SecuritySupport to your class and use

info.magnolia.cms.security.SecuritySupport#getUserManager()
afterwards, you are exposed to plenty of utility method that one can fetch all users or users by group etc.

Title: Get username in magnolia


问:
Undefined start while creating project using expo init Project_name
I need Help
After i create a project using expo init ,it always shows this message : undefined start

答:
Sorry that I cannot comment on this, thus I can only reply as an answer.

I also got the same message asking me to run undefined start. It should mean npm start.

Are you using nvm? I am on Mac Catalina, with nvm and node v12.14.1. I am wondering if this is related to using nvm.


问:
Search maven central for classes extending a given class
How can I search the whole Maven Central repository for classes extending a given class?

(The concrete reason I ask this is that I’d like to see examples of extensions of FileSystemProvider, but I am interested in the question more generally.)

I am also interested in searching for all classes implementing a given interface, I guess the procedure will be similar.

(Here is a related question about searching for classes in the class path; but this question is about searching in the whole Maven Central repository.)

答:
I don't know any option of searching in Maven Central repository, but here's another alternative that might help you.

You could use the GitHub search feature, and what I did was to search for keywords "extends FileSystemProvider". Also, you have the option to select the language, Java in this case. Here's the link to that query: https://github.com/search?q=%22extends+FileSystemProvider%22+language%3AJava&type=Code

For implementing a specific interface, you would search for "implements InterfaceToSearchFor"

This way, you may find some examples of class extensions/interface implementations.


问:
Reg. date format issue in json with jqgrid
I'm using jqgrid and have columns that display date but from the server the date comes in json format as below,

```<code>"CommentedDate": "\/Date(1304324941000+0530)\/"
</code>```

How I can display the date correctly in MM/dd/yyyy format?

Vijaya Anand

答:
If you use predefined formatter 'date' and jqGrid 4.0 it should work automatically. Try for example with the following properties for the column having the date:

```<code>formatter:'date', formatoptions: {newformat:'m/d/Y'}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using jqgrid and have columns that display date but from the server the date comes in json format as below,

"CommentedDate": "\/Date(1304324941000+0530)\/"

How I can display the date correctly in MM/dd/yyyy format?

Vijaya Anand

Body:
If you use predefined formatter 'date' and jqGrid 4.0 it should work automatically. Try for example with the following properties for the column having the date:

formatter:'date', formatoptions: {newformat:'m/d/Y'}


问:
Import leaftlet-control-geocoder in Angular 8 Project?
angular verison: 8

version in package.json:

```<code>"leaflet": "1.5.1",
"leaflet-draw": "1.0.4",
"leaflet-sidebar-v2": "3.0.3",
"esri-leaflet": "2.3.2",
"leaflet-control-geocoder": "1.10.0"
</code>```

I have import leaflet and other like this:

```<code>import * as L from 'leaflet';
import 'leaflet-draw';
import * as esri from 'esri-leaflet';
import 'leaflet-sidebar-v2';
import 'leaflet-control-geocoder';
</code>```

Now i have to use or leaflet-control-geocoder to implement this function but if i write this:

```<code>L.control.geocoder().addTo(map);
</code>```

angular crash.(Property 'geocoder' does not exist on type 'typeof Control')
I try also with esri-leaflet-geocoder, but it's crash too.

any solution?

答:
I had the same problem. I added the geocoder inside L.Routing.control, and it works! (actually, VS Code still says Property 'Geocoder' does not exist on type 'typeof Control') but it works!:

L.Routing.control({
      waypoints: [L.latLng(57.74, 11.94), L.latLng(57.6792, 11.949)],
      showAlternatives: true,
      geocoder: L.Control.Geocoder.nominatim()
    }).addTo(this.map);

I'm working with Angular 8, leaftlet-routing-machine plugin.

Body:
angular verison: 8

version in package.json:

"leaflet": "1.5.1",
"leaflet-draw": "1.0.4",
"leaflet-sidebar-v2": "3.0.3",
"esri-leaflet": "2.3.2",
"leaflet-control-geocoder": "1.10.0"

I have import leaflet and other like this:

import * as L from 'leaflet';
import 'leaflet-draw';
import * as esri from 'esri-leaflet';
import 'leaflet-sidebar-v2';
import 'leaflet-control-geocoder';

Now i have to use or leaflet-control-geocoder to implement this function but if i write this:

L.control.geocoder().addTo(map);

angular crash.(Property 'geocoder' does not exist on type 'typeof Control')
I try also with esri-leaflet-geocoder, but it's crash too.

any solution?


问:
Where to store SparkApplication YAML files on Kubernetes cluster?
I'm using the Helm Chart to deploy Spark Operator to GKE. Then I define a SparkApplication specification in a YAML file. But after reading the User Guide I still don't understand:

Where to store SparkApplication YAML files on Kubernetes cluster or Google storage?

Is it ok/possible to deploy them along with the Spark Operator Helm chart to the Spark Master container?

Is it a good approach to load the SparkApplication configurations to Google Storage and then run kubectl apply -f <YAML GS file path>

What are the best practices for storing SparkApplication configurations on Kubernetes cluster or GS that I may be missing?

答:
To address your questions:

There are a lot of possibilities to store your YAML files. You can store it locally on your PC, laptop or you can store it in the cloud. Going further in that topic, syncing your YAML files to version controlled system (for example Git) would be one of the better options because you will have full history of the changes with ability to check what changes you made and rollback if something failed. The main thing is that the kubectl will need access to this files.

There is no such thing as master container in Kubernetes. There is master node. A master node is a machine which controls and manages a set of worker nodes (workloads runtime)
Please check the official documentation about Kubernetes components.

You can put your YAML files in your Google Storage (bucket). But you would not be able to run command in a way kubectl apply -f FILE. kubectl will not be able to properly interpret file location like gs://NAME_OF_THE_BUCKET/magical-deployment.yaml.

One way to run kubectl apply -f FILE_NAME.yaml would be to have it stored locally and synced outside.

You can access the data inside a bucket through gsutil.  You could try to tinker with gsutil cat gs://NAME_OF_THE_BUCKET/magical-deployment.yaml and try to pipe it into kubectl but I would not recommend that approach.

Please refer to gsutil tool documentation in this case and be aware of:

The gsutil cat command does not compute a checksum of the downloaded data. Therefore, we recommend that users either perform their own validation of the output of gsutil cat or use gsutil cp or rsync (both of which perform integrity checking automatically).

--  https://cloud.google.com/storage/docs/gsutil/commands/cat

Let me know if you have any questions to this.


问:
python - remove directory and subfolders with shutil.rmtree - str object not callable
I'm trying to remove a directory and I guess i'm having an issue with defining the path for the shutil.rmtree(). Does this function take the relative path or the absolute. I use win10 and am having problem understanding how the paths can and should be defined in python, because it seems that for every function the path needs to be defined in a different way.

```<code>import shutil
dir_to_remove = "C:\\Users\name_of_user\\dir_to remove"
shutil.rmtree(dir_to_remove)
</code>```

Result is:

```<code>Traceback (most recent call last):

  File "<ipython-input-257-9cc5f9fe51d2>", line 1, in <module>
    shutil.rmtree(dir_to_remove)

TypeError: 'str' object is not callable
</code>```

Any help or guidance is appreciated.

答:
You are missing the second backslash after C:\\Users.

```<code>dir_to_remove = "C:\\Users\\name_of_user\\dir_to remove"
shutil.rmtree(dir_to_remove)
</code>```

Body:
I'm trying to remove a directory and I guess i'm having an issue with defining the path for the shutil.rmtree(). Does this function take the relative path or the absolute. I use win10 and am having problem understanding how the paths can and should be defined in python, because it seems that for every function the path needs to be defined in a different way.

import shutil
dir_to_remove = "C:\\Users\name_of_user\\dir_to remove"
shutil.rmtree(dir_to_remove)

Result is:

Traceback (most recent call last):

  File "<ipython-input-257-9cc5f9fe51d2>", line 1, in <module>
    shutil.rmtree(dir_to_remove)

TypeError: 'str' object is not callable

Any help or guidance is appreciated.

Body:
You are missing the second backslash after C:\\Users.

dir_to_remove = "C:\\Users\\name_of_user\\dir_to remove"
shutil.rmtree(dir_to_remove)


问:
Use function as react hook?
I wanted to use a function as a react hook to wrap fetch requests to an API.

My current hook:

```<code>export function useAPI(url, options={}) {
    const [auth, setAuth] = useGlobal('auth');
    const [call, setCall] = useState(undefined);

    const apiFetch = async () => {
        const res = await fetch(url, {
            ...options,
        });
        if (!res.ok)
            throw await res.json();
        return await res.json();
    };

    function fetchFunction() {
        fetch(url, {
            ...options,
        });
    }

    useEffect(() => {
        // Only set function if undefined, to prevent setting unnecessarily
        if (call === undefined) {
            setCall(fetchFunction);
            //setCall(apiFetch);
        }

    }, [auth]);

    return call
}
</code>```

That way, in a react function, I could do the following...

```<code>export default function LayoutDash(props) {
    const fetchData = useAPI('/api/groups/mine/'); // should return a function

    useEffect(() => {
        fetchData(); // call API on mount
    }, []);

    render(...stuff);
}
</code>```

But it seems react isn't able to use functions in hooks like that.  If I set call to  fetchFunction, it returns undefined.  If I set it to apiFetch, it executes and returns a promise instead of a function that I can call when I want to in the other component.

I initially went for react hooks because I can't use useGlobal outside react components/hooks.  And I would need to have access to the reactn global variable auth to check if the access token is expired.

So what would be the best way to go about this?  The end goal is being able to pass (url, options) to a function that will be a wrapper to a fetch request.  (It checks if auth.access is expired, and if so, obtains a new access token first, then does the api call, otherwise it just does the API call).  If there's another way I should go about this other than react hooks, I'd like to know.

答:
Instead of putting your function into useState, consider using useCallback. Your code would look something like this:

```<code>export function useAPI(url, options={}) {
    const [auth, setAuth] = useGlobal('auth');

    function fetchFunction() {
        fetch(url, {
            ...options,
        });
    }

    const call = useCallback(fetchFunction, [auth]);

    const apiFetch = async () => {
        const res = await fetch(url, {
            ...options,
        });
        if (!res.ok)
            throw await res.json();
        return await res.json();
    };

    return call
}
</code>```

The returned function is recreated whenever auth changes, therefore somewhat mimicking what you tried to do with useEffect

Title: Use function as react hook?

Body:
I wanted to use a function as a react hook to wrap fetch requests to an API.

My current hook:

export function useAPI(url, options={}) {
    const [auth, setAuth] = useGlobal('auth');
    const [call, setCall] = useState(undefined);

    const apiFetch = async () => {
        const res = await fetch(url, {
            ...options,
        });
        if (!res.ok)
            throw await res.json();
        return await res.json();
    };

    function fetchFunction() {
        fetch(url, {
            ...options,
        });
    }

    useEffect(() => {
        // Only set function if undefined, to prevent setting unnecessarily
        if (call === undefined) {
            setCall(fetchFunction);
            //setCall(apiFetch);
        }

    }, [auth]);

    return call
}

That way, in a react function, I could do the following...

export default function LayoutDash(props) {
    const fetchData = useAPI('/api/groups/mine/'); // should return a function

    useEffect(() => {
        fetchData(); // call API on mount
    }, []);

    render(...stuff);
}

But it seems react isn't able to use functions in hooks like that.  If I set call to  fetchFunction, it returns undefined.  If I set it to apiFetch, it executes and returns a promise instead of a function that I can call when I want to in the other component.

I initially went for react hooks because I can't use useGlobal outside react components/hooks.  And I would need to have access to the reactn global variable auth to check if the access token is expired.

So what would be the best way to go about this?  The end goal is being able to pass (url, options) to a function that will be a wrapper to a fetch request.  (It checks if auth.access is expired, and if so, obtains a new access token first, then does the api call, otherwise it just does the API call).  If there's another way I should go about this other than react hooks, I'd like to know.

Body:
Instead of putting your function into useState, consider using useCallback. Your code would look something like this:

export function useAPI(url, options={}) {
    const [auth, setAuth] = useGlobal('auth');

    function fetchFunction() {
        fetch(url, {
            ...options,
        });
    }

    const call = useCallback(fetchFunction, [auth]);

    const apiFetch = async () => {
        const res = await fetch(url, {
            ...options,
        });
        if (!res.ok)
            throw await res.json();
        return await res.json();
    };

    return call
}

The returned function is recreated whenever auth changes, therefore somewhat mimicking what you tried to do with useEffect


问:
Bash: how to look for the next positional parameter in "case" code without hard-coding its value?
Given the "case" code snippet:

```<code>case $3 in
        -a)
            if [ "$4" == #some regex to match pattern ]; then
                #do some additional work
            else
                #proceed as usual
            fi
            ;;
</code>```

How could I better express my intention to look for a positional parameter which is located right next on the right-hand side of the current position $3 (or $3++, if that makes sense), instead of hard-coding it to $4 in the "if" statement?

EDIT:

the simplest usage of my script would look like this:

```<code>./script.sh company region -a LIST-123
</code>```

the first two mandatory positional arguments (company & region) are fixed.
Starting from the position $3, users have to provide at least one mandatory argument in the format of a preceding dash and a single letter (-a, -b, -c etc).
The single-letter mandatory arguments can have an optional argument (LIST-123 in the example above). If the optional argument is not provided, the script should resume as usual.

I want users to be able provide multiple mandatory-optional argument pairs. like this:

```<code>./script.sh company region -a LIST-123 -b LIST-456 -c LIST-789
</code>```

Also, to have flexibility to provide the mandatory single-letter args in any order:

```<code>./script.sh company region -c LIST-789 -b LIST-456 -a LIST-123
</code>```

And to be able to provide optional arguments only to certain mandatory single-letter args, but not all:

./script.sh company region -c LIST-789 -b -a LIST-123

答:
shift is exactly what you're looking for.  See help shift:

```<code>shift: shift [n]
Shift positional parameters.

Rename the positional parameters $N+1,$N+2 ... to $1,$2 ...  If N is
not given, it is assumed to be 1.

Exit Status:
Returns success unless N is negative or greater than $#.
</code>```

Your (working!) code could look like this:

```<code>#!/usr/bin/env bash

case $3 in
    -a)
    shift
        if [ "$3" == "word" ];
    then
        echo it matches
            #do some additional work
    else
        echo it does not match
            #proceed as usual
        fi
    ;;
esac
</code>```

You could also use eval although it's not
recommended:

```<code>#!/usr/bin/env bash

case $3 in
    -a)
        if [ "$(eval echo \$$((3+1)))" == "word" ];
    then
        echo it matches
            #do some additional work
    else
        echo it does not match
            #proceed as usual
        fi
    ;;
esac
</code>```

Body:
Given the "case" code snippet:

case $3 in
        -a)
            if [ "$4" == #some regex to match pattern ]; then
                #do some additional work
            else
                #proceed as usual
            fi
            ;;

How could I better express my intention to look for a positional parameter which is located right next on the right-hand side of the current position $3 (or $3++, if that makes sense), instead of hard-coding it to $4 in the "if" statement?

EDIT:

the simplest usage of my script would look like this:

./script.sh company region -a LIST-123

the first two mandatory positional arguments (company & region) are fixed.
Starting from the position $3, users have to provide at least one mandatory argument in the format of a preceding dash and a single letter (-a, -b, -c etc).
The single-letter mandatory arguments can have an optional argument (LIST-123 in the example above). If the optional argument is not provided, the script should resume as usual.

I want users to be able provide multiple mandatory-optional argument pairs. like this:

./script.sh company region -a LIST-123 -b LIST-456 -c LIST-789

Also, to have flexibility to provide the mandatory single-letter args in any order:

./script.sh company region -c LIST-789 -b LIST-456 -a LIST-123

And to be able to provide optional arguments only to certain mandatory single-letter args, but not all:

./script.sh company region -c LIST-789 -b -a LIST-123

Body:
shift is exactly what you're looking for.  See help shift:

shift: shift [n]
Shift positional parameters.

Rename the positional parameters $N+1,$N+2 ... to $1,$2 ...  If N is
not given, it is assumed to be 1.

Exit Status:
Returns success unless N is negative or greater than $#.

Your (working!) code could look like this:

#!/usr/bin/env bash

case $3 in
    -a)
    shift
        if [ "$3" == "word" ];
    then
        echo it matches
            #do some additional work
    else
        echo it does not match
            #proceed as usual
        fi
    ;;
esac

You could also use eval although it's not
recommended:

#!/usr/bin/env bash

case $3 in
    -a)
        if [ "$(eval echo \$$((3+1)))" == "word" ];
    then
        echo it matches
            #do some additional work
    else
        echo it does not match
            #proceed as usual
        fi
    ;;
esac


问:
Naming multiple sheets
I have a workbook with two sheet I copy to the end of the workbook.

I am trying to name the two sheet the same name via a InputBox and give them two different suffix as standard, the first is "xxx - Project" and the next is "xxx - Report".

I have placed the two sheets in an array. How do I reference the two sheet via the InputBox?

```<code>Public Sub CopySheets()
    Dim shName As String 'Sheet name var
    Dim shExists As Boolean

    Do

        shName = InputBox("Please enter name of new project", "New Project")

        If shName <> "" Then

            shExists = SheetExists(shName) 'Check for existing sheet name
            If Not shExists Then
                Worksheets(Array(1, 2)).Copy After:=Sheets(Sheets.Count)

            Else
                MsgBox "Project Name:" & Space(1) & shName & " already exists", vbOKOnly + vbCritical, "Deter"
            End If

        End If

    Loop Until Not shExists Or shName = ""
    End Sub

    Private Function SheetExists(ByVal sheetName As String, _
      Optional ByVal wb As Workbook)

    If wb Is Nothing Then Set wb = ActiveWorkbook
    On Error Resume Next
    SheetExists = Not wb.Worksheets(sheetName) Is Nothing
    End Function
</code>```

Sample image:

答:
Something like that in in the if conditon</p>

```<code>    If Not shExists Then
        Worksheets(Array(1, 2)).Copy After:=Sheets(Sheets.Count)

        Dim ws As Worksheet
        Set ws = Sheets(Sheets.Count - 1)
        ws.Name = shName & "- project"

        Set ws = Sheets(Sheets.Count)
        ws.Name = shName & "- report"

    Else
</code>```

Title: Naming multiple sheets

Body:
I have a workbook with two sheet I copy to the end of the workbook.

I am trying to name the two sheet the same name via a InputBox and give them two different suffix as standard, the first is "xxx - Project" and the next is "xxx - Report".

I have placed the two sheets in an array. How do I reference the two sheet via the InputBox?

Public Sub CopySheets()
    Dim shName As String 'Sheet name var
    Dim shExists As Boolean

    Do

        shName = InputBox("Please enter name of new project", "New Project")

        If shName <> "" Then

            shExists = SheetExists(shName) 'Check for existing sheet name
            If Not shExists Then
                Worksheets(Array(1, 2)).Copy After:=Sheets(Sheets.Count)

            Else
                MsgBox "Project Name:" & Space(1) & shName & " already exists", vbOKOnly + vbCritical, "Deter"
            End If

        End If

    Loop Until Not shExists Or shName = ""
    End Sub

    Private Function SheetExists(ByVal sheetName As String, _
      Optional ByVal wb As Workbook)

    If wb Is Nothing Then Set wb = ActiveWorkbook
    On Error Resume Next
    SheetExists = Not wb.Worksheets(sheetName) Is Nothing
    End Function

Sample image:

Body:
Something like that in in the if conditon

    If Not shExists Then
        Worksheets(Array(1, 2)).Copy After:=Sheets(Sheets.Count)

        Dim ws As Worksheet
        Set ws = Sheets(Sheets.Count - 1)
        ws.Name = shName & "- project"

        Set ws = Sheets(Sheets.Count)
        ws.Name = shName & "- report"

    Else


问:
What is causing the 'WrongThreadException' in Unity 3D?
I want to integrate a C++ project in Unity. Unity provides a mechanism called I2CPP (Intermediate Language To C++) which allows to add C++ code to your unity project. I've created a simple C++ class and header in a "Blank App (Universal Windows C++/CX)" project in Visual Studio.

```<code>// header
namespace SomeNamespace {
    public ref class MyRuntimeClass sealed
    {
        public:
            // Constructor
            MyRuntimeClass();

            // Method to check if initialized
            bool IsClassInitialized();

        private:
            bool _isRuntimeInitialized = false;
    };
}
</code>```

and

```<code>// implementation
using SomeNamespace;
MyRuntimeClass::MyRuntimeClass()
{
    _isRuntimeInitialized = true;
}

bool MyRuntimeClass::IsClassInitialized()
{
    return _isRuntimeInitialized;
};
</code>```

I've made in Unity a simple project and made the necessary changes in the Player settings outlined in the documentation. I also added a cube as a game object and attached to the cube a script which uses my C++ code, i.e.

```<code>#if ENABLE_WINMD_SUPPORT
using SomeNamespace;
#endif

public class RuntimeSampleUnity : MonoBehaviour
{
#if ENABLE_WINMD_SUPPORT
    private MyRuntimeClass _myRuntimeClass;
#endif

    // Default MonoBehaviour method
    void Start()
    {
#if ENABLE_WINMD_SUPPORT
        // New instance of runtime class
        _myRuntimeClass = new MyRuntimeClass();

        // Check to see if we initialized C++ runtime component
        var isInit = _myRuntimeClass.IsClassInitialized();
        Debug.LogFormat("MyRuntimeClass: {0}", isInit);
#endif
    }
}
</code>```

In a final step, I've added the winmd file from the C++ project to my assets in Unity. The project builds fine, but when I run the project I get an Platform.WrongThreadException: The application called an interface that was marshalled for a different thread. What is causing this exception (and how do I fix it)?

EDIT: To elaborate a bit why I'm doing what I'm doing: Microsoft provides a project which shows how to integrate OpenCV (C++) to HoloLens-based projects. While it provides a UWP project which mixes OpenCV and C#, it doesn't show how to integrate this particular project into Unity. Somebody actually made this possible via I2CPP. While I ran into issues using his Visual Studio 2017 based project into Visual Studio 2019, I've tried to make a minimal example to understand how it (basically) works.

答:
I think you're misunderstanding the concept of IL2CPP.

IL2CPP (Intermediate Language To C++) is a Unity-developed scripting
  backend  which you can use as an alternative to Mono when building
  projects for various platforms. When building a project using IL2CPP,
  Unity converts IL code from scripts  and assemblies to C++, before
  creating a native binary file (.exe, apk, .xap, for example) for your
  chosen platform. Some of the uses for IL2CPP include increasing the
  performance, security, and platform compatibility of your Unity
  projects.

To use C++ you have to write a Native Plugin.

Body:
I want to integrate a C++ project in Unity. Unity provides a mechanism called I2CPP (Intermediate Language To C++) which allows to add C++ code to your unity project. I've created a simple C++ class and header in a "Blank App (Universal Windows C++/CX)" project in Visual Studio.

// header
namespace SomeNamespace {
    public ref class MyRuntimeClass sealed
    {
        public:
            // Constructor
            MyRuntimeClass();

            // Method to check if initialized
            bool IsClassInitialized();

        private:
            bool _isRuntimeInitialized = false;
    };
}

and

// implementation
using SomeNamespace;
MyRuntimeClass::MyRuntimeClass()
{
    _isRuntimeInitialized = true;
}

bool MyRuntimeClass::IsClassInitialized()
{
    return _isRuntimeInitialized;
};

I've made in Unity a simple project and made the necessary changes in the Player settings outlined in the documentation. I also added a cube as a game object and attached to the cube a script which uses my C++ code, i.e.

#if ENABLE_WINMD_SUPPORT
using SomeNamespace;
#endif

public class RuntimeSampleUnity : MonoBehaviour
{
#if ENABLE_WINMD_SUPPORT
    private MyRuntimeClass _myRuntimeClass;
#endif

    // Default MonoBehaviour method
    void Start()
    {
#if ENABLE_WINMD_SUPPORT
        // New instance of runtime class
        _myRuntimeClass = new MyRuntimeClass();

        // Check to see if we initialized C++ runtime component
        var isInit = _myRuntimeClass.IsClassInitialized();
        Debug.LogFormat("MyRuntimeClass: {0}", isInit);
#endif
    }
}

In a final step, I've added the winmd file from the C++ project to my assets in Unity. The project builds fine, but when I run the project I get an Platform.WrongThreadException: The application called an interface that was marshalled for a different thread. What is causing this exception (and how do I fix it)?

EDIT: To elaborate a bit why I'm doing what I'm doing: Microsoft provides a project which shows how to integrate OpenCV (C++) to HoloLens-based projects. While it provides a UWP project which mixes OpenCV and C#, it doesn't show how to integrate this particular project into Unity. Somebody actually made this possible via I2CPP. While I ran into issues using his Visual Studio 2017 based project into Visual Studio 2019, I've tried to make a minimal example to understand how it (basically) works.


问:
CSVhelper any way to ignore "=" present in CSV
I have an application which generates CSV data. This application "helpfully" includes the Excel fix of using = as a preamble to quoted 0-filled numeric data, to prevent the Excel interpreter from eating the leading 0.

I want to use CSVHelper to read these records. However, when mapping to a number, CSVhelper reports an error for these values with the = prefix.

Other than search/replace to pull the "=" out, is there a way to tell CSVhelper to ignore the leading equals and process successfully?  I see options for including = in the written output but not to allow them in the parse.

Here is an example record:

```"XYZ INC","R1G202113","R2G",<b>="202113"</b>,"D-SRS PRO FLD SM/2",157.49,122.53,True,50,50,0.00,1,False,"N",4.00,6.00,8.00,6.00,""
```

Any hep with this is appreciated.

答:
This is a guess, and there may be a much better way, but perhaps you could do something like this with your mapping:</p>

```<code>public class MyData
{
    //map the raw input to this field as a string
    public string MappedIntField {get;set;}=null;

    // use an integer property not mapped to any column to shadow the string, and lazy-convert to an integer the first time you read it.
    public int ActualIntField
    {
        get {
            if (MappingReady || string.IsNullOrEmpty(MappedIntField)) return _ActualIntField;

            //clean up the extra = character.
            if (MappedIntField[0] == '=') MappedIntField = MappedIntField.Substring(1);

            int result;
            if (int.TryParse(MappedIntField, out result))
            {
                 _ActualIntField = result;
                 MappingReady = true;
                 return result;
            }
            return _ActualIntField;
        }
        set {
            _ActualIntField = value;
            MappingReady = true;
        }
    }
    private int _AcutalIntField;
    // We don't want to re-parse the string on every read, so also flag when this work is done. You could also use a nullable int? to do this.
    private bool MappingReady = false;

}
</code>```

Body:
I have an application which generates CSV data. This application "helpfully" includes the Excel fix of using = as a preamble to quoted 0-filled numeric data, to prevent the Excel interpreter from eating the leading 0.

I want to use CSVHelper to read these records. However, when mapping to a number, CSVhelper reports an error for these values with the = prefix.

Other than search/replace to pull the "=" out, is there a way to tell CSVhelper to ignore the leading equals and process successfully?  I see options for including = in the written output but not to allow them in the parse.

Here is an example record:

"XYZ INC","R1G202113","R2G",="202113","D-SRS PRO FLD SM/2",157.49,122.53,True,50,50,0.00,1,False,"N",4.00,6.00,8.00,6.00,""

Any hep with this is appreciated.

Body:
This is a guess, and there may be a much better way, but perhaps you could do something like this with your mapping:

public class MyData
{
    //map the raw input to this field as a string
    public string MappedIntField {get;set;}=null;

    // use an integer property not mapped to any column to shadow the string, and lazy-convert to an integer the first time you read it.
    public int ActualIntField
    {
        get {
            if (MappingReady || string.IsNullOrEmpty(MappedIntField)) return _ActualIntField;

            //clean up the extra = character.
            if (MappedIntField[0] == '=') MappedIntField = MappedIntField.Substring(1);

            int result;
            if (int.TryParse(MappedIntField, out result))
            {
                 _ActualIntField = result;
                 MappingReady = true;
                 return result;
            }
            return _ActualIntField;
        }
        set {
            _ActualIntField = value;
            MappingReady = true;
        }
    }
    private int _AcutalIntField;
    // We don't want to re-parse the string on every read, so also flag when this work is done. You could also use a nullable int? to do this.
    private bool MappingReady = false;

}


问:
Selection keeps going to first one
```<code>ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO PRESS 1 or 2 to select your task, or 4 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Test
ECHO 2 - Production
ECHO 4 - EXIT
ECHO.
CHOICE /C:124
IF ERRORLEVEL 1 SET M=1
IF ERRORLEVEL 2 SET M=2
IF ERRORLEVEL 4 SET M=4

IF %M%==1 GOTO TEST
IF %M%==2 GOTO PROD
IF %M%==4 GOTO EOF
:TEST
ECHO TEST
cd %~dp0\Test\
start Test.exe
GOTO MENU
:PROD
ECHO PROD
cd %~dp0\Production\
start Production.exe
GOTO MENU
</code>```

no matter which option is selected, it's always launching Test.exe

What am i doing wrong?

答:
This appears to work:

```<code>ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO PRESS 1 or 2 to select your task, or 4 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Test
ECHO 2 - Production
ECHO 4 - EXIT
ECHO.
CHOICE /C:124
IF %ERRORLEVEL% EQU 1 SET M=1
IF %ERRORLEVEL% EQU 2 SET M=2
IF %ERRORLEVEL% EQU 3 SET M=4

IF %M% EQU 1 GOTO TEST
IF %M% EQU 2 GOTO PROD
IF %M% EQU 4 GOTO EOF

:TEST
ECHO TEST
cd %~dp0\Test\
ECHO start Test.exe
GOTO MENU
:PROD
ECHO PROD
cd %~dp0\Production\
start Production.exe
GOTO MENU

:EOF
</code>```

A couple of minor changes to your script required

refer to the %ERRORLEVEL% variable rather than using IF ERRORLEVEL

CHOICE returns the index of the selected option, not the selected value - 4 is the third option and so has the index 3.

Title: Selection keeps going to first one

Body:
ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO PRESS 1 or 2 to select your task, or 4 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Test
ECHO 2 - Production
ECHO 4 - EXIT
ECHO.
CHOICE /C:124
IF ERRORLEVEL 1 SET M=1
IF ERRORLEVEL 2 SET M=2
IF ERRORLEVEL 4 SET M=4

IF %M%==1 GOTO TEST
IF %M%==2 GOTO PROD
IF %M%==4 GOTO EOF
:TEST
ECHO TEST
cd %~dp0\Test\
start Test.exe
GOTO MENU
:PROD
ECHO PROD
cd %~dp0\Production\
start Production.exe
GOTO MENU

no matter which option is selected, it's always launching Test.exe

What am i doing wrong?

Body:
This appears to work:

ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO PRESS 1 or 2 to select your task, or 4 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Test
ECHO 2 - Production
ECHO 4 - EXIT
ECHO.
CHOICE /C:124
IF %ERRORLEVEL% EQU 1 SET M=1
IF %ERRORLEVEL% EQU 2 SET M=2
IF %ERRORLEVEL% EQU 3 SET M=4

IF %M% EQU 1 GOTO TEST
IF %M% EQU 2 GOTO PROD
IF %M% EQU 4 GOTO EOF

:TEST
ECHO TEST
cd %~dp0\Test\
ECHO start Test.exe
GOTO MENU
:PROD
ECHO PROD
cd %~dp0\Production\
start Production.exe
GOTO MENU

:EOF

A couple of minor changes to your script required

refer to the %ERRORLEVEL% variable rather than using IF ERRORLEVEL

CHOICE returns the index of the selected option, not the selected value - 4 is the third option and so has the index 3.


问:
Set selector as multifilter posible?
Hello all (Sorry for my english).
I want to filter by some columns when i add a Sales Order Line (Detail) to my Sales Order.
Look the next image.
Red: When i enter text i want to filter by two columns, in this example for Description and Type.
Green: The first line must be the one that the filter return me because is "Case Labor" on Description column and "Labor" on Type column.
enter image description here

It's an example of how i need to filter mi Inventorys Items on Sales Order Lines.

答:
You can add filtering to other columns using the FastFilterFields property as explained in this answer:
https://stackoverflow.com/a/47076876/7376238

Besides that most behaviors of the selector dialog is not customizable.

To implement custom filter behavior you would have to implement a smart panel dialog:

Reference: https://help-2019r2.acumatica.com/Help?ScreenId=ShowWiki&pageid=2fe4a5bb-c249-4d30-b117-af8d1671a589

Title: Set selector as multifilter posible?


问:
HTML - ReactJS: How to shown an image inside a

I am using Contentful as external container for my images.
I am building a boat visualizer using AISHub. All the vessels I am interested are injected into a table. When I click on the table I locate the marker (vessel) on the map and the image of that vessel pops up on a sidebar on the right of the map.

The problem I have is that I should also visualize the image of the vessel, but unfortunately I only visualize a weird icon as shown below:

Below the code I have so far:

```<code>import React from 'react';
import { Card, CardTitle, CardSubtitle, CardText, CardBody, CardImg } from 'reactstrap';
import '../components/SideBar.css';
import { Link } from 'react-router-dom';
import Client from '../Contentful';

class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    render() {
        return (
            <div className="map-sidebar">
                {this.props.activeShipTypes}
                ```
                    {this.getFilteredShips().map((ship) => (
                        <Card className="mb-2">
                            <CardImg />
                            <CardBody>

                                    {/*
 */}

                                <CardTitle>

{ship.name}

                                </CardTitle>
                                <CardSubtitle>{ship.type}</CardSubtitle>
                                <CardText>

Project Details

For a description of the project view the specification included

                                </CardText>

                                    <SpecsButton />
                                    <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                                        Go to vessel
                                    </Link>

                            </CardBody>
                        </Card>
                    ))}
                ```
            </div>
        );
    }
}

export default Sidebar;
</code>```

EDITS:

```<code>class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    {this.getFilteredShips().map((ship) => (
        console.log(ship);

        return (
            <div className="map-sidebar">
                        <Card className="mb-2">
                            <CardImg />
                            <CardBody>
                                <div className="row">
                                    <img className="image-sizing-primary" src={ship.companylogo} alt="shipImage" />
                                </div>
                                <div>
                                    <img className="image-sizing-secondary" src={ship.images} alt="shipImage" />
                                </div>
                                <CardTitle>
                                    <h3 className="thick">{ship.name}</h3>
                                </CardTitle>
                                <CardSubtitle>{ship.type}</CardSubtitle>
                                <CardText>
                                    <br />
                                    <h6>Project Details</h6>
                                    <p>For a description of the project view the specification included</p>
                                </CardText>
                                <div class="btn-toolbar">
                                    <SpecsButton />
                                    <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                                        Go to vessel
                                    </Link>
                                </div>
                            </CardBody>
                    </Card>
            </div>
        )))}
}

export default Sidebar;
</code>```

EDITS 2:

```<code>class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    {this.getFilteredShips().map((ship) => {
        console.log(ship);
      render() {
        return (
          <Card className="mb-2">
              <CardImg />
              <CardBody>
                  <div className="row">
                      {/* <div className="column"> */}
                      <img className="image-sizing-primary" src={ship.companylogo} alt="shipImage" />
                  </div>
                  <div>
                      <img className="image-sizing-secondary" src={ship.images} alt="shipImage" />
                  </div>
                  <CardTitle>
                      <h3 className="thick">{ship.name}</h3>
                  </CardTitle>
                  <CardSubtitle>{ship.type}</CardSubtitle>
                  <CardText>
                      <br />
                      <h6>Project Details</h6>
                      <p>For a description of the project view the specification included</p>
                  </CardText>
                  <div class="btn-toolbar">
                      <SpecsButton />
                      <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                          Go to vessel
                      </Link>
                  </div>
              </CardBody>
          </Card>
        )
      }
    })}
}

export default Sidebar;
</code>```

Below a print screen on how Contentful is structured:

What I have done so far:

1) I was able to implement the table click event as well as finding the marker (vessel) and show its card on the right of a sidebar, and thought that it would have been easy to finally show the vessel image. Unfortunately the implementation does not show the image.
I should mention that I used reactstrap Cards.
Maybe there is an error in how Contentful is reading the image?

2) After researching more this problem I came across this post which was useful. The problem was that the image uploaded was local, I have an image that is external on an external container.

Thanks for pointing in the right direction.

答:
here you go

```<code>import React from 'react';
import { Card, CardTitle, CardSubtitle, CardText, CardBody, CardImg } from 'reactstrap';
import '../components/SideBar.css';
import { Link } from 'react-router-dom';
import Client from '../Contentful';

class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    render() {
        return (
            <div className="map-sidebar">
                {this.props.activeShipTypes}
                ```
{this.getFilteredShips().map((ship) => {
  console.log(ship);

  return (
    <Card className="mb-2">
        <CardImg />
        <CardBody>

                {/*
 */}

            <CardTitle>

{ship.name}

            </CardTitle>
            <CardSubtitle>{ship.type}</CardSubtitle>
            <CardText>

Project Details

For a description of the project view the specification included

            </CardText>

                <SpecsButton />
                <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                    Go to vessel
                </Link>

        </CardBody>
    </Card>
  )
})}

                ```
            </div>
        );
    }
}

export default Sidebar;
</code>```

Title: HTML - ReactJS: How to shown an image inside a <div>

Body:
I am using Contentful as external container for my images.
I am building a boat visualizer using AISHub. All the vessels I am interested are injected into a table. When I click on the table I locate the marker (vessel) on the map and the image of that vessel pops up on a sidebar on the right of the map.

The problem I have is that I should also visualize the image of the vessel, but unfortunately I only visualize a weird icon as shown below:

Below the code I have so far:

import React from 'react';
import { Card, CardTitle, CardSubtitle, CardText, CardBody, CardImg } from 'reactstrap';
import '../components/SideBar.css';
import { Link } from 'react-router-dom';
import Client from '../Contentful';

class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    render() {
        return (

                {this.props.activeShipTypes}

                    {this.getFilteredShips().map((ship) => (
                        <Card className="mb-2">
                            <CardImg />
                            <CardBody>

                                    {/*
 */}

                                <CardTitle>

{ship.name}

                                </CardTitle>
                                <CardSubtitle>{ship.type}</CardSubtitle>
                                <CardText>

Project Details

For a description of the project view the specification included

                                </CardText>

                                    <SpecsButton />
                                    <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                                        Go to vessel
                                    </Link>

                            </CardBody>
                        </Card>
                    ))}

        );
    }
}

export default Sidebar;

EDITS:

class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    {this.getFilteredShips().map((ship) => (
        console.log(ship);

        return (

                        <Card className="mb-2">
                            <CardImg />
                            <CardBody>

                                <CardTitle>

{ship.name}

                                </CardTitle>
                                <CardSubtitle>{ship.type}</CardSubtitle>
                                <CardText>

Project Details

For a description of the project view the specification included

                                </CardText>

                                    <SpecsButton />
                                    <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                                        Go to vessel
                                    </Link>

                            </CardBody>
                    </Card>

        )))}
}

export default Sidebar;

EDITS 2:

class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    {this.getFilteredShips().map((ship) => {
        console.log(ship);
      render() {
        return (
          <Card className="mb-2">
              <CardImg />
              <CardBody>

                      {/*
 */}

                  <CardTitle>

{ship.name}

                  </CardTitle>
                  <CardSubtitle>{ship.type}</CardSubtitle>
                  <CardText>

Project Details

For a description of the project view the specification included

                  </CardText>

                      <SpecsButton />
                      <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                          Go to vessel
                      </Link>

              </CardBody>
          </Card>
        )
      }
    })}
}

export default Sidebar;

Below a print screen on how Contentful is structured:

What I have done so far:

1) I was able to implement the table click event as well as finding the marker (vessel) and show its card on the right of a sidebar, and thought that it would have been easy to finally show the vessel image. Unfortunately the implementation does not show the image.
I should mention that I used reactstrap Cards.
Maybe there is an error in how Contentful is reading the image?

2) After researching more this problem I came across this post which was useful. The problem was that the image uploaded was local, I have an image that is external on an external container.

Thanks for pointing in the right direction.

Body:
here you go

import React from 'react';
import { Card, CardTitle, CardSubtitle, CardText, CardBody, CardImg } from 'reactstrap';
import '../components/SideBar.css';
import { Link } from 'react-router-dom';
import Client from '../Contentful';

class Sidebar extends React.Component {
    state = {
        ships: []
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cashmanCards'
        });
        const ships = response.items.map((item) => {
            const { name, slug, type, company, description, images, companylogo } = item.fields;
            return {
                name,
                slug,
                type,
                company,
                description,
                images,
                companylogo
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }

        return this.state.ships.filter((ship) => this.props.activeShip.name.toLowerCase() === ship.name.toLowerCase());
    };

    render() {
        return (
            <div className="map-sidebar">
                {this.props.activeShipTypes}
                <pre>
{this.getFilteredShips().map((ship) => {
  console.log(ship);

  return (
    <Card className="mb-2">
        <CardImg />
        <CardBody>
            <div className="row">
                {/* <div className="column"> */}
                <img className="image-sizing-primary" src={ship.companylogo} alt="shipImage" />
            </div>
            <div>
                <img className="image-sizing-secondary" src={ship.images} alt="shipImage" />
            </div>
            <CardTitle>
                <h3 className="thick">{ship.name}</h3>
            </CardTitle>
            <CardSubtitle>{ship.type}</CardSubtitle>
            <CardText>
                <br />
                <h6>Project Details</h6>
                <p>For a description of the project view the specification included</p>
            </CardText>
            <div class="btn-toolbar">
                <SpecsButton />
                <Link to="/vessels/Atchafalaya" className="btn btn-primary">
                    Go to vessel
                </Link>
            </div>
        </CardBody>
    </Card>
  )
})}

                </pre>
            </div>
        );
    }
}

export default Sidebar;


问:
Missing .dll in different Visual Studio versions
I recently came up with an issue. I had a project created on visual studio 2015, using allegro5 library which executed on Debug and Release mode correctly.

When I changed visual studio versions though and started using 2019 version (In the mean time I had to format my PC and re-installed only VS19) and loaded the project, the execution had a missing msvc110d.dll error shown up.

I tried to find a way in order for my project to be "upgraded" and instead of looking into the old version of msvc to try and look up the newer version, but couldn't find anything.

So is there a way for me to change some settings in order for my project to expect newer versions of msvc, or do I have to create a new project and copy paste all the configurations and files/assets inside that new project?

Thank you all

P.S I know that the error can be resolved If I get the .dll file inside that directory, but that is bad practice for sure. Also could you give me a tip on how to setup a project correctly in order to prevent those kind of issues in the future?

答: I think you need to find the VS2015 redistributable on Google and install it on your machine. That should solve it.</p>


问:
How to prevent freezing PhoneGap app in Android when doing asynchronous AJAX call?
I have PhoneGap-Android app and I am using Jquery. I am doing ASYNCHRONOUS AJAX call and during the call, app just freezes and waits after AJAX call finish ( it is mainly noticeable when on GSM connection ).

I would understand this, if I would be doing synchronous request, but I have:

```<code>$.ajax({type: 'POST',url: 'http://www.example.com', data: data,async:true,success:callback});
</code>```

Anybody can help ?

答:
Can you get your AJAX call off the main UI thread?  Example:</p>

```<code>public class JsonParsingActivity extends Activity {

    private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                _initTask = new InitTask();
                _initTask.execute( getApplicationContext() );
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        _initTask.cancel(true);
    }

    protected class InitTask extends AsyncTask<Context, String, SearchResponse>
    {
        @Override
        protected SearchResponse doInBackground( Context... params )
        {
            InputStream source = retrieveStream(url);
            SearchResponse response = null;
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                try {
                    response = gson.fromJson(reader, SearchResponse.class);
                    publishProgress( response.query );
                    reader.close();
                } catch (Exception e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                }
            }
            if (!this.isCancelled()) {
                return response;
            } else {
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... s)
        {
            super.onProgressUpdate(s);
            Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute( SearchResponse response )
        {
            super.onPostExecute(response);
            StringBuilder builder = new StringBuilder();
            if (response != null) {
                String delim = "* ";
                List<Result> results = response.results;
                for (Result result : results) {
                    builder.append(delim).append(result.fromUser);
                    delim="\n* ";
                }
            }
            if (builder.length() > 0) {
                Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
        }

        private InputStream retrieveStream(String url) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet getRequest;
            try {
                getRequest = new HttpGet(url);
                HttpResponse getResponse = client.execute(getRequest);
                HttpEntity getResponseEntity = getResponse.getEntity();
                return getResponseEntity.getContent();
            } catch (Exception e) {
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                return null;
            }
        }

    }

}
</code>```

Body:
I have PhoneGap-Android app and I am using Jquery. I am doing ASYNCHRONOUS AJAX call and during the call, app just freezes and waits after AJAX call finish ( it is mainly noticeable when on GSM connection ).

I would understand this, if I would be doing synchronous request, but I have:

$.ajax({type: 'POST',url: 'http://www.example.com', data: data,async:true,success:callback});

Anybody can help ?

Body:
Can you get your AJAX call off the main UI thread?  Example:

public class JsonParsingActivity extends Activity {

    private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                _initTask = new InitTask();
                _initTask.execute( getApplicationContext() );
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        _initTask.cancel(true);
    }

    protected class InitTask extends AsyncTask<Context, String, SearchResponse>
    {
        @Override
        protected SearchResponse doInBackground( Context... params )
        {
            InputStream source = retrieveStream(url);
            SearchResponse response = null;
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                try {
                    response = gson.fromJson(reader, SearchResponse.class);
                    publishProgress( response.query );
                    reader.close();
                } catch (Exception e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                }
            }
            if (!this.isCancelled()) {
                return response;
            } else {
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... s)
        {
            super.onProgressUpdate(s);
            Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute( SearchResponse response )
        {
            super.onPostExecute(response);
            StringBuilder builder = new StringBuilder();
            if (response != null) {
                String delim = "* ";
                List<Result> results = response.results;
                for (Result result : results) {
                    builder.append(delim).append(result.fromUser);
                    delim="\n* ";
                }
            }
            if (builder.length() > 0) {
                Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
        }

        private InputStream retrieveStream(String url) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet getRequest;
            try {
                getRequest = new HttpGet(url);
                HttpResponse getResponse = client.execute(getRequest);
                HttpEntity getResponseEntity = getResponse.getEntity();
                return getResponseEntity.getContent();
            } catch (Exception e) {
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                return null;
            }
        }

    }

}


问:
Flink: Cluster Execution error of loss of Taskmanager
I am running the real time streaming program on the Flink with 1 master and 2 workers. One worker is running on the separate machine while another one is running on the master machine itself. I am using the JAR of my program in which the Parallelism is set to 2. Also I am read the data from Kafka with 2 brokers and 2 partitions.

With this scenario when I submit the job to the Flink cluster, it will run for a while and get failed with error java.lang.Exception: The slot in which the task was executed has been released. Probably loss of TaskManager 82f8941ff339603995e37c453f8ff401. What is the probable reason of the loss of taskmanager? (Only one Task-manager which is on the master machine is lost, another one is still there and being shown at Flink Web Interface.)

答:
We observed this error when the node that is used for this task manager has lack of free space.

Currently using Flink 3.7.1, but earlier version were also affected.

This was reported ieven as a bug https://issues.apache.org/jira/browse/FLINK-5844
But was closed, because the reporter wasn't responding.


问:
I need to sort an array of strings by popularity of the values inside the array
I have an array of strings, with some values multiple times like this.

```<code>const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']
</code>```

And i'd like to end up with an array of objects with the most popular value first paired with how many of those values are in the array and so on:

```<code>const newArr = [
   { fruit: 'apple', count: 4 },
   { fruit: 'banana', count: 3 },
   { fruit: 'orange', count: 2 }
]
</code>```

答:
You can use find to check if the element has already been included in the newArr; if it is just update the count and if it is not push a new object. And finally sort the newArry:

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']

const newArr = [];

arr.forEach(fruit => {
    let obj = newArr.find(a => a.fruit === fruit);

    if(obj) obj.count++;
    else    newArr.push({fruit: fruit, count: 1});
});

newArr.sort( (a, b) => b.count - a.count);
console.log(newArr);```

Body:
I have an array of strings, with some values multiple times like this.

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']

And i'd like to end up with an array of objects with the most popular value first paired with how many of those values are in the array and so on:

const newArr = [
   { fruit: 'apple', count: 4 },
   { fruit: 'banana', count: 3 },
   { fruit: 'orange', count: 2 }
]


问:
react-bootstrap-table2 column width change on cell click
I have base react-bootstrap-table code:

import React from 'react'
import BootstrapTable from 'react-bootstrap-table-next';
import cellEditFactory from 'react-bootstrap-table2-editor';

const products = [
  {
    id: "0",
    name: "test",
    price: "2100"
  },
  {
    id: "1",
    name: "test",
    price: "2100"
  },
  {
    id: "2",
    name: "test",
    price: "2120"
  }
];

const columns = [
  {
    dataField: "id",
    text: "Product ID"
  },
  {
    dataField: "name",
    text: "Product Name",
  },
  {
    dataField: "price",
    text: "Product Price"
  }
];
export default class App extends React.Component {

    render() {
        return (
            <BootstrapTable
            keyField="id"
            data={ products }
            columns={ columns }
            cellEdit={ cellEditFactory({mode: 'click'})}
            />
        )
    }
}
```

<p>My problem is that  column changes width, when I click editable cell. I see on live demo that is way to block this effect. live demo</p>

<p><img src="https://i.stack.imgur.com/PuIYs.png" alt="screenshoot before click">
<img src="https://i.stack.imgur.com/txFLA.png" alt="screenshoot after click"></p>

<p>I try avoid this effect by adding css with max width, but it's not problem cell, but whole column: </p>

<pre class="lang-js prettyprint-override"><code>editorStyle: {
    backgroundColor: '#20B2AA',
    maxWidth: '30%',
},
</code>```

答: You need add .table {table-layout: 'fixed'}.

Body:
I have base react-bootstrap-table code:

import React from 'react'
import BootstrapTable from 'react-bootstrap-table-next';
import cellEditFactory from 'react-bootstrap-table2-editor';

const products = [
  {
    id: "0",
    name: "test",
    price: "2100"
  },
  {
    id: "1",
    name: "test",
    price: "2100"
  },
  {
    id: "2",
    name: "test",
    price: "2120"
  }
];

const columns = [
  {
    dataField: "id",
    text: "Product ID"
  },
  {
    dataField: "name",
    text: "Product Name",
  },
  {
    dataField: "price",
    text: "Product Price"
  }
];
export default class App extends React.Component {

    render() {
        return (
            <BootstrapTable
            keyField="id"
            data={ products }
            columns={ columns }
            cellEdit={ cellEditFactory({mode: 'click'})}
            />
        )
    }
}

My problem is that  column changes width, when I click editable cell. I see on live demo that is way to block this effect. live demo

I try avoid this effect by adding css with max width, but it's not problem cell, but whole column:

editorStyle: {
    backgroundColor: '#20B2AA',
    maxWidth: '30%',
},


问:
Use pytorch to bulid multi-linear,but the result i get is not what i want?
```<code>import sklearn
    from sklearn.datasets import load_boston
    import torch
    import torch.nn as nn

    boston = load_boston()

    num_epochs = 10

    linear_model = nn.Linear(13,1,bias = True)
    criterion = nn.MSELoss()
    optimizer = torch.optim.SGD(linear_model.parameters(), lr=0.01)

    for epoch in range(num_epochs):

        inputs = torch.from_numpy(boston.data)
        targets = torch.from_numpy(boston.target)
        targets = targets.float()
        inputs = inputs.float()

        outputs = linear_model(inputs)
        loss = criterion(outputs,targets)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        print('epoch:{}/{} ...... loss:{:.4f}'.format(epoch,num_epochs,loss.item()))
</code>```

答:
The problem with your code seems to be data normalization, or, the lack of it.

I edited your code to add data normalization ((x - mean) / std), set epochs to 50 and switched the optimiser to Adam so it converges faster.

```<code>import sklearn
from sklearn.datasets import load_boston
import torch
import numpy as np
import torch.nn as nn

def normalize(X):
    mean = np.mean(X)
    std = np.std(X)
    return ((X - mean) / std), mean, std

boston = load_boston()

m_in = np.zeros(13)
s_in = np.zeros(13)

b_in = boston.data
b_out = boston.target

for i in range(13):
    b_in[:, i], m_in[i], s_in[i] = normalize(b_in[:, i])

b_out, m_out, s_out = normalize(b_out)

num_epochs = 50

linear_model = nn.Linear(13, 1, bias=True)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(linear_model.parameters(), lr=0.01)

linear_model.train()
for epoch in range(num_epochs):
    inputs = torch.from_numpy(b_in)
    targets = torch.from_numpy(b_out)
    targets = targets.float().unsqueeze(1)
    inputs = inputs.float()

    outputs = linear_model(inputs)
    loss = criterion(outputs, targets)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print('epoch: {}/{} ...... loss: {:.4f}'.format(epoch, num_epochs, loss.item()))
</code>```

The new output looks like this:

```<code>epoch: 0/50 ...... loss: 1.2610
epoch: 1/50 ...... loss: 1.1395
epoch: 2/50 ...... loss: 1.0332
epoch: 3/50 ...... loss: 0.9421
epoch: 4/50 ...... loss: 0.8660
epoch: 5/50 ...... loss: 0.8040
epoch: 6/50 ...... loss: 0.7548
epoch: 7/50 ...... loss: 0.7164
epoch: 8/50 ...... loss: 0.6863
epoch: 9/50 ...... loss: 0.6623
epoch: 10/50 ...... loss: 0.6421
epoch: 11/50 ...... loss: 0.6240
epoch: 12/50 ...... loss: 0.6068
epoch: 13/50 ...... loss: 0.5895
epoch: 14/50 ...... loss: 0.5717
epoch: 15/50 ...... loss: 0.5532
epoch: 16/50 ...... loss: 0.5339
epoch: 17/50 ...... loss: 0.5143
epoch: 18/50 ...... loss: 0.4946
epoch: 19/50 ...... loss: 0.4752
epoch: 20/50 ...... loss: 0.4565
epoch: 21/50 ...... loss: 0.4389
epoch: 22/50 ...... loss: 0.4226
epoch: 23/50 ...... loss: 0.4079
epoch: 24/50 ...... loss: 0.3949
epoch: 25/50 ...... loss: 0.3835
epoch: 26/50 ...... loss: 0.3736
epoch: 27/50 ...... loss: 0.3652
epoch: 28/50 ...... loss: 0.3580
epoch: 29/50 ...... loss: 0.3517
epoch: 30/50 ...... loss: 0.3461
epoch: 31/50 ...... loss: 0.3410
epoch: 32/50 ...... loss: 0.3361
epoch: 33/50 ...... loss: 0.3315
epoch: 34/50 ...... loss: 0.3270
epoch: 35/50 ...... loss: 0.3226
epoch: 36/50 ...... loss: 0.3183
epoch: 37/50 ...... loss: 0.3142
epoch: 38/50 ...... loss: 0.3103
epoch: 39/50 ...... loss: 0.3068
epoch: 40/50 ...... loss: 0.3036
epoch: 41/50 ...... loss: 0.3008
epoch: 42/50 ...... loss: 0.2984
epoch: 43/50 ...... loss: 0.2963
epoch: 44/50 ...... loss: 0.2945
epoch: 45/50 ...... loss: 0.2930
epoch: 46/50 ...... loss: 0.2917
epoch: 47/50 ...... loss: 0.2904
epoch: 48/50 ...... loss: 0.2892
epoch: 49/50 ...... loss: 0.2881
</code>```

The features in the dataset seem to have different ranges and this poses a problem for the learning algorithm. By normalizing the data, we make it much easier for the model to learn.

[1] This is a great article that explains why normalization is needed: https://towardsdatascience.com/understand-data-normalization-in-machine-learning-8ff3062101f0

Body:
The problem with your code seems to be data normalization, or, the lack of it.

I edited your code to add data normalization ((x - mean) / std), set epochs to 50 and switched the optimiser to Adam so it converges faster.

import sklearn
from sklearn.datasets import load_boston
import torch
import numpy as np
import torch.nn as nn

def normalize(X):
    mean = np.mean(X)
    std = np.std(X)
    return ((X - mean) / std), mean, std

boston = load_boston()

m_in = np.zeros(13)
s_in = np.zeros(13)

b_in = boston.data
b_out = boston.target

for i in range(13):
    b_in[:, i], m_in[i], s_in[i] = normalize(b_in[:, i])

b_out, m_out, s_out = normalize(b_out)

num_epochs = 50

linear_model = nn.Linear(13, 1, bias=True)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(linear_model.parameters(), lr=0.01)

linear_model.train()
for epoch in range(num_epochs):
    inputs = torch.from_numpy(b_in)
    targets = torch.from_numpy(b_out)
    targets = targets.float().unsqueeze(1)
    inputs = inputs.float()

    outputs = linear_model(inputs)
    loss = criterion(outputs, targets)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print('epoch: {}/{} ...... loss: {:.4f}'.format(epoch, num_epochs, loss.item()))

The new output looks like this:

epoch: 0/50 ...... loss: 1.2610
epoch: 1/50 ...... loss: 1.1395
epoch: 2/50 ...... loss: 1.0332
epoch: 3/50 ...... loss: 0.9421
epoch: 4/50 ...... loss: 0.8660
epoch: 5/50 ...... loss: 0.8040
epoch: 6/50 ...... loss: 0.7548
epoch: 7/50 ...... loss: 0.7164
epoch: 8/50 ...... loss: 0.6863
epoch: 9/50 ...... loss: 0.6623
epoch: 10/50 ...... loss: 0.6421
epoch: 11/50 ...... loss: 0.6240
epoch: 12/50 ...... loss: 0.6068
epoch: 13/50 ...... loss: 0.5895
epoch: 14/50 ...... loss: 0.5717
epoch: 15/50 ...... loss: 0.5532
epoch: 16/50 ...... loss: 0.5339
epoch: 17/50 ...... loss: 0.5143
epoch: 18/50 ...... loss: 0.4946
epoch: 19/50 ...... loss: 0.4752
epoch: 20/50 ...... loss: 0.4565
epoch: 21/50 ...... loss: 0.4389
epoch: 22/50 ...... loss: 0.4226
epoch: 23/50 ...... loss: 0.4079
epoch: 24/50 ...... loss: 0.3949
epoch: 25/50 ...... loss: 0.3835
epoch: 26/50 ...... loss: 0.3736
epoch: 27/50 ...... loss: 0.3652
epoch: 28/50 ...... loss: 0.3580
epoch: 29/50 ...... loss: 0.3517
epoch: 30/50 ...... loss: 0.3461
epoch: 31/50 ...... loss: 0.3410
epoch: 32/50 ...... loss: 0.3361
epoch: 33/50 ...... loss: 0.3315
epoch: 34/50 ...... loss: 0.3270
epoch: 35/50 ...... loss: 0.3226
epoch: 36/50 ...... loss: 0.3183
epoch: 37/50 ...... loss: 0.3142
epoch: 38/50 ...... loss: 0.3103
epoch: 39/50 ...... loss: 0.3068
epoch: 40/50 ...... loss: 0.3036
epoch: 41/50 ...... loss: 0.3008
epoch: 42/50 ...... loss: 0.2984
epoch: 43/50 ...... loss: 0.2963
epoch: 44/50 ...... loss: 0.2945
epoch: 45/50 ...... loss: 0.2930
epoch: 46/50 ...... loss: 0.2917
epoch: 47/50 ...... loss: 0.2904
epoch: 48/50 ...... loss: 0.2892
epoch: 49/50 ...... loss: 0.2881

The features in the dataset seem to have different ranges and this poses a problem for the learning algorithm. By normalizing the data, we make it much easier for the model to learn.

[1] This is a great article that explains why normalization is needed: https://towardsdatascience.com/understand-data-normalization-in-machine-learning-8ff3062101f0


问:
SQL query for group by result in different column
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22
```

<p>I Want Result like</p>

<pre class="lang-none prettyprint-override"><code>Column1 Value1 Value2
A       10      40
B       20      30
C       11      22
</code>```

Is there any query or store Procdure to get such Output

答:
You require DynamicSql + Pivot operation.I am not aware of any other method.

The below query will give you what you want.

```<code>DROP TABLE tmptbl
GO
SELECT * ,
    'Value' + (CONVERT(NVARCHAR(MAX), ROW_NUMBER() OVER (PARTITION BY [Column1] ORDER BY Column1,[Value]))) [ValueColumn]
INTO tmptbl
FROM (
SELECT 'A' [Column1],10 [Value]
UNION ALL
SELECT 'A' [Column1],20 [Value]
UNION ALL
SELECT 'A' [Column1],30 [Value]
UNION ALL
SELECT 'B' [Column1],40 [Value]
UNION ALL
SELECT 'B' [Column1],50 [Value]
UNION ALL
SELECT 'B' [Column1],60 [Value]
UNION ALL
SELECT 'B' [Column1],70 [Value]
) tbl
GO
DECLARE @Vals NVARCHAR(MAX)
SET @Vals = N''
SELECT @Vals = STUFF((SELECT ', ' + QUOTENAME('Value' + CONVERT(NVARCHAR(MAX), ROW_NUMBER() OVER (ORDER BY [Valuecolumn])))
                FROM tmptbl
                GROUP BY [Valuecolumn]
                FOR XML PATH ('')),1,1,'')
SELECT @vals

DECLARE @strsql NVARCHAR(MAX) = ' SELECT [Column1],' + @vals + '
                                  FROM (
                                     SELECT [Column1],[Value],[ValueColumn]
                                     FROM tmptbl
                                       ) t
                                  PIVOT (
                                  AVG([Value])
                                  FOR [ValueColumn] IN (' + @Vals + ')) As p'
EXEC (@strsql)
</code>```

Body:
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22

I Want Result like

Column1 Value1 Value2
A       10      40
B       20      30
C       11      22

Is there any query or store Procdure to get such Output

Body:
You require DynamicSql + Pivot operation.I am not aware of any other method.

The below query will give you what you want.

DROP TABLE tmptbl
GO
SELECT * ,
    'Value' + (CONVERT(NVARCHAR(MAX), ROW_NUMBER() OVER (PARTITION BY [Column1] ORDER BY Column1,[Value]))) [ValueColumn]
INTO tmptbl
FROM (
SELECT 'A' [Column1],10 [Value]
UNION ALL
SELECT 'A' [Column1],20 [Value]
UNION ALL
SELECT 'A' [Column1],30 [Value]
UNION ALL
SELECT 'B' [Column1],40 [Value]
UNION ALL
SELECT 'B' [Column1],50 [Value]
UNION ALL
SELECT 'B' [Column1],60 [Value]
UNION ALL
SELECT 'B' [Column1],70 [Value]
) tbl
GO
DECLARE @Vals NVARCHAR(MAX)
SET @Vals = N''
SELECT @Vals = STUFF((SELECT ', ' + QUOTENAME('Value' + CONVERT(NVARCHAR(MAX), ROW_NUMBER() OVER (ORDER BY [Valuecolumn])))
                FROM tmptbl
                GROUP BY [Valuecolumn]
                FOR XML PATH ('')),1,1,'')
SELECT @vals

DECLARE @strsql NVARCHAR(MAX) = ' SELECT [Column1],' + @vals + '
                                  FROM (
                                     SELECT [Column1],[Value],[ValueColumn]
                                     FROM tmptbl
                                       ) t
                                  PIVOT (
                                  AVG([Value])
                                  FOR [ValueColumn] IN (' + @Vals + ')) As p'
EXEC (@strsql)


问:
Fixed positioned div inside of relative positioned div causes strange overscroll behavior in mobile Safari
When I position a fixed div inside of a relative div, and align the fixed div to the bottom of the viewport, then attempt to scroll past the bottom in mobile Safari (iOS 13) I get a strange effect. It looks as though the div becomes obscured by a white rectangle. Is there any way to prevent this behavior without changing the position of the outer or inner divs?

.outer {
  position: relative;
  z-index: 1;
  display: block;
  height: 100%;
  overflow: auto;
  padding: 5px;
}

.inner {
  color: white;
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1030;
  width: 100%;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <div class="outer">
    <div class="inner">
      test test test <br/> test test test
    </div>
  </div>
</body>

</html></code>```

答:
The .inner content goes outside the boundaries of the .outer wrapper.
You'd need to set overflow to visible on the .outer parent to make its content visible outside of its relative parent.

See the result : https://codepen.io/romainpetit/pen/BaNLaZr

Tested.

```<code>.outer {
  position: relative;
  z-index: 1;
  display: block;
  height: 100%;
  overflow: auto;
  padding: 5px;
}

.inner {
  color: white;
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1030;
  width: 100%;
  background: blue;
}
</code>```

Body:
When I position a fixed div inside of a relative div, and align the fixed div to the bottom of the viewport, then attempt to scroll past the bottom in mobile Safari (iOS 13) I get a strange effect. It looks as though the div becomes obscured by a white rectangle. Is there any way to prevent this behavior without changing the position of the outer or inner divs?

.outer {
  position: relative;
  z-index: 1;
  display: block;
  height: 100%;
  overflow: auto;
  padding: 5px;
}

.inner {
  color: white;
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1030;
  width: 100%;
  background: blue;
}

      test test test
 test test test

Body:
The .inner content goes outside the boundaries of the .outer wrapper.
You'd need to set overflow to visible on the .outer parent to make its content visible outside of its relative parent.

See the result : https://codepen.io/romainpetit/pen/BaNLaZr

Tested.

.outer {
  position: relative;
  z-index: 1;
  display: block;
  height: 100%;
  overflow: auto;
  padding: 5px;
}

.inner {
  color: white;
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1030;
  width: 100%;
  background: blue;
}