问:
Sharing via Twitter, Facebook, LinkedIn, and Google Plus
I would like a section where users can share a certain link on different social media platforms from our app. I have the twitter link working properly but Facebook, LinkedIn, and G+ are only sharing the URL and not a custom message.

Twitter

```<code>a.twitter-share-button href="http://twitter.com/intent/tweet?source=sharethiscom&text=BlahBlahBlah&url=http://#{Figs.ms.url}/#{@app.uuid}" target="_blank"
</code>```

Facebook

```<code>a.fb-share-button href="https://www.facebook.com/sharer.php?u=http://#{Figs.ms.url}/#{@app.uuid}&t=BlahBlahBlah target="_blank"
</code>```

LinkedIn

```<code>a.linkedin-share-button href="https://www.linkedin.com/cws/share?url=http://#{Figs.ms.url}/#{@app.uuid}&summary=BlahBlahBlah” target="_blank"
</code>```

G+

```<code>a.gplus-share-button href="https://plus.google.com/share?url=http://#{Figs.ms.url}/#{@app.uuid}" target="_blank"
</code>```

I’d like the custom message to be BlahBlahBlah so when they click any of these links it would fill out the custom message and include the link.

答:
Twitter: Official Twitter Share Documentation

```<code>https://twitter.com/intent/tweet?url={url}&text={title}&via={user_id}&hashtags={hash_tags}
</code>```

Facebook: Official Facebook Dialog Documentation / Official Facebook Sharer Documentation

If you have an API key...

```<code>https://www.facebook.com/dialog/share?app_id={app_id}&display={page_type}&href={url}&redirect_uri={redirect_url}
</code>```

And if you don't...

```<code>https://www.facebook.com/sharer.php?u={url}
</code>```

LinkedIn: Official LinkedIn Share Documentation

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Google+: Official Google+ Share Documentation

```<code>N/A : Service disabled.
</code>```

Body:
I would like a section where users can share a certain link on different social media platforms from our app. I have the twitter link working properly but Facebook, LinkedIn, and G+ are only sharing the URL and not a custom message.

Twitter

a.twitter-share-button href="http://twitter.com/intent/tweet?source=sharethiscom&text=BlahBlahBlah&url=http://#{Figs.ms.url}/#{@app.uuid}" target="_blank"

Facebook

a.fb-share-button href="https://www.facebook.com/sharer.php?u=http://#{Figs.ms.url}/#{@app.uuid}&t=BlahBlahBlah target="_blank"

LinkedIn

a.linkedin-share-button href="https://www.linkedin.com/cws/share?url=http://#{Figs.ms.url}/#{@app.uuid}&summary=BlahBlahBlah” target="_blank"

G+

a.gplus-share-button href="https://plus.google.com/share?url=http://#{Figs.ms.url}/#{@app.uuid}" target="_blank"

I’d like the custom message to be BlahBlahBlah so when they click any of these links it would fill out the custom message and include the link.

Body:
Twitter: Official Twitter Share Documentation

https://twitter.com/intent/tweet?url={url}&text={title}&via={user_id}&hashtags={hash_tags}

Facebook: Official Facebook Dialog Documentation / Official Facebook Sharer Documentation

If you have an API key...

https://www.facebook.com/dialog/share?app_id={app_id}&display={page_type}&href={url}&redirect_uri={redirect_url}

And if you don't...

https://www.facebook.com/sharer.php?u={url}

LinkedIn: Official LinkedIn Share Documentation

https://www.linkedin.com/sharing/share-offsite/?url={url}

Google+: Official Google+ Share Documentation

N/A : Service disabled.


来源: stackexchange

问:
Prompting INSTALL_FAILED_INVALID_APK while debugging Flash Builder 4 mobile app on real device
I am trying to build a demo application to test how can i debug or launch my android application on real device.

I have Froyo Android, OSX laptop and Flash Builder 4 IDE.

I build a very simple application, please have a look on image below:

in this when user click on "Click Me" button an email and address will be display in bottom textArea. Application is working fine on Flash Builder 4 emulator but when i try to debug application on my device, it prompt me the error below:

Error occurred while installing the
  application: 1580 KB/s (6108444 bytes
  in 3.773s) pkg:
  /data/local/tmp/Runtime.apk Failure
  [INSTALL_FAILED_INVALID_APK]

or when i create .apk file and try to install it on my device, Again it says me "Error in installation".

Please guide me, how can i fix that issue.

Many Thanks

答:
try this one,

Actually there is a change when creating an apk for a device or an emulator.

So adt.exe/jar is ok, you just need to provide different -target value, i.e.:

For physical device:

```<code>adt.bat -package -target apk -storetype pkcs12...
</code>```

For emulator:

```<code>adt.bat -package -target apk-emulator -storetype pkcs12...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
try this one,

Actually there is a change when creating an apk for a device or an emulator.

So adt.exe/jar is ok, you just need to provide different -target value, i.e.:

For physical device:

adt.bat -package -target apk -storetype pkcs12...

For emulator:

adt.bat -package -target apk-emulator -storetype pkcs12...


问:
How can i get this Object from my api call am using retrofit
Am trying to access my api that return an object with an array of data but i cant access am getting an error saying Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ am using retrofit into my android application

Here is what the api returns when i call it

```<code>{
"students": [
    {
        "_id": "5e74775518b0f00c0123925b",
        "registrationno": "IWR/D/2016/0024",
        "firstname": "Mariam",
        "lastname": "Wamigomba",
        "amount": 10000,
        "reason": "lost key ",
        "__v": 0
    }]}
</code>```

here is my interface

```<code>public interface OcappJsonApiSNAL {
    @GET("getStudents")
    Call<List<StudentClearanceSNAL>> getStudents(@Header ("Authorization") String token);
}
</code>```

On my java class

```<code>OcappJsonApiSNAL ocappJsonApi = retrofit.create (OcappJsonApiSNAL.class);
Call<List<StudentClearanceSNAL>> listCall = ocappJsonApi.getStudents ("Bearer token");
listCall.enqueue (new Callback<List<StudentClearanceSNAL>> () {
    @Override
    public void onResponse(Call<List<StudentClearanceSNAL>> call, Response<List<StudentClearanceSNAL>> response) {
        if(!response.isSuccessful ()) {
            Toast.makeText (getActivity (),"From OCApp " + response.code (),Toast.LENGTH_LONG).show ();
            return;
        }
        List<StudentClearanceSNAL> studentClearancess = response.body ();
           for (  final StudentClearanceSNAL studentClearance: studentClearancess)
                        {
</code>```

Error Am Getting

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

答:
```<code>Call<List<StudentClearanceSNAL>> listCall = ocappJsonApi.getStudents ("Bearer token");
</code>```

Instead of map list externally  you just create new model with list

Create new model :

```<code> Class StudentClearanceSNALList{
 @SerializedName("students") // it’s must match with your Jason object name
 List<StudentClearanceSNAL> studentClearanceSNAL = new Arraylist<>();
//getter and setter
}
</code>```

Then update your interface and class like the following code:

Interface:

```<code>public interface OcappJsonApiSNAL {
    @GET("getStudents")
    Call<StudentClearanceSNALList> getStudents(@Header ("Authorization") String token);
}
</code>```

Class :

```<code>OcappJsonApiSNAL ocappJsonApi = retrofit.create (OcappJsonApiSNAL.class);
Call<StudentClearanceSNALList> listCall = ocappJsonApi.getStudents ("Bearer token");
listCall.enqueue (new Callback<StudentClearanceSNALList> () {
    @Override
    public void onResponse(Call<StudentClearanceSNALList> call, Response<StudentClearanceSNALList> response) {
        if(!response.isSuccessful ()) {
            Toast.makeText (getActivity (),"From OCApp " + response.code (),Toast.LENGTH_LONG).show ();
            return;
        }
 StudentClearanceSNALList studentClearancess = response.body ();
</code>```

Why I suggest this means it’s expect list but you pass object so it’s not accept so please use the above code.

I hope it’s helps you thanks

ContentLicense: CC BY-SA 4.0

Body:
Am trying to access my api that return an object with an array of data but i cant access am getting an error saying Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ am using retrofit into my android application

Here is what the api returns when i call it

{
"students": [
    {
        "_id": "5e74775518b0f00c0123925b",
        "registrationno": "IWR/D/2016/0024",
        "firstname": "Mariam",
        "lastname": "Wamigomba",
        "amount": 10000,
        "reason": "lost key ",
        "__v": 0
    }]}

here is my interface

public interface OcappJsonApiSNAL {
    @GET("getStudents")
    Call<List<StudentClearanceSNAL>> getStudents(@Header ("Authorization") String token);
}

On my java class

OcappJsonApiSNAL ocappJsonApi = retrofit.create (OcappJsonApiSNAL.class);
Call<List<StudentClearanceSNAL>> listCall = ocappJsonApi.getStudents ("Bearer token");
listCall.enqueue (new Callback<List<StudentClearanceSNAL>> () {
    @Override
    public void onResponse(Call<List<StudentClearanceSNAL>> call, Response<List<StudentClearanceSNAL>> response) {
        if(!response.isSuccessful ()) {
            Toast.makeText (getActivity (),"From OCApp " + response.code (),Toast.LENGTH_LONG).show ();
            return;
        }
        List<StudentClearanceSNAL> studentClearancess = response.body ();
           for (  final StudentClearanceSNAL studentClearance: studentClearancess)
                        {

Error Am Getting

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Body:
Call<List<StudentClearanceSNAL>> listCall = ocappJsonApi.getStudents ("Bearer token");

Instead of map list externally  you just create new model with list

Create new model :

 Class StudentClearanceSNALList{
 @SerializedName("students") // it’s must match with your Jason object name
 List<StudentClearanceSNAL> studentClearanceSNAL = new Arraylist<>();
//getter and setter
}

Then update your interface and class like the following code:

Interface:

public interface OcappJsonApiSNAL {
    @GET("getStudents")
    Call<StudentClearanceSNALList> getStudents(@Header ("Authorization") String token);
}

Class :

OcappJsonApiSNAL ocappJsonApi = retrofit.create (OcappJsonApiSNAL.class);
Call<StudentClearanceSNALList> listCall = ocappJsonApi.getStudents ("Bearer token");
listCall.enqueue (new Callback<StudentClearanceSNALList> () {
    @Override
    public void onResponse(Call<StudentClearanceSNALList> call, Response<StudentClearanceSNALList> response) {
        if(!response.isSuccessful ()) {
            Toast.makeText (getActivity (),"From OCApp " + response.code (),Toast.LENGTH_LONG).show ();
            return;
        }
 StudentClearanceSNALList studentClearancess = response.body ();

Why I suggest this means it’s expect list but you pass object so it’s not accept so please use the above code.

I hope it’s helps you thanks


问:
Conditional render based on route
I have an element that I want to display only when I'm on "/" route if It's changing I want to hide the element
how should I do it correctly?
I'm using react-router-dom, to change the route I use   so I guess that's the problem, what am I missing?, also I tried to use if (history.location == '/') then/else
its doesn't work</p>

答:
You can use the <Route /> component from react-router-dom.

From the official react-router docs:

The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when its path matches the current URL.

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from "react-router-dom";

const Home = () => (

My Home Component

);

const App = () => (
  <BrowserRouter>
    <Route exact path="/">
      <Home />
    </Route>
  </BrowserRouter>
);

render(<App />, document.getElementById("root"));
```

Codesandbox example: https://codesandbox.io/s/cranky-albattani-b0y03?file=/src/index.js

Title: Conditional render based on route

Body:
You can use the <Route /> component from react-router-dom.

From the official react-router docs:

The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when its path matches the current URL.

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from "react-router-dom";

const Home = () => (
  <h1>My Home Component</h1>
);

const App = () => (
  <BrowserRouter>
    <Route exact path="/">
      <Home />
    </Route>
  </BrowserRouter>
);

render(<App />, document.getElementById("root"));

Codesandbox example: https://codesandbox.io/s/cranky-albattani-b0y03?file=/src/index.js


问:
Alternatives to insert a FAVICON?
I have a problem with the advanced website manager that I am currently using, and that is that it does not allow me access to the HEAD tag, therefore I cannot set a FAVICON on the website. I would like to know if there are other alternatives to insert a favicon on the website without changing the HEAD code. The website lacks the appropriate tag to insert a favicon.

I know it can be a little crazy, but thanks anyway...

答:
You can add a favicon.ico file to the root directory, browsers will still check for it even if it’s not defined in the .

BTW, this is a great site for generating all the various app icons and associated code https://realfavicongenerator.net

Title: Alternatives to insert a FAVICON?

Body:
You can add a favicon.ico file to the root directory, browsers will still check for it even if it’s not defined in the <head>.

BTW, this is a great site for generating all the various app icons and associated code https://realfavicongenerator.net


问:
What is efficient way to check if current word is close to a word in string?
consider examples below :

Example 1 :

```<code>str1 = "wow...it  looks amazing"
str2 = "looks amazi"
</code>```

You see that amazi is close to amazing, str2 is mistyped, i wanted to write a program that will tell me that amazi is close to amazing then in str2 i will replace amazi with amazing

Example 2 :

```<code>str1 = "is looking good"
str2 = "looks goo"
</code>```

In this case updated str2 will be "looking good"

Example 3 :

```<code>str1 = "you are really looking good"
str2 = "lok goo"
</code>```

In this case str2 will be "good" as lok is not close to looking (or even if program can convert in this case lok to looking then it's just fine for my  problem's solution)

Example 4 :

```<code>str1 = "Stu is actually SEVERLY sunburnt....it hurts!!!"
str2 = "hurts!!"
</code>```

Updated str2 will be "hurts!!!"

Example 5 :

```<code>str1 = "you guys were absolutely amazing tonight, a..."
str2 = "ly amazin"
</code>```

Updated str2 will be "amazing", "ly" shall be removed or replace by absolutely.

What will be the  algo and  code for this?

Maybe we can do it by looking at character lexicographically and set a
threshold like 0.8 or 80% so if word2 gets 80% sequential characters of word1 from str1 then we replace word2 in str2 with word of str1?
Any other efficient solution with python code please?

答:
Like this:

```<code>str1 = "wow...it looks amazing"
str2 =  "looks amazi"
str3 = []

# Checking for similar strings in both strings:
for n in str1.split():
    for m in str2.split():
        if m in n:
            str3.append(n)

# If found 2 similar strings:
if len(str3) == 2:
    # If their indexes align:
    if str1.split().index(str3[1]) - str1.split().index(str3[0]) == 1:
        print(' '.join(str3))

elif len(str3) == 1:
    print(str3[0])
</code>```

Output:

```<code>looks amazing
</code>```

UPDATE with condition given by the OP:

```<code>str1 = "good..."
str2 =  "god.."
str3 = []

# Checking for similar strings in both strings:
for n in str1.split():
    for m in str2.split():

        # Calculating matching character in the 2 words:
        c = ''
        for i in m:
            if i in n:
                c+=i
        # If the amount of matching characters is greater or equal to 50% the length of the larger word
        # or the smaller word is in the larger word:
        if len(list(c)) >= len(n)*0.50 or m in n:
            str3.append(n)

# If found 2 similar strings:
if len(str3) == 2:
    # If their indexes align:
    if str1.split().index(str3[1]) - str1.split().index(str3[0]) == 1:
        print(' '.join(str3))

elif len(str3) == 1:
    print(str3[0])
</code>```

Body:
consider examples below :

Example 1 :

str1 = "wow...it  looks amazing"
str2 = "looks amazi"

You see that amazi is close to amazing, str2 is mistyped, i wanted to write a program that will tell me that amazi is close to amazing then in str2 i will replace amazi with amazing

Example 2 :

str1 = "is looking good"
str2 = "looks goo"

In this case updated str2 will be "looking good"

Example 3 :

str1 = "you are really looking good"
str2 = "lok goo"

In this case str2 will be "good" as lok is not close to looking (or even if program can convert in this case lok to looking then it's just fine for my  problem's solution)

Example 4 :

str1 = "Stu is actually SEVERLY sunburnt....it hurts!!!"
str2 = "hurts!!"

Updated str2 will be "hurts!!!"

Example 5 :

str1 = "you guys were absolutely amazing tonight, a..."
str2 = "ly amazin"

Updated str2 will be "amazing", "ly" shall be removed or replace by absolutely.

What will be the  algo and  code for this?

Maybe we can do it by looking at character lexicographically and set a
threshold like 0.8 or 80% so if word2 gets 80% sequential characters of word1 from str1 then we replace word2 in str2 with word of str1?
Any other efficient solution with python code please?

Body:
Like this:

str1 = "wow...it looks amazing"
str2 =  "looks amazi"
str3 = []

# Checking for similar strings in both strings:
for n in str1.split():
    for m in str2.split():
        if m in n:
            str3.append(n)

# If found 2 similar strings:
if len(str3) == 2:
    # If their indexes align:
    if str1.split().index(str3[1]) - str1.split().index(str3[0]) == 1:
        print(' '.join(str3))

elif len(str3) == 1:
    print(str3[0])

Output:

looks amazing

UPDATE with condition given by the OP:

str1 = "good..."
str2 =  "god.."
str3 = []

# Checking for similar strings in both strings:
for n in str1.split():
    for m in str2.split():

        # Calculating matching character in the 2 words:
        c = ''
        for i in m:
            if i in n:
                c+=i
        # If the amount of matching characters is greater or equal to 50% the length of the larger word
        # or the smaller word is in the larger word:
        if len(list(c)) >= len(n)*0.50 or m in n:
            str3.append(n)

# If found 2 similar strings:
if len(str3) == 2:
    # If their indexes align:
    if str1.split().index(str3[1]) - str1.split().index(str3[0]) == 1:
        print(' '.join(str3))

elif len(str3) == 1:
    print(str3[0])


问:
WKWebView in Cocoa app can't get the cursor on click
I created a simple test app where one field is an NSTextField and another is a <textarea> instead a WKWebView. I can click into the web view once, but if I go back to the NSTextField, I'm unable to get the cursor back into the web view ever again.

Here's a demonstration:

As you can see, the web view is still interactive to some extent, it just can't become (I assume) the first responder again.

Is there something weird about WKWebView and the responder chain? How can I make the WebWebView behave like a normal NSTextField?

Here is a sample project built in Xcode 11.5 in case you want to try it out.

How can this be fixed?

答:
The issue seems to be related to the textarea, using content editable  does seem to work.

A workaround for using the textarea is to subclass WKWebView like this:

```<code>- (void)mouseDown:(NSEvent *)event
{
    [super mouseDown:event];
    [[self window] makeFirstResponder:self];
}
</code>```

Body:
The issue seems to be related to the textarea, using content editable <body contenteditable="true"></body> does seem to work.

A workaround for using the textarea is to subclass WKWebView like this:

- (void)mouseDown:(NSEvent *)event
{
    [super mouseDown:event];
    [[self window] makeFirstResponder:self];
}


答:
You will be able to insert a <link rel="favicon"> by adding a short javascript just before the closing body tag ():

```<code><script>
let faviconLink = document.createElement('link');

faviconLink.setAttribute('rel', 'favicon');
faviconLink.setAttribute('href', '/path/to/favicon.svg');
faviconLink.setAttribute('type', 'image/svg+xml');

document.head.appendChild(faviconLink);
</script>
</code>```

The example above uses an SVG favicon, but you can just as easily use another image format with another MIME type:

PNG: type="image/png"

GIF: type="image/gif"

Title: Alternatives to insert a FAVICON?

Body:
I have a problem with the advanced website manager that I am currently using, and that is that it does not allow me access to the HEAD tag, therefore I cannot set a FAVICON on the website. I would like to know if there are other alternatives to insert a favicon on the website without changing the HEAD code. The website lacks the appropriate tag to insert a favicon.

I know it can be a little crazy, but thanks anyway...

Body:
You will be able to insert a <link rel="favicon"> by adding a short javascript just before the closing body tag (</body>):

<script>
let faviconLink = document.createElement('link');

faviconLink.setAttribute('rel', 'favicon');
faviconLink.setAttribute('href', '/path/to/favicon.svg');
faviconLink.setAttribute('type', 'image/svg+xml');

document.head.appendChild(faviconLink);
</script>

The example above uses an SVG favicon, but you can just as easily use another image format with another MIME type:

PNG: type="image/png"

GIF: type="image/gif"


问:
Modal ScatterViewItem
Can anyone please point out how could i possibly create a modal ScatterViewItem?
I want a ScatterViewItem that will stay on top preventing interaction with anything else until closed. Kind of like a myWindowInstance.ShowDialog() in window forms.

Thanx!

答: Make it the only item in a scatterview.  Set the scatterview's background to Transparent (which, unlike a null background, will block input from going through it).</p>

Title: Modal ScatterViewItem


问:
C++: Matching regex, what is in smatch?
I'm using a modified regex example from Stroustrup C++ 4th Ed. Page 127 & 128.  I'm trying to understand what is in the vector smatch matches.

```<code>$ ./a.out
AB00000-0000
AB00000-0000.-0000.

$ ./a.out
AB00000
AB00000..
</code>```

It seems like the matches in parenthesis () appear in match[1], match[2], ... which the total match appears in match[0].

Appreciate any insight into this.

```<code>#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char *argv[])
{
    // ZIP code pattern: XXddddd-dddd and variants
    regex pat (R"(\w{2}\s*\d{5}(-\d{4})?)");

    for (string line; getline(cin,line);) {
        smatch matches; // matched strings go here
        if (regex_search(line, matches, pat)) { // search for pat in line
            for (auto p : matches) {
                cout << p << ".";
            }
        }
        cout << endl;
    }

    return 0;
}
</code>```

答:
The type of matches is a std::match_results, not a vector, but it does have an operator[].

From the reference:

If n == 0, returns a reference to the std::sub_match representing the part of the target sequence matched by the entire matched regular expression.

If n > 0 and n < size(), returns a reference to the std::sub_match representing the part of the target sequence that was matched by the nth captured marked subexpression).

where n is the argument to operator[]. So matches[0] contains the entire matched expression, and matches[1], matches[2], ... contain consecutive capture group expressions.

Title: C++: Matching regex, what is in smatch?

Body:
I'm using a modified regex example from Stroustrup C++ 4th Ed. Page 127 & 128.  I'm trying to understand what is in the vector smatch matches.

$ ./a.out
AB00000-0000
AB00000-0000.-0000.

$ ./a.out
AB00000
AB00000..

It seems like the matches in parenthesis () appear in match[1], match[2], ... which the total match appears in match[0].

Appreciate any insight into this.

#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char *argv[])
{
    // ZIP code pattern: XXddddd-dddd and variants
    regex pat (R"(\w{2}\s*\d{5}(-\d{4})?)");

    for (string line; getline(cin,line);) {
        smatch matches; // matched strings go here
        if (regex_search(line, matches, pat)) { // search for pat in line
            for (auto p : matches) {
                cout << p << ".";
            }
        }
        cout << endl;
    }

    return 0;
}


问:
Angular Material: Open second dialog left to the first on same level
The use case: I have a record of a customer and want to display additional information in a second dialog. This information is read only, i.e. I need just some selections.

I have opened in Angular Material one modal dialog. To open a second seems quite easy. I have created a sample on Stackblitz.

```<code>this.dialog.open(DialogElementsExampleDialog2, ...
</code>```

So my challenge is now

After opening the second dialog: position the dialogs and resize them to fit next to each other on the screen.

Open the second dialog on the same level as the first, i.e. not over the very first.

The second one should be closable independent from the very first one. If the very first one closes the second should close as well.

For positioning and moving around the second dialog I have already a custom solution. So I just need to dis

答:
Do you need the second dialog?

I altered your stackblitz example to have a hidden second div that can only be opened via the first dialog and has a button to close itself.

https://stackblitz.com/edit/angular-idmii3-dezz4p

otherwise I think it will be a bigger undertaking to extend the dialog module with this functionality and might not be very future proof. But then I think its easier to create a fully custom dialog box yourself with css and functionality as needed.

Body:
The use case: I have a record of a customer and want to display additional information in a second dialog. This information is read only, i.e. I need just some selections.

I have opened in Angular Material one modal dialog. To open a second seems quite easy. I have created a sample on Stackblitz.

this.dialog.open(DialogElementsExampleDialog2, ...

So my challenge is now

After opening the second dialog: position the dialogs and resize them to fit next to each other on the screen.

Open the second dialog on the same level as the first, i.e. not over the very first.

The second one should be closable independent from the very first one. If the very first one closes the second should close as well.

For positioning and moving around the second dialog I have already a custom solution. So I just need to dis


问:
Please explain the mistake I am making in the piece of code?
Please refer to the code below:

```<code>import pandas as pd
import numpy as np
import math

class ElNinoData(object):
    # Your implementation here
    # class variables
    add = 0
    count = 0
    average = 0

    # class methods
    def __init__(self , object):
        self.object = object

    def get_humidity():
        return self.object['humidity']

    def conversion():
        self.object = self.object.astype({'zon_winds':'float64','mer_winds':'float64','humidity':'float64','air_temp':'float64','s_s_temp':'float64'})
        return self.object

    def replace_null():
        if not math.isnan(self.object['humidity']):
            global add
            global count
            global average

            add += pd.to_numeric(self.object['humidity'])
            count += 1
            average = add / count
        else:
            self.object['humidity'] = average
        return self.object['humidity']

def get_obj_it():
    lst = ['bouy','day','latitude','longitude','zon_winds','mer_winds','humidity','air_temp','s_s_temp']
    df = pd.read_csv('C:\\Users\\suel.abbasi\\Downloads\\elnino.gz', sep='\s+', header=None)
    df.columns = lst
    df = df.replace({'.':np.nan})

    for i , j in df.iterrows():
        yield ElNinoData(j)

def average_humidity():
    e_n_generator = get_obj_it()

    count = 0;
    hum_sum = 0;

    for e_n_row in e_n_generator:
        e_n_row = e_n_row.conversion()
        count += 1
        hum_sum += e_n_row.get_humidity()

    print("Mean Humidity is '{}' Percent".format(hum_sum/count))
average_humidity()
</code>```

The code keeps throwing an error, I cant understand the error. I am trying to implement a class to programatically represent the data entries.

The error is below is:

TypeError: conversion() takes 0 positional arguments but 1 was

答: In your class defined functions, you need to pass self as an argument when defining them. So, instead of def conversions():, try def conversion(self). Do the same with get_humidity() and replace_null().

Body:
Please refer to the code below:

import pandas as pd
import numpy as np
import math

class ElNinoData(object):
    # Your implementation here
    # class variables
    add = 0
    count = 0
    average = 0

    # class methods
    def __init__(self , object):
        self.object = object

    def get_humidity():
        return self.object['humidity']

    def conversion():
        self.object = self.object.astype({'zon_winds':'float64','mer_winds':'float64','humidity':'float64','air_temp':'float64','s_s_temp':'float64'})
        return self.object

    def replace_null():
        if not math.isnan(self.object['humidity']):
            global add
            global count
            global average

            add += pd.to_numeric(self.object['humidity'])
            count += 1
            average = add / count
        else:
            self.object['humidity'] = average
        return self.object['humidity']

def get_obj_it():
    lst = ['bouy','day','latitude','longitude','zon_winds','mer_winds','humidity','air_temp','s_s_temp']
    df = pd.read_csv('C:\\Users\\suel.abbasi\\Downloads\\elnino.gz', sep='\s+', header=None)
    df.columns = lst
    df = df.replace({'.':np.nan})

    for i , j in df.iterrows():
        yield ElNinoData(j)

def average_humidity():
    e_n_generator = get_obj_it()

    count = 0;
    hum_sum = 0;

    for e_n_row in e_n_generator:
        e_n_row = e_n_row.conversion()
        count += 1
        hum_sum += e_n_row.get_humidity()

    print("Mean Humidity is '{}' Percent".format(hum_sum/count))
average_humidity()

The code keeps throwing an error, I cant understand the error. I am trying to implement a class to programatically represent the data entries.

The error is below is:

TypeError: conversion() takes 0 positional arguments but 1 was


问:
How can I replace a hash key with another key?
I have a condition that gets a hash.

```<code>  hash = {"_id"=>"4de7140772f8be03da000018", .....}
</code>```

Yet, I want to rename the key of that hash as follows.

```<code>  hash = {"id"=>"4de7140772f8be03da000018", ......}
</code>```

P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.

答:
If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:

```<code>h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
</code>```

The k[1, k.length - 1] bit grabs all of k except the first character. If you want a copy, then:

```<code>new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]
</code>```

Or

```<code>new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }
</code>```

You could also use sub if you don't like the k[] notation for extracting a substring:

```<code>h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
</code>```

And, if only some of the keys have the underscore prefix:

```<code>h.keys.each do |k|
  if(k[0,1] == '_')
    h[k[1, k.length - 1]] = h[k]
    h.delete(k)
  end
end
</code>```

Similar modifications can be done to all the other variants above but these two:

```<code>Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
</code>```

should be okay with keys that don't have underscore prefixes without extra modifications.

Body:
I have a condition that gets a hash.

  hash = {"_id"=>"4de7140772f8be03da000018", .....}

Yet, I want to rename the key of that hash as follows.

  hash = {"id"=>"4de7140772f8be03da000018", ......}

P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.

Body:
If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:

h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }

The k[1, k.length - 1] bit grabs all of k except the first character. If you want a copy, then:

new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]

Or

new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }

You could also use sub if you don't like the k[] notation for extracting a substring:

h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }

And, if only some of the keys have the underscore prefix:

h.keys.each do |k|
  if(k[0,1] == '_')
    h[k[1, k.length - 1]] = h[k]
    h.delete(k)
  end
end

Similar modifications can be done to all the other variants above but these two:

Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }

should be okay with keys that don't have underscore prefixes without extra modifications.


问:
SQL performance subquery in field vs join
I want to know which query's performance will be better by using subquery in the field or join.

For example i have two tables book & author (with one to many relationship between them as Author 1->* Book).

```<code>Sub Query in field (fetching author name using subquery):
select
 b.book_id,
 b.book_name,
 b.author_id,
 (select author_name from author where author.id=b.author_id as author_name
 from book b

Join Query (fetching author name by joining book & author tables):
select
 b.book_id,
 b.book_name,
 b.author_id,
 a.author_name
 from book b inner join author a on b.author_id = a.author_id
</code>```

I am using Postgres DB and if i check query plan then join is doing nested loop, whereas subquery just using PK author_id. I have index on author_id column.

答:
These do different things.  The equivalent of the first query is a left join, not an inner join.  And then they are only equivalent if you can guarantee that author never has more than one match.

In addition, the first will return an error if author returns more than one row for a given author_id.

So, you should use the version that does what you want.

That said, if you have two equivalent versions of the query (using a left join), then then execution plans should be pretty similar.  In particular, both will take advantage of an index on authors(author_id) -- which is what you really care about from a performance perspective.

Body:
I want to know which query's performance will be better by using subquery in the field or join.

For example i have two tables book & author (with one to many relationship between them as Author 1->* Book).

Sub Query in field (fetching author name using subquery):
select
 b.book_id,
 b.book_name,
 b.author_id,
 (select author_name from author where author.id=b.author_id as author_name
 from book b

Join Query (fetching author name by joining book & author tables):
select
 b.book_id,
 b.book_name,
 b.author_id,
 a.author_name
 from book b inner join author a on b.author_id = a.author_id

I am using Postgres DB and if i check query plan then join is doing nested loop, whereas subquery just using PK author_id. I have index on author_id column.


问:
Avoiding TreeMap ConcurrentModificationException?
I am calling function that returns TreeMap instance, and in the calling code I wanted to modify the TreeMap. However,  I am getting a ConcurrentModificationException.

Here is my code:

```<code>public Map<String, String> function1() {
    Map<String, String> key_values = Collections.synchronizedMap(new TreeMap<String, String>());
    // all key_values.put() goes here

    return key_values;
}
</code>```

And my calling code is:

```<code>Map<String, String> key_values =Collections.synchronizedMap(Classname.function1());
//here key_values.put() giving ConcurrentModificationException
</code>```

答:
This is what I was doing that raised ConcurrentModificationException:

```<code>TreeMap<Integer, Integer> map = new TreeMap<>();

for (Integer i : map.keySet()) {
    map.remove(i)
}
</code>```

This is what I did for the same functionality to fix the exception:

```<code>TreeMap<Integer, Integer> map = new TreeMap<>();

// I would not recommend this in production as it will create multiple
// copies of map
for (Integer i : new HashMap<>(integers).keySet()) {
    map.remove(i)
}
</code>```

Body:
I am calling function that returns TreeMap instance, and in the calling code I wanted to modify the TreeMap. However,  I am getting a ConcurrentModificationException.

Here is my code:

public Map<String, String> function1() {
    Map<String, String> key_values = Collections.synchronizedMap(new TreeMap<String, String>());
    // all key_values.put() goes here

    return key_values;
}

And my calling code is:

Map<String, String> key_values =Collections.synchronizedMap(Classname.function1());
//here key_values.put() giving ConcurrentModificationException

Body:
This is what I was doing that raised ConcurrentModificationException:

TreeMap<Integer, Integer> map = new TreeMap<>();

for (Integer i : map.keySet()) {
    map.remove(i)
}

This is what I did for the same functionality to fix the exception:

TreeMap<Integer, Integer> map = new TreeMap<>();

// I would not recommend this in production as it will create multiple
// copies of map
for (Integer i : new HashMap<>(integers).keySet()) {
    map.remove(i)
}


问:
Impact of large dataset on the trained model size?
If the dataset is large does it mean that the model size will also be large?</p>

答:
for example our real world data is function y = ax + b

dataset is all data point on this line

model is our mathematical representation for representing these data

model size is number of parameter we use for representation

now the model size is related to a real world function we want to representing.

we can create a huge dataset for line ax + b but the model of this function only need two parameters a and b and if we have only two point of this line we can create model

real world data are not simple as a line but if we have some model with same result model with least number of parameter is beast one.

The training dataset size depends on the complexity of our model


问:
bootstrap4 tagsinput, delete tag: how to check with ajax and then cancel
I am using tagsinput with bootstrap4. I want the user to click on deleting a tag (the 'x' button), then ajax the tag-delete request to the server which checks if user is allowed to do it. Server responds yes or no (and deletes the tag in DB if yes). And tagsinput should be notified to delete the tag from the input element and its internal state (on client side).

From what I understand, I add the beforeItemRemove event to the tagsinput-element and use the event.cancel=true; to cancel deletion of tag. Like this:

```<code>$(inputel).on('beforeItemRemove', function(event) {
  ajaxreq(..., onSuccess(r){}, onError(e,m){ event.cancel = true; });
});
</code>```

But as you would have guessed the event.cancel is set too late because the event is long processed and exits before the ajax request is completed!

What I ended doing is this:

```<code>event.cancel = true; // we cancel the deletion by default
$(inputel).on('beforeItemRemove', function(event) {
  ajaxreq(..., onSuccess(r){
   // ajax succeeded and server allowed to delete, let's also delete from inputel
   $(inputel).tagsinput('remove', event.item, {preventPost: true});
}, onError(e,m){});
});
// the event is returning much earlier than ajax completing
// but with event.cancel=true it does nothing until we call the 'remove'
</code>```

Is this the right solution?

EDIT: relevant documentation here: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/      (search e.g. for beforeItemRemove)

EDIT2: I have just confirmed that this works in the case where the user is not allowed to delete a tag and the server via ajax refuses to delete it. And indeed nothing gets deleted in the input element. However, in the case where the user can and does delete the tag, the event is fired repeatedly (despite the preventPost: true which I only speculate that it removes without firing remove-event) and bombs the db.

答:
Cloning and patching the JS file bootstrap-tagsinput.js from https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ was my last resort and it did work. So this in not ideal at all. Plus, there are lots of bootstrap "tagsinput" JS files out there which makes this a very bad solution.

The edits were in 3 places.

1) at registering the functions add and remove so that they accept a 3rd parameter, their signature shows they take 3 params in (the last one is the options as an object with keys like preventPost) but the registration below does not pass the 3rd arg! (mind you arg1 is function name like "add" or "remove"):

```<code>  /**
   * Register JQuery plugin
   */

   /* bliako modifies: add arg4 at the end, after arg3: */
  $.fn.tagsinput = function(arg1, arg2, arg3, arg4) {
    var results = [];

    this.each(function() {
...
      } else if(tagsinput[arg1] !== undefined) {
          // Invoke function on existing tags input
/* bliako modifies: */
var retVal = tagsinput[arg1](arg2, arg3, arg4);
/* bliako modifies: and comment out the following - which may introduce side-effects, the problem is that I can't see how these functions get an "options" 3rd arg without arg4 (arg1 is the function name, e.g."add")
So this hopefully passes an options={preventPost: true} back to the add() and remove() functions.
*/
/*            if(tagsinput[arg1].length === 3 && arg3 !== undefined){
               var retVal = tagsinput[arg1](arg2, null, arg3);
            }else{
               var retVal = tagsinput[arg1](arg2);
            }
*/
</code>```

2) modify the "add" function to NOT trigger events when options arg contains preventPost: true

```<code>      // if length greater than limit
      if (self.items().toString().length + item.length + 1 > self.options.maxInputLength)
        return;

      // raise beforeItemAdd arg
/* bliako modifies: don't trigger the &*Q&* event if preventPost == true */
if( (options == null) || ! options.hasOwnProperty('preventPost') || ! options.preventPost ){
      var beforeItemAddEvent = $.Event('beforeItemAdd', { item: item, cancel: false, options: options});
      self.$element.trigger(beforeItemAddEvent);
      if (beforeItemAddEvent.cancel)
        return;
} else { console.log("tags/remove() : blocked beforeItemRemoveEvent"); }
</code>```

3) The same modification as above but for the "remove" function:

```<code>        if (typeof item === "object")
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  self.optio$
        else
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  item; } );

        item = item[item.length-1];
      }

      if (item) {
/* bliako modifies: don't trigger the @*&*Q& event if preventPost == true */
if( (options==null) || ! options.hasOwnProperty('preventPost') || ! options.preventPost ){
        var beforeItemRemoveEvent = $.Event('beforeItemRemove', { item: item, cancel: false, options: options $
        self.$element.trigger(beforeItemRemoveEvent);
        if (beforeItemRemoveEvent.cancel)
          return;
} else { console.log("tags/remove() : blocked beforeItemRemoveEvent"); }
</code>```

The idea is simple and better to follow the idea to 1) allow add and remove functions to take a 3rd parameter as options so that you can pass add(item, dontpushval, {preventPost: true});
2) modify said functions to actually read the options parameter (as their signatures already show, misleadingly, that they accept an options parameter) and whenever the preventPost exists and is set to true, to block triggering the beforeItemAdd and beforeItemRemove

This just shows how broken the "web" is and how billions worth of businesses excelling out there are founded on rotten, clay legs.

bw, bliako

p.s. I am astonished on the lack of any SO troll arriving instantly to declare this question irrelevant, off-topic, vague, already-solved or one of their "computer-says-no" excuse of the day. Perhaps they are all busy in a "community" meeting to make SO "greater".

Body:
I am using tagsinput with bootstrap4. I want the user to click on deleting a tag (the 'x' button), then ajax the tag-delete request to the server which checks if user is allowed to do it. Server responds yes or no (and deletes the tag in DB if yes). And tagsinput should be notified to delete the tag from the input element and its internal state (on client side).

From what I understand, I add the beforeItemRemove event to the tagsinput-element and use the event.cancel=true; to cancel deletion of tag. Like this:

$(inputel).on('beforeItemRemove', function(event) {
  ajaxreq(..., onSuccess(r){}, onError(e,m){ event.cancel = true; });
});

But as you would have guessed the event.cancel is set too late because the event is long processed and exits before the ajax request is completed!

What I ended doing is this:

event.cancel = true; // we cancel the deletion by default
$(inputel).on('beforeItemRemove', function(event) {
  ajaxreq(..., onSuccess(r){
   // ajax succeeded and server allowed to delete, let's also delete from inputel
   $(inputel).tagsinput('remove', event.item, {preventPost: true});
}, onError(e,m){});
});
// the event is returning much earlier than ajax completing
// but with event.cancel=true it does nothing until we call the 'remove'

Is this the right solution?

EDIT: relevant documentation here: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/      (search e.g. for beforeItemRemove)

EDIT2: I have just confirmed that this works in the case where the user is not allowed to delete a tag and the server via ajax refuses to delete it. And indeed nothing gets deleted in the input element. However, in the case where the user can and does delete the tag, the event is fired repeatedly (despite the preventPost: true which I only speculate that it removes without firing remove-event) and bombs the db.

Body:
Cloning and patching the JS file bootstrap-tagsinput.js from https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ was my last resort and it did work. So this in not ideal at all. Plus, there are lots of bootstrap "tagsinput" JS files out there which makes this a very bad solution.

The edits were in 3 places.

1) at registering the functions add and remove so that they accept a 3rd parameter, their signature shows they take 3 params in (the last one is the options as an object with keys like preventPost) but the registration below does not pass the 3rd arg! (mind you arg1 is function name like "add" or "remove"):

  /**
   * Register JQuery plugin
   */

   /* bliako modifies: add arg4 at the end, after arg3: */
  $.fn.tagsinput = function(arg1, arg2, arg3, arg4) {
    var results = [];

    this.each(function() {
...
      } else if(tagsinput[arg1] !== undefined) {
          // Invoke function on existing tags input
/* bliako modifies: */
var retVal = tagsinput[arg1](arg2, arg3, arg4);
/* bliako modifies: and comment out the following - which may introduce side-effects, the problem is that I can't see how these functions get an "options" 3rd arg without arg4 (arg1 is the function name, e.g."add")
So this hopefully passes an options={preventPost: true} back to the add() and remove() functions.
*/
/*            if(tagsinput[arg1].length === 3 && arg3 !== undefined){
               var retVal = tagsinput[arg1](arg2, null, arg3);
            }else{
               var retVal = tagsinput[arg1](arg2);
            }
*/

2) modify the "add" function to NOT trigger events when options arg contains preventPost: true

      // if length greater than limit
      if (self.items().toString().length + item.length + 1 > self.options.maxInputLength)
        return;

      // raise beforeItemAdd arg
/* bliako modifies: don't trigger the &*Q&* event if preventPost == true */
if( (options == null) || ! options.hasOwnProperty('preventPost') || ! options.preventPost ){
      var beforeItemAddEvent = $.Event('beforeItemAdd', { item: item, cancel: false, options: options});
      self.$element.trigger(beforeItemAddEvent);
      if (beforeItemAddEvent.cancel)
        return;
} else { console.log("tags/remove() : blocked beforeItemRemoveEvent"); }

3) The same modification as above but for the "remove" function:

        if (typeof item === "object")
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  self.optio$
        else
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  item; } );

        item = item[item.length-1];
      }

      if (item) {
/* bliako modifies: don't trigger the @*&*Q& event if preventPost == true */
if( (options==null) || ! options.hasOwnProperty('preventPost') || ! options.preventPost ){
        var beforeItemRemoveEvent = $.Event('beforeItemRemove', { item: item, cancel: false, options: options $
        self.$element.trigger(beforeItemRemoveEvent);
        if (beforeItemRemoveEvent.cancel)
          return;
} else { console.log("tags/remove() : blocked beforeItemRemoveEvent"); }

The idea is simple and better to follow the idea to 1) allow add and remove functions to take a 3rd parameter as options so that you can pass add(item, dontpushval, {preventPost: true});
2) modify said functions to actually read the options parameter (as their signatures already show, misleadingly, that they accept an options parameter) and whenever the preventPost exists and is set to true, to block triggering the beforeItemAdd and beforeItemRemove

This just shows how broken the "web" is and how billions worth of businesses excelling out there are founded on rotten, clay legs.

bw, bliako

p.s. I am astonished on the lack of any SO troll arriving instantly to declare this question irrelevant, off-topic, vague, already-solved or one of their "computer-says-no" excuse of the day. Perhaps they are all busy in a "community" meeting to make SO "greater".


问:
Unique index by another column for postgresql
For example, I have this table (postgresql):

CREATE TABLE t(
 a TEXT,
 b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);
```

<p>I want to create unique constraint/index for <code>b</code> and <code>a</code> columns. But not simple <code>ADD CONSTRAINT t_ab UNIQUE (a, b)</code>. I want unique <code>b</code> by <code>a</code>:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'
</code>```

How can I do this?

Edit:

Why do I need this? For example, If I have users table and I want to create email changing feature, I need structure like this:

CREATE TABLE users(
 email TEXT,
 unconfirmed_email TEXT
 -- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);
```

User can set value into unconfirmed_email column, but only if this value don't used in email column.

答:
As I understand it, you want a UNIQUE index over a and b combined.

You update narrowed it down (b shall not exist in a). This solution is stricter.

Solution

After trying and investigating quite a bit (see below!) I came up with this:

```<code>ALTER TABLE tbl ADD CONSTRAINT a_not_equal_b CHECK (a <> b);
ALTER TABLE tbl ADD CONSTRAINT ab_unique
   EXCLUDE USING gist ((ARRAY[hashtext(COALESCE(a, ''))
                            , hashtext(COALESCE(b, ''))]) gist__int_ops WITH &&);
</code>```

db<>fiddle here

Since the exclusion constraint won't currently (pg 12) work with text[], I work with int4[] of hash values. hashtext() is the built-in hash function that's also used for hash-partitioning (among other uses). Seems perfect for the job.

The operator class gist__int_ops is provided by the additional module intarray, which has to be installed once per database. Its optional, the solution works with the default array operator class as well. Just drop gist__int_ops to fall back. But intarray is faster. Related:

How to create an index for elements of an array in PostgreSQL?

Caveats

int4 may not be big enough to rule out hash collisions sufficiently. You might want to go with bigint instead. But that's more expensive and can't use the gist__int_ops operator class to improve performance. Your call.

Unicode has the dismal property that equal strings can be encoded in different ways. If you work with Unicode (typical encoding UTF8) and use non-ASCII characters (and this matters to you), compare normalized forms to rule out such duplicates. The upcoming Postgres 13 adds the function normalize() for that purpose. This is a general caveat of character type duplicates, though, not specific to my solution.

NULL value is allowed, but collides with empty string (''). I would rather go with NOT NULL columns and drop COALESCE() from the expressions.

Obstacle course to an exclusion constraint

My first thought was: exclusion constraint. But it falls through:

```<code>ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) WITH &&);
</code>```

```<code>ERROR:  data type text[] has no default operator class for access method "gist"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.
</code>```

There is an open TODO item for this. Related:

ERROR: data type text[] has no default operator class for access method “gist”

But can't we use a GIN index for text[]? Alas, no:

```<code>ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gin ((ARRAY[a,b]) WITH &&);
</code>```

```<code>ERROR:  access method "gin" does not support exclusion constraints
</code>```

Why? The manual:

The access method must support amgettuple (see Chapter 61); at present this means GIN cannot be used.

It seems hard to implement, so don't hold your breath.

If a and b were integer columns, we could make it work with an integer array:

```<code>ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) WITH &&);
</code>```

Or with the gist__int_ops operator class from the additional module intarray (typically faster):

```<code>ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) gist__int_ops WITH &&);
</code>```

To also forbid duplicates within the same row, add a CHECK constraint:

```<code>ALTER TABLE tbl ADD CONSTRAINT a_not_equal_b CHECK (a <> b);
</code>```

Remaining issue: Does work with NULL values.

Workaround

Add a helper table to store values from a and b in one column:

```<code>CREATE TABLE tbl_ab(ab text PRIMARY KEY);
</code>```

Main table, like you had it, plus FK constraints.

```<code>CREATE TABLE tbl (
  a text REFERENCES tbl_ab ON UPDATE CASCADE ON DELETE CASCADE
, b text REFERENCES tbl_ab ON UPDATE CASCADE ON DELETE CASCADE
);
</code>```

Use a function like this to INSERT:

```<code>ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) WITH &&);
</code>```0

db<>fiddle here

Or implement a trigger to take care of it in the background.

```<code>ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) WITH &&);
</code>```1

db<>fiddle here

NULL handling can be changed as desired.

Either way, while the added (optional) FK constraints enforce that we can't sidestep the helper table tbl_ab, and allow to UPDATE and DELETE in tbl_ab to cascade, you still need to project UPDATE and DELETE into the helper table as well (or implement more triggers). Tricky corner cases, but there are solutions. Not going into this, after I found the solution above with an exclusion constraint using hashtext() ...

Related:

Can PostgreSQL have a uniqueness constraint on array elements?

Body:
For example, I have this table (postgresql):

CREATE TABLE t(
 a TEXT,
 b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);

I want to create unique constraint/index for b and a columns. But not simple ADD CONSTRAINT t_ab UNIQUE (a, b). I want unique b by a:

INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'

How can I do this?

Edit:

Why do I need this? For example, If I have users table and I want to create email changing feature, I need structure like this:

CREATE TABLE users(
 email TEXT,
 unconfirmed_email TEXT
 -- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);

User can set value into unconfirmed_email column, but only if this value don't used in email column.

Body:
As I understand it, you want a UNIQUE index over a and b combined.

You update narrowed it down (b shall not exist in a). This solution is stricter.

Solution

After trying and investigating quite a bit (see below!) I came up with this:

ALTER TABLE tbl ADD CONSTRAINT a_not_equal_b CHECK (a <> b);
ALTER TABLE tbl ADD CONSTRAINT ab_unique
   EXCLUDE USING gist ((ARRAY[hashtext(COALESCE(a, ''))
                            , hashtext(COALESCE(b, ''))]) gist__int_ops WITH &&);

db<>fiddle here

Since the exclusion constraint won't currently (pg 12) work with text[], I work with int4[] of hash values. hashtext() is the built-in hash function that's also used for hash-partitioning (among other uses). Seems perfect for the job.

The operator class gist__int_ops is provided by the additional module intarray, which has to be installed once per database. Its optional, the solution works with the default array operator class as well. Just drop gist__int_ops to fall back. But intarray is faster. Related:

How to create an index for elements of an array in PostgreSQL?

Caveats

int4 may not be big enough to rule out hash collisions sufficiently. You might want to go with bigint instead. But that's more expensive and can't use the gist__int_ops operator class to improve performance. Your call.

Unicode has the dismal property that equal strings can be encoded in different ways. If you work with Unicode (typical encoding UTF8) and use non-ASCII characters (and this matters to you), compare normalized forms to rule out such duplicates. The upcoming Postgres 13 adds the function normalize() for that purpose. This is a general caveat of character type duplicates, though, not specific to my solution.

NULL value is allowed, but collides with empty string (''). I would rather go with NOT NULL columns and drop COALESCE() from the expressions.

Obstacle course to an exclusion constraint

My first thought was: exclusion constraint. But it falls through:

ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) WITH &&);

ERROR:  data type text[] has no default operator class for access method "gist"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.

There is an open TODO item for this. Related:

ERROR: data type text[] has no default operator class for access method “gist”

But can't we use a GIN index for text[]? Alas, no:

ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gin ((ARRAY[a,b]) WITH &&);

ERROR:  access method "gin" does not support exclusion constraints

Why? The manual:

The access method must support amgettuple (see Chapter 61); at present this means GIN cannot be used.

It seems hard to implement, so don't hold your breath.

If a and b were integer columns, we could make it work with an integer array:

ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) WITH &&);

Or with the gist__int_ops operator class from the additional module intarray (typically faster):

ALTER TABLE tbl ADD CONSTRAINT ab_unique EXCLUDE USING gist ((ARRAY[a,b]) gist__int_ops WITH &&);

To also forbid duplicates within the same row, add a CHECK constraint:

ALTER TABLE tbl ADD CONSTRAINT a_not_equal_b CHECK (a <> b);

Remaining issue: Does work with NULL values.

Workaround

Add a helper table to store values from a and b in one column:

CREATE TABLE tbl_ab(ab text PRIMARY KEY);

Main table, like you had it, plus FK constraints.

CREATE TABLE tbl (
  a text REFERENCES tbl_ab ON UPDATE CASCADE ON DELETE CASCADE
, b text REFERENCES tbl_ab ON UPDATE CASCADE ON DELETE CASCADE
);

Use a function like this to INSERT:

CREATE OR REPLACE FUNCTION f_tbl_insert(_a text, _b text)
 RETURNS void
 LANGUAGE sql AS
$func$
WITH ins_ab AS (
   INSERT INTO tbl_ab(ab)
   SELECT _a WHERE _a IS NOT NULL  -- NULL is allowed (?)
   UNION ALL
   SELECT _b WHERE _b IS NOT NULL
   )
INSERT INTO tbl(a,b)
VALUES (_a, _b);
$func$;

db<>fiddle here

Or implement a trigger to take care of it in the background.

CREATE OR REPLACE FUNCTION trg_tbl_insbef()
  RETURNS trigger AS
$func$
BEGIN
   INSERT INTO tbl_ab(ab)
   SELECT NEW.a WHERE NEW.a IS NOT NULL  -- NULL is allowed (?)
   UNION ALL
   SELECT NEW.b WHERE NEW.b IS NOT NULL;

   RETURN NEW;
END
$func$ LANGUAGE plpgsql;

CREATE TRIGGER tbl_insbef
BEFORE INSERT ON tbl
FOR EACH ROW EXECUTE PROCEDURE trg_tbl_insbef();

db<>fiddle here

NULL handling can be changed as desired.

Either way, while the added (optional) FK constraints enforce that we can't sidestep the helper table tbl_ab, and allow to UPDATE and DELETE in tbl_ab to cascade, you still need to project UPDATE and DELETE into the helper table as well (or implement more triggers). Tricky corner cases, but there are solutions. Not going into this, after I found the solution above with an exclusion constraint using hashtext() ...

Related:

Can PostgreSQL have a uniqueness constraint on array elements?


问:
Using objects to discriminate union types
I am trying to create union types in TypeScript where the discriminator is a value on a nested object, rather than a primitive value directly on the type. I am working with objects returned from an API and therefore cannot alter the data structures being returned.

Is this possible in TypeScript, without needing to resort to user-defined type guards?

Here is a simplified example:

```<code>type SquareIdentifier = {
  type: "square";
};

type CircleIdentifier = {
  type: "circle";
};

type SquareShape = {
  identifier: SquareIdentifier;
  sideLength: number;
};

type CircleShape = {
  identifier: CircleIdentifier;
  diameter: number;
};

type Shape = SquareShape | CircleShape;

// assume we have been given a variable `x` of Shape
const x = ({} as any) as Shape;

// at this point, x.identifier is considered a SquareIdentifier | CircleIdentifier
if (x.identifier.type === "square") {
  // at this point, x.identifier is considered a SquareIdentifier
  // however, x is still considered a Shape, not a SquareShape, which is the only Shape to contain a ShapeIdentifier
  // error here is:
  // "Property 'sideLength' does not exist on type 'Shape'"
  // "Property 'sideLength' does not exist on type 'CircleShape'"
  console.log(x.sideLength);
}
</code>```

答:
Yes, it's possible. You need to use user defined type guards

For example like this:

```<code>if (isSquareShape(x)) {
  console.log(x.sideLength);
}

function isSquareShape(value: Shape): value is SquareShape {
    return value.identifier.type === 'square';
}
</code>```

Body:
I am trying to create union types in TypeScript where the discriminator is a value on a nested object, rather than a primitive value directly on the type. I am working with objects returned from an API and therefore cannot alter the data structures being returned.

Is this possible in TypeScript, without needing to resort to user-defined type guards?

Here is a simplified example:

type SquareIdentifier = {
  type: "square";
};

type CircleIdentifier = {
  type: "circle";
};

type SquareShape = {
  identifier: SquareIdentifier;
  sideLength: number;
};

type CircleShape = {
  identifier: CircleIdentifier;
  diameter: number;
};

type Shape = SquareShape | CircleShape;

// assume we have been given a variable `x` of Shape
const x = ({} as any) as Shape;

// at this point, x.identifier is considered a SquareIdentifier | CircleIdentifier
if (x.identifier.type === "square") {
  // at this point, x.identifier is considered a SquareIdentifier
  // however, x is still considered a Shape, not a SquareShape, which is the only Shape to contain a ShapeIdentifier
  // error here is:
  // "Property 'sideLength' does not exist on type 'Shape'"
  // "Property 'sideLength' does not exist on type 'CircleShape'"
  console.log(x.sideLength);
}

Body:
Yes, it's possible. You need to use user defined type guards

For example like this:

if (isSquareShape(x)) {
  console.log(x.sideLength);
}

function isSquareShape(value: Shape): value is SquareShape {
    return value.identifier.type === 'square';
}


问:
Error message 'Class "\Aimeos\MShop\Index\Manager\PgSQL" not available' on aimeos package
I am trying install aimeos with postgresql database, and after solved LOTS of problems that occurs when we use other database that isnot mysql, this message is showed on home page

```<code>Class "\Aimeos\MShop\Index\Manager\PgSQL" not available
</code>```

How to fix this? Whats is missing?

答:
1) after every change !!!!!
php artisan cache:clear
php artisan config:cache

2) Edit vendor/aimeos/aimeos-laravel/src/default.php

.....
    'Aimeos' => array(
        'mshop' => array(

```<code>        'index' => array(

            'manager' => array(

                'attribute' => array(

                    'name' => 'Standard',

                ),

                'catalog' => array(

                    'name' => 'Standard',

                ),

                'price' => array(

                    'name' => 'Standard',

                ),

                'supplier' => array(

                    'name' => 'Standard',

                ),

                'text' => array(

                    'name' => 'PgSQL',

                ),

            ),

        ),

    ),
</code>```

),
3) Edit config/shop.php
    'mshop' => array(

```<code>    'index' => array(

        'manager' => array(

            'attribute' => array(

                'name' => 'Standard',

            ),

            'catalog' => array(

                'name' => 'Standard',

            ),

            'price' => array(

                'name' => 'Standard',

            ),

            'supplier' => array(

                'name' => 'Standard',

            ),

            'text' => array(

                'name' => 'PgSQL',

            ),

        ),

    ),

),
</code>```

4)  run

php artisan cache:clear
php artisan config:cache

Body:
I am trying install aimeos with postgresql database, and after solved LOTS of problems that occurs when we use other database that isnot mysql, this message is showed on home page

Class "\Aimeos\MShop\Index\Manager\PgSQL" not available

How to fix this? Whats is missing?

Body:
1) after every change !!!!!
php artisan cache:clear
php artisan config:cache

2) Edit vendor/aimeos/aimeos-laravel/src/default.php

.....
    'Aimeos' => array(
        'mshop' => array(

        'index' => array(

            'manager' => array(

                'attribute' => array(

                    'name' => 'Standard',

                ),

                'catalog' => array(

                    'name' => 'Standard',

                ),

                'price' => array(

                    'name' => 'Standard',

                ),

                'supplier' => array(

                    'name' => 'Standard',

                ),

                'text' => array(

                    'name' => 'PgSQL',

                ),

            ),

        ),

    ),

),
3) Edit config/shop.php
    'mshop' => array(

    'index' => array(

        'manager' => array(

            'attribute' => array(

                'name' => 'Standard',

            ),

            'catalog' => array(

                'name' => 'Standard',

            ),

            'price' => array(

                'name' => 'Standard',

            ),

            'supplier' => array(

                'name' => 'Standard',

            ),

            'text' => array(

                'name' => 'PgSQL',

            ),

        ),

    ),

),

4)  run

php artisan cache:clear
php artisan config:cache


答:
You can get what you need with type guards:

type SquareIdentifier = {
  type: "square";
};

type CircleIdentifier = {
  type: "circle";
};

type SquareShape = {
  identifier: SquareIdentifier;
  sideLength: number;
};

type CircleShape = {
  identifier: CircleIdentifier;
  diameter: number;
};

type Shape = SquareShape | CircleShape;

const isSquareShape = (x: any): x is SquareShape => {
    return x.type && x.type === 'sqaure';
}
const testFunction = (x: any) => {
    if (isSquareShape(x)) {
        const y = x.sideLength; // this now works, because typescript 'knows' we have a square shape
    }
}
```

The function isSquareShape allows typescript to determine that a value is of type SquareShape, and so once we have code which passes the value through this check (if (isSquareShape(x)), in this instance) we're able to access the value as though it were a SquareShape with no type errors.

Title: Using objects to discriminate union types

Body:
You can get what you need with type guards:

type SquareIdentifier = {
  type: "square";
};

type CircleIdentifier = {
  type: "circle";
};

type SquareShape = {
  identifier: SquareIdentifier;
  sideLength: number;
};

type CircleShape = {
  identifier: CircleIdentifier;
  diameter: number;
};

type Shape = SquareShape | CircleShape;

const isSquareShape = (x: any): x is SquareShape => {
    return x.type && x.type === 'sqaure';
}
const testFunction = (x: any) => {
    if (isSquareShape(x)) {
        const y = x.sideLength; // this now works, because typescript 'knows' we have a square shape
    }
}

The function isSquareShape allows typescript to determine that a value is of type SquareShape, and so once we have code which passes the value through this check (if (isSquareShape(x)), in this instance) we're able to access the value as though it were a SquareShape with no type errors.


问:
Using remote JavaScript in Chrome Extensions
Is there any way to get remote JS file to chrome extension?

My manifest.json looks like this:

```<code>{
    "name": "My Extension",
    "version": "0.1",
    "content_scripts": [
    {
        "matches": ["http://*/*"],
        "js": ["jquery.js", "main.js"],
        "run_at": "document_end",
        "all_frames": true
    }
    ]
}
</code>```

I want use one JavaScript API, which is limited by usage on selected domain, so I can't insert it simply to loaded page in Chrome like this:

```<code>$('head').append('<script src="http://example.com/myApi.js?key=%key%"></script>');
</code>```

because the JS API alerted me, that I'm using it on URL, which I haven't gave them.

I want just use some functions from this remote JS. The API key can be fortunately registered and used on localhost.

But I don't have any clue, how to solve this problem - where to put the remote JS file to be able to use it.

I've got an idea to create a "virtual DOM", but perhaps it's not a solution, because the JS API code can't be executed.

Where to insert the code? Some background page??

答: Currently can't find a way to host code for an extension remotely, but still allow that code to use chrome.* javascript calls. </p>

ContentLicense: CC BY-SA 2.5

Body:
Is there any way to get remote JS file to chrome extension?

My manifest.json looks like this:

{
    "name": "My Extension",
    "version": "0.1",
    "content_scripts": [
    {
        "matches": ["http://*/*"],
        "js": ["jquery.js", "main.js"],
        "run_at": "document_end",
        "all_frames": true
    }
    ]
}

I want use one JavaScript API, which is limited by usage on selected domain, so I can't insert it simply to loaded page in Chrome like this:

$('head').append('');

because the JS API alerted me, that I'm using it on URL, which I haven't gave them.

I want just use some functions from this remote JS. The API key can be fortunately registered and used on localhost.

But I don't have any clue, how to solve this problem - where to put the remote JS file to be able to use it.

I've got an idea to create a "virtual DOM", but perhaps it's not a solution, because the JS API code can't be executed.

Where to insert the code? Some background page??


问:
How to remove keys from a params array of hashes
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

```<code><ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>
</code>```

答:
You can store a "copy" of params where you modify the sales_attribute values:

```<code>params.each_with_object({}) do |(key, values), hash|
  hash[key] = if key == :sales_attributes
                values.map do |sales_attribute|
                  sales_attribute.except(:code, :name)
                end
              else
                hash[key] = values
              end
end
# { "patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
#  [{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0"},
#   {"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0"},
#   {"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0"}] }
</code>```

Basically, you iterate params and assign every key/value to a temporal hash, but in case the key is equal to :sales_attributes then you map the values using except and get their keys/values except :code and :name.

Body:
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

<ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>

Body:
You can store a "copy" of params where you modify the sales_attribute values:

params.each_with_object({}) do |(key, values), hash|
  hash[key] = if key == :sales_attributes
                values.map do |sales_attribute|
                  sales_attribute.except(:code, :name)
                end
              else
                hash[key] = values
              end
end
# { "patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
#  [{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0"},
#   {"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0"},
#   {"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0"}] }

Basically, you iterate params and assign every key/value to a temporal hash, but in case the key is equal to :sales_attributes then you map the values using except and get their keys/values except :code and :name.


问:
What does it mean for an element to be 'Self-Contained'
I'm very new to HTML.  I'm following an online tutorial.   I need to put some images on the page and I need to enclose these images in
 tags.  The tutorial doesn't explain why I need to do this.  In fact, it gives no information about the
 tag at all.  So, I googled it and this is what I found:

The HTML  (Figure With Optional Caption) element represents self-contained content, potentially with an optional caption, which is specified using the (
) element. The figure, its caption, and its contents are referenced as a single unit.

Emphasis mine.

This explanation doesn't help me.  Please could someone explain what is meant by 'self-contained content'?  Isn't all content essentially 'self-contained'?  If it wasn't then any adjustment to any element would affect every other element.  Is 'self-contained content' some kind of reserved term with a special meaning in web design?  I just don't understand what it means for content to be 'self-contained' in this context.  As a consequence, I can't understand the point of the

 tags.

Many thanks.

答:
No. The meaning of "self-contained" comes from English, not a term with special meaning in web design.

"Self-contained" means independent of its surrounding context. The best way to think of the
 element is as analogous to a figure in a text book. Figures are, for reading convenience, often printed close to the text that explains the relevance of the figure's content to the chapter as a whole. But you can also just read the figure and understand what it's telling you without having to read the context in which it appears.

So you could move the all figures to elsewhere in the book, and you could open the book for the first time at the page which the figure was on, and you'd still be able to understand what the figure was telling you. And so long as where-ever the text needed to reference the figure it could do so, by for example saying "see figure 23b", it works as a figure.

Body:
No. The meaning of "self-contained" comes from English, not a term with special meaning in web design.

"Self-contained" means independent of its surrounding context. The best way to think of the <figure> element is as analogous to a figure in a text book. Figures are, for reading convenience, often printed close to the text that explains the relevance of the figure's content to the chapter as a whole. But you can also just read the figure and understand what it's telling you without having to read the context in which it appears.

So you could move the all figures to elsewhere in the book, and you could open the book for the first time at the page which the figure was on, and you'd still be able to understand what the figure was telling you. And so long as where-ever the text needed to reference the figure it could do so, by for example saying "see figure 23b", it works as a figure.


问:
case statement inside of fetchxml script
Please note that although this question is an entirely different question, it relates directly to this question.

The following is the script that returns the dataset for my SSRS chart:

```<code><fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false" aggregate="true">
      <entity name="account">
        <attribute name="bio_employeesworldwide" alias="TotalWorldWideEmployees" aggregate="sum" />
        <filter>
          <condition attribute="customertypecode" operator="eq" value="2" />
        </filter>
     <link-entity name="contact" from="parentcustomerid" to="accountid" alias="contact">

        <attribute name="bio_webuseraccountstatus" alias="count_bio_webuseraccountstatus" aggregate="countcolumn" />

        <attribute name="bio_webuseraccountstatus" alias="bio_webuseraccountstatusgroupby" groupby="true" />

      </link-entity>
      </entity>
    </fetch>
</code>```

The values for bio_webuseraccountstatus can be Active, Inactive, Disabled, Pending, etc..

In FetchXML is there a way to do a case statement where you "InActive" for every value that is not equal to "Active" ?

As you can see I've been trying to solve this issue within the reporting layer, but am experiencing lots of "string format" issues.

Can this be done with the dataset layer (fetchxml) instead?

答:
You can always parse the output of the fetchxml on return.
So rather than pushing to the screen, report, or db, the original record field of isreceivetravelalerts, you check the status (zero or one) and rewrite it, and add the new variable to your output.  Clunky, but useful.</p>

```<code>if ($record->isreceivetravelalerts == 1)
{
    $travel_alerts = "Active";
}

$travel_alerts = "Inactive";
</code>```

Body:
Please note that although this question is an entirely different question, it relates directly to this question.

The following is the script that returns the dataset for my SSRS chart:

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false" aggregate="true">
      <entity name="account">
        <attribute name="bio_employeesworldwide" alias="TotalWorldWideEmployees" aggregate="sum" />
        <filter>
          <condition attribute="customertypecode" operator="eq" value="2" />
        </filter>
     <link-entity name="contact" from="parentcustomerid" to="accountid" alias="contact">

        <attribute name="bio_webuseraccountstatus" alias="count_bio_webuseraccountstatus" aggregate="countcolumn" />

        <attribute name="bio_webuseraccountstatus" alias="bio_webuseraccountstatusgroupby" groupby="true" />

      </link-entity>
      </entity>
    </fetch>

The values for bio_webuseraccountstatus can be Active, Inactive, Disabled, Pending, etc..

In FetchXML is there a way to do a case statement where you "InActive" for every value that is not equal to "Active" ?

As you can see I've been trying to solve this issue within the reporting layer, but am experiencing lots of "string format" issues.

Can this be done with the dataset layer (fetchxml) instead?

Body:
You can always parse the output of the fetchxml on return.
So rather than pushing to the screen, report, or db, the original record field of isreceivetravelalerts, you check the status (zero or one) and rewrite it, and add the new variable to your output.  Clunky, but useful.

if ($record->isreceivetravelalerts == 1)
{
    $travel_alerts = "Active";
}

$travel_alerts = "Inactive";


问:
Get extra value in datatable ajax call
I am filling data by below code

```<code>$(document).ready(function() {

manageTable = $('#manageTable').DataTable({
    'ajax': base_url + 'products/fetchProductData',
    'order': []
  });
</code>```

here I want total assets as well means product_price * qty = assets of all product to show as summary like $100000 assets we have so I changed the controller ad added the new statistics obj and here is the value in assets keys.

and question is how can i show this extra value to this page.

image reference

答:
You can use a DataTables function "drawCallback" to get an extra value after the table populated completely with server side json response and further use it for any purpose. Following is the modified code:</p>

```<code>manageTable = $('#manageTable').DataTable({
    'ajax': base_url + 'products/fetchProductData',
    'order': [],
    'drawCallback': function(response) {
      console.log(response.json.total_assets);
    },
});
</code>```

Title: Get extra value in datatable ajax call

Body:
I am filling data by below code

$(document).ready(function() {

manageTable = $('#manageTable').DataTable({
    'ajax': base_url + 'products/fetchProductData',
    'order': []
  });

here I want total assets as well means product_price * qty = assets of all product to show as summary like $100000 assets we have so I changed the controller ad added the new statistics obj and here is the value in assets keys.

and question is how can i show this extra value to this page.

image reference

Body:
You can use a DataTables function "drawCallback" to get an extra value after the table populated completely with server side json response and further use it for any purpose. Following is the modified code:

manageTable = $('#manageTable').DataTable({
    'ajax': base_url + 'products/fetchProductData',
    'order': [],
    'drawCallback': function(response) {
      console.log(response.json.total_assets);
    },
});


问:
How do i load all images before rendering the page?
So i have a preloader that works, i just have some problems with my image component itself.
My image component below in my theory should after the first render get all of my image tags used in my project.

Then when the image event onLoad is fired, it should update a state which is didLoad and set it to true. When the page is rerendered again because of the updated state, it should check if didLoad is true, if it's true it should execute the useEffect inside the condition once and add 1 to the amount loaded.

And then i check if images is higher than 0, and images is equal to images loaded then remove preloader.

Obviously something is wrong since i can't get it to work, it needs to work with all images not one at a time because it's not a lazyload for the image itself, but the preloader for the whole page.

Ignore preload: false it's for when the preloader is removed, then it should play page animations.

/** @jsx jsx */
import React, { useContext, useEffect, useState } from "react";
import { css, jsx } from "@emotion/core";
import preloadContext from "../../context/preload.context";

const Img = ({ src, alt }) => {
  const [didLoad, setLoad] = useState(false);
  const [preload, setPreload] = useContext(preloadContext);
  const imgStyle = css`
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
  `;

  useEffect(() => {
    setPreload({
      amount: preload.amount++,
      preload: preload.preload,
      isLoaded: preload.isLoaded,
    });
  }, []);

  if (didLoad === true) {
    useEffect(() => {
      setPreload({
        amount: preload.amount,
        preload: preload.preload,
        isLoaded: preload.isLoaded++,
      });
    }, []);
  }

  return (
     {
        setLoad(true);
      }}
      css={imgStyle}
      alt={alt}
      onDragStart={(e) => e.preventDefault()}
    />
  );
};

export default Img;

```

答:
The answer is You can and You cannot.

We can : if you're trying to hold rendering of a certain component until an  (Outside of this component is loaded)

We cannot : If you're trying to track loading of  which is INSIDE of a not rendered component. In this case Image won't load until we render it's parent component.

For the first option here's how you can do it:

```<code>constructor(props) {
    super(props);
    this.state = { loaded: 0 };
    this.handleImageLoaded = this.handleImageLoaded.bind(this);
    this.image = React.createRef();
}

componentDidMount() {
    const img = this.image.current;
    if (img && img.complete) {
        this.handleImageLoaded(10); // 100 / Number of images to track
    }
}

handleImageLoaded(loadIncrement) {
    if (!this.state.loaded)
        this.setState({ loaded: loadIncrement });
}

render() {
    return (
        <div>
             <img src='image.jpg' ref={this.image} onLoad={this.handleImageLoaded} />
             {this.state.loaded >= 100 && <MyComponent />}
        </div>
    );
}
</code>```

As mentioned in the comment you must divide 100 to number of images you wish to track and then one the image is loaded it will add the loading percentage to the parent state. One the loaded state reach 100 or above it will render <MyComponent />

Body:
The answer is You can and You cannot.

We can : if you're trying to hold rendering of a certain component until an <img /> (Outside of this component is loaded)

We cannot : If you're trying to track loading of <img /> which is INSIDE of a not rendered component. In this case Image won't load until we render it's parent component.

For the first option here's how you can do it:

constructor(props) {
    super(props);
    this.state = { loaded: 0 };
    this.handleImageLoaded = this.handleImageLoaded.bind(this);
    this.image = React.createRef();
}

componentDidMount() {
    const img = this.image.current;
    if (img && img.complete) {
        this.handleImageLoaded(10); // 100 / Number of images to track
    }
}

handleImageLoaded(loadIncrement) {
    if (!this.state.loaded)
        this.setState({ loaded: loadIncrement });
}

render() {
    return (
        <div>
             <img src='image.jpg' ref={this.image} onLoad={this.handleImageLoaded} />
             {this.state.loaded >= 100 && <MyComponent />}
        </div>
    );
}

As mentioned in the comment you must divide 100 to number of images you wish to track and then one the image is loaded it will add the loading percentage to the parent state. One the loaded state reach 100 or above it will render <MyComponent />


问:
JavaScript removeChild input from the dom
I'm trying to delete the form input posted onto the DOM, but the removeChild code isn't functioning, When inspecting the console I will be given an error which is: materialize.min.js:6 Uncaught TypeError: Cannot read property 'M_Modal' of null at HTMLBodyElement.value (materialize.min.js:6)

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  });

//Delete Exercises
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
if(e.target.className == 'delete'){
  const h6 = e.target.parentElement;
  h6.removeChild(e.target);
}
});

// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  const h6 = document.createElement('h6');

  // Add Content
  h6.textContent = value;

  // Append To Dom
  addExerciseDom.appendChild(h6);

});```

答:
You can do it like this

      // ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  });

//Delete Exercises
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
  const h6 = document.getElementsByTagName('h6')[0];
   h6.remove();
});

// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  const h6 = document.createElement('h6');

  // Add Content
  h6.textContent = value;

  // Append To Dom
  addExerciseDom.appendChild(h6);

  //Disable Btn
  disabledExersiceBtn.setAttribute('disabled', 'disabled');

});```


问:
React Native: RenderItem in FlatList. How to map array stored in local state?
I'm creating a small application with React Native that has a local SQLite database for storing images but having trouble rendering my array of images (fetched from the local database and stored in the local state).

Before I was rendered by mapping the data and that worked fine.

```<code>  state = {
    items:[when the user uses the app this array fills with images],
  };
</code>```

```<code><ScrollView>
        {items.map(({ id, value }) => (
          <TouchableOpacity onPress={this.deletePhoto}
            key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
          </TouchableOpacity>

        ))}
      </ScrollView>
    );
  }
</code>```

But now I would like to go a step further and render the data in a FlatList with my choice of formatting (a grid). Although I can get the FlatList to render the number of images within the array, I can't get the actual image to show. I'm not sure how to pass the data successfully?

```<code>  renderItem = ({ id, value }) => {
  const { items } = this.state;
  if (items.empty === true) {
    return <View style={[styles.item, styles.itemInvisible]} />;
  }
  return (
    <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
    </TouchableOpacity>
  );
  };
</code>```

For context, this is the creation of the 'items' SQL Table with the 'id' and 'value' attributes:

```<code>componentDidMount() {
    db.transaction(tx => {
      tx.executeSql(
        'create table if not exists items (id integer primary key not null, value text);'
      );
    });
  }
</code>```

I guess the question is, how do I pass/access the attributes of the items array into a functional component?

Update:

https://ibb.co/hMY1qBy (What I'm getting - e.g DB Entry creating a View but no image rendering)
https://ibb.co/RN4rqyK (What I'm getting from the answer below)

答:
The flatlist renderItem prop gets a argument with multiple properties the main ones will be item and index which are commonly used to access the item in of the row you can use item like below</p>

```<code><FlatList
        data={items}
        renderItem={({ item }) => (
          <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={item.id}>
            <Image source={{ uri: item.value }} style={{ width: null, height: 400 }} />
    </TouchableOpacity>
        )}
        keyExtractor={item => item.id}
      />
</code>```

Body:
I'm creating a small application with React Native that has a local SQLite database for storing images but having trouble rendering my array of images (fetched from the local database and stored in the local state).

Before I was rendered by mapping the data and that worked fine.

  state = {
    items:[when the user uses the app this array fills with images],
  };

<ScrollView>
        {items.map(({ id, value }) => (
          <TouchableOpacity onPress={this.deletePhoto}
            key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
          </TouchableOpacity>

        ))}
      </ScrollView>
    );
  }

But now I would like to go a step further and render the data in a FlatList with my choice of formatting (a grid). Although I can get the FlatList to render the number of images within the array, I can't get the actual image to show. I'm not sure how to pass the data successfully?

  renderItem = ({ id, value }) => {
  const { items } = this.state;
  if (items.empty === true) {
    return <View style={[styles.item, styles.itemInvisible]} />;
  }
  return (
    <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
    </TouchableOpacity>
  );
  };

For context, this is the creation of the 'items' SQL Table with the 'id' and 'value' attributes:

componentDidMount() {
    db.transaction(tx => {
      tx.executeSql(
        'create table if not exists items (id integer primary key not null, value text);'
      );
    });
  }

I guess the question is, how do I pass/access the attributes of the items array into a functional component?

Update:

https://ibb.co/hMY1qBy (What I'm getting - e.g DB Entry creating a View but no image rendering)
https://ibb.co/RN4rqyK (What I'm getting from the answer below)

Body:
The flatlist renderItem prop gets a argument with multiple properties the main ones will be item and index which are commonly used to access the item in of the row you can use item like below

<FlatList
        data={items}
        renderItem={({ item }) => (
          <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={item.id}>
            <Image source={{ uri: item.value }} style={{ width: null, height: 400 }} />
    </TouchableOpacity>
        )}
        keyExtractor={item => item.id}
      />