问:
Is this a bug in dynamic?
When implementing dynamic dispatch using dynamic on a generic class, and the generic type parameter is a private inner class on another class, the runtime binder throws an exception.

For example:

```<code>using System;

public abstract class Dispatcher<T> {
    public T Call(object foo) { return CallDispatch((dynamic)foo); }

    protected abstract T CallDispatch(int foo);
    protected abstract T CallDispatch(string foo);
}

public class Program {
    public static void Main() {
        TypeFinder d = new TypeFinder();

        Console.WriteLine(d.Call(0));
        Console.WriteLine(d.Call(""));
    }

    private class TypeFinder : Dispatcher<CallType> {
        protected override CallType CallDispatch(int foo) {
            return CallType.Int;
        }

        protected override CallType CallDispatch(string foo) {
            return CallType.String;
        }
    }

    private enum CallType { Int, String }
}
</code>```

Here, a RuntimeBinderException will be thrown with the message

'Dispatcher.CallDispatch(int)' is inaccessible due to its protection level

The reason for the inaccessibility is that the type parameter T is the private CallType which Dispatcher<T> cannot access. Therefore, CallDispatch must be inaccessible - but it isn't, because it's accessible as T.

Is this a bug with dynamic, or is this not supposed to be supported?

答:
It's a bug because the following static typing change should be equivalent

```<code>using System;

public abstract class Dispatcher<T>
{
    public T Call(int foo) { return CallDispatch(foo); }
    public T Call(string foo) { return CallDispatch(foo); }

    protected abstract T CallDispatch(int foo);
    protected abstract T CallDispatch(string foo);
}
</code>```

And it works.

This issue seems to be an issue with the compiler and the dlr calls it makes and the static information the compiler includes in the invocation. It can be worked around with the open source framework ImpromptuInterface that manually setups the dlr calls. With Impromptu by setting the context to this it's getting access permissions from the runtime type which will be TypeFinder.

```<code>using System;
using ImpromptuInterface.Dynamic;
public abstract class Dispatcher<T>
{
    protected CacheableInvocation _cachedDynamicInvoke;

    protected Dispatcher()
    {
        _cachedDynamicInvoke= new CacheableInvocation(InvocationKind.InvokeMember, "CallDispatch", argCount: 1, context: this);
    }

    public T Call(object foo)
    {
        return (T) _cachedDynamicInvoke.Invoke(this, foo);
    }

    protected abstract T CallDispatch(int foo);
    protected abstract T CallDispatch(string foo);
}
</code>```

Title: Is this a bug in dynamic?

Body:
When implementing dynamic dispatch using dynamic on a generic class, and the generic type parameter is a private inner class on another class, the runtime binder throws an exception.

For example:

using System;

public abstract class Dispatcher<T> {
    public T Call(object foo) { return CallDispatch((dynamic)foo); }

    protected abstract T CallDispatch(int foo);
    protected abstract T CallDispatch(string foo);
}

public class Program {
    public static void Main() {
        TypeFinder d = new TypeFinder();

        Console.WriteLine(d.Call(0));
        Console.WriteLine(d.Call(""));
    }

    private class TypeFinder : Dispatcher<CallType> {
        protected override CallType CallDispatch(int foo) {
            return CallType.Int;
        }

        protected override CallType CallDispatch(string foo) {
            return CallType.String;
        }
    }

    private enum CallType { Int, String }
}

Here, a RuntimeBinderException will be thrown with the message

'Dispatcher.CallDispatch(int)' is inaccessible due to its protection level

The reason for the inaccessibility is that the type parameter T is the private CallType which Dispatcher<T> cannot access. Therefore, CallDispatch must be inaccessible - but it isn't, because it's accessible as T.

Is this a bug with dynamic, or is this not supposed to be supported?

Body:
It's a bug because the following static typing change should be equivalent

using System;

public abstract class Dispatcher<T>
{
    public T Call(int foo) { return CallDispatch(foo); }
    public T Call(string foo) { return CallDispatch(foo); }

    protected abstract T CallDispatch(int foo);
    protected abstract T CallDispatch(string foo);
}

And it works.

This issue seems to be an issue with the compiler and the dlr calls it makes and the static information the compiler includes in the invocation. It can be worked around with the open source framework ImpromptuInterface that manually setups the dlr calls. With Impromptu by setting the context to this it's getting access permissions from the runtime type which will be TypeFinder.

using System;
using ImpromptuInterface.Dynamic;
public abstract class Dispatcher<T>
{
    protected CacheableInvocation _cachedDynamicInvoke;

    protected Dispatcher()
    {
        _cachedDynamicInvoke= new CacheableInvocation(InvocationKind.InvokeMember, "CallDispatch", argCount: 1, context: this);
    }

    public T Call(object foo)
    {
        return (T) _cachedDynamicInvoke.Invoke(this, foo);
    }

    protected abstract T CallDispatch(int foo);
    protected abstract T CallDispatch(string foo);
}


来源: stackexchange

问:
Why is my Express server responding with 404 for all files except index.html?
I'm learning Node.js with Express to get a little server running for studying. I'm getting response code 404 for all requests to files linked in my index.html file (e.g. the .css, .js, and image files).

The code I used to send index.html:

```<code>routes.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "/clientSide/index.html"));
})
</code>```

If I change the path to the whole folder instead:

```<code>routes.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "/clientSide"));
})
</code>```

I get in my browser the path from my hard drive to the folder, but I still can't view the files that way.

The clientSide folder contains index.html, app.js, style.css, and 2 or 3 images, all in the same folder. I can't view any of them.

I changed the filenames and folder name, and checked for capitalization to no avail.

SOLVED

I was using app.use(express.static(path.join(__dirname, "static/")));

With app = express();

That does not work, but using routes.use instead of app.use, while routes = express.Router();, is what solves that

The end

答:
In your first code snippet, when you write:

routes.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "/clientSide/index.html"));
})
```

<p>You defined a new middleware function for requests to route <code>/</code>; that's what <code>routes.get('/', ...)</code> does. Assuming your server is running on port 3000, route <code>/</code> maps to <code>http://127.0.0.1:3000/</code>. For exactly that URL, and no other, Express executes your provided function, which replies with the the file <code>clientSide/index.html</code>. Thus, when your browser requests <code>http://127.0.0.1:3000/</code>, Express responds correctly.</p>

<p>But you've said nothing about the other files, such as <code>http://127.0.0.1:3000/style.css</code>, which would be route <code>/style.css</code>. You haven't defined any middleware for that route. So Express, not knowing what to do, by default responds with 404 and an error message. Thus, when your browser tries to load <code>http://127.0.0.1:3000/style.css</code> while fetching the resources referenced in <code>index.html</code>, the stylesheet fails to load.</p>

<p>Your second code snippet doesn't fix anything. It really makes things worse, because <code>res.sendFile()</code> can't send folders (how would that even work?) and that generates errors. You still haven't defined routes other than <code>/</code>, and now all your files are inaccessible.</p>

<p>To actually solve the problem, you could, theoretically, tediously define a route for every file, or more cleverly define one route with a route parameter. But serving a static folder with Express is a solved problem. You can simply offload the work to <code>express.static</code> by replacing all your code with:</p>

<pre class="lang-js prettyprint-override"><code>routes.use(express.static(path.join(__dirname, "clientSide/")));
</code>```

To go even further, you don't need Express or Node.js for a static file server. Try nginx. And for simple webpages, you don't need a server at all; just double-click index.html and let your browser open it.

ContentLicense: CC BY-SA 4.0

Body:
I'm learning Node.js with Express to get a little server running for studying. I'm getting response code 404 for all requests to files linked in my index.html file (e.g. the .css, .js, and image files).

The code I used to send index.html:

routes.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "/clientSide/index.html"));
})

If I change the path to the whole folder instead:

routes.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "/clientSide"));
})

I get in my browser the path from my hard drive to the folder, but I still can't view the files that way.

The clientSide folder contains index.html, app.js, style.css, and 2 or 3 images, all in the same folder. I can't view any of them.

I changed the filenames and folder name, and checked for capitalization to no avail.

SOLVED

I was using app.use(express.static(path.join(__dirname, "static/")));

With app = express();

That does not work, but using routes.use instead of app.use, while routes = express.Router();, is what solves that

The end

Body:
In your first code snippet, when you write:

routes.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "/clientSide/index.html"));
})

You defined a new middleware function for requests to route /; that's what routes.get('/', ...) does. Assuming your server is running on port 3000, route / maps to http://127.0.0.1:3000/. For exactly that URL, and no other, Express executes your provided function, which replies with the the file clientSide/index.html. Thus, when your browser requests http://127.0.0.1:3000/, Express responds correctly.

But you've said nothing about the other files, such as http://127.0.0.1:3000/style.css, which would be route /style.css. You haven't defined any middleware for that route. So Express, not knowing what to do, by default responds with 404 and an error message. Thus, when your browser tries to load http://127.0.0.1:3000/style.css while fetching the resources referenced in index.html, the stylesheet fails to load.

Your second code snippet doesn't fix anything. It really makes things worse, because res.sendFile() can't send folders (how would that even work?) and that generates errors. You still haven't defined routes other than /, and now all your files are inaccessible.

To actually solve the problem, you could, theoretically, tediously define a route for every file, or more cleverly define one route with a route parameter. But serving a static folder with Express is a solved problem. You can simply offload the work to express.static by replacing all your code with:

routes.use(express.static(path.join(__dirname, "clientSide/")));

To go even further, you don't need Express or Node.js for a static file server. Try nginx. And for simple webpages, you don't need a server at all; just double-click index.html and let your browser open it.


问:
An error is reported when the app is installed on a mobile phone
When I install the APK on a mobile phone, the following error information is displayed:
failed to find provider com.google.android.gsf.gservices, excepted to find a valid ContentProvider for this anthority.</p>

答:
Generally, the problem is caused by the low version of the Firebase SDK.

Check whether Google Mobile Services is installed on your phone.

Check whether the app depends on the firebase-perf SDK. If yes, upgrade the app to the latest version (19.0.5).


问:
react-autocomplete multiple suggestions
```<code>  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().slice(0, inputLength) === inputValue
    );
  };
</code>```

The current algorithm of react-autocomplete only finds the first word of a phase.
For example I can only find "Coca Cola Zero Sugar Cola" when I write "coc" or"coca" but I cannot find it if I write "Cola", "Zero" or "Sugar". I asked in repo's issues but cannot get and answer. I tried myself without success.
How can I write algorithm that will work as I explained above?

答:
This also does it</p>

```<code>  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;
    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    );
  };
</code>```

Title: react-autocomplete multiple suggestions

Body:
  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().slice(0, inputLength) === inputValue
    );
  };

The current algorithm of react-autocomplete only finds the first word of a phase.
For example I can only find "Coca Cola Zero Sugar Cola" when I write "coc" or"coca" but I cannot find it if I write "Cola", "Zero" or "Sugar". I asked in repo's issues but cannot get and answer. I tried myself without success.
How can I write algorithm that will work as I explained above?

Body:
This also does it

  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;
    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    );
  };


问:
How to properly connect MySQL database with C# application?
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

```<code>static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";
</code>```

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

答:
Couple of possible things to try -

Match your server name in the connection string against what is set on Azure portal.

Looks like the username and password you mentioned are dummy ones (understandably so). Check if your actual user name or password have any special characters, you will have to encode them appropriately to escape.

For example, if your password is my>Pass, connection string should look like this.
static string connstring = @"server=servername;userid=user;password=my>Pass;database=db_name;port=3306";

Here is a full list if you would like to explore.

Body:
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

Body:
Couple of possible things to try -

Match your server name in the connection string against what is set on Azure portal.

Looks like the username and password you mentioned are dummy ones (understandably so). Check if your actual user name or password have any special characters, you will have to encode them appropriately to escape.

For example, if your password is my>Pass, connection string should look like this.
static string connstring = @"server=servername;userid=user;password=my&gt;Pass;database=db_name;port=3306";

Here is a full list if you would like to explore.


问:
How to do a regular expression replace in MySQL?
I have a table with ~500k rows; varchar(255) UTF8 column filename contains a file name;

I'm trying to strip out various strange characters out of the filename - thought I'd use a character class: [^a-zA-Z0-9()_ .\-]

Now, is there a function in MySQL that lets you replace through a regular expression? I'm looking for a similar functionality to REPLACE() function - simplified example follows:

```<code>SELECT REPLACE('stackowerflow', 'ower', 'over');

Output: "stackoverflow"

/* does something like this exist? */
SELECT X_REG_REPLACE('Stackoverflow','/[A-Zf]/','-');

Output: "-tackover-low"
</code>```

I know about REGEXP/RLIKE, but those only check if there is a match, not what the match is.

(I could do a "SELECT pkey_id,filename FROM foo WHERE filename RLIKE '[^a-zA-Z0-9()_ .\-]'" from a PHP script, do a preg_replace and then "UPDATE foo ... WHERE pkey_id=...", but that looks like a last-resort slow & ugly hack)

答:
I recently wrote a MySQL function to replace strings using regular expressions. You could find my post at the following location:

http://techras.wordpress.com/2011/06/02/regex-replace-for-mysql/

Here is the function code:

```<code>DELIMITER $$

CREATE FUNCTION  `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN
 DECLARE temp VARCHAR(1000);
 DECLARE ch VARCHAR(1);
 DECLARE i INT;
 SET i = 1;
 SET temp = '';
 IF original REGEXP pattern THEN
  loop_label: LOOP
   IF i>CHAR_LENGTH(original) THEN
    LEAVE loop_label;
   END IF;
   SET ch = SUBSTRING(original,i,1);
   IF NOT ch REGEXP pattern THEN
    SET temp = CONCAT(temp,ch);
   ELSE
    SET temp = CONCAT(temp,replacement);
   END IF;
   SET i=i+1;
  END LOOP;
 ELSE
  SET temp = original;
 END IF;
 RETURN temp;
END$$

DELIMITER ;
</code>```

Example execution:

```<code>mysql> select regex_replace('[^a-zA-Z0-9\-]','','2my test3_text-to. check \\ my- sql (regular) ,expressions ._,');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table with ~500k rows; varchar(255) UTF8 column filename contains a file name;

I'm trying to strip out various strange characters out of the filename - thought I'd use a character class: [^a-zA-Z0-9()_ .\-]

Now, is there a function in MySQL that lets you replace through a regular expression? I'm looking for a similar functionality to REPLACE() function - simplified example follows:

SELECT REPLACE('stackowerflow', 'ower', 'over');

Output: "stackoverflow"

/* does something like this exist? */
SELECT X_REG_REPLACE('Stackoverflow','/[A-Zf]/','-');

Output: "-tackover-low"

I know about REGEXP/RLIKE, but those only check if there is a match, not what the match is.

(I could do a "SELECT pkey_id,filename FROM foo WHERE filename RLIKE '[^a-zA-Z0-9()_ .\-]'" from a PHP script, do a preg_replace and then "UPDATE foo ... WHERE pkey_id=...", but that looks like a last-resort slow & ugly hack)

Body:
I recently wrote a MySQL function to replace strings using regular expressions. You could find my post at the following location:

http://techras.wordpress.com/2011/06/02/regex-replace-for-mysql/

Here is the function code:

DELIMITER $$

CREATE FUNCTION  `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN
 DECLARE temp VARCHAR(1000);
 DECLARE ch VARCHAR(1);
 DECLARE i INT;
 SET i = 1;
 SET temp = '';
 IF original REGEXP pattern THEN
  loop_label: LOOP
   IF i>CHAR_LENGTH(original) THEN
    LEAVE loop_label;
   END IF;
   SET ch = SUBSTRING(original,i,1);
   IF NOT ch REGEXP pattern THEN
    SET temp = CONCAT(temp,ch);
   ELSE
    SET temp = CONCAT(temp,replacement);
   END IF;
   SET i=i+1;
  END LOOP;
 ELSE
  SET temp = original;
 END IF;
 RETURN temp;
END$$

DELIMITER ;

Example execution:

mysql> select regex_replace('[^a-zA-Z0-9\-]','','2my test3_text-to. check \\ my- sql (regular) ,expressions ._,');


问:
Adding check marks to Bootstrap button drop-down items
I am using Twitter bootstrap drop down button:

http://getbootstrap.com/components/#btn-dropdowns-single

And I would like to add checkmarks (not necessarily checkboxes) to those list items that the user has selected. Is there style already built in do this or does someone already have a solution built for this?

Thanks!

答:
I adapted claviska's great CSS-only answer so that it draws it with a rotated box that has 2 bordered sides, and this provides a more modern, geometric look than an HTML entity would provide.</p>

```<code>.dropdown-item-checked::before
{
position: absolute;
left: 0.8rem;
margin-top: 1px;
content: '';
width: 6px;
height: 12px;
border-bottom: 3px solid #333;
border-right: 3px solid #333;
transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
}
</code>```

Body:
I adapted claviska's great CSS-only answer so that it draws it with a rotated box that has 2 bordered sides, and this provides a more modern, geometric look than an HTML entity would provide.

.dropdown-item-checked::before
{
position: absolute;
left: 0.8rem;
margin-top: 1px;
content: '';
width: 6px;
height: 12px;
border-bottom: 3px solid #333;
border-right: 3px solid #333;
transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
}


问:
How to handle social login? - example flow
I have more conteptual question, how exactly should I handle social login in my project.
The use case is that I would like to allow user to login with Facebook, and keep on my backend information about this user (email, firstname, lastname)

I have some proposal Flow, but I'm not sure if it's a proper approach.

Let's say that I have application architecture as above. Now I would like to explain step-by-step full success flow.

Client (Vue application) make a call to AuthProvider (Facebook)

AuthProvider returns access_token

Client after reciving access_token make a call to backend endpoint like /fb_profile with access_token and userID (?)

Backend make a call to AuthProvider to check if given by client access_token is valid or not.

AuthProvider returns information about user. Backend after getting information about user, save it to database and generate new JWT token

Backend returns generated token to user

Now my question is - Is this good approach? Or should i handle it in other way? Like keep more logic to backend part? Instead of make a call to Facebook from Client, maybe should I make a call to backend, and backend make a call to Facebook?

答:
The above will be the sequence of the request flow ( same as yours ).

This would be the standard practice we used to integrate with Facebook. In this case, I strictly advise you to use the JavaScript SDK for Facebook.

Refer below link in case if you run into the following issue:

Vuejs component wait for facebook sdk to load


问:
Calling count distinct on varchar field gets error
I am getting the below error while doing a count distinct on a varchar field

```<code>Function EXTRACT does not support VARCHAR(16777216) argument type
</code>```

I am not able to figure out how to solve this

答:
I am getting the below error while doing a count distinct on a varchar field

Please include a query that reproduces the issue for better answers. The limited description does not cover the context behind the error message.

Function EXTRACT does not support VARCHAR(16777216) argument type

Going by the error message alone, it appears you've used more than just COUNT over your VARCHAR typed column (perhaps there are predicates with other functions in use).

Specifically, Snowflake's EXTRACT function cannot be applied to a VARCHAR type, it only accepts a DATE or TIMESTAMP type.

This is just a example/guess, but replace your EXTRACT(year FROM column_name) portion with EXTRACT(year FROM TO_TIMESTAMP(column_name)) if the column can be parsed as a timestamp.

Body:
I am getting the below error while doing a count distinct on a varchar field

Function EXTRACT does not support VARCHAR(16777216) argument type

I am not able to figure out how to solve this


问:
complex and double complex methods not working in visual studio c project
The below code is throwing error in Visual Studio C project. That same code is working in Linux with GCC compiler. Please let me know any solution to execute properly in Windows.

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

typedef struct {
    float r, i;
} complex_;

double c_abs(complex_* z)
{
    return  (cabs(z->r + I * z->i));
}

int main()
{
    complex_ number1 = { 3.0, 4.0 };

    double d = c_abs(&number1);

    printf("The absolute value of %f + %fi is %f\n", number1.r, number1.i, d);
    return 0;
}
</code>```

The error I am getting was

C2088: '*': illegal for struct

Here what t I observed the I macro not working properly...
So is there any other way we can handle in Windows?

答:
error C2088: '*': illegal for struct

This is the error MSVC returns when compiling the code (as C) for this line.

```<code>  return  (cabs(z->r + I * z->i));
</code>```

The MSVC C compiler does not have a native complex type, and (quoting the docs) "therefore the Microsoft implementation uses structure types to represent complex numbers".

The imaginary unit I a.k.a. _Complex_I is defined as an _Fcomplex structure in <complex.h>, which explains compile error C2088, since there is no operator * to multiply that structure with a float value.

Even if the multiplication worked out by some magic, the end result would be a float value being passed into the cabs call, but MSVC declares cabs as double cabs(_Dcomplex z); and there is no automatic conversion from float to _Dcomplex so the call would still fail to compile.

What would work with MSVC, however, is replace that line with the following, which constructs a _Dcomplex on the fly from the float real and imaginary parts.

```<code>  return  cabs(_Dcomplex{z->r, z->i});
</code>```

Body:
The below code is throwing error in Visual Studio C project. That same code is working in Linux with GCC compiler. Please let me know any solution to execute properly in Windows.

#include<stdio.h>
#include <complex.h>
#include <math.h>

typedef struct {
    float r, i;
} complex_;

double c_abs(complex_* z)
{
    return  (cabs(z->r + I * z->i));
}

int main()
{
    complex_ number1 = { 3.0, 4.0 };

    double d = c_abs(&number1);

    printf("The absolute value of %f + %fi is %f\n", number1.r, number1.i, d);
    return 0;
}

The error I am getting was

C2088: '*': illegal for struct

Here what t I observed the I macro not working properly...
So is there any other way we can handle in Windows?

Body:
error C2088: '*': illegal for struct

This is the error MSVC returns when compiling the code (as C) for this line.

  return  (cabs(z->r + I * z->i));

The MSVC C compiler does not have a native complex type, and (quoting the docs) "therefore the Microsoft implementation uses structure types to represent complex numbers".

The imaginary unit I a.k.a. _Complex_I is defined as an _Fcomplex structure in <complex.h>, which explains compile error C2088, since there is no operator * to multiply that structure with a float value.

Even if the multiplication worked out by some magic, the end result would be a float value being passed into the cabs call, but MSVC declares cabs as double cabs(_Dcomplex z); and there is no automatic conversion from float to _Dcomplex so the call would still fail to compile.

What would work with MSVC, however, is replace that line with the following, which constructs a _Dcomplex on the fly from the float real and imaginary parts.

  return  cabs(_Dcomplex{z->r, z->i});


问:
On focusing number box (input type="number"), the defaultValue(0) should be cleared out and it should be blank in Reactjs
Please help me in clearing the number box. Thanks in advance.</p>

```<code>    const [number,SetNumber] = useState(0)
    const handleFocus = (event) => {
       //If it is text box setNumber("")
       //for number box, how to clear?
    }
    return (
        <div>
            <form>
                <input type="number" onFocus={handleFocus} value={number} />
                <button>Submit</button>
            </form>
        </div>
    )
}```
</code>```

答:
Use placeholder instead:

```<code>const [number,setNumber] = useState(null)

<input
  type="number"
  onChange={() => setNumber(this.value)}
  value={number || ''}
  placeholder="0" />
</code>```

It will do:

Display 0 on input field as placeholder.

The initial value is empty.

When user types in, the number value gets displayed.

Body:
Please help me in clearing the number box. Thanks in advance.

    const [number,SetNumber] = useState(0)
    const handleFocus = (event) => {
       //If it is text box setNumber("")
       //for number box, how to clear?
    }
    return (

            <form>
                <input type="number" onFocus={handleFocus} value={number} />
                <button>Submit</button>
            </form>

    )
}```

Body:
Use placeholder instead:

const [number,setNumber] = useState(null)

<input
  type="number"
  onChange={() => setNumber(this.value)}
  value={number || ''}
  placeholder="0" />

It will do:

Display 0 on input field as placeholder.

The initial value is empty.

When user types in, the number value gets displayed.


问:
Java applet: run native code from browser?
Is it still possible to start a 'native' application under windows via a java applet in a browser? IE "Click here to start notepad.exe" on a web page. The most recent reference I could find for this was dated 2002. Im wondering if this model / concept is no longer supported. </p>

答: The portable way of doing this is to create a signed Applet.</p>


问:
bootstrap4 carousel transition shows both images
So, I cannot figure out why the bootstrap4 transition momentarily displays both of my images with their captions, one on top of the other, during the transition and then behaves normally.  Here is my code:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  <link rel="stylesheet" href="css/jQueryUI-1.12.1.custom/jquery-ui.min.css">
  <link rel="stylesheet" href="css/jQueryUI-1.12.1.custom/jquery-ui.theme.css">

  ...

Title

 Some text...

Title

 Some text...

Title

 Some text...

       Previous

        Next

  ...
```

I compared my code with the docs and W3School, but cannot trouble-shoot this odd behavior.  Also the caption shows up with a grey background. Is this normal or am I overriding the bootstrap4 class somewhere in my site?

答:
It is the m-auto class causing the issue. Remove it and it shall work properly.
Change all three
 to

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  ...

Title

 Some text...

Title

 Some text...

Title

 Some text...

       Previous

        Next

  ...
```

Body:
So, I cannot figure out why the bootstrap4 transition momentarily displays both of my images with their captions, one on top of the other, during the transition and then behaves normally.  Here is my code:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  <link rel="stylesheet" href="css/jQueryUI-1.12.1.custom/jquery-ui.min.css">
  <link rel="stylesheet" href="css/jQueryUI-1.12.1.custom/jquery-ui.theme.css">

  ...

Title

 Some text...

Title

 Some text...

Title

 Some text...

       Previous

        Next

  ...

I compared my code with the docs and W3School, but cannot trouble-shoot this odd behavior.  Also the caption shows up with a grey background. Is this normal or am I overriding the bootstrap4 class somewhere in my site?

Body:
It is the m-auto class causing the issue. Remove it and it shall work properly.
Change all three <div class="carousel-item m-auto"> to <div class="carousel-item">

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
  <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  <link rel="stylesheet" href="css/jQueryUI-1.12.1.custom/jquery-ui.min.css">
  <link rel="stylesheet" href="css/jQueryUI-1.12.1.custom/jquery-ui.theme.css">-->
</head>

<body>
  ...

  <div class="carousel slide carousel-fade w-100" id="featured" data-ride="carousel">
    <ol class="carousel-indicators">
      <li data-target="#featured" data-slide-to="0"></li>
      <li data-target="#featured" data-slide-to="1"></li>
      <li data-target="#featured" data-slide-to="2" class="active"></li>
    </ol>
    <div class="carousel-inner">
      <div class="carousel-item">
        <img class="d-block  m-auto" src="https://picsum.photos/id/500/400/300" alt="Convoluted Excel ">
        <div class="carousel-caption d-none d-md-block">
          <h3>Title</h3>
          <p> Some text... </p>
        </div>
      </div>

      <div class="carousel-item">
        <img class="d-block m-auto " src="https://picsum.photos/id/600/400/300" alt="Excel Prone to errors">
        <div class="carousel-caption d-none d-md-block">
          <h3>Title</h3>
          <p> Some text... </p>
        </div>
      </div>

      <div class="carousel-item active">
        <img class="d-block m-auto " src="https://picsum.photos/id/700/400/300" alt="Clear dashboard">
        <div class="carousel-caption d-none d-md-block">
          <h3>Title</h3>
          <p> Some text... </p>
        </div>
      </div>

    </div>
    <a class="carousel-control-prev" href="#featured" role="button" data-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true">
       <span class="sr-only">Previous</span>
      </span>
    </a>
    <a class="carousel-control-next" href="#featured" role="button" data-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true">
        <span class="sr-only">Next</span>
      </span>
    </a>
  </div>
  ...
</body>


问:
Chart.js: Legend doesn't update on first call to chart.update()
I'm having trouble updating the legend in chart.js.

Here's a sandbox to follow along.

I have a standard bar chart with two data points per label, such as:

```<code>let chartData = {
  apple: {
    a: 1,
    b: 3
  },
  orange: {
    a: 2,
    b: 2
  },
  banana: {
    a: 3,
    b: 1
  }
};
</code>```

On button click, the sort is changed from a->b or the reverse.

The colors also change and therein lies my problem:

The legend doesn't update on the first toggle. Afterward it is always one toggle behind.

I've tried looking at how to explicitly set the colors within the legend so that I can just manually update them in the updateChart() function, but in the docs I only see the ability to change font color and the legend itself - not the individual label colors.

I'd prefer to not have to use custom CSS to override... Is this a bug in Chart.js? Am I performing the update incorrectly? Do I have to call generateLegend()?

Thank you so much for your help!

答:
It's beacause your labels are not sorted initially. If you sort them when assigning the data to sortedKeys, it will work as expected.

```<code>let sortedKeys = Object.keys(chartData).sort(
  (a, b) => chartData[b][sortByCol] - chartData[a][sortByCol]
);
</code>```

Please have a look at your amended code sandbox.

Body:
I'm having trouble updating the legend in chart.js.

Here's a sandbox to follow along.

I have a standard bar chart with two data points per label, such as:

let chartData = {
  apple: {
    a: 1,
    b: 3
  },
  orange: {
    a: 2,
    b: 2
  },
  banana: {
    a: 3,
    b: 1
  }
};

On button click, the sort is changed from a->b or the reverse.

The colors also change and therein lies my problem:

The legend doesn't update on the first toggle. Afterward it is always one toggle behind.

I've tried looking at how to explicitly set the colors within the legend so that I can just manually update them in the updateChart() function, but in the docs I only see the ability to change font color and the legend itself - not the individual label colors.

I'd prefer to not have to use custom CSS to override... Is this a bug in Chart.js? Am I performing the update incorrectly? Do I have to call generateLegend()?

Thank you so much for your help!

Body:
It's beacause your labels are not sorted initially. If you sort them when assigning the data to sortedKeys, it will work as expected.

let sortedKeys = Object.keys(chartData).sort(
  (a, b) => chartData[b][sortByCol] - chartData[a][sortByCol]
);

Please have a look at your amended code sandbox.


问:
execution failed for appmergeDebugResources task in intelliJ android project
I am not able to get over this error. I'm using IntelliJ 2020.1.1 and I've tried every suggested solution- upgrading(6.1) and downgrading(both 6.0 and 5.6.4) gradle, changing gradle properties, clean/rebuild etc. Nothing works.

Executing tasks: [:app:assembleDebug] in project D:\MyApplication1

Task :app:preBuild UP-TO-DATE
  Task :app:preDebugBuild UP-TO-DATE
  Task :app:compileDebugAidl NO-SOURCE
  Task :app:generateDebugBuildConfig UP-TO-DATE
  Task :app:compileDebugRenderscript NO-SOURCE
  Task :app:javaPreCompileDebug UP-TO-DATE
  Task :app:mainApkListPersistenceDebug UP-TO-DATE
  Task :app:generateDebugResValues UP-TO-DATE
  Task :app:generateDebugResources UP-TO-DATE
  Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
  Task :app:extractDeepLinksDebug UP-TO-DATE
  Task :app:processDebugManifest UP-TO-DATE
  Task :app:mergeDebugShaders
  Task :app:compileDebugShaders
  Task :app:generateDebugAssets
  Task :app:mergeDebugAssets
  Task :app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:mergeDebugResources'.

Multiple task action failures occurred:
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #3: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #4: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #5: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #6: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #7: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #8: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #9: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  AAPT2 aapt2-3.6.0-rc01-6040484-windows Daemon #10: Daemon startup failed
      Please check if you installed the Windows Universal C Runtime.
      This should not happen under normal circumstances, please file an issue if it does.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 33s
11 actionable tasks: 4 executed, 7 up-to-date`

答:
It worked after installing Universal C Runtime.
I was getting "The update is not applicable to your computer" message everytime I tried to install CRT. Turns out Service pack 1 was not installed on my system. CRT was installed after this update and my project also executed finally.</p>


问:
How to put a generic function type into std::map?
Can I use a generic function type as the value of std::map? This eliminates the need to write different std::maps for different function parameters and return values.</p>

```<code>template<class Function,class ... Args>
inline auto FuncWrapper(Function &&f, Args && ... args)-> decltype(f(std::forward<Args>(args)...))
{
    return f(std::forward<Args>(args)...);
}

std::map<std::string, FuncWrapper>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"]([](std::string data){ return "MD5: "+ data; }, "some data");
    FUNCS["RSA"]([](std::string data, std::string key) {return "RSA: "+ data +':' + key;}, "some data", "some key");
    FUNCS["Other"]([](int a, double b, char c){return (c-'0')+a+b;}, 1, 2.0, 'c');
}
</code>```

答:
Using templates you cant achieve this.

Its a different type in C++.

Related to this would be the following:
Take any stl container all of them provide a custom Allocater template, a big problem was that one container that had a different allocater wasnt assignable from the same container that had a different Allocater type.

Btw, because of this Bloomberg bd library rewrote stl containers just using virtual Allocaters which is ok because it uses dynamic dispatch.

Body:
Can I use a generic function type as the value of std::map? This eliminates the need to write different std::maps for different function parameters and return values.

template<class Function,class ... Args>
inline auto FuncWrapper(Function &&f, Args && ... args)-> decltype(f(std::forward<Args>(args)...))
{
    return f(std::forward<Args>(args)...);
}

std::map<std::string, FuncWrapper>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"]([](std::string data){ return "MD5: "+ data; }, "some data");
    FUNCS["RSA"]([](std::string data, std::string key) {return "RSA: "+ data +':' + key;}, "some data", "some key");
    FUNCS["Other"]([](int a, double b, char c){return (c-'0')+a+b;}, 1, 2.0, 'c');
}


问:
Getting vertical lists of lists of lists in prolog?
a List of Lists like

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

and i want to get in this case all vertical lists like

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

how to do that? i thought about 2 counters witch work together like two "for to do" repeats.
i need to check with "is_set" if [1,4,7] is a set or [3,6,3] witch of course is not.

like this:

el_at(Llist,Gl,1),

```<code>el_at(EList, Llist,1),
</code>```

```<code>         globalListVertikalCheck(ListVertikal),
         addlist(Elist,ListVertikal,NewListVertikal),
</code>```

el_at(Llist,Gl,2),

```<code>el_at(EList, Llist,2),
</code>```

```<code>       globalListVertikalCheck(ListVertikal),
       addlist(Elist,ListVertikal,NewListVertikal),
</code>```

thanks

答:
A list of all vertical lists is known as a transposed matrix.
SWI's library(clpfd) contains such code. </p>

Body:
a List of Lists like

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

and i want to get in this case all vertical lists like

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

how to do that? i thought about 2 counters witch work together like two "for to do" repeats.
i need to check with "is_set" if [1,4,7] is a set or [3,6,3] witch of course is not.

like this:

el_at(Llist,Gl,1),

el_at(EList, Llist,1),

         globalListVertikalCheck(ListVertikal),
         addlist(Elist,ListVertikal,NewListVertikal),

el_at(Llist,Gl,2),

el_at(EList, Llist,2),

       globalListVertikalCheck(ListVertikal),
       addlist(Elist,ListVertikal,NewListVertikal),

thanks


问:
How to unfreeze a user's memory limit?
For these two days, I have met a weird question.

STAR from https://github.com/alexdobin/STAR is a program used to build suffix array indexes. I have been used this program for years. It works OK until recently.

For these days, when I run STAR, it will always be killed.

```<code>root@localhost:STAR --runMode genomeGenerate --runThreadN 10  --limitGenomeGenerateRAM 31800833920 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
.
.
.
Killed

root@localhost:STAR --runMode genomeGenerate --runThreadN 10 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
Jun 03 10:15:08 ..... started STAR run
Jun 03 10:15:08 ... starting to generate Genome files
Jun 03 10:17:24 ... starting to sort Suffix Array. This may take a long time...
Jun 03 10:17:51 ... sorting Suffix Array chunks and saving them to disk...
Killed
</code>```

A month ago, the same command with same inputs and same parameters runs OK. It does cost some memory, but not a lot.

I have tried 3 recently released version of this program, all failed. So I do not think it is the question of STAR program but my sever configuration.

I also tried to run this program as both root and normal user, no lucky for each.

I suspect there is a limitation of memory usage in my server.

But I do not know how the memory is limited? I wonder if some one can give me some hints.

Thanks!

Tong

The following is my debug process and system info.

Command dmesg -T| grep -E -i -B5 'killed process' showing it is Out of memory problem.

But before the STAR program is killed, top command showing only 5% mem is occupied by this porgram.

```<code>[一 6  1 23:43:00 2020] [40479]  1002 40479   101523    18680     112      487             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40480]  1002 40480   101526    18681     112      486             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40481]  1002 40481   101529    18682     112      485             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40482]  1002 40482   101531    18673     111      493             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] Out of memory: Kill process 33822 (STAR) score 36 or sacrifice child
[一 6  1 23:43:00 2020] Killed process 33822 (STAR) total-vm:23885188kB, anon-rss:10895128kB, file-rss:4kB, shmem-rss:0kB

[三 6  3 10:02:13 2020] [12296]  1002 12296   101652    18681     113      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12330]  1002 12330   101679    18855     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12335]  1002 12335   101688    18682     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12365]  1349 12365    30067     1262      11        0             0 bash
[三 6  3 10:02:13 2020] Out of memory: Kill process 7713 (STAR) score 40 or sacrifice child
[三 6  3 10:02:13 2020] Killed process 7713 (STAR) total-vm:19751792kB, anon-rss:12392428kB, file-rss:0kB, shmem-rss:0kB
--
[三 6月  3 10:42:17 2020] [ 4697]  1002  4697   101526    18681     112      486             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4698]  1002  4698   101529    18682     112      485             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4699]  1002  4699   101532    18680     112      487             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4701]  1002  4701   101534    18673     110      493             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] Out of memory: Kill process 21097 (STAR) score 38 or sacrifice child
[三 6月  3 10:42:17 2020] Killed process 21097 (STAR) total-vm:19769500kB, anon-rss:11622928kB, file-rss:884kB, shmem-rss:0kB
</code>```

Command free -hl showing I have enough memory.

```<code>              total        used        free      shared  buff/cache   available
Mem:           251G         10G         11G        227G        229G         12G
Low:           251G        240G         11G
High:            0B          0B          0B
Swap:           29G         29G          0B
</code>```

Also as showed by ulimit -a, no virtual memory limitation is set.

```<code>core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 1030545
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1030545
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
</code>```

Here is the version of my Centos and Kernel (output by hostnamectl):

```<code>hostnamectl
   Static hostname: localhost.localdomain
         Icon name: computer-server
           Chassis: server
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-514.26.2.el7.x86_64
      Architecture: x86-64
</code>```

Here shows the content of cat /etc/security/limits.conf:

```<code>#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4
* soft nofile 65536
* hard nofile 65536

#@intern    hard    as 162400000
#@intern    hard    nproc 150

# End of file
</code>```

As suggested, I have updated the output of df -h:

```<code>Filesystem            All  Used  Available (Used)% Mount
devtmpfs             126G     0  126G    0% /dev
tmpfs                126G  1.3M  126G    1% /dev/shm
tmpfs                126G  4.0G  122G    4% /run
tmpfs                126G     0  126G    0% /sys/fs/cgroup
/dev/mapper/cl-root  528G  271G  257G   52% /
/dev/sda1            492M  246M  246M   51% /boot
tmpfs                 26G     0   26G    0% /run/user/0
tmpfs                 26G     0   26G    0% /run/user/1002
tmpfs                 26G     0   26G    0% /run/user/1349
tmpfs                 26G     0   26G    0% /run/user/1855
</code>```

```<code>ls -a /dev/shm/
.  ..
</code>```

```<code>grep Shmem /proc/meminfo
Shmem:          238640272 kB
</code>```

Several tmpfs costs 126G memory. I am googleing this, but still not sure what should be done?

That is the problem of shared memory due to program terminated abnormally.

ipcrm is used to clear all shared memory and then STAR running is fine.

```<code>$ ipcrm
.....
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           251G         11G        226G        3.9G         14G        235G
Swap:           29G        382M         29G
</code>```

答:
It looks like the problem is with shared memory: you have 227G of memory eaten up by shared objects.

Shared memory files are persistent.  Have a look in /dev/shm and any other tmpfs mounts to see if there are large files that can be removed to free up more physical memory (RAM+swap).

$ ls -l /dev/shm
...
$ df -h | grep '^Filesystem\|^tmpfs'
...
```

Title: How to unfreeze a user's memory limit?

Body:
For these two days, I have met a weird question.

STAR from https://github.com/alexdobin/STAR is a program used to build suffix array indexes. I have been used this program for years. It works OK until recently.

For these days, when I run STAR, it will always be killed.

root@localhost:STAR --runMode genomeGenerate --runThreadN 10  --limitGenomeGenerateRAM 31800833920 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
.
.
.
Killed

root@localhost:STAR --runMode genomeGenerate --runThreadN 10 --genomeDir star_GRCh38 --genomeFastaFiles GRCh38.fa --sjdbGTFfile GRCh38.gtf --sjdbOverhang 100
Jun 03 10:15:08 ..... started STAR run
Jun 03 10:15:08 ... starting to generate Genome files
Jun 03 10:17:24 ... starting to sort Suffix Array. This may take a long time...
Jun 03 10:17:51 ... sorting Suffix Array chunks and saving them to disk...
Killed

A month ago, the same command with same inputs and same parameters runs OK. It does cost some memory, but not a lot.

I have tried 3 recently released version of this program, all failed. So I do not think it is the question of STAR program but my sever configuration.

I also tried to run this program as both root and normal user, no lucky for each.

I suspect there is a limitation of memory usage in my server.

But I do not know how the memory is limited? I wonder if some one can give me some hints.

Thanks!

Tong

The following is my debug process and system info.

Command dmesg -T| grep -E -i -B5 'killed process' showing it is Out of memory problem.

But before the STAR program is killed, top command showing only 5% mem is occupied by this porgram.

[一 6  1 23:43:00 2020] [40479]  1002 40479   101523    18680     112      487             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40480]  1002 40480   101526    18681     112      486             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40481]  1002 40481   101529    18682     112      485             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] [40482]  1002 40482   101531    18673     111      493             0 /anaconda2/bin/
[一 6  1 23:43:00 2020] Out of memory: Kill process 33822 (STAR) score 36 or sacrifice child
[一 6  1 23:43:00 2020] Killed process 33822 (STAR) total-vm:23885188kB, anon-rss:10895128kB, file-rss:4kB, shmem-rss:0kB

[三 6  3 10:02:13 2020] [12296]  1002 12296   101652    18681     113      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12330]  1002 12330   101679    18855     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12335]  1002 12335   101688    18682     112      486             0 /anaconda2/bin/
[三 6  3 10:02:13 2020] [12365]  1349 12365    30067     1262      11        0             0 bash
[三 6  3 10:02:13 2020] Out of memory: Kill process 7713 (STAR) score 40 or sacrifice child
[三 6  3 10:02:13 2020] Killed process 7713 (STAR) total-vm:19751792kB, anon-rss:12392428kB, file-rss:0kB, shmem-rss:0kB
--
[三 6月  3 10:42:17 2020] [ 4697]  1002  4697   101526    18681     112      486             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4698]  1002  4698   101529    18682     112      485             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4699]  1002  4699   101532    18680     112      487             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] [ 4701]  1002  4701   101534    18673     110      493             0 /anaconda2/bin/
[三 6月  3 10:42:17 2020] Out of memory: Kill process 21097 (STAR) score 38 or sacrifice child
[三 6月  3 10:42:17 2020] Killed process 21097 (STAR) total-vm:19769500kB, anon-rss:11622928kB, file-rss:884kB, shmem-rss:0kB

Command free -hl showing I have enough memory.

              total        used        free      shared  buff/cache   available
Mem:           251G         10G         11G        227G        229G         12G
Low:           251G        240G         11G
High:            0B          0B          0B
Swap:           29G         29G          0B

Also as showed by ulimit -a, no virtual memory limitation is set.

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 1030545
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1030545
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Here is the version of my Centos and Kernel (output by hostnamectl):

hostnamectl
   Static hostname: localhost.localdomain
         Icon name: computer-server
           Chassis: server
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-514.26.2.el7.x86_64
      Architecture: x86-64

Here shows the content of cat /etc/security/limits.conf:

#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4
* soft nofile 65536
* hard nofile 65536

#@intern    hard    as 162400000
#@intern    hard    nproc 150

# End of file

As suggested, I have updated the output of df -h:

Filesystem            All  Used  Available (Used)% Mount
devtmpfs             126G     0  126G    0% /dev
tmpfs                126G  1.3M  126G    1% /dev/shm
tmpfs                126G  4.0G  122G    4% /run
tmpfs                126G     0  126G    0% /sys/fs/cgroup
/dev/mapper/cl-root  528G  271G  257G   52% /
/dev/sda1            492M  246M  246M   51% /boot
tmpfs                 26G     0   26G    0% /run/user/0
tmpfs                 26G     0   26G    0% /run/user/1002
tmpfs                 26G     0   26G    0% /run/user/1349
tmpfs                 26G     0   26G    0% /run/user/1855

ls -a /dev/shm/
.  ..

grep Shmem /proc/meminfo
Shmem:          238640272 kB

Several tmpfs costs 126G memory. I am googleing this, but still not sure what should be done?

That is the problem of shared memory due to program terminated abnormally.

ipcrm is used to clear all shared memory and then STAR running is fine.

$ ipcrm
.....
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           251G         11G        226G        3.9G         14G        235G
Swap:           29G        382M         29G


问:
Caching audio Buffers to prevent decoding Audio data each time
I am working with audio files where in I upload and each time the audio file is fetched from the server it is represented in the UI with functionality to play/pause etc. I am working with .wav/.mp3 files of duration close to about an hour.

The library I am using for displaying the waveform loads the entire audio file at once into an audioBuffer so streaming is out of option.

I am trying to find a way to cache the audioBuffer in order to skip the decodeAudioData() step entirely.

What I am currently doing is store the Float32Array representation using audioBuffer.getChannelData(0) method and convert back to audioBuffer (which almost takes the same amount of time) and using localforage to use indexedDB to set and get, but it has it's limitations and cannot store the Float32Array for large mp3 files (1hr ~ file size of about 86-100mb)

I cannot direclty store audioBuffers in indexedDB due to incompatibility of indexedDB to store such formats.

I need a way to skip the decodeAudioData() step and directly consume the audioBuffer of the files already loaded once.

答:
As an alternative, it may be worth caching the visual waveform once it's generated (or pre-rendering on the server).  Perhaps the visualization can be rasterized and stored as a png/jpg locally or sent from the server.  Or if it's SVG, those elements could be saved.  Or if it's canvas, perhaps the pixel matrix could be saved, which would probably use less memory than decoded audio.

One thing the <audio> element is good for is streaming and seeking.  The browsers do a lot of that heavy lifting for you and should balance performance optimizations without needing to fetch and decode the entire 1hr audio file.  If you could leverage the native platform features while using visual component caching, this may be a way around local cache size limitations.


问:
Does React.js require to have a node_modules folder to run?
I am asking this question, because I installed react for a project, I made some changes as usual, I received the error message below. I searched to see where that error was coming from, and one of the solution was to delete the node_modules folder from react, and then run npm.

I did that, and now it is working. But, I am checking the frontend folder and the node_module folder is not there. There is only one node_module folder, but it is in the backend folder.

答:
I think this is happening because you are missing the node_modules folder in your react app.
 This is a simple fix

Just go in your react app and run

npm install

or

yarn install

this will create the node_modules folder for you.


问:
v-if and v-else not working because updating page every time
I have the issue that the div in the v-if statement is not correctly working. If you run the server and the page when you click the button Sign Up it will briefly showing the div for signing up but it will get back the the original div in the first v-if statement after few seconds.

Instead I expect that it would show just show the div in the v-else because I am changing the boolean showSignUp with the v-on:click="signUp" which will call the function in the Vue App that will change the boolean.

This is the HTML :

```<code><body onload="init()">
        <!-- using the Vue App -->
        <div id="app">
            <!-- If it is not signed in just make it sign -->
            <div v-if="!isLoggedIn" class="container-fluid">
                <!-- Top Bar -->
                <div class="row align-items-center justify-content-start">
                    <nav class="navbar navbar-light bg-light">
                        <h1>UST Computer Science Submission Tool</h1>
                    </nav>
                </div>
                <div class="row align-items-center justify-content-end">
                    <div v-if="!showSignUp">
                        <form class="getSpace" > <!-- SIGN IN FORM -->
                            <!-- Input fields -->
                            <div class="form-group">
                                <label for="inputEmail">Email address</label>
                                <input type="email" class="form-control" id="inputEmail">
                            </div>
                            <div class="form-group">
                                <label for="inputPassword">Password</label>
                                <input type="password" class="form-control" id="inputPassword">
                            </div>
                            <!-- Buttons -->
                            <button v-on:click="signIn" class="btn btn-primary">Sign In</button>
                            <button v-on:click="signUp" class="btn btn-primary">Sign Up</button>
                        </form>
                    </div>
                    <div v-if="showSignUp">
                        <form class="getSpace"> <!-- SIGN UP FORM -->
                            <!-- Input fields -->
                            <div class="form-group">
                                <label for="inputEmail">Email address</label>
                                <input type="email" class="form-control" id="singUpEmail">
                            </div>
                            <div class="form-group">
                                <label for="inputPassword">Password</label>
                                <input type="password" class="form-control" id="singUpInputPassword">
                            </div>
                            <!-- Buttons -->
                            <button v-on:click="submitRegistration" class="btn btn-primary">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
            <!-- Else is already signed in -->
            <div v-else class="container-fluid">
                <div class="row">
                    <div class="col">You did it</div>
                    <div class="col"></div>
                </div>
            </div>
        </div>
    </body>
</code>```

This is the JS for the Vue App:

```<code>let app

// On loading page
function init() {
    app = new Vue({
        el: '#app',
        data: {
            email: '',
            password: '',
            isLoggedIn: false,
            showSignUp: false
        },
        methods: {
            signIn: signIn,
            signUp: signUp,
            submitRegistration: submitRegistration,
        }
    });
}

// methods
function signIn(event) { // when clicked Sing In button
    // check before in the data base if it is correct

    // Now show the Users page
    app.isLoggedIn = !app.isLoggedIn;
}

function signUp (event) { // when clicked Sing Up button
    // This will change the form
    console.log('was here');
    app.showSignUp = true;
}

function submitRegistration (event) {
    console.log(event);
    // Call http
}
</code>```

答:
you need to prevent the action</p>

```<code><button v-on:click.prevent="signUp" class="btn btn-primary">Sign Up</button>
</code>```

Body:
I have the issue that the div in the v-if statement is not correctly working. If you run the server and the page when you click the button Sign Up it will briefly showing the div for signing up but it will get back the the original div in the first v-if statement after few seconds.

Instead I expect that it would show just show the div in the v-else because I am changing the boolean showSignUp with the v-on:click="signUp" which will call the function in the Vue App that will change the boolean.

This is the HTML :

UST Computer Science Submission Tool

                        <form class="getSpace" >

                                Email address
                                <input type="email" class="form-control" id="inputEmail">

                                Password
                                <input type="password" class="form-control" id="inputPassword">

                            <button v-on:click="signIn" class="btn btn-primary">Sign In</button>
                            <button v-on:click="signUp" class="btn btn-primary">Sign Up</button>
                        </form>

                        <form class="getSpace">

                                Email address
                                <input type="email" class="form-control" id="singUpEmail">

                                Password
                                <input type="password" class="form-control" id="singUpInputPassword">

                            <button v-on:click="submitRegistration" class="btn btn-primary">Submit</button>
                        </form>

You did it

This is the JS for the Vue App:

let app

// On loading page
function init() {
    app = new Vue({
        el: '#app',
        data: {
            email: '',
            password: '',
            isLoggedIn: false,
            showSignUp: false
        },
        methods: {
            signIn: signIn,
            signUp: signUp,
            submitRegistration: submitRegistration,
        }
    });
}

// methods
function signIn(event) { // when clicked Sing In button
    // check before in the data base if it is correct

    // Now show the Users page
    app.isLoggedIn = !app.isLoggedIn;
}

function signUp (event) { // when clicked Sing Up button
    // This will change the form
    console.log('was here');
    app.showSignUp = true;
}

function submitRegistration (event) {
    console.log(event);
    // Call http
}

Body:
you need to prevent the action

<button v-on:click.prevent="signUp" class="btn btn-primary">Sign Up</button>


问:
material ui styling not applying
For some reason my material ui styles are not applying to my html element? Any idea why? I have no other styles applied to this page</p>

```<code>import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '@material-ui/core';

const classes = makeStyles( (theme) => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "white"
  },
}) )

class Login extends Component {
  render() {
    return(
      <div className = {classes.root}>
        <LoginForm/>
      </div>
    );
  }
}
export default Login;
</code>```

答:
In your case, if you want to style your class component, you should use withStyles.
 Try this:

import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { withStyles } from '@material-ui/core/styles';

const useStyles = (theme) => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "white"
  },
})

class Login extends Component {
  render() {
    const { classes } = this.props
    return(

        <LoginForm/>

    );
  }
}
export default withStyles(useStyles)(Login);```

Title: material ui styling not applying

Body:
For some reason my material ui styles are not applying to my html element? Any idea why? I have no other styles applied to this page

import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '@material-ui/core';

const classes = makeStyles( (theme) => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "white"
  },
}) )

class Login extends Component {
  render() {
    return(

        <LoginForm/>

    );
  }
}
export default Login;

Body:
In your case, if you want to style your class component, you should use withStyles.
 Try this:

import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { withStyles } from '@material-ui/core/styles';

const useStyles = (theme) => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "white"
  },
})

class Login extends Component {
  render() {
    const { classes } = this.props
    return(
      <div className = {classes.root}>
        <LoginForm/>
      </div>
    );
  }
}
export default withStyles(useStyles)(Login);


问:
React native on layout change (listen view position)
I want to listen the position of a view I am moving with a pan responder. I am using the onLayout prop to get the width, height, x and y positions, but it only runs when the first render. Any ideas?

Here is the code:

```<code>import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }]),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

 const onLayout = (event) => {
    const {
      nativeEvent: { layout },
    } = event;

    // Recalculate top and buttom views' height (setNativeProps)
  };

  const panStyle = {
    transform: pan.getTranslateTransform(),
  };

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});
</code>```

What I am trying to do is get the middle view position when the user moves it, and then recalculate the top and buttom views' height.

答:
Problem:

OnLayout method not being triggerd on an Animated.View with a custom PanResponder passed in. when the Animated.View is moved using style transformations.

Solution(full code snippet is at the bottom):

Adding a additional listener to the onPanResponderMove method on the PanResponder that can trigger what ever method that is needed with the move event information.

```<code>onPanResponderMove: Animated.event([null, { dy: pan.y }], {listener: ({nativeEvent}) => {onSquareMoved(nativeEvent)}}),

const onSquareMoved = (event) => {
  console.log('square moved changes')
}
</code>```

In order to call a method everytime the panResponder moves, we add a listner that listens to the event and calls the onSquareXChanged method - which is a renamed version of onLayout.

I've added a full snack that calls a method everytime the square moves, you can find it here:
https://snack.expo.io/@m4qr/spunky-soda

It uses code from an answer provided by @ajthyng.
When running your version of the snack, I was getting the onLayout to fire only on first render and not when moving the squre. Combining the result of the debugging and the response on the following github issue: https://github.com/facebook/react-native/issues/28775, it seems that onLayout does not get triggered when style transformation values are changed in an Animated.View.

If your componenet inside of the Animated.View is a more complex one, or the animation required is heavier in terms of calculations, you might stumble upon performance issues. If you are intrested in adding more complex animation effects without losing performance, I'd recommend you look into the Reanimated 2 library which is currently in Alpha.
The library allows you to declare logic for animations that will later on be executed on its own thread as it levereges the worklet feature to allow running animation logic on it's own thread while maintaing 60 fps.

There is a great video by William Candillon exploring the new syntax of the library with an example similar to the snack in the question above:
https://www.youtube.com/watch?time_continue=471&v=e5ALKoP1m-k&feature=emb_title

please let me know if there is anything further questions in regards to this.

Full example of working code:

```<code>import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }],
        {listener: ({nativeEvent}) => onSquareMoved(nativeEvent)}}),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

  const onSquareMoved = (event) => {
    console.log('square was moved')
  }

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});
</code>```

Body:
I want to listen the position of a view I am moving with a pan responder. I am using the onLayout prop to get the width, height, x and y positions, but it only runs when the first render. Any ideas?

Here is the code:

import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }]),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

 const onLayout = (event) => {
    const {
      nativeEvent: { layout },
    } = event;

    // Recalculate top and buttom views' height (setNativeProps)
  };

  const panStyle = {
    transform: pan.getTranslateTransform(),
  };

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});

What I am trying to do is get the middle view position when the user moves it, and then recalculate the top and buttom views' height.

Body:
Problem:

OnLayout method not being triggerd on an Animated.View with a custom PanResponder passed in. when the Animated.View is moved using style transformations.

Solution(full code snippet is at the bottom):

Adding a additional listener to the onPanResponderMove method on the PanResponder that can trigger what ever method that is needed with the move event information.

onPanResponderMove: Animated.event([null, { dy: pan.y }], {listener: ({nativeEvent}) => {onSquareMoved(nativeEvent)}}),

const onSquareMoved = (event) => {
  console.log('square moved changes')
}

In order to call a method everytime the panResponder moves, we add a listner that listens to the event and calls the onSquareXChanged method - which is a renamed version of onLayout.

I've added a full snack that calls a method everytime the square moves, you can find it here:
https://snack.expo.io/@m4qr/spunky-soda

It uses code from an answer provided by @ajthyng.
When running your version of the snack, I was getting the onLayout to fire only on first render and not when moving the squre. Combining the result of the debugging and the response on the following github issue: https://github.com/facebook/react-native/issues/28775, it seems that onLayout does not get triggered when style transformation values are changed in an Animated.View.

If your componenet inside of the Animated.View is a more complex one, or the animation required is heavier in terms of calculations, you might stumble upon performance issues. If you are intrested in adding more complex animation effects without losing performance, I'd recommend you look into the Reanimated 2 library which is currently in Alpha.
The library allows you to declare logic for animations that will later on be executed on its own thread as it levereges the worklet feature to allow running animation logic on it's own thread while maintaing 60 fps.

There is a great video by William Candillon exploring the new syntax of the library with an example similar to the snack in the question above:
https://www.youtube.com/watch?time_continue=471&v=e5ALKoP1m-k&feature=emb_title

please let me know if there is anything further questions in regards to this.

Full example of working code:

import React, { useState, useRef } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  StyleSheet,
} from "react-native";

const WINDOW_HEIGHT = Dimensions.get("window").height;

export default function Cropper({ photo }) {
  const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future

  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, { dy: pan.y }],
        {listener: ({nativeEvent}) => onSquareMoved(nativeEvent)}}),
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

  const onSquareMoved = (event) => {
    console.log('square was moved')
  }

  return (
    <View style={styles.container}>
      <View style={styles.blurView} />
      <Animated.View
        onLayout={(event) => onLayout(event)}
        {...panResponder.panHandlers}
        style={[
          styles.cropper,
          panStyle,
          {
            height: height,
          },
        ]}
      />
      <View style={styles.blurView} />
      <View style={styles.bottomButtonsContainer}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  blurView: {
    flex: 1,
    width: "100%",
    backgroundColor: "rgba(0, 0, 0, .9)",
  },
  cropper: {
    width: "100%",
    backgroundColor: "red",
  },
  bottomButtonsContainer: {
    position: "absolute",
    bottom: 0,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    height: 120,
  },
});


问:
Prevent single tap from changing SeekBar progress
I am using a SeekBar in my Android app. When a user single taps anywhere on the SeekBar, its progress value is changed. I only want the progress value to change when the user slides the SeekBar thumb (just like a UISlider in iOS).

I have tried setting the clickable property of the SeekBar to false but that didn't work. How can I achieve the desired behavior?

答:
See answer here. It only allows progress to be changed via the thumb rather than the progress drawable.
https://stackoverflow.com/a/62165116/1159930</p>


问:
check if input equals a specific string without repeating code
So im making a simple console menu for my program.

```<code># Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)
</code>```

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

答:
The easiest way to break out of a loop (or do anything else exceptional that breaks the normal control flow) from an inner function call without threading a bunch of returns and checks back through multiple scopes is to raise an Exception.

```<code>class QuitException(Exception):
    pass

def get_input(msg: str) -> str:
   uinput = input(msg)
   if uinput == "quit":
       raise QuitException()
   return uinput

while True:
    try:
        option = get_input(menu)
        if option in {"1", "2"}:
            process_params(
                get_input("Input parameters: "),
                option=int(option)
            )
    except QuitException:
        break
</code>```

Body:
So im making a simple console menu for my program.

# Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

Body:
The easiest way to break out of a loop (or do anything else exceptional that breaks the normal control flow) from an inner function call without threading a bunch of returns and checks back through multiple scopes is to raise an Exception.

class QuitException(Exception):
    pass

def get_input(msg: str) -> str:
   uinput = input(msg)
   if uinput == "quit":
       raise QuitException()
   return uinput

while True:
    try:
        option = get_input(menu)
        if option in {"1", "2"}:
            process_params(
                get_input("Input parameters: "),
                option=int(option)
            )
    except QuitException:
        break


问:
How to get date of last "pay period" end for a particular employee?
I'm using a separate scheduling program to feed data to Kronos via API. I'm starting to use it to sign off timecards for employees (always for previous pay period), but I need to get the date to which the timecard is signed off as we have different pay cycles. So, after sending the below request, how do I determine the date through which Kronos signed off the timecard?

```<code><Request Action="SignOff">
    <ApproveSignoff>
        <Employee>
            <PersonIdentity PersonNumber="XXXXXX"/>
        </Employee>
    </ApproveSignoff>
</Request>
</code>```

If it's possible to get the last signed off date of the employee's timecard, that'd be even better.

答:
I've come up with a solution for this. In case any others are following in my footsteps, here's what I've found.

Make a Load call on the Timesheet:

```<code><Request Action="Load">
    <Timesheet>
        <Employee>
            <PersonIdentity PersonNumber="12345"/>
        </Employee>
        <Period>
            <TimeFramePeriod PeriodDateSpan = "01/01/2050 - 01/01/2050" TimeFrameName = "9" />
        </Period>
    </Timesheet>
</Request>
</code>```

I used 1 Jan 2050 to avoid getting irrelevant timesheet info if possible. Within the response, you'll get a  tag. Within that tag, if the employee had ever been signed off, will be a "ManagerSignoffDateTime" property with the date to which that employee's timecard is signed off. If they've never been signed off, that property will be absent. Hope that helps someone.

Body:
I'm using a separate scheduling program to feed data to Kronos via API. I'm starting to use it to sign off timecards for employees (always for previous pay period), but I need to get the date to which the timecard is signed off as we have different pay cycles. So, after sending the below request, how do I determine the date through which Kronos signed off the timecard?

<Request Action="SignOff">
    <ApproveSignoff>
        <Employee>
            <PersonIdentity PersonNumber="XXXXXX"/>
        </Employee>
    </ApproveSignoff>
</Request>

If it's possible to get the last signed off date of the employee's timecard, that'd be even better.

Body:
I've come up with a solution for this. In case any others are following in my footsteps, here's what I've found.

Make a Load call on the Timesheet:

<Request Action="Load">
    <Timesheet>
        <Employee>
            <PersonIdentity PersonNumber="12345"/>
        </Employee>
        <Period>
            <TimeFramePeriod PeriodDateSpan = "01/01/2050 - 01/01/2050" TimeFrameName = "9" />
        </Period>
    </Timesheet>
</Request>

I used 1 Jan 2050 to avoid getting irrelevant timesheet info if possible. Within the response, you'll get a  tag. Within that tag, if the employee had ever been signed off, will be a "ManagerSignoffDateTime" property with the date to which that employee's timecard is signed off. If they've never been signed off, that property will be absent. Hope that helps someone.


问:
Plotting subplots using dataframes
I have dictionary containing 9 dataframes. I want to create a 3,3 subplot and plot bar charts for each dataframe.

To plot a single plot I would do this (just a singplot not considering subplots),

```<code>%matplotlib inline
with plt.style.context('bmh'):
    famd = satFAMD_obj['MODIS.NDVI']
    df_norm = satFAMD_dfNorm['MODIS.NDVI']
    df_cor =famd.column_correlations(df_norm)
    df_cor.columns = ['component 1','component 2', 'component 3']
    df_cor.plot(kind = 'bar',cmap = 'Set1', figsize = (10,6))
plt.show()
</code>```

where satFAMD_obj & satFAMD_dfNorm are two dictionaries containing factor analysis trained objects and a dataframes. In the next line I create a new dataframe called df_cor and then plot it using this line df_cor.plot(kind = 'bar',cmap = 'Set1', figsize = (10,6)).

Now my problem is when it comes to multiple subplots how do I do this ?
I cannot simply do this,

```<code>fig,ax = plt.subplots(3,3, figsize = (12,8))
ax[0,0].df_cor.plot(kind = 'bar',cmap = 'Set1')
</code>```

Any ideas?

答:
I'm supposing that all of your keys in your two dictionaries will need to be plotted.

You will:

declare subplots,

iterate over dictionaries,

iterate over the axes objects,

plot to each set of axes.

Using code like the below example:

```<code>fig,ax = plt.subplots(3,3, figsize = (12,8))

for k1,k2 in zip(satFAMD_obj.keys(),satFAMD_dfNorm.keys()):
    for axes in ax.flatten():
        famd = satFAMD_obj[k1]
        df_norm = satFAMD_dfNorm[k2]
        df_cor = famd.column_correlations(df_norm)
        df_cor.columns = ['component 1','component 2', 'component 3']
        df_cor.plot(kind = 'bar',cmap = 'Set1',ax=axes)
        #                                      ^^^^^^^
</code>```

Title: Plotting subplots using dataframes

Body:
I have dictionary containing 9 dataframes. I want to create a 3,3 subplot and plot bar charts for each dataframe.

To plot a single plot I would do this (just a singplot not considering subplots),

%matplotlib inline
with plt.style.context('bmh'):
    famd = satFAMD_obj['MODIS.NDVI']
    df_norm = satFAMD_dfNorm['MODIS.NDVI']
    df_cor =famd.column_correlations(df_norm)
    df_cor.columns = ['component 1','component 2', 'component 3']
    df_cor.plot(kind = 'bar',cmap = 'Set1', figsize = (10,6))
plt.show()

where satFAMD_obj & satFAMD_dfNorm are two dictionaries containing factor analysis trained objects and a dataframes. In the next line I create a new dataframe called df_cor and then plot it using this line df_cor.plot(kind = 'bar',cmap = 'Set1', figsize = (10,6)).

Now my problem is when it comes to multiple subplots how do I do this ?
I cannot simply do this,

fig,ax = plt.subplots(3,3, figsize = (12,8))
ax[0,0].df_cor.plot(kind = 'bar',cmap = 'Set1')

Any ideas?

Body:
I'm supposing that all of your keys in your two dictionaries will need to be plotted.

You will:

declare subplots,

iterate over dictionaries,

iterate over the axes objects,

plot to each set of axes.

Using code like the below example:

fig,ax = plt.subplots(3,3, figsize = (12,8))

for k1,k2 in zip(satFAMD_obj.keys(),satFAMD_dfNorm.keys()):
    for axes in ax.flatten():
        famd = satFAMD_obj[k1]
        df_norm = satFAMD_dfNorm[k2]
        df_cor = famd.column_correlations(df_norm)
        df_cor.columns = ['component 1','component 2', 'component 3']
        df_cor.plot(kind = 'bar',cmap = 'Set1',ax=axes)
        #                                      ^^^^^^^


问:
Why does std::set.erase(first, last) impact the container from which (first, last) were taken?
I will preface that I'm fairly new to C++ in general. Recently, I ran into some perplexing behavior from the std::set.erase() method, which I have isolated into the following code. This code sample crashes with a segmentation fault when it hits the second for loop:

```<code>#include <set>
#include <iostream>

int main() {
    std::set<int> foo = {0, 1, 2};
    std::set<int> bar = {0, 1, 2, 3, 4};
    for(int i : foo) {
        printf("%d\n", i);
    }
    bar.erase(foo.begin(), foo.end());
    for(int i : foo) { //Crash happens right here, before entering the body of the loop.
        printf("%d\n", i);
    }
    return 0;
}
</code>```

Whereas if you remove the call to erase() it does not crash.

This is somewhat surprising behavior. Calling bar.erase() is obviously supposed to modify "bar" but I would not generally expect it to have any impact on how "foo" functions. What does std::set.erase() do that causes a segmentation fault to occur?

This is simple enough to bypass just by creating a copy of "foo" to supply start and end iterators to erase(), but I am curious why this behavior happens in the first place.

答:
The arguments to the erase function are iterators.  Iterators are not portable across objects.  The iterators that you pass to bar.erase are supposed to be iterators on bar.  If they're not, you get undefined behavior.

The crash probably happened because the call to bar.erase somehow got rid of the contents of foo, because it used foo-based iterators, but foo thought they were still there.

You should not create a copy of foo to provide iterators to bar.erase.  You should use iterators based on bar.

Body:
I will preface that I'm fairly new to C++ in general. Recently, I ran into some perplexing behavior from the std::set.erase() method, which I have isolated into the following code. This code sample crashes with a segmentation fault when it hits the second for loop:

#include <set>
#include <iostream>

int main() {
    std::set<int> foo = {0, 1, 2};
    std::set<int> bar = {0, 1, 2, 3, 4};
    for(int i : foo) {
        printf("%d\n", i);
    }
    bar.erase(foo.begin(), foo.end());
    for(int i : foo) { //Crash happens right here, before entering the body of the loop.
        printf("%d\n", i);
    }
    return 0;
}

Whereas if you remove the call to erase() it does not crash.

This is somewhat surprising behavior. Calling bar.erase() is obviously supposed to modify "bar" but I would not generally expect it to have any impact on how "foo" functions. What does std::set.erase() do that causes a segmentation fault to occur?

This is simple enough to bypass just by creating a copy of "foo" to supply start and end iterators to erase(), but I am curious why this behavior happens in the first place.


问:
Is it possible to have multiple objects in a business layer for 3-tier architecture
I'm working on a school project and just wondering if it is possible to have 2 business objects linking to each other to 1 presentation layer.
Attached an example of what I'm trying to say here:

3-tier Architecture Image

I have Purchase Process and Items Details Process linked up in Business Layer because I do need some modules in the purchase process to be able to run in items details and get the details from the API.
However, I'd only like to have 1 Output in the Presentation Layer.

Any idea if this works in a 3-tier architecture system or am I not supposed to link up my 2 objects in the Business Layer?

答:
Here the principal you are looking for is the separation of concerns.

With the available context what I can say is there are no issues couple two functions of the business layer into one presentation layer function if that's your business requirement but the only problem is it will be highly coupled and would be troublesome to operate independently of each other.