问:
Is there a better way to change button display in javascript/Vue?
After writing so many if else, I feel very tired. I'm using Vue. The following code are written in the script section of the vue file. I get a json from file, and then read the values in json, then set what button should be display based on employee level and on application status. Is there a better way to change the button display status in Vue?

```<code>if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")
    ) {
      this.pullDisplay = true;
    } else {
      this.pullDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.cancelDisplay = true;
    } else {
      this.cancelDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.saveDisplay = true;
    } else {
      this.saveDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.reviseDisplay = true;
    } else {
      this.reviseDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.sendDisplay = true;
    } else {
      this.sendDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking")
    ) {
      this.approvalDisplay = true;
    } else {
      this.approvalDisplay = false;
    };
</code>```

And also there are a few ones need three conditions:

```<code>    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].requestCategory ==
        "External Request" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus ==
        "Pending"
    ) {
      this.returnDisplay = true;
    } else {
      this.returnDisplay = false;
    }
</code>```

答:
If you use a property often it makes sense to introduce a local variable for it to clean things up:

```<code> const { employeeLevel, detail: { [this.detailId]: { currentStatus }}} = his.GLOBAL2.jsonForGlobal;
</code>```

Secondly you don't need the if / else, you can just assign the boolean:

```<code>  this.pullDisplay = (
     employeeLevel == "1" && ["Checking", "Pending", "Approved"].includes(currentStatus) ||
     employeeLevel == "2" && ["Pending", "Approved"].includes(currentStatus) ||
     employeeLevel == "3" && currentStatus == "Approved"
)
</code>```

Body:
After writing so many if else, I feel very tired. I'm using Vue. The following code are written in the script section of the vue file. I get a json from file, and then read the values in json, then set what button should be display based on employee level and on application status. Is there a better way to change the button display status in Vue?

if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")
    ) {
      this.pullDisplay = true;
    } else {
      this.pullDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.cancelDisplay = true;
    } else {
      this.cancelDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.saveDisplay = true;
    } else {
      this.saveDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.reviseDisplay = true;
    } else {
      this.reviseDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.sendDisplay = true;
    } else {
      this.sendDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking")
    ) {
      this.approvalDisplay = true;
    } else {
      this.approvalDisplay = false;
    };

And also there are a few ones need three conditions:

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].requestCategory ==
        "External Request" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus ==
        "Pending"
    ) {
      this.returnDisplay = true;
    } else {
      this.returnDisplay = false;
    }

Body:
If you use a property often it makes sense to introduce a local variable for it to clean things up:

 const { employeeLevel, detail: { [this.detailId]: { currentStatus }}} = his.GLOBAL2.jsonForGlobal;

Secondly you don't need the if / else, you can just assign the boolean:

  this.pullDisplay = (
     employeeLevel == "1" && ["Checking", "Pending", "Approved"].includes(currentStatus) ||
     employeeLevel == "2" && ["Pending", "Approved"].includes(currentStatus) ||
     employeeLevel == "3" && currentStatus == "Approved"
)


来源: stackexchange

问:
How to read .csv file in Perl to get required fields only, perform some operation and write back the results to same file?
I have a CSV file which contains IP, Alive fields like below:

```<code>ip, alive
127.0.0.1, Yes
127.0.0.2, No
</code>```

I want to ping each IP and if the ping is reachable then I need to put Yes in front of that IP in same CSV file.

I'm trying with below code, but stuck at reading and writing the same CSV file.

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
use Data::Dumper;

my $file = 'servers.csv';
my @filedata;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);
    push @filedata, \@fields;
}
print Dumper(@filedata);

my $p = Net::Ping->new();

if ($p->ping('127.0.0.1'))
{
   print "\nYes\n";
}
</code>```

My code for ping and reading file is working fine but I'm not much sure about loop through the data read from file and then ping and store the result back to CSV file.

Any help will be highly appreciated.

答:
I think this does what you want:</p>

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
use Data::Dumper;
use File::Copy;

my $file = 'servers.csv';
my $fileOut = 'serversOut.csv';

my @filedata;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
open(my $fhOut, '>', $fileOut) or die "Can't read file '$fileOut' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);

    my $p = Net::Ping->new();
    if($fields[0] eq 'ip') {
        print "Header $fields[0]\n";
        print $fhOut 'ping, ' . $line . "\n";
        next;
    }
    if ($p->ping($fields[0])) {
        print "Pinging $fields[0] - yes\n";
        print $fhOut 'Yes, ' . $line . "\n";
    }
    else {
        print "Pinging $fields[0] - no\n";
        print $fhOut 'No, ' . $line . "\n";
    }
}
close $fh;
close $fhOut;

move($fileOut, $file) or die "Can't move '$fileOut' file '$file' [$!]\n";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a CSV file which contains IP, Alive fields like below:

ip, alive
127.0.0.1, Yes
127.0.0.2, No

I want to ping each IP and if the ping is reachable then I need to put Yes in front of that IP in same CSV file.

I'm trying with below code, but stuck at reading and writing the same CSV file.

#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
use Data::Dumper;

my $file = 'servers.csv';
my @filedata;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);
    push @filedata, \@fields;
}
print Dumper(@filedata);

my $p = Net::Ping->new();

if ($p->ping('127.0.0.1'))
{
   print "\nYes\n";
}

My code for ping and reading file is working fine but I'm not much sure about loop through the data read from file and then ping and store the result back to CSV file.

Any help will be highly appreciated.

Body:
I think this does what you want:

#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
use Data::Dumper;
use File::Copy;

my $file = 'servers.csv';
my $fileOut = 'serversOut.csv';

my @filedata;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
open(my $fhOut, '>', $fileOut) or die "Can't read file '$fileOut' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);

    my $p = Net::Ping->new();
    if($fields[0] eq 'ip') {
        print "Header $fields[0]\n";
        print $fhOut 'ping, ' . $line . "\n";
        next;
    }
    if ($p->ping($fields[0])) {
        print "Pinging $fields[0] - yes\n";
        print $fhOut 'Yes, ' . $line . "\n";
    }
    else {
        print "Pinging $fields[0] - no\n";
        print $fhOut 'No, ' . $line . "\n";
    }
}
close $fh;
close $fhOut;

move($fileOut, $file) or die "Can't move '$fileOut' file '$file' [$!]\n";


Title: How to search list elements in a data frame?

Body:
I have a list dates with dates as string objects with all dates from 2003-01-01 to 2017-06-30:

['2003-01-01', '2003-01-02', '2003-01-03', '2003-01-04', '2003-01-05', '2003-01-06', '2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10', '2003-01-11', '2003-01-12', '2003-01-13', '2003-01-14', '2003-01-15', '2003-01-16', '2003-01-17', '2003-01-18', '2003-01-19', '2003-01-20', '2003-01-21',...]

And I have a dataframe with date time objects:

0       2013-01-09 09:07:49
1       2013-01-09 09:16:25
2       2013-01-09 11:14:28
3       2013-01-09 11:25:51
4       2013-01-09 11:25:51
5       2013-01-09 11:33:35
6       2013-01-09 11:35:31
7       2013-01-09 18:11:03
8       2013-03-13 21:04:58
9       2013-03-13 21:05:57
10      2013-03-15 14:07:27
11      2013-03-26 21:53:35
12      2013-03-26 22:19:20
13      2013-04-09 14:21:48
14      2013-04-09 14:22:29
15      2013-04-09 14:22:45
16      2013-04-22 12:10:47
...

Then I want to check if the dates in the list dates exist in the dataframe. So I want to do something like this:

df = pd.read_csv("blabla.csv")
df['time'] = pd.to_datetime(df['time'])
for j in dates:
  if j in df['time']:
       return(yes)

How can I compare a string object with a datetime object in a dataframe?

This is my full code:

dates=[]
start = date(2003, 1, 1)
end = date(2017, 6, 30)

delta = end - start

for i in range(delta.days + 1):
    newdate = start + timedelta(days=i)
    dates.append(newdate.strftime("%Y-%m-%d"))

df = pd.read_csv("blabla.csv",parse_dates=True)
df['time'] = pd.to_datetime(df['time'])

Body:
First we convert your time column to datetime, so we can acces solely the dates with Series.dt.dates. When we extracted the date from your datetime we convert it to string so we can compare it to your list.

Finally we use the isin method to create your new column as an indicator.

df['Time'] = pd.to_datetime(df['Time'])

df['Indicator'] = df['Time'].dt.date.astype(str).isin(dates)

                  Time  Indicator
0  2013-01-09 09:07:49      False
1  2013-01-09 09:16:25      False
2  2013-01-09 11:14:28      False
3  2013-01-09 11:25:51      False
4  2013-01-09 11:25:51      False
5  2013-01-09 11:33:35      False
6  2013-01-09 11:35:31      False
7  2013-01-09 18:11:03      False
8  2013-03-13 21:04:58      False
9  2013-03-13 21:05:57      False
10 2013-03-15 14:07:27      False
11 2013-03-26 21:53:35      False
12 2013-03-26 22:19:20      False
13 2013-04-09 14:21:48      False
14 2013-04-09 14:22:29      False
15 2013-04-09 14:22:45      False
16 2013-04-22 12:10:47      False

Note: your list is not a very good example, since none of the dates exist in your dataframe, that's why it returns all False.

If I use a list which has some date of your dataframe, it will look like the following:

dates = ['2013-01-09', '2013-02-09', '2013-03-26']
df['Indicator'] = df['Time'].dt.date.astype(str).isin(dates)

                  Time  Indicator
0  2013-01-09 09:07:49       True
1  2013-01-09 09:16:25       True
2  2013-01-09 11:14:28       True
3  2013-01-09 11:25:51       True
4  2013-01-09 11:25:51       True
5  2013-01-09 11:33:35       True
6  2013-01-09 11:35:31       True
7  2013-01-09 18:11:03       True
8  2013-03-13 21:04:58      False
9  2013-03-13 21:05:57      False
10 2013-03-15 14:07:27      False
11 2013-03-26 21:53:35       True
12 2013-03-26 22:19:20       True
13 2013-04-09 14:21:48      False
14 2013-04-09 14:22:29      False
15 2013-04-09 14:22:45      False
16 2013-04-22 12:10:47      False

Extensive information about isin: link


问:
Flow inject "arbitrary" properties type annotation ('inject' from mobx-react)
I am using flow types with mobx-react as provider for stores.  mobx-react provides the store dat using a utility function that creates HOCs:

inject('a', 'b' ....) returns a function That takes a react component and returns a component with properties 'a' and 'b' set.

ie:

```<code>type PropTy = {
    eventStore: EventStore; //or well somewhere else set
}

inject('eventStore')(class EventView extends React.Component<PropTy>) {
    render() {
        return <div>this.props.eventStore.length</div>
    }
}
</code>```

I understand that this cannot be 100% safe: there is no way to know for sure the type "injected" (via a string) is the actual type. But for now I wish to ignore that part. I wish to focus on using said components. -- Where I use this component flow "complains" that I haven't set all required properties. (Due to me not setting eventStore explicitly.

So for the type I tried the following:

```<code>inject: <Config: {}>(...args: Array<string>) =>
    ((React.AbstractComponent<Config>) =>
        React.AbstractComponent<$Diff<Config, args>>
    ),
</code>```

However this complains with flow cannot resolve args at the inner function. - How would I annotate this?

答:
This is what I could come up with:

```<code>import * as React from 'react';

declare function inject<Config: {}, InjectedConfig: {}>(
  ...args: Array<$Keys<InjectedConfig>>
): (React.AbstractComponent<Config> => React.AbstractComponent<$Diff<Config, InjectedConfig>>);

type FooProps = { a: number, b: string };
function Foo({ a, b }: FooProps) {
  return a + b;
}

type InjectedProps = { a: number };
const injectA = inject<FooProps, InjectedProps>('a');
const injectB = inject<FooProps, InjectedProps>('b'); // error

const Bar = injectA(Foo);

function App() {
  return (
    <>
      <Foo a={1} b="hi" />
      <Bar b="bye" />
      <Bar b={1} /> // error
    </>
  );
}
</code>```

Try Flow

I noticed that if you do not pass in InjectedProps to inject, Flow will not always infer the right thing. So I would recommend always declaring what InjectedProps is to ensure that Flow correctly validates args and the JSX parameters.

Try Flow example without InjectedProps.

Body:
I am using flow types with mobx-react as provider for stores.  mobx-react provides the store dat using a utility function that creates HOCs:

inject('a', 'b' ....) returns a function That takes a react component and returns a component with properties 'a' and 'b' set.

ie:

type PropTy = {
    eventStore: EventStore; //or well somewhere else set
}

inject('eventStore')(class EventView extends React.Component<PropTy>) {
    render() {
        return
this.props.eventStore.length

    }
}

I understand that this cannot be 100% safe: there is no way to know for sure the type "injected" (via a string) is the actual type. But for now I wish to ignore that part. I wish to focus on using said components. -- Where I use this component flow "complains" that I haven't set all required properties. (Due to me not setting eventStore explicitly.

So for the type I tried the following:

inject: <Config: {}>(...args: Array<string>) =>
    ((React.AbstractComponent<Config>) =>
        React.AbstractComponent<$Diff<Config, args>>
    ),

However this complains with flow cannot resolve args at the inner function. - How would I annotate this?

Body:
This is what I could come up with:

import * as React from 'react';

declare function inject<Config: {}, InjectedConfig: {}>(
  ...args: Array<$Keys<InjectedConfig>>
): (React.AbstractComponent<Config> => React.AbstractComponent<$Diff<Config, InjectedConfig>>);

type FooProps = { a: number, b: string };
function Foo({ a, b }: FooProps) {
  return a + b;
}

type InjectedProps = { a: number };
const injectA = inject<FooProps, InjectedProps>('a');
const injectB = inject<FooProps, InjectedProps>('b'); // error

const Bar = injectA(Foo);

function App() {
  return (
    <>
      <Foo a={1} b="hi" />
      <Bar b="bye" />
      <Bar b={1} /> // error
    </>
  );
}

<a href="https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdAJlrgDbKVwECuAdvsAi84wXgCsWMADwBhIQWABzAFxwA3gF8ANHACS4yVkZzeCleo0A+ABR04cAHROOi1KoCCUKMgCeUgCQA0lg+qFL6EvhGJmaWlnQAlKrW2HgwDu4ARqgw3vhy4EJYvNIxSpZwALwVqfgZ2blpBZC8xdL+ACLABASy8ko6EYbG-YpxCfR0MD5gWHAAYhAQAArEYOiV6iiqvNwgmVhQOpmqOVCiinAa9Dz8MILCixDWaijHV6pPqxDrCep2cEoMG4UGEyDgAGo4Jl6BoGNNZnoDFFGN91lUtsgdnsDlArvRcEIciJkTB3BjRJFpF81qhBqSjGjUDYyMgyBM6ITeMTKZIAEIU0lSGk-OlIqmM2kszLsmhwAD08rgh2IUAYXOJfI4gqp7msTw5dFuAiEcHcYDA1j+agBQJBwls9nsUniTqdwqWKEqagAjBpoZUAEQAC2AgYVrrdcCkWrxmSDmR8WHD8sjbpj2vjvv9qYBztz9g5cLoQA" rel="nofollow noreferrer">Try Flow

I noticed that if you do not pass in InjectedProps to inject, Flow will not always infer the right thing. So I would recommend always declaring what InjectedProps is to ensure that Flow correctly validates args and the JSX parameters.

<a href="https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdAJlrgDbKVwECuAdvsAi84wXgCsWMADwBhIQWABzAFxwA3gF8ANHACS4yVkZzeCleo0A+ABR04cAHROOi1KoCCUKMgCeUgCQA0lg+qFL6EvhGJmaWlnQAlKrW2HgwDu4ARqgw3vhy4EJYvNIxSpZwALwVqfgZ2blpBZC8xdL+ACLABASy8ko6EYbG-YpxCfR0MD5gWHAAYhAQAArEYOiV6iiqvNwgmVhQOpmqOVCiinAa9Dz8MILCixDWaijHV6pPqxDrCep2cEoMG4UGEyDgAGo4Jl6BoGLghDkRAZ8O4qsjIjBrGRkGQJnQEbwkaJMQAhdEkyTYzJ4mhwAD09Lgh2IUHhiPgpI4FJRMHc1ie+LotwEQjg7jAYGsfzUAKBIOEtns9ik8WVyqkTxQlTUAEYNNDKgAiAAWwCNDLV6rgUi5UENRsyPiwFvpVvVtu5mR1+stAJVboB+LhdCAA" rel="nofollow noreferrer">Try Flow example without InjectedProps.


问:
I am not able to place a picture in React Native
I am trying to make an app in react native and am starting to at least place an image as the screen when you click on the app.

The problem is that the app is unable to find the image or the javascript file that I call. I tried to change the location of the files and it seems to not be doing anything.

Here is the code for the Start Screen file

```<code>    import React, {Component} from 'react';
import {Image} from 'react-native';

const StartScreen = () => (
    <Image source = {require('./src/assets/images/StartScreen.png')} />
)

export default StartScreen
</code>```

Here is the code for the App.js file

```<code>import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import StartScreen from './src/screens/StartScreen'

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View>
         <StartScreen />
      </View>
    );
  }
}
</code>```

I should be getting the picture but am instead getting told that the picture or the file do not exist. The App.js file is in the top level of the folder, while the picture and StartScreen.js are in a src folder.

答:
It sounds like your problem lies in your folder structure & the path you're using to require your image.

From what I can gather, your StartScreen.js file is in a screens folder (which is in src), and your image is in an assets folder (which is also in src).

So in your StartScreen component your relative path for your image is wrong. Take a look here for an explanation of how relative paths work.

Try the below:

<Image source = {require('../assets/images/StartScreen.png')} />

Body:
I am trying to make an app in react native and am starting to at least place an image as the screen when you click on the app.

The problem is that the app is unable to find the image or the javascript file that I call. I tried to change the location of the files and it seems to not be doing anything.

Here is the code for the Start Screen file

    import React, {Component} from 'react';
import {Image} from 'react-native';

const StartScreen = () => (
    <Image source = {require('./src/assets/images/StartScreen.png')} />
)

export default StartScreen

Here is the code for the App.js file

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import StartScreen from './src/screens/StartScreen'

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View>
         <StartScreen />
      </View>
    );
  }
}

I should be getting the picture but am instead getting told that the picture or the file do not exist. The App.js file is in the top level of the folder, while the picture and StartScreen.js are in a src folder.


问:
How to fix "ERROR: Failed to build gem native extension." when installing eventmachine on macOS Mojave
I am a novice with ruby and the command line.

Ruby -v: ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]

Mac: Mojave 10.14.2

I am trying to open my Jekyll blog on my localhost, something which hasn't given me issues previously. However I ran

```<code>bundle exec jekyll serve
</code>```

and get this error:

```<code>Could not find eventmachine-1.2.7 in any of the sources
Run `bundle install` to install missing gems.
</code>```

As suggested, I then run

```<code>bundle install
</code>```

and get this error:

```<code>    Ignoring ffi-1.9.25 because its extensions are not built.  Try: gem pristine ffi --version 1.9.25
Ignoring http_parser.rb-0.6.0 because its extensions are not built.  Try: gem pristine http_parser.rb --version 0.6.0
Fetching gem metadata from https://rubygems.org/...........
Using rake 10.5.0
Using public_suffix 3.0.3
Using addressable 2.5.2
Using bundler 2.0.1
Using colorator 1.1.0
Using concurrent-ruby 1.0.5
Fetching eventmachine 1.2.7
Installing eventmachine 1.2.7 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/name/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/gems/eventmachine-1.2.7/ext
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby -r ./siteconf20190212-57509-l19d0i.rb extconf.rb
--with-cppflags=-I/usr/local/opt/openssl/include
checking for main() in -lcrypto... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/$(RUBY_BASE_NAME)
    --with-ssl-dir
    --without-ssl-dir
    --with-ssl-include
    --without-ssl-include=${ssl-dir}/include
    --with-ssl-lib
    --without-ssl-lib=${ssl-dir}/lib
    --with-openssl-config
    --without-openssl-config
    --with-pkg-config
    --without-pkg-config
    --with-cryptolib
    --without-cryptolib
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to
generate an executable file. (RuntimeError)
You have to install development tools first.
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:535:in `block in try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/tmpdir.rb:89:in `mktmpdir'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:532:in `try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:556:in `try_link'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:765:in `try_func'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:997:in `block in have_library'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:346:in `postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:992:in `have_library'
    from extconf.rb:8:in `block in check_libs'
    from extconf.rb:8:in `each'
    from extconf.rb:8:in `all?'
    from extconf.rb:8:in `check_libs'
    from extconf.rb:95:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/Users/name/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-18/2.3.0/eventmachine-1.2.7/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in
/Users/nbame/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/gems/eventmachine-1.2.7 for inspection.
Results logged to
/Users/name/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-18/2.3.0/eventmachine-1.2.7/gem_make.out

An error occurred while installing eventmachine (1.2.7), and Bundler cannot continue.
Make sure that `gem install eventmachine -v '1.2.7' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  jekyll was resolved to 3.8.3, which depends on
    em-websocket was resolved to 0.5.1, which depends on
      eventmachine
</code>```

I have tried:

Using gem install eventmachine -v '1.2.7' --source 'https://rubygems.org/' which gives me the "ERROR: Failed to build gem native extension."

brew install coreutils as recommended here

Every answer to this question

The answers here relating to Mojave and gem update failing

gem pristine ffi --version 1.9.25 because it suggested so in the error message

My mkmf.log log is below

```<code>"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/universal-darwin18 -I/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0 -I. -I/usr/local/opt/openssl/include  -g -Os -pipe -DHAVE_GCC_ATOMIC_BUILTINS conftest.c  -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib -L.     -lruby.2.3.0  -lpthread -ldl -lobjc "
In file included from conftest.c:1:
In file included from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby.h:33:
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby/ruby.h:24:10: fatal error: 'ruby/config.h' file not found
#include "ruby/config.h"
         ^~~~~~~~~~~~~~~
1 error generated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

"pkg-config --exists openssl"
package configuration for openssl is not found
</code>```

答:
I've had luck installing libffi with Homebrew, then using the recommended build flags:

```<code>$ brew install libffi
==> Downloading https://homebrew.bintray.com/bottles/libffi-3.2.1.mojave.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libffi-3.2.1.mojave.bottle.tar.gz
==> Caveats
libffi is keg-only, which means it was not symlinked into /usr/local,
because some formulae require a newer version of libffi.

For compilers to find libffi you may need to set:
  export LDFLAGS="-L/usr/local/opt/libffi/lib"

For pkg-config to find libffi you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig"
</code>```

```<code>$ LDFLAGS="-L/usr/local/opt/libffi/lib" PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig" bundle install
</code>```

I have lots of projects that use FFI, but rather than exporting those variables (since they are global), I added an alias to my Bash profile so I can easily set them on the fly:

```<code># ~/.bash_profile
alias ffi='LDFLAGS="-L/usr/local/opt/libffi/lib" PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig"'
</code>```

Now whenever I have a project that uses FFI, I can install the gem like this:

```<code>$ ffi bundle install
</code>```

Body:
I am a novice with ruby and the command line.

Ruby -v: ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]

Mac: Mojave 10.14.2

I am trying to open my Jekyll blog on my localhost, something which hasn't given me issues previously. However I ran

bundle exec jekyll serve

and get this error:

Could not find eventmachine-1.2.7 in any of the sources
Run `bundle install` to install missing gems.

As suggested, I then run

bundle install

and get this error:

    Ignoring ffi-1.9.25 because its extensions are not built.  Try: gem pristine ffi --version 1.9.25
Ignoring http_parser.rb-0.6.0 because its extensions are not built.  Try: gem pristine http_parser.rb --version 0.6.0
Fetching gem metadata from https://rubygems.org/...........
Using rake 10.5.0
Using public_suffix 3.0.3
Using addressable 2.5.2
Using bundler 2.0.1
Using colorator 1.1.0
Using concurrent-ruby 1.0.5
Fetching eventmachine 1.2.7
Installing eventmachine 1.2.7 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/name/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/gems/eventmachine-1.2.7/ext
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby -r ./siteconf20190212-57509-l19d0i.rb extconf.rb
--with-cppflags=-I/usr/local/opt/openssl/include
checking for main() in -lcrypto... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/$(RUBY_BASE_NAME)
    --with-ssl-dir
    --without-ssl-dir
    --with-ssl-include
    --without-ssl-include=${ssl-dir}/include
    --with-ssl-lib
    --without-ssl-lib=${ssl-dir}/lib
    --with-openssl-config
    --without-openssl-config
    --with-pkg-config
    --without-pkg-config
    --with-cryptolib
    --without-cryptolib
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to
generate an executable file. (RuntimeError)
You have to install development tools first.
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:535:in `block in try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/tmpdir.rb:89:in `mktmpdir'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:532:in `try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:556:in `try_link'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:765:in `try_func'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:997:in `block in have_library'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:346:in `postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/mkmf.rb:992:in `have_library'
    from extconf.rb:8:in `block in check_libs'
    from extconf.rb:8:in `each'
    from extconf.rb:8:in `all?'
    from extconf.rb:8:in `check_libs'
    from extconf.rb:95:in `'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/Users/name/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-18/2.3.0/eventmachine-1.2.7/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in
/Users/nbame/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/gems/eventmachine-1.2.7 for inspection.
Results logged to
/Users/name/Desktop/GitHub/blog/vendor/bundle/ruby/2.3.0/extensions/universal-darwin-18/2.3.0/eventmachine-1.2.7/gem_make.out

An error occurred while installing eventmachine (1.2.7), and Bundler cannot continue.
Make sure that `gem install eventmachine -v '1.2.7' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  jekyll was resolved to 3.8.3, which depends on
    em-websocket was resolved to 0.5.1, which depends on
      eventmachine

I have tried:

Using gem install eventmachine -v '1.2.7' --source 'https://rubygems.org/' which gives me the "ERROR: Failed to build gem native extension."

brew install coreutils as recommended here

Every answer to this question

The answers here relating to Mojave and gem update failing

gem pristine ffi --version 1.9.25 because it suggested so in the error message

My mkmf.log log is below

"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/universal-darwin18 -I/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0 -I. -I/usr/local/opt/openssl/include  -g -Os -pipe -DHAVE_GCC_ATOMIC_BUILTINS conftest.c  -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib -L.     -lruby.2.3.0  -lpthread -ldl -lobjc "
In file included from conftest.c:1:
In file included from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby.h:33:
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby/ruby.h:24:10: fatal error: 'ruby/config.h' file not found
#include "ruby/config.h"
         ^~~~~~~~~~~~~~~
1 error generated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

"pkg-config --exists openssl"
package configuration for openssl is not found

Body:
I've had luck installing libffi with Homebrew, then using the recommended build flags:

$ brew install libffi
==> Downloading https://homebrew.bintray.com/bottles/libffi-3.2.1.mojave.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libffi-3.2.1.mojave.bottle.tar.gz
==> Caveats
libffi is keg-only, which means it was not symlinked into /usr/local,
because some formulae require a newer version of libffi.

For compilers to find libffi you may need to set:
  export LDFLAGS="-L/usr/local/opt/libffi/lib"

For pkg-config to find libffi you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig"

$ LDFLAGS="-L/usr/local/opt/libffi/lib" PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig" bundle install

I have lots of projects that use FFI, but rather than exporting those variables (since they are global), I added an alias to my Bash profile so I can easily set them on the fly:

# ~/.bash_profile
alias ffi='LDFLAGS="-L/usr/local/opt/libffi/lib" PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig"'

Now whenever I have a project that uses FFI, I can install the gem like this:

$ ffi bundle install


问:
N-Body CUDA optimization
I'm developing an N-body algorithm in CUDA and I would like to learn some tips and tricks for optimization.

I've managed to get 16384 bodies to run at 20Flops on an NVIDIA Geforce GTX 260, which has 27 Streaming Multiprocessors.

The KernelcomputeForces function is the slow poke taking about 95% of the time and I was wondering if there is anymore that I can do to optimize my code.

As far as I see, I've optimized for memory-space-locality and memory-writing. Somewhere in the CUDA docs, it says shared-memory is faster but I dont see how I can make use of that. I've divided the work in 16 blocks with 512 threads on each, but thats a bit fuzzy for me.

Please help and thanks for reading this.

```<code>n   is number of bodies

gm  is the gpu mass pointer

gpx is the gpu position x pointer

gpy is the gpu position y pointer

gpz is the gpu position z pointer

gfx is the gpu force x pointer

gfy is the gpu force y pointer

gfz is the gpu force z pointer
</code>```

The relevant kernel function

```<code>__global__ void KernelcomputeForces( unsigned int n, float* gm, float* gpx, float* gpy, float* gpz, float* gfx, float* gfy, float* gfz ){
    int tid = blockDim.x * blockIdx.x + threadIdx.x;
    int numThreads = blockDim.x * gridDim.x;

    float GRAVITY = 0.00001f;

    //compare all with all
    for( unsigned int ia=tid; ia<n; ia+=numThreads ){
        float lfx = 0.0f;
        float lfy = 0.0f;
        float lfz = 0.0f;

        for( unsigned int ib=0; ib<n; ib++ ){
            //compute distance
            float dx = ( gpx[ib] - gpx[ia]);
            float dy = ( gpy[ib] - gpy[ia] );
            float dz = ( gpz[ib] - gpz[ia] );
            //float distance = sqrt( dx*dx + dy*dy + dz*dz );
            float distanceSquared = dx*dx + dy*dy + dz*dz;

            //prevent slingshots and division by zero
            //distance += 0.1f;
            distanceSquared += 0.01f;

            //calculate gravitational magnitude between the bodies
            //float magnitude = GRAVITY * ( gm[ia] * gm[ib] ) / ( distance * distance * distance * distance );
            float magnitude = GRAVITY * ( gm[ia] * gm[ib] ) / ( distanceSquared );

            //calculate forces for the bodies
            //magnitude times direction
            lfx += magnitude * ( dx );
            lfy += magnitude * ( dy );
            lfz += magnitude * ( dz );
        }

        //stores local memory to global memory
        gfx[ia] = lfx;
        gfy[ia] = lfy;
        gfz[ia] = lfz;
    }
}

extern void GPUcomputeForces( unsigned int n, float* gm, float* gpx, float* gpy, float* gpz, float* gfx, float* gfy, float* gfz ){
    dim3 gridDim( 16, 1, 1 ); //specifys how many blocks in three possible dimensions
    dim3 blockDim( 512, 1, 1 ); //threads per block
    KernelcomputeForces<<<gridDim, blockDim>>>( n, gm, gpx, gpy, gpz, gfx, gfy, gfz );
}
</code>```

答:
Shared memory is going to be a useful optimization in this sort of kernel - it allows coalescing of the reads of particle positions and masses, which on a GT200 will be very important. I found this to be about twice as fast as your version (launched with your 16384 particles using a 128 blocks of 128 threads):

```<code>template<int blocksize>
__global__
void KernelcomputeForces1( unsigned int n1, float* gm, float* gpx,
                float* gpy, float* gpz, float* gfx, float* gfy, float* gfz )
{
    __shared__ float lgpx[blocksize], lgpy[blocksize],
               lgpz[blocksize], lgm[blocksize];

    const float GRAVITY = 0.00001f;

    //compare all with all
    float lfx = 0.0f, lfy = 0.0f, lfz = 0.0f;
    int ia = blockDim.x * blockIdx.x + threadIdx.x;
    float lgpx0 = gpx[ia], lgpy0 = gpy[ia],
          lgpz0 = gpz[ia], lgm0 = gm[ia];

    for( unsigned int ib=0; ib<n1; ib+=blocksize ){

        lgpx[threadIdx.x] = gpx[ib + threadIdx.x];
        lgpy[threadIdx.x] = gpy[ib + threadIdx.x];
        lgpz[threadIdx.x] = gpz[ib + threadIdx.x];
        lgm[threadIdx.x] = gm[ib + threadIdx.x];
        __syncthreads();

#pragma unroll
        for(unsigned int ic=0; ic<blocksize; ic++) {

            //compute distance
            float dx = ( lgpx[ic] - lgpx0 );
            float dy = ( lgpy[ic] - lgpy0 );
            float dz = ( lgpz[ic] - lgpz0 );
            float distanceSquared = dx*dx + dy*dy + dz*dz;

            //prevent slingshots and division by zero
            distanceSquared += 0.01f;

            //calculate gravitational magnitude between the bodies
            float magnitude = GRAVITY * ( lgm0 * lgm[ic] )
                    / ( distanceSquared );

            //calculate forces for the bodies
            //magnitude times direction
            lfx += magnitude * ( dx );
            lfy += magnitude * ( dy );
            lfz += magnitude * ( dz );
        }
        __syncthreads();
    }

    //stores local memory to global memory
    gfx[ia] = lfx;
    gfy[ia] = lfy;
    gfz[ia] = lfz;
}
</code>```

You would need to do something a little different for the number of particles which fall outside the nice multiple of block size, probably a second stanza which won't be unrolled. Watch the potential for warp divergence with the __syncthreads() calls, that can make the kernel hang if you are not careful.

ContentLicense: CC BY-SA 3.0

Title: N-Body CUDA optimization

Body:
I'm developing an N-body algorithm in CUDA and I would like to learn some tips and tricks for optimization.

I've managed to get 16384 bodies to run at 20Flops on an NVIDIA Geforce GTX 260, which has 27 Streaming Multiprocessors.

The KernelcomputeForces function is the slow poke taking about 95% of the time and I was wondering if there is anymore that I can do to optimize my code.

As far as I see, I've optimized for memory-space-locality and memory-writing. Somewhere in the CUDA docs, it says shared-memory is faster but I dont see how I can make use of that. I've divided the work in 16 blocks with 512 threads on each, but thats a bit fuzzy for me.

Please help and thanks for reading this.

n   is number of bodies

gm  is the gpu mass pointer

gpx is the gpu position x pointer

gpy is the gpu position y pointer

gpz is the gpu position z pointer

gfx is the gpu force x pointer

gfy is the gpu force y pointer

gfz is the gpu force z pointer

The relevant kernel function

__global__ void KernelcomputeForces( unsigned int n, float* gm, float* gpx, float* gpy, float* gpz, float* gfx, float* gfy, float* gfz ){
    int tid = blockDim.x * blockIdx.x + threadIdx.x;
    int numThreads = blockDim.x * gridDim.x;

    float GRAVITY = 0.00001f;

    //compare all with all
    for( unsigned int ia=tid; ia<n; ia+=numThreads ){
        float lfx = 0.0f;
        float lfy = 0.0f;
        float lfz = 0.0f;

        for( unsigned int ib=0; ib<n; ib++ ){
            //compute distance
            float dx = ( gpx[ib] - gpx[ia]);
            float dy = ( gpy[ib] - gpy[ia] );
            float dz = ( gpz[ib] - gpz[ia] );
            //float distance = sqrt( dx*dx + dy*dy + dz*dz );
            float distanceSquared = dx*dx + dy*dy + dz*dz;

            //prevent slingshots and division by zero
            //distance += 0.1f;
            distanceSquared += 0.01f;

            //calculate gravitational magnitude between the bodies
            //float magnitude = GRAVITY * ( gm[ia] * gm[ib] ) / ( distance * distance * distance * distance );
            float magnitude = GRAVITY * ( gm[ia] * gm[ib] ) / ( distanceSquared );

            //calculate forces for the bodies
            //magnitude times direction
            lfx += magnitude * ( dx );
            lfy += magnitude * ( dy );
            lfz += magnitude * ( dz );
        }

        //stores local memory to global memory
        gfx[ia] = lfx;
        gfy[ia] = lfy;
        gfz[ia] = lfz;
    }
}

extern void GPUcomputeForces( unsigned int n, float* gm, float* gpx, float* gpy, float* gpz, float* gfx, float* gfy, float* gfz ){
    dim3 gridDim( 16, 1, 1 ); //specifys how many blocks in three possible dimensions
    dim3 blockDim( 512, 1, 1 ); //threads per block
    KernelcomputeForces<<<gridDim, blockDim>>>( n, gm, gpx, gpy, gpz, gfx, gfy, gfz );
}

Body:
Shared memory is going to be a useful optimization in this sort of kernel - it allows coalescing of the reads of particle positions and masses, which on a GT200 will be very important. I found this to be about twice as fast as your version (launched with your 16384 particles using a 128 blocks of 128 threads):

template<int blocksize>
__global__
void KernelcomputeForces1( unsigned int n1, float* gm, float* gpx,
                float* gpy, float* gpz, float* gfx, float* gfy, float* gfz )
{
    __shared__ float lgpx[blocksize], lgpy[blocksize],
               lgpz[blocksize], lgm[blocksize];

    const float GRAVITY = 0.00001f;

    //compare all with all
    float lfx = 0.0f, lfy = 0.0f, lfz = 0.0f;
    int ia = blockDim.x * blockIdx.x + threadIdx.x;
    float lgpx0 = gpx[ia], lgpy0 = gpy[ia],
          lgpz0 = gpz[ia], lgm0 = gm[ia];

    for( unsigned int ib=0; ib<n1; ib+=blocksize ){

        lgpx[threadIdx.x] = gpx[ib + threadIdx.x];
        lgpy[threadIdx.x] = gpy[ib + threadIdx.x];
        lgpz[threadIdx.x] = gpz[ib + threadIdx.x];
        lgm[threadIdx.x] = gm[ib + threadIdx.x];
        __syncthreads();

#pragma unroll
        for(unsigned int ic=0; ic<blocksize; ic++) {

            //compute distance
            float dx = ( lgpx[ic] - lgpx0 );
            float dy = ( lgpy[ic] - lgpy0 );
            float dz = ( lgpz[ic] - lgpz0 );
            float distanceSquared = dx*dx + dy*dy + dz*dz;

            //prevent slingshots and division by zero
            distanceSquared += 0.01f;

            //calculate gravitational magnitude between the bodies
            float magnitude = GRAVITY * ( lgm0 * lgm[ic] )
                    / ( distanceSquared );

            //calculate forces for the bodies
            //magnitude times direction
            lfx += magnitude * ( dx );
            lfy += magnitude * ( dy );
            lfz += magnitude * ( dz );
        }
        __syncthreads();
    }

    //stores local memory to global memory
    gfx[ia] = lfx;
    gfy[ia] = lfy;
    gfz[ia] = lfz;
}

You would need to do something a little different for the number of particles which fall outside the nice multiple of block size, probably a second stanza which won't be unrolled. Watch the potential for warp divergence with the __syncthreads() calls, that can make the kernel hang if you are not careful.


问:
Auto Layout not properly handling iPhone X notch
I have implemented a pageViewIndicator to the top of my application using swift. I have constantly tested it on my personal iPhone, which has worked, but when using the iPhone X simulator, I have noticed that it disappears behind the notch, simply because I did not reference to place it within the safe area or the safe area is not properly configured yet. Here is the comparison:

It seems like an easy question, yet I currently have not found any proper support on how to handle this: the main suggestion is to adjust the safeAreaInsets, yet I do not understand how to apply this to the AutoLayout functionality. I have tried adding a topAnchor constraint to the pageController, yet would it even be possible editing this using basic arithmetic?

```<code>pageControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
</code>```

答:
I have the same issue in an app I'm currently upgrading. It has a column of buttons on the right side on the main screen. In landscape orientation with the notch on the right, the buttons are partially cut off. I don't want to move the buttons if I don't have to because that will significantly reduce the dimensions of a message area to the left of that, especially in Portrait mode.

I didn't see a constraint in Xcode corresponding to a "safe area" and didn't want to go into the rabbit hole that is dynamic positioning, so my solution was to restrict the orientations to Portrait and Landscape Right (which means notch on the left).

It would be great if we had per-device-type orientation restrictions, but not holding my breath for that.

Hoping in a couple of years, this ugly notch fad goes away.

Body:
I have implemented a pageViewIndicator to the top of my application using swift. I have constantly tested it on my personal iPhone, which has worked, but when using the iPhone X simulator, I have noticed that it disappears behind the notch, simply because I did not reference to place it within the safe area or the safe area is not properly configured yet. Here is the comparison:

It seems like an easy question, yet I currently have not found any proper support on how to handle this: the main suggestion is to adjust the safeAreaInsets, yet I do not understand how to apply this to the AutoLayout functionality. I have tried adding a topAnchor constraint to the pageController, yet would it even be possible editing this using basic arithmetic?

pageControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true


问:
how to make a sharepoint restful call from node
I'm new in node and I want to connect between sharepoint 2013 (on demand) and node.

I want to get list of items from sharepoint website.
Our users using smart cards to connect to our system (Active directory users) so I can't get their password.

I want to know if there is a way to connect sharepoint with node and what is the best way to do so.

Example of http call : http.get(http://servername/portal/_api/web/lists/getByTitle('dsfd')/items)

答:
I recommend you to use pnp/js because is specifically developed for SharePoint request and you can install it via npm i and use it easily.

If you don't want use pnp/js you can always launch manually a REST API request thank to fetch (doesn't work on IE) or axios.


问:
Check if key exists without touching disks
We're hitting IO limit with our Cassandra setup. I wonder if there is a way to check if certain key exists without touching disks. I'm aware of key cache but the memory usage is quite a lot for us. Also, I learned that Cassandra uses bloom filters for index scans. Is there a way to test key existence with the internal setup of Cassandra?</p>

答:
I don't know what you are talking about for index scans. The keycache if filled will tell you for certain if a key exists on disk though.

Each sstable has a bloom filter thats in memory and some metadata that can help but cannot guarantee it. The bloom filter will tell you for sure if it does not exist, but may give a false positive. There are stats for this you can check and you can set the false positive percentage goal. Also each sstable has a min/max token and min/max clustering key which if your key does not exist in it can also exclude it from being possible.

Unfortunately you cannot execute this without actually doing the read, so once it finds an sstable it will attempt to read from it. You can do a LIMIT 1 to at least minimize that though. You could also put in your application a cache of keys you know do or do not exist if your ok with it being potentially out of sync. And some mechanism to evict them when added or removed.


问:
How to extract an ID number from a URL string in SQL?
I am trying to extract an ID from a URL and running into some issues.  The URL's will look something like this:

http://www.website.com/news/view.aspx?id=95

http://www.website.com/news/view.aspx?id=20&ReturnURL=%2fnews%2fview.aspx%3fid%3d20

I am trying to return back the number following "?id=" and nothing after the number.  I will then convert it to an INT in reference to another table.  Any suggestions as how to do this properly?

答:
Here is an option that you can use when you want to find the value of any parameter value within a URL, it also supports parsing text values that contain a URL</p>

```<code>DECLARE @Param varchar(50) = 'event'
DECLARE @Data varchar(8000) = 'User Logged into  https://my.website.org/default.aspx?id=3066&event=49de&event=true from ip'

DECLARE @ParamIndex int = (select PatIndex('%'+@param+'=%', @Data)+LEN(@param)+1)
-- @ParamValueSubstring chops off everthing before the first instance of the parameter value
DECLARE @ParamValueSubstring varchar(8000) = SubString(@Data, @ParamIndex, 8000)

SELECT @ParamValueSubstring as ParamSubstring

DECLARE @SpaceIndex int = (SELECT CHARINDEX(' ', @ParamValueSubstring))-1
DECLARE @AmpIndex int = (SELECT CHARINDEX('&', @ParamValueSubstring))-1
DECLARE @valueLength int = -1

-- find first instance of ' ' or & after parameter value
IF @SpaceIndex = -1
  SET @valueLength = @AmpIndex
ELSE IF @AmpIndex = -1
  SET @valueLength = @SpaceIndex
ELSE IF @SpaceIndex < @AmpIndex
  SET @valueLength = @SpaceIndex
ELSE
  SET @valueLength = @AmpIndex

IF(@valueLength = -1) -- check to see if there was no space or '&' following the parameter value
BEGIN
   SET @valueLength = 8000
END

select Left(@ParamValueSubstring, @valueLength) as ParamValue

-- approach similar to idea function found here http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server/

</code>```

Body:
Here is an option that you can use when you want to find the value of any parameter value within a URL, it also supports parsing text values that contain a URL

DECLARE @Param varchar(50) = 'event'
DECLARE @Data varchar(8000) = 'User Logged into  https://my.website.org/default.aspx?id=3066&event=49de&event=true from ip'

DECLARE @ParamIndex int = (select PatIndex('%'+@param+'=%', @Data)+LEN(@param)+1)
-- @ParamValueSubstring chops off everthing before the first instance of the parameter value
DECLARE @ParamValueSubstring varchar(8000) = SubString(@Data, @ParamIndex, 8000)

SELECT @ParamValueSubstring as ParamSubstring

DECLARE @SpaceIndex int = (SELECT CHARINDEX(' ', @ParamValueSubstring))-1
DECLARE @AmpIndex int = (SELECT CHARINDEX('&', @ParamValueSubstring))-1
DECLARE @valueLength int = -1

-- find first instance of ' ' or & after parameter value
IF @SpaceIndex = -1
  SET @valueLength = @AmpIndex
ELSE IF @AmpIndex = -1
  SET @valueLength = @SpaceIndex
ELSE IF @SpaceIndex < @AmpIndex
  SET @valueLength = @SpaceIndex
ELSE
  SET @valueLength = @AmpIndex

IF(@valueLength = -1) -- check to see if there was no space or '&' following the parameter value
BEGIN
   SET @valueLength = 8000
END

select Left(@ParamValueSubstring, @valueLength) as ParamValue

-- approach similar to idea function found here http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server/


问:
XMLUnit for C++
Does anyone know if there exists something like XMLUnit for C++? I'm looking for an easy way to check nodes, values, etc in a XML output. We are using Google test in Visual Studio but I suppose any library that makes the work easier will be enough.

I'm using Xerces as an XML parser but XMLUnit (http://xmlunit.sourceforge.net/) has some features wrapped over the XML parser that are very useful for unit testing. For example, asserts using XPath expressions, functions to compare two "similar" XMLs, etc.

答: I'm currently using libxml++ for a personal project of mine.</p>

OwnerDisplayName: Jordi

LastEditorDisplayName: Jordi

Title: XMLUnit for C++

OwnerDisplayName: MighMoS

ContentLicense: CC BY-SA 2.5


问:
list indices must be integers or slices not str
I have a code like this,

```<code>def myfunction(json_dict):
     mylistsize = len((list(json_normalize(json_dict,'data')['title'])))-1
     print(mylistsize)
     data = [c for c in json_dict['data']][0]#This line when it is 0 or 1 or 2 works for me.
     df = pd.DataFrame()
     data_paragraphs = data['paragraphs']
</code>```

But when I change it to include all the elements of my array, to something like this -

```<code>data = [c for c in json_dict['data']][0:mylistsize]
</code>```

It gives me an error on this line -     data_paragraphs = data['paragraphs']

Kindly help me with this.

答: data is a list, from data = [c for c in json_dict['data']][0:mylistsize]. You access values in it like data[0]. To access json inside an item in the list, you do data[0]['paragraphs'].

Body:
I have a code like this,

def myfunction(json_dict):
     mylistsize = len((list(json_normalize(json_dict,'data')['title'])))-1
     print(mylistsize)
     data = [c for c in json_dict['data']][0]#This line when it is 0 or 1 or 2 works for me.
     df = pd.DataFrame()
     data_paragraphs = data['paragraphs']

But when I change it to include all the elements of my array, to something like this -

data = [c for c in json_dict['data']][0:mylistsize]

It gives me an error on this line -     data_paragraphs = data['paragraphs']

Kindly help me with this.


问:
Spring can not call Rest Endpoint get 404
I have setup a service with spring boot but I can't call my rest endpoint.

CODE:

```<code>@RestController
@RequestMapping("/route")
@SessionAttributes("session_userId")
public class RoutingController extends BaseController implements WebMvcConfigurer{
</code>```

Endpoint:

```<code>@RequestMapping("/users/web")
    public ModelAndView routeToUserInterfaceServiceWeb(HttpSession session,Device device) {
</code>```

The service runs on port 8000. So when I do in my browser:
"localhost:8000/route/users/web" I expect a any answer of the server. But all I get is a 404.

答:
Try removing the controller annotation:

```<code>@RequestMapping("/route")
</code>```

Keep the original annotation on the method:

```<code>@RequestMapping("/route/users/web")
</code>```

ModelAndView is a Spring MVC construction.  I would expect a REST service to return a ResponseEntity.

Body:
I have setup a service with spring boot but I can't call my rest endpoint.

CODE:

@RestController
@RequestMapping("/route")
@SessionAttributes("session_userId")
public class RoutingController extends BaseController implements WebMvcConfigurer{

Endpoint:

@RequestMapping("/users/web")
    public ModelAndView routeToUserInterfaceServiceWeb(HttpSession session,Device device) {

The service runs on port 8000. So when I do in my browser:
"localhost:8000/route/users/web" I expect a any answer of the server. But all I get is a 404.

Body:
Try removing the controller annotation:

@RequestMapping("/route")

Keep the original annotation on the method:

@RequestMapping("/route/users/web")

ModelAndView is a Spring MVC construction.  I would expect a REST service to return a ResponseEntity.


问:
How do I count distinct values from same id?
How do I count distinct values from a column if there are some duplicates for each ID?

I've tried COUNT, DISTINCT, CASE and everything but I can't count distinct values for each ID. I have a table like this.

```<code>ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough
</code>```

I want to obtain something like this.

```<code>ID    Symptom
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough
</code>```

Or how do I obtain the total count? Like there are 5 distinct symtomps but not 11 symptoms (If I use DISTINCT I would obtain 4).

答:
You need distinct with select statement :

```<code>select distinct id, Symptom
from table t;
</code>```

If you need unique count then use it inside count() :

```<code>select id, count(distinct Symptom)
from table t
group by id;
</code>```

Body:
How do I count distinct values from a column if there are some duplicates for each ID?

I've tried COUNT, DISTINCT, CASE and everything but I can't count distinct values for each ID. I have a table like this.

ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough

I want to obtain something like this.

ID    Symptom
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough

Or how do I obtain the total count? Like there are 5 distinct symtomps but not 11 symptoms (If I use DISTINCT I would obtain 4).

Body:
You need distinct with select statement :

select distinct id, Symptom
from table t;

If you need unique count then use it inside count() :

select id, count(distinct Symptom)
from table t
group by id;


问:
inheritance from xmlrpclib.ServerProxy in python
Why this code doesn't work ?

```
#!/usr/bin/python2
from xmlrpclib import ServerProxy
class ServerProxy1(ServerProxy):
    def __str__(self):
        return str(self.__host)

proxy = ServerProxy1("http://workshop:58846/")
print proxy
```

Original_str_:

```
    def __repr__(self):
        return (
            "" %
            (self.__host, self.__handler)
            )

    __str__ = __repr__
```

Result:

```
  File "/usr/lib/python2.7/xmlrpclib.py", line 793, in close
    raise Fault(**self._stack[0])
xmlrpclib.Fault: :method "_ServerProxy1__host.__str__" is not supported'>
```

答:
The answer is hiding in this SO post

The member self.__host in class ServerProxy was declared using the double-underscore naming that's meant to indicate that it shouldn't be accessed by derived classes. To do this, the interpreter mangles its name internally in the form _className__memberName -- Python isn't C++, and treats that 'private' notation as a strong hint, not as an absolute prohibition.

When code is written with the double underscore prefix, you can access it like

```<code>class ServerProxy1(ServerProxy):
    def __str__(self):
        return str(self._ServerProxy__host)
</code>```

..but you shouldn't be surprised if a future version of the ServerProxy class changes its internal implementation and breaks your code.

Body:
Why this code doesn't work ?

#!/usr/bin/python2
from xmlrpclib import ServerProxy
class ServerProxy1(ServerProxy):
    def __str__(self):
        return str(self.__host)

proxy = ServerProxy1("http://workshop:58846/")
print proxy

Original_str_:

    def __repr__(self):
        return (
            "" %
            (self.__host, self.__handler)
            )

    __str__ = __repr__

Result:

  File "/usr/lib/python2.7/xmlrpclib.py", line 793, in close
    raise Fault(**self._stack[0])
xmlrpclib.Fault: :method "_ServerProxy1__host.__str__" is not supported'>

Body:
The answer is hiding in this SO post

The member self.__host in class ServerProxy was declared using the double-underscore naming that's meant to indicate that it shouldn't be accessed by derived classes. To do this, the interpreter mangles its name internally in the form _className__memberName -- Python isn't C++, and treats that 'private' notation as a strong hint, not as an absolute prohibition.

When code is written with the double underscore prefix, you can access it like

class ServerProxy1(ServerProxy):
    def __str__(self):
        return str(self._ServerProxy__host)

..but you shouldn't be surprised if a future version of the ServerProxy class changes its internal implementation and breaks your code.


问:
How to clear and show an error in more than one autcomplete component when an item is not selected from the suggested options
I created a stackBliz that is a smaller example of what I am trying to acheive, but if I can get it to work there. Then, I should be able to figure out the rest.

https://stackblitz.com/edit/angular-nkajg5

I want to clear or the set the value of the component to '' when the input entered by a user is not an item from the suggested items in the mat-autocomplete. Then, I also want to display a mat-error to them that "Value entered is NOT VALID please selected only from suggested values."

I got it to work by following two examples I found.
Clearing out the input

https://stackblitz.com/edit/autocomplete-force-selection-tests-w2fqww?file=app%2Fapp.component.html

Telling them an error message

https://stackblitz.com/edit/angular-kdym4u

However, I have three autocomplete components and it is causing issues when I try to use the method on all three components and call them from ngAfterViewInit. No error messages it just doesn't clear out the input or show the error message. So my function doesn't seem to be getting called. (to be honest not really sure what the subscription variable is used for in the code) I think it has to do something with the subscription and where I am calling it from the ngAfterViewInt(). I tested it out and only the first component works by itself. I tried the other two components by themeselves too and they don't work at all even when they are the only control being used. I have the three matAutocomplete in a tabGroup and the other two are in the second tab of the tabGroup.

My constructor with my form groups

```<code>  constructor(private dialogRecipient:MatDialog,private fb: FormBuilder, private dialogRef: MatDialogRef<UpdateTaskComponent>,private snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA){Enabled ,TaskName, TaskDescription,EmailSubject, EmailBody, tTaskTeam, PK_Task}, private service: TaskService ) {
      this.pk_Task = PK_Task;
      console.log(this.pk_Task)
      this.form = fb.group({
        enabled: [Enabled],
        tTaskTeam: [tTaskTeam, Validators.required],
        taskName: [TaskName],
        taskDescription: [TaskDescription],
        emailSubject: [EmailSubject],
        emailBody: [EmailBody]
      })

      this.AdditionalRecipientForm = fb.group({
        recipientType: ['',Validators.required],
        tofficeUser: ['',Validators.required],
        tOfficeUserEmail: '',
        FK_Task: [this.pk_Task]
      })

    }
</code>```

How I am using the @ViewChild to get the MatAutoCompletes

```<code>  @ViewChild(MatAutocomplete) autoCompleteForTaskTeam: MatAutocomplete;
  @ViewChild('auto') auto: MatAutocomplete;
  @ViewChild('autotest') autotest: MatAutocomplete;
  @ViewChild(MatTable) table: MatTable<RecipientInterface>;
  @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
  subscription: Subscription;
</code>```

Where I am calling the method on the controls

```<code>ngAfterViewInit() {
</code>```

If I only call the tTaskTeam control it works, but when I put all three it stops working

```<code>this._subscribeToClosingActions(this.form.controls.tTaskTeam);
this._subscribeToClosingActions(this.AdditionalRecipientForm.controls.recipientType);
    this._subscribeToClosingActions(this.AdditionalRecipientForm.controls.tofficeUser);
        }

ngOnDestroy() {
  if (this.subscription && !this.subscription.closed) {
    this.subscription.unsubscribe();
  }
}
</code>```

the method that shows the error, sets my control to '', and clears out if it is not a value from the suggested.

```<code>private _subscribeToClosingActions(control): void {
  if (this.subscription && !this.subscription.closed) {
    this.subscription.unsubscribe();
  }
  this.subscription = this.trigger.panelClosingActions
    .subscribe(e => {
      if (!e || !e.source) {
       control.setValue('');
      }
    },
    err => this._subscribeToClosingActions(control),
    () => this._subscribeToClosingActions(control));
}
</code>```

template code:

```<code><h2 mat-dialog-title>Update Entry</h2>
<mat-tab-group dynamicHeight>
  <mat-tab label="Task Information">
    <div class="example-small-box mat-elevation-z4">
      <mat-dialog-content  [formGroup]="form" class="example-form" >
        <mat-slide-toggle color="primary" (click)="textForToggle()" formControlName="enabled" >{{toggle ? 'Enabled': 'Disabled'}}</mat-slide-toggle>

            <mat-form-field class="task-info-form-field" >
                <input matInput placeholder="Report Name" formControlName="taskName">
            </mat-form-field>
            <br>
            <mat-form-field  appearance="outline" class="task-info-form-field" >
</code>```

The first autoComplete component

```<code><input matInput (keyup.enter)="chooseFirstOption(autoCompleteForTaskTeam)" [matAutocomplete]="autoCompleteForTaskTeam" formControlName="tTaskTeam" matTooltip="You can search and it will try to autocomplete the name for you!" placeholder="Select Group">
                  <mat-autocomplete #autoCompleteForTaskTeam='matAutocomplete'  [displayWith]="displayTeamName">
                    <mat-option class="matAutoCompleteSelect"*ngFor="let user of filteredOptions | async"
                      [value]="user">
                      <span>{{ user.TeamName }}</span>
                    </mat-option>
                  </mat-autocomplete>
                  <mat-error >
                    Value entered is NOT VALID please selected only from suggested values.
                  </mat-error>
                </mat-form-field>
                <br>
                <mat-form-field class="task-info-form-field" >
                  <textarea #message matInput placeholder="Report Description"  formControlName="taskDescription"></textarea>
                  <mat-hint align="end">{{message.value.length}} / 256</mat-hint>
                  <mat-hint align="start"><strong>Put a detailed Description</strong> </mat-hint>
                  <mat-error >
                    Please enter less than 256 characters.
                  </mat-error>
                </mat-form-field>
                <br>
                <mat-form-field class="task-info-form-field" >
                  <input matInput placeholder="Email Subject: " formControlName="emailSubject">
                </mat-form-field>
                <br>
                <mat-form-field class="task-info-form-field">
                  <textarea matInput #message2 placeholder="Email Body"  formControlName="emailBody"></textarea>
                  <mat-hint align="end">{{message2.value.length}} / 256</mat-hint>
                  <mat-error >
                    Please enter less than 256 characters.
                  </mat-error>
                </mat-form-field>
          </mat-dialog-content>

        </div>
      </mat-tab>
      <mat-tab class="example-containerGrid" label="Recipient Information">

        <div class="example-containerGrid mat-elevation-z8">
          <div class="example-header">
            <mat-form-field class="searchGrid-form-field">
              <input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Filter Doesn't Work At The Moment">
              <button mat-icon-button matSuffix aria-label="clear" *ngIf="filter.value" (click)="filter.value=''; applyFilter('');">
                <mat-icon>close</mat-icon>
              </button>
            </mat-form-field>
          </div>

          <mat-table #table [dataSource]="dataSource">

            <ng-container matColumnDef="Login">
              <mat-header-cell *matHeaderCellDef> Login </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.tOfficeUser.Login}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="Email">
              <mat-header-cell class="actionsCell" *matHeaderCellDef> Email </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.tOfficeUser.Email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="typerecipient">
              <mat-header-cell *matHeaderCellDef> Type Of Recipient </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.RecipientType.typerecipient}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="Actions">
                <mat-header-cell  *matHeaderCellDef> Actions  </mat-header-cell>
                <mat-cell  *matCellDef="let element"> {{element.Actions}}
                <div class="example-button-row">
                  <button mat-raised-button color="primary"  (click)="updateRecipientInfo(element)"> <mat-icon class="example-icon" matTooltip="You can edit this report">edit</mat-icon> <b>Edit</b></button>
                  <!-- <button mat-raised-button (click)="test">  <mat-icon class="example-icon" matTooltip="This button is to copy reports"> filter_none </mat-icon><b>Copy</b></button> -->
                  <button mat-raised-button color="warn" (click)="deleteRecipient(element)">  <mat-icon class="example-icon" matTooltip="This is to delete this report"> delete_outline</mat-icon><b>Delete</b></button>
                </div>
              </mat-cell>
            </ng-container>

            <!-- Fav Column -->
            <!-- <ng-container matColumnDef="fav">
              <mat-header-cell *matHeaderCellDef> Favorite </mat-header-cell>
              <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                  <mat-select [(value)]="element.fav" placeholder="Favorite">
                    <mat-option>None</mat-option>
                    <mat-option value="Yes">Yes</mat-option>
                  </mat-select>
                </mat-form-field>
              </mat-cell>
            </ng-container> -->

            <mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></mat-header-row>
            <mat-row *matRowDef="let row; columns: columnsToDisplay;"></mat-row>
          </mat-table>
          <mat-card class="spinnerMatCard" *ngIf="isLoading">
              <mat-progress-spinner
                color="primary"
                mode="indeterminate">
              </mat-progress-spinner>
            </mat-card>
        </div>

        <div class="example-container mat-elevation-z8">
            <mat-accordion>
                <mat-expansion-panel [formGroup]="AdditionalRecipientForm">
                  <mat-expansion-panel-header [collapsedHeight]="customCollapsedHeight" [expandedHeight]="customExpandedHeight">
                    <mat-panel-title>
                      Add Additional Recipients
                    </mat-panel-title>
                    <mat-panel-description>
                      Type your name and age
                    </mat-panel-description>
                  </mat-expansion-panel-header>
                  <button mat-raised-button (click)="createNewRecipientUser()" [disabled]="!AdditionalRecipientForm.valid" [disabled]="!AdditionalRecipientForm.dirty" color="primary"><b>Update</b></button>
                  <button mat-raised-button  (click)="resetFields()" color="primary"><b>Reset</b></button>
                  <br>

                    <mat-form-field appearance="outline">
                        <mat-label>Login Name Field</mat-label>
</code>```

The second autoComplete component

```<code> matTooltip="You can search and it will try to autocomplete the name for you!" placeholder="Select Type Of Logins">

                <mat-hint>You can type in the name and it will autocomplete for you!</mat-hint>
              <mat-autocomplete #auto [displayWith]="displayLogin">
                  <mat-option class="matAutoCompleteSelect"*ngFor="let user of OfficeUserfilteredOptions | async"
                    [value]="user">
                    <span>{{ user.Login }}</span>
                  </mat-option>
              </mat-autocomplete>
              <mat-error >
                Value entered is NOT VALID please selected only from suggested values.
              </mat-error>
            </mat-form-field>

            <mat-form-field class="add-addtional-recipients-form-field" appearance="outline">
                <mat-label>Email Field</mat-label>
              <input  matInput placeholder="User Email Address"   formControlName="tOfficeUserEmail">

              <mat-hint align="left"><strong>You cannot edit user email address here! Select a login to see the email.</strong> </mat-hint>
            </mat-form-field>

            <mat-form-field class="add-addtional-recipients-form-field" appearance="outline">
                <mat-label>Recipient Type</mat-label>
</code>```

The third autoComplete component

```<code>   <input matInput [matAutocomplete]="autotest" (keyup.enter)="chooseFirstOptionForAutoTest()" formControlName="recipientType" matTooltip="You can search and it will try to autocomplete the name for you!" placeholder="Select Type Of Recipient">
                <mat-hint>Start typing in the type of reicpient you want. </mat-hint>
                <mat-autocomplete #autotest  [displayWith]="displayRecipientName">
                  <mat-option class="matAutoCompleteSelect"*ngFor="let user of filteredRecipientOptions | async"
                    [value]="user">
                    <span>{{ user.typerecipient }}</span>
                  </mat-option>
                </mat-autocomplete>
                <mat-error >
                  Value entered is NOT VALID please selected only from suggested values.
                </mat-error>
              </mat-form-field>
        </mat-expansion-panel>
      </mat-accordion>
</div>
</code>```

  Close
  Save

答:
If someone ever starts working with more than one autocomplete in a form and want to clear out the input if it's not one of the item suggested from your data and show an error message. I found a solution:

My problem is that the trigger I was trying to reference only finds the first autocomplete that it finds in the DOM.

```<code> @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
</code>```

So, I need to subscribe to each MatAutoComplete trigger since each of them have their own. To be able to do that we have to create a

```<code>@ViewChildren(MatAutocompleteTrigger) triggerCollection: QueryList<MatAutocompleteTrigger>;
</code>```

This will hold a collect of all the matAutComplete controls triggers.

From there we can go through the collection by making it an array and checking which of the controls is dirty.

```<code>private _subscribeToClosingActions(): void {

    if (this.subscription && !this.subscription.closed) {
      this.subscription.unsubscribe();
    }

for (var trigger of this.triggerCollection.toArray()) {
    this.subscription = trigger.panelClosingActions
      .subscribe(e => {
        if (!e || !e.source) {
        if(this.CarsFormGroup.controls.carCtrl.dirty) {
 this.CarsFormGroup.controls.carCtrl.setValue(null);
          }
        if(this.StatesFormGroup.controls.stateCtrl.dirty) {
 this.StatesFormGroup.controls.stateCtrl.setValue(null);
          }
        }
  });
}
  }
</code>```

Body:
I created a stackBliz that is a smaller example of what I am trying to acheive, but if I can get it to work there. Then, I should be able to figure out the rest.

https://stackblitz.com/edit/angular-nkajg5

I want to clear or the set the value of the component to '' when the input entered by a user is not an item from the suggested items in the mat-autocomplete. Then, I also want to display a mat-error to them that "Value entered is NOT VALID please selected only from suggested values."

I got it to work by following two examples I found.
Clearing out the input

https://stackblitz.com/edit/autocomplete-force-selection-tests-w2fqww?file=app%2Fapp.component.html

Telling them an error message

https://stackblitz.com/edit/angular-kdym4u

However, I have three autocomplete components and it is causing issues when I try to use the method on all three components and call them from ngAfterViewInit. No error messages it just doesn't clear out the input or show the error message. So my function doesn't seem to be getting called. (to be honest not really sure what the subscription variable is used for in the code) I think it has to do something with the subscription and where I am calling it from the ngAfterViewInt(). I tested it out and only the first component works by itself. I tried the other two components by themeselves too and they don't work at all even when they are the only control being used. I have the three matAutocomplete in a tabGroup and the other two are in the second tab of the tabGroup.

My constructor with my form groups

  constructor(private dialogRecipient:MatDialog,private fb: FormBuilder, private dialogRef: MatDialogRef<UpdateTaskComponent>,private snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA){Enabled ,TaskName, TaskDescription,EmailSubject, EmailBody, tTaskTeam, PK_Task}, private service: TaskService ) {
      this.pk_Task = PK_Task;
      console.log(this.pk_Task)
      this.form = fb.group({
        enabled: [Enabled],
        tTaskTeam: [tTaskTeam, Validators.required],
        taskName: [TaskName],
        taskDescription: [TaskDescription],
        emailSubject: [EmailSubject],
        emailBody: [EmailBody]
      })

      this.AdditionalRecipientForm = fb.group({
        recipientType: ['',Validators.required],
        tofficeUser: ['',Validators.required],
        tOfficeUserEmail: '',
        FK_Task: [this.pk_Task]
      })

    }

How I am using the @ViewChild to get the MatAutoCompletes

  @ViewChild(MatAutocomplete) autoCompleteForTaskTeam: MatAutocomplete;
  @ViewChild('auto') auto: MatAutocomplete;
  @ViewChild('autotest') autotest: MatAutocomplete;
  @ViewChild(MatTable) table: MatTable<RecipientInterface>;
  @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
  subscription: Subscription;

Where I am calling the method on the controls

ngAfterViewInit() {

If I only call the tTaskTeam control it works, but when I put all three it stops working

this._subscribeToClosingActions(this.form.controls.tTaskTeam);
this._subscribeToClosingActions(this.AdditionalRecipientForm.controls.recipientType);
    this._subscribeToClosingActions(this.AdditionalRecipientForm.controls.tofficeUser);
        }

ngOnDestroy() {
  if (this.subscription && !this.subscription.closed) {
    this.subscription.unsubscribe();
  }
}

the method that shows the error, sets my control to '', and clears out if it is not a value from the suggested.

private _subscribeToClosingActions(control): void {
  if (this.subscription && !this.subscription.closed) {
    this.subscription.unsubscribe();
  }
  this.subscription = this.trigger.panelClosingActions
    .subscribe(e => {
      if (!e || !e.source) {
       control.setValue('');
      }
    },
    err => this._subscribeToClosingActions(control),
    () => this._subscribeToClosingActions(control));
}

template code:

Update Entry

<mat-tab-group dynamicHeight>
  <mat-tab label="Task Information">

      <mat-dialog-content  [formGroup]="form" class="example-form" >
        <mat-slide-toggle color="primary" (click)="textForToggle()" formControlName="enabled" >{{toggle ? 'Enabled': 'Disabled'}}</mat-slide-toggle>

            <mat-form-field class="task-info-form-field" >
                <input matInput placeholder="Report Name" formControlName="taskName">
            </mat-form-field>

            <mat-form-field  appearance="outline" class="task-info-form-field" >

The first autoComplete component

<input matInput (keyup.enter)="chooseFirstOption(autoCompleteForTaskTeam)" [matAutocomplete]="autoCompleteForTaskTeam" formControlName="tTaskTeam" matTooltip="You can search and it will try to autocomplete the name for you!" placeholder="Select Group">
                  <mat-autocomplete #autoCompleteForTaskTeam='matAutocomplete'  [displayWith]="displayTeamName">
                    <mat-option class="matAutoCompleteSelect"*ngFor="let user of filteredOptions | async"
                      [value]="user">
                      {{ user.TeamName }}
                    </mat-option>
                  </mat-autocomplete>
                  <mat-error >
                    Value entered is NOT VALID please selected only from suggested values.
                  </mat-error>
                </mat-form-field>

                <mat-form-field class="task-info-form-field" >
                  <textarea #message matInput placeholder="Report Description"  formControlName="taskDescription"></textarea>
                  <mat-hint align="end">{{message.value.length}} / 256</mat-hint>
                  <mat-hint align="start">Put a detailed Description </mat-hint>
                  <mat-error >
                    Please enter less than 256 characters.
                  </mat-error>
                </mat-form-field>

                <mat-form-field class="task-info-form-field" >
                  <input matInput placeholder="Email Subject: " formControlName="emailSubject">
                </mat-form-field>

                <mat-form-field class="task-info-form-field">
                  <textarea matInput #message2 placeholder="Email Body"  formControlName="emailBody"></textarea>
                  <mat-hint align="end">{{message2.value.length}} / 256</mat-hint>
                  <mat-error >
                    Please enter less than 256 characters.
                  </mat-error>
                </mat-form-field>
          </mat-dialog-content>

      </mat-tab>
      <mat-tab class="example-containerGrid" label="Recipient Information">

            <mat-form-field class="searchGrid-form-field">
              <input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Filter Doesn't Work At The Moment">
              <button mat-icon-button matSuffix aria-label="clear" *ngIf="filter.value" (click)="filter.value=''; applyFilter('');">
                <mat-icon>close</mat-icon>
              </button>
            </mat-form-field>

          <mat-table #table [dataSource]="dataSource">

            <ng-container matColumnDef="Login">
              <mat-header-cell *matHeaderCellDef> Login </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.tOfficeUser.Login}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="Email">
              <mat-header-cell class="actionsCell" *matHeaderCellDef> Email </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.tOfficeUser.Email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="typerecipient">
              <mat-header-cell *matHeaderCellDef> Type Of Recipient </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.RecipientType.typerecipient}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="Actions">
                <mat-header-cell  *matHeaderCellDef> Actions  </mat-header-cell>
                <mat-cell  *matCellDef="let element"> {{element.Actions}}

                  <button mat-raised-button color="primary"  (click)="updateRecipientInfo(element)"> <mat-icon class="example-icon" matTooltip="You can edit this report">edit</mat-icon> Edit</button>

                  <button mat-raised-button color="warn" (click)="deleteRecipient(element)">  <mat-icon class="example-icon" matTooltip="This is to delete this report"> delete_outline</mat-icon>Delete</button>

              </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></mat-header-row>
            <mat-row *matRowDef="let row; columns: columnsToDisplay;"></mat-row>
          </mat-table>
          <mat-card class="spinnerMatCard" *ngIf="isLoading">
              <mat-progress-spinner
                color="primary"
                mode="indeterminate">
              </mat-progress-spinner>
            </mat-card>

            <mat-accordion>
                <mat-expansion-panel [formGroup]="AdditionalRecipientForm">
                  <mat-expansion-panel-header [collapsedHeight]="customCollapsedHeight" [expandedHeight]="customExpandedHeight">
                    <mat-panel-title>
                      Add Additional Recipients
                    </mat-panel-title>
                    <mat-panel-description>
                      Type your name and age
                    </mat-panel-description>
                  </mat-expansion-panel-header>
                  <button mat-raised-button (click)="createNewRecipientUser()" [disabled]="!AdditionalRecipientForm.valid" [disabled]="!AdditionalRecipientForm.dirty" color="primary">Update</button>
                  <button mat-raised-button  (click)="resetFields()" color="primary">Reset</button>

                    <mat-form-field appearance="outline">
                        <mat-label>Login Name Field</mat-label>

The second autoComplete component

 matTooltip="You can search and it will try to autocomplete the name for you!" placeholder="Select Type Of Logins">

                <mat-hint>You can type in the name and it will autocomplete for you!</mat-hint>
              <mat-autocomplete #auto [displayWith]="displayLogin">
                  <mat-option class="matAutoCompleteSelect"*ngFor="let user of OfficeUserfilteredOptions | async"
                    [value]="user">
                    {{ user.Login }}
                  </mat-option>
              </mat-autocomplete>
              <mat-error >
                Value entered is NOT VALID please selected only from suggested values.
              </mat-error>
            </mat-form-field>

            <mat-form-field class="add-addtional-recipients-form-field" appearance="outline">
                <mat-label>Email Field</mat-label>
              <input  matInput placeholder="User Email Address"   formControlName="tOfficeUserEmail">

              <mat-hint align="left">You cannot edit user email address here! Select a login to see the email. </mat-hint>
            </mat-form-field>

            <mat-form-field class="add-addtional-recipients-form-field" appearance="outline">
                <mat-label>Recipient Type</mat-label>

The third autoComplete component

   <input matInput [matAutocomplete]="autotest" (keyup.enter)="chooseFirstOptionForAutoTest()" formControlName="recipientType" matTooltip="You can search and it will try to autocomplete the name for you!" placeholder="Select Type Of Recipient">
                <mat-hint>Start typing in the type of reicpient you want. </mat-hint>
                <mat-autocomplete #autotest  [displayWith]="displayRecipientName">
                  <mat-option class="matAutoCompleteSelect"*ngFor="let user of filteredRecipientOptions | async"
                    [value]="user">
                    {{ user.typerecipient }}
                  </mat-option>
                </mat-autocomplete>
                <mat-error >
                  Value entered is NOT VALID please selected only from suggested values.
                </mat-error>
              </mat-form-field>
        </mat-expansion-panel>
      </mat-accordion>

  Close
  Save

Body:
If someone ever starts working with more than one autocomplete in a form and want to clear out the input if it's not one of the item suggested from your data and show an error message. I found a solution:

My problem is that the trigger I was trying to reference only finds the first autocomplete that it finds in the DOM.

 @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;

So, I need to subscribe to each MatAutoComplete trigger since each of them have their own. To be able to do that we have to create a

@ViewChildren(MatAutocompleteTrigger) triggerCollection: QueryList<MatAutocompleteTrigger>;

This will hold a collect of all the matAutComplete controls triggers.

From there we can go through the collection by making it an array and checking which of the controls is dirty.

private _subscribeToClosingActions(): void {

    if (this.subscription && !this.subscription.closed) {
      this.subscription.unsubscribe();
    }

for (var trigger of this.triggerCollection.toArray()) {
    this.subscription = trigger.panelClosingActions
      .subscribe(e => {
        if (!e || !e.source) {
        if(this.CarsFormGroup.controls.carCtrl.dirty) {
 this.CarsFormGroup.controls.carCtrl.setValue(null);
          }
        if(this.StatesFormGroup.controls.stateCtrl.dirty) {
 this.StatesFormGroup.controls.stateCtrl.setValue(null);
          }
        }
  });
}
  }


问:
How to publish/deploy a npm package to custom artifactory
I want to do something like this:

Create an npm package. Basically, a common code which I want to use for all of my projects. Which I created.

But now What I want is, Every time I commit something in git for this project, Jenkins should build it with updated alpha/beta version and should publish to my own artifactory.

答:
Your Jenkins job can be configured to be triggered by a webhook, which would take care of the first part (every time I commit). Depending on which Git server you're using you can find a lot of tutorials how to do that:

For GitHub

For GitLab

For Gogs

please note this is just a random selection of tutorials how to set up the webhook triggers to work with Git servers and by no means an exhaustive list

To publish your package to JFrog Artifactory you can either use the Jenkins Artifactory Plugin, or use the NPM command line. If you want to use the npm command line, you'll need to authenticate first:

```<code># setting the default registry to Artifactory
npm config set registry http://<ARTIFACTORY_SERVER_DOMAIN>:8081/artifactory/api/npm/npm-repo/
# log in
npm login
</code>```

alternatively you can get a .npmrc file directly from Artifactory using:

```<code>curl -u admin:<CREDENTIAL> http://<ARTIFACTORY_SERVER_DOMAIN>:8081/artifactory/api/npm/auth
</code>```

After that, there are two ways you can push your package to Artifactory:

Edit your package.json file and add a publishConfig section to a local repository: "publishConfig":{"registry":"http://localhost:8081/artifactory/api/npm/npm-repo/"}

Provide a local repository to the npm publish command: npm publish --registry http://localhost:8081/artifactory/api/npm/npm-repo/

Body:
Your Jenkins job can be configured to be triggered by a webhook, which would take care of the first part (every time I commit). Depending on which Git server you're using you can find a lot of tutorials how to do that:

For GitHub

For GitLab

For Gogs

please note this is just a random selection of tutorials how to set up the webhook triggers to work with Git servers and by no means an exhaustive list

To publish your package to JFrog Artifactory you can either use the Jenkins Artifactory Plugin, or use the NPM command line. If you want to use the npm command line, you'll need to authenticate first:

# setting the default registry to Artifactory
npm config set registry http://<ARTIFACTORY_SERVER_DOMAIN>:8081/artifactory/api/npm/npm-repo/
# log in
npm login

alternatively you can get a .npmrc file directly from Artifactory using:

curl -u admin:<CREDENTIAL> http://<ARTIFACTORY_SERVER_DOMAIN>:8081/artifactory/api/npm/auth

After that, there are two ways you can push your package to Artifactory:

Edit your package.json file and add a publishConfig section to a local repository: "publishConfig":{"registry":"http://localhost:8081/artifactory/api/npm/npm-repo/"}

Provide a local repository to the npm publish command: npm publish --registry http://localhost:8081/artifactory/api/npm/npm-repo/