问:
how to create exceptions to JWT filter based on URLs
I am working on JWT authentication.I want to bypass ( not allow to pass through jwt filter), the provided URLs. Below is the code snippet.

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    http.cors().and().csrf().disable().authorizeRequests().antMatchers(bypassURLs)
                    .permitAll().anyRequest().authenticated().and().addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtConfigProperties))
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);}
</code>```

In the above code, I want the system Not to filter for bypassURLs.
If I am passing "/sayHello", then JWTAuthenticationFilter should not be applied to this while the URLs other than "/sayHello" must pass through the JWTAuthenticationFilter.

I have tried http.csrf().ignoringAntMatchers("/sayHello"); and some some regex but not succeded. Please help.

答:
When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup");
}
</code>```

And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.

Body:
I am working on JWT authentication.I want to bypass ( not allow to pass through jwt filter), the provided URLs. Below is the code snippet.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.cors().and().csrf().disable().authorizeRequests().antMatchers(bypassURLs)
                    .permitAll().anyRequest().authenticated().and().addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtConfigProperties))
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);}

In the above code, I want the system Not to filter for bypassURLs.
If I am passing "/sayHello", then JWTAuthenticationFilter should not be applied to this while the URLs other than "/sayHello" must pass through the JWTAuthenticationFilter.

I have tried http.csrf().ignoringAntMatchers("/sayHello"); and some some regex but not succeded. Please help.

Body:
When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup");
}

And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.


来源: stackexchange

问:
center image in html mail
How can I center an image in a html mail that it works in outlook as well.

I tried this:

```<code><th align="center">
        <center data-parsed="" class="logo">
            <img src="[%embedded-image(1335);logo.png]" alt="" width="207" height="55" border="0"/>
        </center>
</th>
</code>```

as well tried like this

```<code><p style="text-align: center"><img src="[%embedded-image(1335);logo.png]" alt="" width="207" height="55" border="0"/></>
</code>```

In browser it looks nice. But in outlook not.

What could be a working solution?

thanks.

答:
```<code><table align="center" width="75%">
    <tr>
        <th>
            <div style="margin: 0 auto; text-align: center;">
                <img align="center" src="[%embedded-image(1335);logo.png]" alt="" width="207" height="55" border="0"/>
            </div>
        </th>
    </tr>
</table>
</code>```

Trick is to make the parent table fixed width with align center property.

Giving margin: 0 auto; is 2nd option.

And if it is regular text content, then only align="center" will do the job. Like the following,

```<code><table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>
</code>```

Hope this one helps.

ContentLicense: CC BY-SA 3.0

Title: center image in html mail

Body:
How can I center an image in a html mail that it works in outlook as well.

I tried this:

as well tried like this

</>

In browser it looks nice. But in outlook not.

What could be a working solution?

thanks.

Body:
<table align="center" width="75%">
    <tr>
        <th>
            <div style="margin: 0 auto; text-align: center;">
                <img align="center" src="[%embedded-image(1335);logo.png]" alt="" width="207" height="55" border="0"/>
            </div>
        </th>
    </tr>
</table>

Trick is to make the parent table fixed width with align center property.

Giving margin: 0 auto; is 2nd option.

And if it is regular text content, then only align="center" will do the job. Like the following,

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

Hope this one helps.


问:
Reorder Umbraco to have Articles/Year/Month/Article map structure
I have a website that's been running for over a year. The overview is getting lost in the Articles doctype and I've been asked to change the file structure from Articles/Article to Articles/Year/Month/Article.

In short, the admin opens Umbraco and sees the Articles and clicks the arrow to see all the articles. It then takes a couple of minutes since the are all loaded. Instead I want a map structure that devides the articles into year and month published.

Since i'm talking about 5k articles, I can't really do this manually.

Any advice?

答:
You need to look at the UrlProvider and ContentFinder configuration in your umbraco instance.

Shouldn't require any manual editing of the articles provided they were posted on the days you would like them to display as.

Take a look at this: https://24days.in/umbraco-cms/2014/urlprovider-and-contentfinder/


问:
Cordova on Android 4.4 CSS and Javascript compatibility
I'm developing a cordova app, testing on Android 7 and 6 everything works.
When I try to install the app on an Android 4.4 device it starts, but the CSS is rendered very bad (missing borders and other ugly stuff) and some Javascript functions are not supported (e.g. Array.forEach).

I think because the webview on Android 4.4 is old but I don't know how to solve this.

I tried to install Crosswalk but it does nothing, it doesn't appear in navigator.userAgent so I think it doesn't work.
I have this in my plugin list:

```<code>cordova-plugin-crosswalk-webview 2.3.0 "Crosswalk WebView Engine"
</code>```

And this in my navigator.userAgent

```<code>"Mozilla/5.0 (Linux; Android 4.4.2; Android SDK built for x86 Build/KK) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36"
</code>```

答:
I solved the problem myself.
Crosswalk was the solution but I failed at installing it because you need to build from cordova and not from Android Studio.
I was building from android studio because cordova gave me an error with gradle version.
I fixed the build from cordova, reinstalled crosswalk and now I can use it without problems and it supports all the new functionalities.</p>

Body:
I'm developing a cordova app, testing on Android 7 and 6 everything works.
When I try to install the app on an Android 4.4 device it starts, but the CSS is rendered very bad (missing borders and other ugly stuff) and some Javascript functions are not supported (e.g. Array.forEach).

I think because the webview on Android 4.4 is old but I don't know how to solve this.

I tried to install Crosswalk but it does nothing, it doesn't appear in navigator.userAgent so I think it doesn't work.
I have this in my plugin list:

cordova-plugin-crosswalk-webview 2.3.0 "Crosswalk WebView Engine"

And this in my navigator.userAgent

"Mozilla/5.0 (Linux; Android 4.4.2; Android SDK built for x86 Build/KK) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36"


问:
Attach object's properties or an array to a node's properties
I am creating a dynamic form with many different divs inside. Each div has its own unique input combination. I have read that appendChild is faster than changing the innerHTML so my solution is to build number of arrays. Each array is a div in the form and in each array there are several objects defined. Each object is an input.

e.g:

```<code>        var div = [
            label = {
                tag: "label",
                text: "Enter password",
                for: "pass"
            },
                input = {
                tag: "input",
                type: "password",
                name: "pass"
            }
        ];
</code>```

At first, I used a foreach statement to attach the object's property onto a new element using
setAttribute like so: (while using a 'tag' property as the html tag and than deleting it so it will not appear as an attribute).

```<code>for(var elem in div) {
    var temp = document.createElement(div[elem].tag);
    delete div[elem].tag;
    for(var prop in div[elem]) {
        temp.setAttribute(prop,input[prop]);
    }
    parentDiv.appendChild(temp);
}
</code>```

The problem is I have more things I would like to add to the element that cannot be added thru attributes. Like: innerText. So maybe I could make the array an array of properties that I can merge into the 'temp' node?

Thanks in advance!

答:
You could just handle that in a different section just before the for loop like this</p>

```<code>for(var elem in div) {
  var temp = document.createElement(div[elem].tag);
  delete div[elem].tag;

  // add the other properties
  ["innerHtml", "innerText"].forEach(function (attr) {
     if(div[ele][attr]) {
        temp[attr] = div[ele][attr]
        delete div[ele][attr];
  });

  // add the attributes
  for(var prop in div[elem]) {
     temp.setAttribute(prop.input[prop]);
  }
  parentDiv.appendChild(temp);
}
</code>```

Body:
I am creating a dynamic form with many different divs inside. Each div has its own unique input combination. I have read that appendChild is faster than changing the innerHTML so my solution is to build number of arrays. Each array is a div in the form and in each array there are several objects defined. Each object is an input.

e.g:

        var div = [
            label = {
                tag: "label",
                text: "Enter password",
                for: "pass"
            },
                input = {
                tag: "input",
                type: "password",
                name: "pass"
            }
        ];

At first, I used a foreach statement to attach the object's property onto a new element using
setAttribute like so: (while using a 'tag' property as the html tag and than deleting it so it will not appear as an attribute).

for(var elem in div) {
    var temp = document.createElement(div[elem].tag);
    delete div[elem].tag;
    for(var prop in div[elem]) {
        temp.setAttribute(prop,input[prop]);
    }
    parentDiv.appendChild(temp);
}

The problem is I have more things I would like to add to the element that cannot be added thru attributes. Like: innerText. So maybe I could make the array an array of properties that I can merge into the 'temp' node?

Thanks in advance!

Body:
You could just handle that in a different section just before the for loop like this

for(var elem in div) {
  var temp = document.createElement(div[elem].tag);
  delete div[elem].tag;

  // add the other properties
  ["innerHtml", "innerText"].forEach(function (attr) {
     if(div[ele][attr]) {
        temp[attr] = div[ele][attr]
        delete div[ele][attr];
  });

  // add the attributes
  for(var prop in div[elem]) {
     temp.setAttribute(prop.input[prop]);
  }
  parentDiv.appendChild(temp);
}


问:
how can we get popup by touching on particular image i n android?? code will be better help for me
how can we get popup by touching on particular image and popup should be cancel by moving out from image in android?? code will be better help for me...</p>

答:
```<code><ImageViewName>.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction()==0)//0-ACTION_DOWN
             {
                Toast.makeText(<Current Activity>.this, "Image is Pressed", Toast.LENGTH_SHORT).show();
             }else
                 if(event.getAction()==1)//0-ACTION_UP
                 {

                 }
            return false;
        }
    });
</code>```

Through the above code we can display a pop up msg.In my code i am display a simple message.

ContentLicense: CC BY-SA 2.5

Body:
<ImageViewName>.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction()==0)//0-ACTION_DOWN
             {
                Toast.makeText(<Current Activity>.this, "Image is Pressed", Toast.LENGTH_SHORT).show();
             }else
                 if(event.getAction()==1)//0-ACTION_UP
                 {

                 }
            return false;
        }
    });

Through the above code we can display a pop up msg.In my code i am display a simple message.


问:
Clang replacement for -mthreads option
When I compile a project with clang using -mthreads option I have a warning: argument unused during compilation '-mthreads'. Is there correct replacement for -mthreads in clang. Or what must I do to compile a project correct in this case.

答:
You need -pthread flag, and not -mthreads.

PS: GCC uses that flag too.

Title: Clang replacement for -mthreads option


问:
convert dictonay in to list in python, Dictonary has multiple value in single key
I want to get the values of the key. but issue is the key has multiple values. I want all the values in normal array/list:
here is my code:

```<code>dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    temp = [value]
    dictlist.append(temp)
print(dictlist[0])
</code>```

output:

```<code>[['john', 'vincin', 'tenzin']]
[Finished in 0.1s]
</code>```

Expected result like this(normal list):

```<code>dictlist[0]="john"
dictlist[1]="vincin"
dictlist[2]="tenzin"
</code>```

答:
You could also just take the value from the dict, as it is already a list:

```<code>dict={"Data": ["john", "vincin","tenzin"]}
dictlist = dict['Data']

print(dictlist)
</code>```

Gives:

```<code>  ['john', 'vincin', 'tenzin']
</code>```

Body:
I want to get the values of the key. but issue is the key has multiple values. I want all the values in normal array/list:
here is my code:

dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    temp = [value]
    dictlist.append(temp)
print(dictlist[0])

output:

[['john', 'vincin', 'tenzin']]
[Finished in 0.1s]

Expected result like this(normal list):

dictlist[0]="john"
dictlist[1]="vincin"
dictlist[2]="tenzin"

Body:
You could also just take the value from the dict, as it is already a list:

dict={"Data": ["john", "vincin","tenzin"]}
dictlist = dict['Data']

print(dictlist)

Gives:

  ['john', 'vincin', 'tenzin']


问:
Disable auto-scroll in IntelliJ Terminal
I want to start debugging while my program is still running and producing output. The scroll position always jumps to the newest output. I want to disable this auto-scroll behaviour (and re-enable it) when necessary.

I remember other tools/terminals that stop auto-scrolling if you manually scroll in their window. Is there a setting I am missing?

答:
```<code>ctrl +s will suspend the terminal process
ctrl +q will resume the terminal process
</code>```

<p>Not a actual solution but a work around </p>

Body:
ctrl +s will suspend the terminal process
ctrl +q will resume the terminal process

Not a actual solution but a work around


问:
join two tables in R using Names from both tables
Hi guys I know there are few questions related to joining tables in R, I tried most of them but they didn't work, in my case, I have two tables first one (A) has two columns (Id and company_name), 70,000 rows, and the second one (B) has company_name, registration number .....etc with 10,000,000 rows.

I want to join them to get the registration number for all the companies in A.

hint, I tried to merge, inner join using sqldf,fuzzyjoin and vlookup in excel but it didn't return all the record in A.

答:
It's hard to give an answer without any example code or data but let me try.

I can see three possible problems here.

1: Do you want to have all entries from A in your result set? even if there were no match from B? then you should use a left outer join.
for example with merge you should have merge(A,B,by="company_name",all.x = TRUE)

2: As I can see you want to join on company_name, is the class character in both A and B? sometimes it is converted for some reason to factor when you read in the file. convert them to character with A$company_name = as.character(A$company_name) and do the same for B

3: maybe there are extra characters in the names (like whitespaces) or special characters. If it's only that you can remove them and do the merging after that. use this: gsub('[^[:alnum:]]','',tolower(iconv(A$company_name, to='ASCII//TRANSLIT'))). This will make sure you get rid off all unwanted stuff.

ContentLicense: CC BY-SA 4.0


问:
How to sort a NSArray which contains NSDictionary?
I have a plist like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>
</code>```

Now I want to sort this by the highscoreInSeconds.

```<code>   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];
</code>```

How can I sort this now?

Thank you very much!
:)

Have a nice day.

PS: It should look like this at the end:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>
</code>```

You don't need to say me how to write a plist i knew that.

答:
I use this:

```<code>NSArray* sorted = [highscoreAll sortedArrayUsingComparator:(NSComparator)^(NSDictionary *item1, NSDictionary *item2) {
            NSString *score1 = [item1 objectForKey:@"highscoreInSeconds"];
            NSString *score2 = [item2 objectForKey:@"highscoreInSeconds"];
            return [score1 compare:score2 options:NSNumericSearch];
            }];
</code>```

and it worked.

Body:
I have a plist like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>

Now I want to sort this by the highscoreInSeconds.

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];

How can I sort this now?

Thank you very much!
:)

Have a nice day.

PS: It should look like this at the end:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>

You don't need to say me how to write a plist i knew that.

Body:
I use this:

NSArray* sorted = [highscoreAll sortedArrayUsingComparator:(NSComparator)^(NSDictionary *item1, NSDictionary *item2) {
            NSString *score1 = [item1 objectForKey:@"highscoreInSeconds"];
            NSString *score2 = [item2 objectForKey:@"highscoreInSeconds"];
            return [score1 compare:score2 options:NSNumericSearch];
            }];

and it worked.


问:
Dynamic 3DObject use in ARKit-SceneKit
I want to download the 3D Object-dae(collada) file from server and want to display on surface dynamically so can please share how can I achieve this in ARKit via SceneKit or else?</p>

答:
You can check this link: https://the-nerd.be/2014/11/07/dynamically-load-collada-files-in-scenekit-at-runtime/ it is old post but I don't think something is changed since that

According to this (see the Discussion section): https://developer.apple.com/documentation/modelio/mdlasset/1391813-canimportfileextension?language=objc

dae is not supported at runtime (ModelIO).

Additionally I'm working on a library called AssetKit (In Progress) and it will full support COLLADA and glTF, it is too early to say that but after initial release, you will be able to load dae files dynamically. It is written with C99 but I'll optimize it for Swift (by writing wrappers or integration with SceneKit...). Since it is still in progress I suggest that follow the first link

Title: Dynamic 3DObject use in ARKit-SceneKit


问:
Can we use ternary operator within an if statement?
My teacher says we can't use a ternary operator within an if statement as it's an alternative for it... Can anyone please tell me if we can use ternary operators within an if statement in c++? </p>

答:
Yes you can.

A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.

An example is the perversion

```<code>if (unemployed ? false : true)
</code>```

which stands in for

```<code>if (!unemployed)
</code>```

Naturally, whether or not it's a good thing to do depends on the context.

Body:
Yes you can.

A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.

An example is the perversion

if (unemployed ? false : true)

which stands in for

if (!unemployed)

Naturally, whether or not it's a good thing to do depends on the context.


问:
Transforming kwic objects into single dfm
I have a corpus of newspaper articles of which only specific parts are of interest for my research. I'm not happy with the results I get from classifying texts along different frames because the data contains too much noise. I therefore want to extract only the relevant parts from the documents. I was thinking of doing so by transforming several kwic objects generated by the quanteda package into a single df.

So far I've tried the following

```<code>exampletext <- c("The only reason for (the haste) which we can discern is the prospect of an Olympic medal, which is the raison d'etat of the banana republic,'' The Guardian said in an editorial under the headline ''Whatever Zola Wants. . .'' The Government made it clear it had acted promptly on the application to insure that the 5-foot-2-inch track star could qualify for the British Olympic team. The International Olympic Organization has a rule that says athletes who change their nationality must wait three years before competing for that country - a rule, however, that is often waived by the I.O.C. The British Olympic Association said it consulted with the I.O.C. before asserting Miss Budd's eligibility for the British team. ''Since Zola is now here and has a British passport she should be made to feel welcome and accepted by other British athletes,'' said Paul Dickenson, chairman of the International Athletes Club, an organization that raises money for amateur athletes and looks after their political interests. ''The thing we objected to was the way she got into the country by the Government and the Daily Mail and the commercialization exploitation associated with it.", "That left 14 countries that have joined the Soviet-led withdrawal. Albania and Iran had announced that they would not compete and did not send written notification. Bolivia, citing financial trouble, announced Sunday it would not participate.The 1972 Munich Games had the previous high number of competing countries, 122.No Protest Planned on Zola Budd YAOUNDE, Cameroon, June 4 (AP) - African countries do not plan to boycott the Los Angeles Olympics in protest of the inclusion of Zola Budd, the South African-born track star, on the British team, according to Lamine Ba, the secretary-general of the Supreme Council for Sport in Africa. Because South Africa is banned from participation in the Olympics, Miss Budd, whose father is of British descent, moved to Britain in March and was granted British citizenship.75 Olympians to Train in Atlanta ATLANTA, June 4 (AP) - About 75 Olympic athletes from six African countries and Pakistan will participate in a month-long training camp this summer in Atlanta under a program financed largely by a grant from the United States Information Agency, Anne Bassarab, a member of Mayor Andrew Young's staff, said today. The athletes, from Mozambique, Tanzania, Zambia, Zimbabwe, Uganda, Somalia and Pakistan, will arrive here June 24.")
mycorpus <- corpus(exampletext)
mycorpus.nat <- corpus(kwic(mycorpus, "nationalit*", window = 5, valuetype = "glob"))
mycorpus.cit <- corpus(kwic(mycorpus, "citizenship", window = 5, valuetype = "glob"))
mycorpus.kwic <- mycorpus.nat + mycorpus.cit
mydfm <- dfm(mycorpus.kwic)
</code>```

This, however, generates a dfm that contains 4 documents instead of 2, and when both keywords are present in a document even more. I can't think of a way to bring the dfm down to the original number of documents.

Thank you for helping me out.

答:
We recently added window argument to tokens_select() for this purpose:

```<code>    require(quanteda)
    txt <- c("The only reason for (the haste) which we can discern is the prospect of an Olympic medal, which is the raison d'etat of the banana republic,'' The Guardian said in an editorial under the headline ''Whatever Zola Wants. . .'' The Government made it clear it had acted promptly on the application to insure that the 5-foot-2-inch track star could qualify for the British Olympic team. The International Olympic Organization has a rule that says athletes who change their nationality must wait three years before competing for that country - a rule, however, that is often waived by the I.O.C. The British Olympic Association said it consulted with the I.O.C. before asserting Miss Budd's eligibility for the British team. ''Since Zola is now here and has a British passport she should be made to feel welcome and accepted by other British athletes,'' said Paul Dickenson, chairman of the International Athletes Club, an organization that raises money for amateur athletes and looks after their political interests. ''The thing we objected to was the way she got into the country by the Government and the Daily Mail and the commercialization exploitation associated with it.", "That left 14 countries that have joined the Soviet-led withdrawal. Albania and Iran had announced that they would not compete and did not send written notification. Bolivia, citing financial trouble, announced Sunday it would not participate.The 1972 Munich Games had the previous high number of competing countries, 122.No Protest Planned on Zola Budd YAOUNDE, Cameroon, June 4 (AP) - African countries do not plan to boycott the Los Angeles Olympics in protest of the inclusion of Zola Budd, the South African-born track star, on the British team, according to Lamine Ba, the secretary-general of the Supreme Council for Sport in Africa. Because South Africa is banned from participation in the Olympics, Miss Budd, whose father is of British descent, moved to Britain in March and was granted British citizenship.75 Olympians to Train in Atlanta ATLANTA, June 4 (AP) - About 75 Olympic athletes from six African countries and Pakistan will participate in a month-long training camp this summer in Atlanta under a program financed largely by a grant from the United States Information Agency, Anne Bassarab, a member of Mayor Andrew Young's staff, said today. The athletes, from Mozambique, Tanzania, Zambia, Zimbabwe, Uganda, Somalia and Pakistan, will arrive here June 24.")
    toks <- tokens(txt)
    mt_nat <- dfm(tokens_select(toks, "nationalit*", window = 5))
    mt_cit <- dfm(tokens_select(toks, "citizenship*", window = 5))
</code>```

Please make sure that you are using the latest version of Quanteda.

Body:
I have a corpus of newspaper articles of which only specific parts are of interest for my research. I'm not happy with the results I get from classifying texts along different frames because the data contains too much noise. I therefore want to extract only the relevant parts from the documents. I was thinking of doing so by transforming several kwic objects generated by the quanteda package into a single df.

So far I've tried the following

exampletext <- c("The only reason for (the haste) which we can discern is the prospect of an Olympic medal, which is the raison d'etat of the banana republic,'' The Guardian said in an editorial under the headline ''Whatever Zola Wants. . .'' The Government made it clear it had acted promptly on the application to insure that the 5-foot-2-inch track star could qualify for the British Olympic team. The International Olympic Organization has a rule that says athletes who change their nationality must wait three years before competing for that country - a rule, however, that is often waived by the I.O.C. The British Olympic Association said it consulted with the I.O.C. before asserting Miss Budd's eligibility for the British team. ''Since Zola is now here and has a British passport she should be made to feel welcome and accepted by other British athletes,'' said Paul Dickenson, chairman of the International Athletes Club, an organization that raises money for amateur athletes and looks after their political interests. ''The thing we objected to was the way she got into the country by the Government and the Daily Mail and the commercialization exploitation associated with it.", "That left 14 countries that have joined the Soviet-led withdrawal. Albania and Iran had announced that they would not compete and did not send written notification. Bolivia, citing financial trouble, announced Sunday it would not participate.The 1972 Munich Games had the previous high number of competing countries, 122.No Protest Planned on Zola Budd YAOUNDE, Cameroon, June 4 (AP) - African countries do not plan to boycott the Los Angeles Olympics in protest of the inclusion of Zola Budd, the South African-born track star, on the British team, according to Lamine Ba, the secretary-general of the Supreme Council for Sport in Africa. Because South Africa is banned from participation in the Olympics, Miss Budd, whose father is of British descent, moved to Britain in March and was granted British citizenship.75 Olympians to Train in Atlanta ATLANTA, June 4 (AP) - About 75 Olympic athletes from six African countries and Pakistan will participate in a month-long training camp this summer in Atlanta under a program financed largely by a grant from the United States Information Agency, Anne Bassarab, a member of Mayor Andrew Young's staff, said today. The athletes, from Mozambique, Tanzania, Zambia, Zimbabwe, Uganda, Somalia and Pakistan, will arrive here June 24.")
mycorpus <- corpus(exampletext)
mycorpus.nat <- corpus(kwic(mycorpus, "nationalit*", window = 5, valuetype = "glob"))
mycorpus.cit <- corpus(kwic(mycorpus, "citizenship", window = 5, valuetype = "glob"))
mycorpus.kwic <- mycorpus.nat + mycorpus.cit
mydfm <- dfm(mycorpus.kwic)

This, however, generates a dfm that contains 4 documents instead of 2, and when both keywords are present in a document even more. I can't think of a way to bring the dfm down to the original number of documents.

Thank you for helping me out.

Body:
We recently added window argument to tokens_select() for this purpose:

    require(quanteda)
    txt <- c("The only reason for (the haste) which we can discern is the prospect of an Olympic medal, which is the raison d'etat of the banana republic,'' The Guardian said in an editorial under the headline ''Whatever Zola Wants. . .'' The Government made it clear it had acted promptly on the application to insure that the 5-foot-2-inch track star could qualify for the British Olympic team. The International Olympic Organization has a rule that says athletes who change their nationality must wait three years before competing for that country - a rule, however, that is often waived by the I.O.C. The British Olympic Association said it consulted with the I.O.C. before asserting Miss Budd's eligibility for the British team. ''Since Zola is now here and has a British passport she should be made to feel welcome and accepted by other British athletes,'' said Paul Dickenson, chairman of the International Athletes Club, an organization that raises money for amateur athletes and looks after their political interests. ''The thing we objected to was the way she got into the country by the Government and the Daily Mail and the commercialization exploitation associated with it.", "That left 14 countries that have joined the Soviet-led withdrawal. Albania and Iran had announced that they would not compete and did not send written notification. Bolivia, citing financial trouble, announced Sunday it would not participate.The 1972 Munich Games had the previous high number of competing countries, 122.No Protest Planned on Zola Budd YAOUNDE, Cameroon, June 4 (AP) - African countries do not plan to boycott the Los Angeles Olympics in protest of the inclusion of Zola Budd, the South African-born track star, on the British team, according to Lamine Ba, the secretary-general of the Supreme Council for Sport in Africa. Because South Africa is banned from participation in the Olympics, Miss Budd, whose father is of British descent, moved to Britain in March and was granted British citizenship.75 Olympians to Train in Atlanta ATLANTA, June 4 (AP) - About 75 Olympic athletes from six African countries and Pakistan will participate in a month-long training camp this summer in Atlanta under a program financed largely by a grant from the United States Information Agency, Anne Bassarab, a member of Mayor Andrew Young's staff, said today. The athletes, from Mozambique, Tanzania, Zambia, Zimbabwe, Uganda, Somalia and Pakistan, will arrive here June 24.")
    toks <- tokens(txt)
    mt_nat <- dfm(tokens_select(toks, "nationalit*", window = 5))
    mt_cit <- dfm(tokens_select(toks, "citizenship*", window = 5))

Please make sure that you are using the latest version of Quanteda.


问:
Plsql block in process
Plsql code in process:

I want to join two procedure according to my item selection in apex page process:

P1_text_field - if I enter some email id then the procedure 1 should work

P2_select_list - if I enter somthing in this field then procedure 2 should work.

答:
It sounds like you want to write some conditional PL/SQL in a submit process:

```<code>if :P1_TEXT_FIELD is not null then
  procedure_1;
elsif :P2_SELECT_LIST is not null then
  procedure_2;
end if;
</code>```

This will only be run when the page is submitted, which could be when the user clicks a button or triggered by the item itself (see item properties).

Title: Plsql block in process

Body:
It sounds like you want to write some conditional PL/SQL in a submit process:

if :P1_TEXT_FIELD is not null then
  procedure_1;
elsif :P2_SELECT_LIST is not null then
  procedure_2;
end if;

This will only be run when the page is submitted, which could be when the user clicks a button or triggered by the item itself (see item properties).


问:
Java/Scala multi-threading issue for a web service
In a web service environment, I want to make a few independent http calls per each request that my application receives. As these calls are independent, it doesn't make sense to make them serially so I need a sort of concurrency.

To my understanding, it doesn't make sense to carelessly create new threads for each http call. And also, recreating all these threads brings a lot of overhead.

So I think my best option would be to create a FixedThreadPool in a singleton for all http calls and use that across the application.

Is this the best choice?

答: You should take a serious look at Akka, and specifically, the Camel support it offers.</p>


问:
WPF Datagrid in ScrollViewer with Dockpanel
I want to make my UI more responsable and right now I have this problem:

```<code><ScrollViewer VerticalScrollBarVisibility="Auto">
    <DockPanel LastChildFill="True">
        <StatusBar HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" DockPanel.Dock="Bottom">
            <StatusBarItem>
                <Ellipse Width="15" Height="15" Fill="{Binding StatusColor}"></Ellipse>
            </StatusBarItem>
            <StatusBarItem>
                <TextBlock Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}"></TextBlock>
            </StatusBarItem>
            <StatusBarItem HorizontalAlignment="Right">
                <TextBlock Text="{Binding StatusLastAction}"></TextBlock>
            </StatusBarItem>
        </StatusBar>
        <Grid DockPanel.Dock="Bottom" Margin="0,0,0,10">
            //
            // Fields to edid data from MySelectedItem
            //
        </Grid>
        <Grid DockPanel.Dock="Top">
            <DataGrid MinHeight="150" AutoGenerateColumns="True" SelectedItem="{Binding MySelectedItem}" HorizontalAlignment="Stretch" Margin="10,10,10,0" VerticalAlignment="Stretch" ItemsSource="{Binding MyItems}" IsReadOnly="True"/>
        </Grid>
    </DockPanel>
</ScrollViewer>
</code>```

This works like a charm until the point when the DataGrid gets to many items. The grid doesn't create a own scrollviewer it just uses the full height from the "Main"-ScrollViewer. (see image below - bottom-right)

Look here for wanted UI design (imgur)

black > Window

green > Scrollviewer

red > DataGrid

orange > fields to edit data

top left image (good):

there is enough space in the window to show everything

the DataGrid (red) fills the available space and has a own scoll viewer if there are to many items to show

top right image (good):

there isn't enough space to show all

the 'DataGrid' uses the min-height and the ScrollViewer (green) gets visible to show the rest (orange)

bottom left image (bad):

there is not enough space to show all

the DataGrid doen't use the min-height

bottom right image (bad):

there is enough space to show everything

the DataGrid uses all needed space to show all Item

Is there a way to design the UI as shown in the top images?

答:
I usually do not create screens so that they have an external scroll, that makes everything else complicated.
According to what you illustrated in the image, your DataGrid should have no height greater than the height of the screen.

So what you need to do is set a size for your grid, example: 60%, 70%, 80% of the height of your screen and the rest your other information

In the solution below I leave the DataGrid always with 80% of the height on the screen

XAML

```<code><Window x:Class="MyApp.MainWindow"
        .....
        Title="MainWindow"
        Name="MainWindowName"
        >

<DataGrid Height="{Binding ActualHeight, ElementName=MainWindowName, Converter={StaticResource PercentConverter}}"
          ScrollViewer.VerticalScrollBarVisibility="Auto"
          ScrollViewer.HorizontalScrollBarVisibility="Auto"
          ScrollViewer.CanContentScroll="True"
          />
</code>```

Converter Class

```<code>public class PercentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return 0;
        var valor = (int)(int.Parse(value.ToString()) * 0.8); //80% of my Window Height
        return valor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var valor = (int)(int.Parse(value.ToString()) / 0.8);
        return valor;
    }
}
</code>```

I tested with a large number of data generated in a simple loop

ViewModel (My test)

```<code>public MainViewModel()
{
    MyItems = new ObservableCollection<MyData>();
    for (var i = 0;i < 1000;i++)
        MyItems.Add(new MyData { Id = i, Name = GenerateNames() });

}

private string GenerateNames()
{
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var n = _random.Next(5, 15);
    return new string(Enumerable.Repeat(chars, n).Select(s => s[_random.Next(s.Length)]).ToArray());
}
</code>```

resulting in the image below, and whatever the size of the window the DataGrid will be 80% of the height of it

Edit:
if you do not need the external scroll, ie if it is possible to keep everything visible at the same time on the screen the best way is to leave everything with relative position, this way:

```<code><Grid.RowDefinitions>
    <RowDefinition Height="6*"/> // 6*
    <RowDefinition Height="3*"/>
    <RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<!-- 6 *, 3 *, *, Auto, <fixed value> are possible values at row height, 6 and 3 means how much of the ratio I'm adding to them -->

<Grid Grid.Row="0" >
    <DataGrid AutoGenerateColumns="True"
              SelectedItem="{Binding MySelectedItem}"
              HorizontalAlignment="Stretch"
              Margin="10,10,10,0"
              VerticalAlignment="Stretch"
              ItemsSource="{Binding MyItems}"
              IsReadOnly="True"
              ScrollViewer.VerticalScrollBarVisibility="Auto"
              ScrollViewer.HorizontalScrollBarVisibility="Auto"
              ScrollViewer.CanContentScroll="True"
              />
</Grid>

<Grid  Grid.Row="1" Margin="0,0,0,10">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Content="This is an example"/>
    <Label Grid.Row="1" Content="This is an example"/>
</Grid>

<StatusBar Grid.Row="2"
           HorizontalAlignment="Stretch"
           Margin="0,0,0,0"
           VerticalAlignment="Stretch"
           DockPanel.Dock="Bottom">
    <StatusBarItem>
        <Ellipse Width="15" Height="15" Fill="{Binding StatusColor}"></Ellipse>
    </StatusBarItem>
    <StatusBarItem>
        <TextBlock Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}"></TextBlock>
    </StatusBarItem>
    <StatusBarItem HorizontalAlignment="Right">
        <TextBlock Text="{Binding StatusLastAction}"></TextBlock>
    </StatusBarItem>
</StatusBar>
</code>```

Body:
I want to make my UI more responsable and right now I have this problem:

<ScrollViewer VerticalScrollBarVisibility="Auto">
    <DockPanel LastChildFill="True">
        <StatusBar HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" DockPanel.Dock="Bottom">
            <StatusBarItem>
                <Ellipse Width="15" Height="15" Fill="{Binding StatusColor}"></Ellipse>
            </StatusBarItem>
            <StatusBarItem>
                <TextBlock Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}"></TextBlock>
            </StatusBarItem>
            <StatusBarItem HorizontalAlignment="Right">
                <TextBlock Text="{Binding StatusLastAction}"></TextBlock>
            </StatusBarItem>
        </StatusBar>
        <Grid DockPanel.Dock="Bottom" Margin="0,0,0,10">
            //
            // Fields to edid data from MySelectedItem
            //
        </Grid>
        <Grid DockPanel.Dock="Top">
            <DataGrid MinHeight="150" AutoGenerateColumns="True" SelectedItem="{Binding MySelectedItem}" HorizontalAlignment="Stretch" Margin="10,10,10,0" VerticalAlignment="Stretch" ItemsSource="{Binding MyItems}" IsReadOnly="True"/>
        </Grid>
    </DockPanel>
</ScrollViewer>

This works like a charm until the point when the DataGrid gets to many items. The grid doesn't create a own scrollviewer it just uses the full height from the "Main"-ScrollViewer. (see image below - bottom-right)

Look here for wanted UI design (imgur)

black > Window

green > Scrollviewer

red > DataGrid

orange > fields to edit data

top left image (good):

there is enough space in the window to show everything

the DataGrid (red) fills the available space and has a own scoll viewer if there are to many items to show

top right image (good):

there isn't enough space to show all

the 'DataGrid' uses the min-height and the ScrollViewer (green) gets visible to show the rest (orange)

bottom left image (bad):

there is not enough space to show all

the DataGrid doen't use the min-height

bottom right image (bad):

there is enough space to show everything

the DataGrid uses all needed space to show all Item

Is there a way to design the UI as shown in the top images?

Body:
I usually do not create screens so that they have an external scroll, that makes everything else complicated.
According to what you illustrated in the image, your DataGrid should have no height greater than the height of the screen.

So what you need to do is set a size for your grid, example: 60%, 70%, 80% of the height of your screen and the rest your other information

In the solution below I leave the DataGrid always with 80% of the height on the screen

XAML

<Window x:Class="MyApp.MainWindow"
        .....
        Title="MainWindow"
        Name="MainWindowName"
        >

<DataGrid Height="{Binding ActualHeight, ElementName=MainWindowName, Converter={StaticResource PercentConverter}}"
          ScrollViewer.VerticalScrollBarVisibility="Auto"
          ScrollViewer.HorizontalScrollBarVisibility="Auto"
          ScrollViewer.CanContentScroll="True"
          />

Converter Class

public class PercentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return 0;
        var valor = (int)(int.Parse(value.ToString()) * 0.8); //80% of my Window Height
        return valor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var valor = (int)(int.Parse(value.ToString()) / 0.8);
        return valor;
    }
}

I tested with a large number of data generated in a simple loop

ViewModel (My test)

public MainViewModel()
{
    MyItems = new ObservableCollection<MyData>();
    for (var i = 0;i < 1000;i++)
        MyItems.Add(new MyData { Id = i, Name = GenerateNames() });

}

private string GenerateNames()
{
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var n = _random.Next(5, 15);
    return new string(Enumerable.Repeat(chars, n).Select(s => s[_random.Next(s.Length)]).ToArray());
}

resulting in the image below, and whatever the size of the window the DataGrid will be 80% of the height of it

Edit:
if you do not need the external scroll, ie if it is possible to keep everything visible at the same time on the screen the best way is to leave everything with relative position, this way:

<Grid.RowDefinitions>
    <RowDefinition Height="6*"/> // 6*
    <RowDefinition Height="3*"/>
    <RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<!-- 6 *, 3 *, *, Auto, <fixed value> are possible values at row height, 6 and 3 means how much of the ratio I'm adding to them -->

<Grid Grid.Row="0" >
    <DataGrid AutoGenerateColumns="True"
              SelectedItem="{Binding MySelectedItem}"
              HorizontalAlignment="Stretch"
              Margin="10,10,10,0"
              VerticalAlignment="Stretch"
              ItemsSource="{Binding MyItems}"
              IsReadOnly="True"
              ScrollViewer.VerticalScrollBarVisibility="Auto"
              ScrollViewer.HorizontalScrollBarVisibility="Auto"
              ScrollViewer.CanContentScroll="True"
              />
</Grid>

<Grid  Grid.Row="1" Margin="0,0,0,10">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Content="This is an example"/>
    <Label Grid.Row="1" Content="This is an example"/>
</Grid>

<StatusBar Grid.Row="2"
           HorizontalAlignment="Stretch"
           Margin="0,0,0,0"
           VerticalAlignment="Stretch"
           DockPanel.Dock="Bottom">
    <StatusBarItem>
        <Ellipse Width="15" Height="15" Fill="{Binding StatusColor}"></Ellipse>
    </StatusBarItem>
    <StatusBarItem>
        <TextBlock Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}"></TextBlock>
    </StatusBarItem>
    <StatusBarItem HorizontalAlignment="Right">
        <TextBlock Text="{Binding StatusLastAction}"></TextBlock>
    </StatusBarItem>
</StatusBar>


问:
Upload image using postman
Hi I got this error whenever i want to upload images in NODE JS (MongoDB)using postman could anyone explain .  Below is the screenshot of the error.
 I use the header content type = image/png and use the raw to upload image

[Error: EACCES: permission denied, open '/home/pavithra/node-mobile/uploads/posts/2209fb177948bc4801dc5f6c244013f5'

    at Error (native)

答: Probably you are missing some kind of authentication required to POST data to the server.

Title: Upload image using postman


问:
check previous and current element of array
Imagine: I have a an array: ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];

I consider which function should I use to:

find first NaN element in array (let say index = 2) and check if the next (index = 3) is also NaN and if yes (delete from array element with index = 2).

So the result of the transformed array should be: ["1", "2",".", "4", "3", "-", "12"];

I do not want your code, just suggestion/help how to start it.

Thank you for your responses and help.

答:
You could just check the array for two following NaN values.

var array = ["1", "2", "X", ".", "4", "3", "Z", "-", "12"],
    result = array.filter((v, i, a) => !isNaN(v) || !isNaN(a[i + 1]));

console.log(result);```


问:
Docker-image-as-executable: should I execute in CMD or ENTRYPOINT?
I am creating a Docker image to initialize my PostgreSQL database. It looks like this:

```<code>FROM debian:stretc

RUN set -x \
     && ... ommitted ...
     && apt-get install postgresql-client -y

COPY scripts /scripts

CMD cd /scripts && psql -f myscript.sql
</code>```

This works great. Every time I need to initialize my database I start the container (docker run --rm my-image). After the psql command is done, the container is automatically stopped and removed (because of the --rm). So basically, I have a Docker-image-as-executable.

But, I am confused whether that last line should be:

```<code>CMD cd /scripts && psql -f myscript.sql
</code>```

or

```<code>ENTRYPOINT cd /scripts && psql -f myscript.sql
</code>```

Which one should be used in my case (Docker-image-as-excutable)? Why?

答:
Both Entrypoint and Command will do the same thing. The only main difference is that when you use CMD you have more flexibilty in overriding the command that runs from the CLI.

so If you have the dockerfile:

```<code>FROM debian:stretc

RUN set -x \
     && ... ommitted ...
     && apt-get install postgresql-client -y

COPY scripts /scripts

CMD cd /scripts && psql -f myscript.sql
</code>```

You can override the CMD defined in the dockerfile from the cli to run a different command:

```<code>docker run --rm my-image psql -f MYSCRIPT2.sql
</code>```

This will run MYSCRIPT2.sql as given in the cli. You can't do that with ENRTYPOINT.

Body:
I am creating a Docker image to initialize my PostgreSQL database. It looks like this:

FROM debian:stretc

RUN set -x \
     && ... ommitted ...
     && apt-get install postgresql-client -y

COPY scripts /scripts

CMD cd /scripts && psql -f myscript.sql

This works great. Every time I need to initialize my database I start the container (docker run --rm my-image). After the psql command is done, the container is automatically stopped and removed (because of the --rm). So basically, I have a Docker-image-as-executable.

But, I am confused whether that last line should be:

CMD cd /scripts && psql -f myscript.sql

or

ENTRYPOINT cd /scripts && psql -f myscript.sql

Which one should be used in my case (Docker-image-as-excutable)? Why?

Body:
Both Entrypoint and Command will do the same thing. The only main difference is that when you use CMD you have more flexibilty in overriding the command that runs from the CLI.

so If you have the dockerfile:

FROM debian:stretc

RUN set -x \
     && ... ommitted ...
     && apt-get install postgresql-client -y

COPY scripts /scripts

CMD cd /scripts && psql -f myscript.sql

You can override the CMD defined in the dockerfile from the cli to run a different command:

docker run --rm my-image psql -f MYSCRIPT2.sql

This will run MYSCRIPT2.sql as given in the cli. You can't do that with ENRTYPOINT.


问:
TypeError: must be str, not datetime.timedelta
here is my code it works fine for the first print and the give me this error
TypeError: must be str, not datetime.timedelta

```<code>import datetime
hour = datetime.datetime.now().hour
tomorrow = datetime.datetime.now()
for i in range(50):
    hour += 1
    print(hour)
    if hour >= 23:
        tomorrow = tomorrow + datetime.timedelta(days=1)
        tomorrow = tomorrow.strftime('%d/%m/%Y')
        hour = 9
        print (tomorrow)
</code>```

here is the output :

```<code>13
14
15
16
17
18
19
20
21
22
23
07/12/2017
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Traceback (most recent call last):
  File "C:\Users\hamza.salhi\Desktop\datetime test.py", line 8, in <module>
    tomorrow = tomorrow + datetime.timedelta(days=1)
TypeError: must be str, not datetime.timedelta
</code>```

please can someone tell me why it works fine at first then i get that error

答:
tomorrow = tomorrow.strftime('%d/%m/%Y')
Changes the type of tomorrow to string, so it can't be added to datetime.timedelta.

Instead of doing:

```<code>tomorrow = tomorrow + datetime.timedelta(days=1)
tomorrow = tomorrow.strftime('%d/%m/%Y')
...
print (tomorrow)
</code>```

Try:

```<code>tomorrow = tomorrow + datetime.timedelta(days=1)
...
print('{:%d/%m/%Y}'.format(tomorrow))
</code>```

Body:
here is my code it works fine for the first print and the give me this error
TypeError: must be str, not datetime.timedelta

import datetime
hour = datetime.datetime.now().hour
tomorrow = datetime.datetime.now()
for i in range(50):
    hour += 1
    print(hour)
    if hour >= 23:
        tomorrow = tomorrow + datetime.timedelta(days=1)
        tomorrow = tomorrow.strftime('%d/%m/%Y')
        hour = 9
        print (tomorrow)

here is the output :

13
14
15
16
17
18
19
20
21
22
23
07/12/2017
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Traceback (most recent call last):
  File "C:\Users\hamza.salhi\Desktop\datetime test.py", line 8, in <module>
    tomorrow = tomorrow + datetime.timedelta(days=1)
TypeError: must be str, not datetime.timedelta

please can someone tell me why it works fine at first then i get that error

Body:
tomorrow = tomorrow.strftime('%d/%m/%Y')
Changes the type of tomorrow to string, so it can't be added to datetime.timedelta.

Instead of doing:

tomorrow = tomorrow + datetime.timedelta(days=1)
tomorrow = tomorrow.strftime('%d/%m/%Y')
...
print (tomorrow)

Try:

tomorrow = tomorrow + datetime.timedelta(days=1)
...
print('{:%d/%m/%Y}'.format(tomorrow))


问:
output showing nil result in console when passing
I am new iOS development and still learning basics, my query is when i passed the data to other view controller from my main tableView controller so it is passing smoothly but the output result is showing nil in the console as shown below
here as you can see output in console is nil.This is my second view controller named as movieDetailViewController

below is my main tableView controller from where i am calling my second view controller.

```<code>   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        destination.film = movies[(tables.indexPathForSelectedRow?.row)!] as? Movie
    }
  }
}
</code>```

Here the structure Movie is a normal swift file containing attributes that i want to print shown as below:

```<code>import Foundation

struct Movie {

     var title: String
     var overview: String
     var poster_path: String

}
</code>```

Now as i describe that output when passed to another view controller is showing nil. I have been stuck in this problem from 1 week and also searched a lot but no solution helped me in this .

答:
try this </p>

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

 let mv = movies[indexPath.row]

 performSegue(withIdentifier: "showDetails", sender: mv)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if let destination = segue.destination as? movieDetailViewController
{
    destination.film = sender as? Movie
}
}
</code>```

Body:
I am new iOS development and still learning basics, my query is when i passed the data to other view controller from my main tableView controller so it is passing smoothly but the output result is showing nil in the console as shown below
here as you can see output in console is nil.This is my second view controller named as movieDetailViewController

below is my main tableView controller from where i am calling my second view controller.

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        destination.film = movies[(tables.indexPathForSelectedRow?.row)!] as? Movie
    }
  }
}

Here the structure Movie is a normal swift file containing attributes that i want to print shown as below:

import Foundation

struct Movie {

     var title: String
     var overview: String
     var poster_path: String

}

Now as i describe that output when passed to another view controller is showing nil. I have been stuck in this problem from 1 week and also searched a lot but no solution helped me in this .

Body:
try this

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

 let mv = movies[indexPath.row]

 performSegue(withIdentifier: "showDetails", sender: mv)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if let destination = segue.destination as? movieDetailViewController
{
    destination.film = sender as? Movie
}
}


问:
Select the specific column of ListView and print it in a new messagebox in C#.net
I've just started to use ListView in C#.net.

I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.

I want to know how to do this.

I found this code to list a specific selected data from a row:

ListView.SelectedIndexCollection sel = listView1.SelectedIndices;

```<code>        if (sel.Count == 1)
        {
            ListViewItem selItem = listView1.Items[sel[0]];
            MessageBox.Show(selItem.SubItems[2].Text);
        }
</code>```

That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?

答:
```<code>    private string[] GetListViewItemColumns(ListViewItem item) {
        var columns = new string[item.SubItems.Count];
        for (int column = 0; column < columns.Length; column++) {
            columns[column] = item.SubItems[column].Text;
        }
        return columns;
    }
</code>```

I would recommend some caution against doing this.  A ListView is really meant to display information, it is not a great collection class.  Getting the data out of it is slow and crummy, it can only store strings.  Keep the data in your program in its original form, maybe a List<Foo>.  Now it is simple and fast.

Body:
I've just started to use ListView in C#.net.

I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.

I want to know how to do this.

I found this code to list a specific selected data from a row:

ListView.SelectedIndexCollection sel = listView1.SelectedIndices;

        if (sel.Count == 1)
        {
            ListViewItem selItem = listView1.Items[sel[0]];
            MessageBox.Show(selItem.SubItems[2].Text);
        }

That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?

Body:
    private string[] GetListViewItemColumns(ListViewItem item) {
        var columns = new string[item.SubItems.Count];
        for (int column = 0; column < columns.Length; column++) {
            columns[column] = item.SubItems[column].Text;
        }
        return columns;
    }

I would recommend some caution against doing this.  A ListView is really meant to display information, it is not a great collection class.  Getting the data out of it is slow and crummy, it can only store strings.  Keep the data in your program in its original form, maybe a List<Foo>.  Now it is simple and fast.


问:
PHP Regex Extract Substring with Quotes and Brackets
I have the following String examples:

```<code>new myProduct('', 'bbc_609'),
new myProduct('', '35857'),
</code>```

I want to be able to extract just the codes in the second set of single quotes:  bbc_609 or 35857

What I have tried:

```<code>$str = "new myProduct('', 'bbc_609'),";
preg_match('/ new myProduct('', '  ' (.*?) ''),/', $str, $match);
echo $match[1];
</code>```

I am getting a parse error so I am assuming that I am not escaping the quotes or brackets properly?

Any help appreciated.

Cheers

Body:
I have the following String examples:

new myProduct('', 'bbc_609'),
new myProduct('', '35857'),

I want to be able to extract just the codes in the second set of single quotes:  bbc_609 or 35857

What I have tried:

$str = "new myProduct('', 'bbc_609'),";
preg_match('/ new myProduct('', '  ' (.*?) ''),/', $str, $match);
echo $match[1];

I am getting a parse error so I am assuming that I am not escaping the quotes or brackets properly?

Any help appreciated.

Cheers

Body:
You can try that:

\(\s*'[^'\)]*'\s*,\s*'\K[^'\)]*(?=\s*')

Demo


问:
React - What is the best way to change an elements text each time the user clicks anywhere on screen?
I've started learning React, and after having read through the documentation, have a question..

I want to do the following:

I want to render text as part of a component. Then when a user clicks anywhere on the screen, the text changes, then changes again on a second click, and then again on a third, and finally, a fourth click.

I'd like to know what best practice would be when doing this in react? I was thinking about using the 'onClick' method, but that would only allow for two states?

Some assistance would be very much appreciated to help me on my react journey.

const welcome =
Welcome to my app 1/4
;

ReactDOM.render(
  welcome,
  document.getElementById('theapp')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/styles.css">
  <title>Learn ReactJS</title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>
  <script src="https://s3.amazonaws.com/codecademy-content/courses/React/react-course-bundle.min.js"></script>
  <script src="/app.compiled.js"></script>

  <div id="theapp"></div>

</body>

</html></code>```

答:
Since you know you want exactly 4 messages, create an array containing them. Then, on each click update a counter which is then used to fetch the relevant item from the array.

Check the demos below.

Message change on
 click

This snippet has a counter/index and an array with the messages to display defined in the initial state. We are then adding an eventlistener to the h1 element to trigger on click. Doing so increases the index as long as it's not greater than 2 (at which point there are no more messages left to display).

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      messages: ["foo", "bar", "baz", "qux"],
      index: 0
    };
    this.incrementCounter = this.incrementCounter.bind(this);
  }

  incrementCounter() {
    if(this.state.index > 2) return;
    this.setState((prevState) => ({index: prevState.index + 1}));
  }

  render() {
    return
{this.state.messages[this.state.index]}

  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Message change on window click

Similar to the previous example, here we are adding the listener to the window object itself. We need to do this in the componentDidMount method.

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      messages: ["foo", "bar", "baz", "qux"],
      index: 0
    };
  }

  componentDidMount() {
    window.addEventListener("click", function() {
      if(this.state.index > 2) return;
      this.setState((prevState) => ({index: prevState.index + 1}));
    }.bind(this));
  }

  render() {
    return
{this.state.messages[this.state.index]}

  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
I've started learning React, and after having read through the documentation, have a question..

I want to do the following:

I want to render text as part of a component. Then when a user clicks anywhere on the screen, the text changes, then changes again on a second click, and then again on a third, and finally, a fourth click.

I'd like to know what best practice would be when doing this in react? I was thinking about using the 'onClick' method, but that would only allow for two states?

Some assistance would be very much appreciated to help me on my react journey.

const welcome =
Welcome to my app 1/4
;

ReactDOM.render(
  welcome,
  document.getElementById('theapp')
);

<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="/styles.css">
  <title>Learn ReactJS</title>

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

Body:
Since you know you want exactly 4 messages, create an array containing them. Then, on each click update a counter which is then used to fetch the relevant item from the array.

Check the demos below.

Message change on <h1> click

This snippet has a counter/index and an array with the messages to display defined in the initial state. We are then adding an eventlistener to the h1 element to trigger on click. Doing so increases the index as long as it's not greater than 2 (at which point there are no more messages left to display).

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      messages: ["foo", "bar", "baz", "qux"],
      index: 0
    };
    this.incrementCounter = this.incrementCounter.bind(this);
  }

  incrementCounter() {
    if(this.state.index > 2) return;
    this.setState((prevState) => ({index: prevState.index + 1}));
  }

  render() {
    return <h1 onClick={this.incrementCounter}>{this.state.messages[this.state.index]}</h1>
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Message change on window click

Similar to the previous example, here we are adding the listener to the window object itself. We need to do this in the componentDidMount method.

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      messages: ["foo", "bar", "baz", "qux"],
      index: 0
    };
  }

  componentDidMount() {
    window.addEventListener("click", function() {
      if(this.state.index > 2) return;
      this.setState((prevState) => ({index: prevState.index + 1}));
    }.bind(this));
  }

  render() {
    return <h1>{this.state.messages[this.state.index]}</h1>
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
Using Java Stream anymatch with filter for null check
I am using Stream.anymatch to check if any of the four string is empty or null- Can we get handle to the list of Strings that are null  as a part of this check for subsequent logic   </p>

```<code>if(Stream.of(stringA, stringB,stringC, stringD)
        .anyMatch(field -> field == null || field.trim().isEmpty()))
</code>```

答:
I would suggest you use StringUtils.isBlank() from Apache Commons libraries https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

Then you can use a temporary value to store Objects with blank values using

```<code>List<String> blank = Stream.of(stringA, stringB,stringC, stringD)
                           .filter(StringUtils::isBlank)
                           .collect(Collectors.toList());
if (blank.size() > 0) {
      // your code here
}
</code>```

I suggest you use multiple if(StringUtils.isBlank(stringX)){} statements if you need to execute different code in each case.

Body:
I am using Stream.anymatch to check if any of the four string is empty or null- Can we get handle to the list of Strings that are null  as a part of this check for subsequent logic

if(Stream.of(stringA, stringB,stringC, stringD)
        .anyMatch(field -> field == null || field.trim().isEmpty()))

Body:
I would suggest you use StringUtils.isBlank() from Apache Commons libraries https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

Then you can use a temporary value to store Objects with blank values using

List<String> blank = Stream.of(stringA, stringB,stringC, stringD)
                           .filter(StringUtils::isBlank)
                           .collect(Collectors.toList());
if (blank.size() > 0) {
      // your code here
}

I suggest you use multiple if(StringUtils.isBlank(stringX)){} statements if you need to execute different code in each case.


问:
How can I find a range in an array using user input?
```<code>package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}
</code>```

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

```<code>Arrays.asList(a).indexOf(index1)
</code>```

but that will give me -1 every time
And I don't know how to make it wors in the other method

答:
```<code>public double doubleSegsum(double[] a, int from, int to) {
    return DoubleStream.of(a).skip(from).limit(to-from).sum();
}
</code>```

Body:
package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

Arrays.asList(a).indexOf(index1)

but that will give me -1 every time
And I don't know how to make it wors in the other method


问:
How to get id from the directive template and pass in function?
I am trying to get id from a template's function, but i am unable to get it. without arguments i can easily call a function but with arguments i dont know how to do this. So far this is what i did.

Directive Template (Job search Html)

```<code><div class="artist-job-search-filters">
                    <div class="foo" ng-click="$ctrl.changeArtistJobFilter(1)" ng-class="$ctrl.searchFilterAll ? 'artist-filter-selected' : 'artist-filter'">All</div>
                    <div class="foo" ng-click="$ctrl.changeArtistJobFilter(2)" ng-class="$ctrl.searchFilterJob ? 'artist-filter-selected' : 'artist-filter'">Job</div>
                    <div class="foo" ng-click="$ctrl.changeArtistJobFilter(3)" ng-class="$ctrl.searchFilterStandBy ? 'artist-filter-selected' : 'artist-filter'">Standby</div>
                    <div class="foo" ng-click="$ctrl.changeArtistJobFilter(4)" ng-class="$ctrl.searchFilterAudition ? 'artist-filter-selected' : 'artist-filter'">Audition</div>
                    <div class="foo" ng-click="$ctrl.changeArtistJobFilter(5)" ng-class="$ctrl.searchFilterApplied ? 'artist-filter-selected' : 'artist-filter'">Applied</div>
                </div>
</code>```

Here changeArtistJobFilteris my function and i am passing values. Below is my directive.js

Directive.js

```<code>app.directive('jobsSearch', function () {

return {
    restrict: 'EA',
    scope: {
        'artistSearchModel': "=",
        'showDropdown': "=",
        'operaticRoleSearchResult' : "=",
        'viewAllJobs' : "&",
        'musicalWorkSearchResult' : "=",
        'institutionSearchResult' : "=",
        'changeArtistJobFilter' : "&",
        'searchFilterAll' : "=",
        'searchFilterJob' : "=",
        'searchFilterStandBy' : "=",
        'searchFilterAudition' : "=",
        'searchFilterApplied' : "=",
        'searchArtistJob': "&"
    },
    controller: function () { },
    controllerAs: '$ctrl',
    bindToController: true,
    templateUrl: '/views/profile/directives/job_search.html'
};
</code>```

});

And here is the view from where i am calling the directive.

View Html with directive

```<code><jobs-search artist-search-model="jobDashboard.artistSearchModel"
          search-artist-job="jobDashboard.searchArtistJob()"
          show-dropdown="jobDashboard.showDropdown"
          operatic-roleSearch-result="jobDashboard.operaticRoleSearchResult"
          view-all-jobs="jobDashboard.viewAllJobs()"
          musical-work-search-result="jobDashboard.musicalWorkSearchResult"
          institution-search-result="jobDashboard.institutionSearchResult"
          change-artist-job-filter="jobDashboard.changeArtistJobFilter()"
          search-filter-all="jobDashboard.searchFilterAll"
          search-filter-job="jobDashboard.searchFilterJob"
          search-filter-stand-by="jobDashboard.searchFilterStandBy"
          search-filter-audition="jobDashboard.searchFilterAudition"
          search-filter-applied="jobDashboard.searchFilterApplied"
          ></jobs-search>
</code>```

答:
Just put an argument inside function from where you calling the directive</p>

```<code>change-artist-job-filter="jobDashboard.changeArtistJobFilter(**filter**)"
</code>```

Body:
I am trying to get id from a template's function, but i am unable to get it. without arguments i can easily call a function but with arguments i dont know how to do this. So far this is what i did.

Directive Template (Job search Html)

All

Job

Standby

Audition

Applied

Here changeArtistJobFilteris my function and i am passing values. Below is my directive.js

Directive.js

app.directive('jobsSearch', function () {

return {
    restrict: 'EA',
    scope: {
        'artistSearchModel': "=",
        'showDropdown': "=",
        'operaticRoleSearchResult' : "=",
        'viewAllJobs' : "&",
        'musicalWorkSearchResult' : "=",
        'institutionSearchResult' : "=",
        'changeArtistJobFilter' : "&",
        'searchFilterAll' : "=",
        'searchFilterJob' : "=",
        'searchFilterStandBy' : "=",
        'searchFilterAudition' : "=",
        'searchFilterApplied' : "=",
        'searchArtistJob': "&"
    },
    controller: function () { },
    controllerAs: '$ctrl',
    bindToController: true,
    templateUrl: '/views/profile/directives/job_search.html'
};

});

And here is the view from where i am calling the directive.

View Html with directive

<jobs-search artist-search-model="jobDashboard.artistSearchModel"
          search-artist-job="jobDashboard.searchArtistJob()"
          show-dropdown="jobDashboard.showDropdown"
          operatic-roleSearch-result="jobDashboard.operaticRoleSearchResult"
          view-all-jobs="jobDashboard.viewAllJobs()"
          musical-work-search-result="jobDashboard.musicalWorkSearchResult"
          institution-search-result="jobDashboard.institutionSearchResult"
          change-artist-job-filter="jobDashboard.changeArtistJobFilter()"
          search-filter-all="jobDashboard.searchFilterAll"
          search-filter-job="jobDashboard.searchFilterJob"
          search-filter-stand-by="jobDashboard.searchFilterStandBy"
          search-filter-audition="jobDashboard.searchFilterAudition"
          search-filter-applied="jobDashboard.searchFilterApplied"
          ></jobs-search>

Body:
Just put an argument inside function from where you calling the directive

change-artist-job-filter="jobDashboard.changeArtistJobFilter(**filter**)"


问:
DAX Calculate the MAX of a SUM measure
I have an SSAS tabular model based on Inventory data.  The data contains not only the current (i.e. todays) On Hand values, but also 90 days worth of history.  Here is a very small sample of data:

I need to create a DAX measure that will return that MAX Qty on Hand for each Material over the 90 days worth of history.  In the sample above, the MAX would be 6, because on 2-Dec there was 3 in Loc A and 3 in Loc b.

I have tried the following DAX calculation:

```<code>CALCULATE (MAX(Inventory[SAP Qty On Hand]), ALL('Date'))
</code>```

However, this is returning 3, rather than 6.  It needs to aggregate by date before doing the MAX.

Any ideas?

答:
Try creating a summary table first, then taking the max of the summary</p>

```<code>MAXX(
    SUMMARIZE(
        'Inventory',
        [Date],
        "Total Date Qty",
        SUM([SAP Qty On Hand])
    ),
    [Total Date Qty]
)
</code>```

Title: DAX Calculate the MAX of a SUM measure

Body:
I have an SSAS tabular model based on Inventory data.  The data contains not only the current (i.e. todays) On Hand values, but also 90 days worth of history.  Here is a very small sample of data:

I need to create a DAX measure that will return that MAX Qty on Hand for each Material over the 90 days worth of history.  In the sample above, the MAX would be 6, because on 2-Dec there was 3 in Loc A and 3 in Loc b.

I have tried the following DAX calculation:

CALCULATE (MAX(Inventory[SAP Qty On Hand]), ALL('Date'))

However, this is returning 3, rather than 6.  It needs to aggregate by date before doing the MAX.

Any ideas?

Body:
Try creating a summary table first, then taking the max of the summary

MAXX(
    SUMMARIZE(
        'Inventory',
        [Date],
        "Total Date Qty",
        SUM([SAP Qty On Hand])
    ),
    [Total Date Qty]
)


问:
How to check if there is a string equal to your variable in a csv file line
I have a variable (aTerm) which contains an 8 digit random number which im using to uniquely identify each individual line of a csv file.

Here is the code I wrote to remove the line which has the corresponding number:

```<code>def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not aTerm in line:
                newFile.write(line)
return
</code>```

The only trouble is that it doesn't work at all unless I type out the 8 digit number as a string in the if statement. So this works perfectly:

```<code>def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not "45893243" in line:
                newFile.write(line)
return
</code>```

I don't understand and would greatly appreciate the help thanks

答: The problem was that for some reason the innerHTML I had passed from my webpage to flask had a tonne of spaces around it so I had to strip it. This question has been answered by Reblochon Masque.</p>

Body:
I have a variable (aTerm) which contains an 8 digit random number which im using to uniquely identify each individual line of a csv file.

Here is the code I wrote to remove the line which has the corresponding number:

def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not aTerm in line:
                newFile.write(line)
return

The only trouble is that it doesn't work at all unless I type out the 8 digit number as a string in the if statement. So this works perfectly:

def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not "45893243" in line:
                newFile.write(line)
return

I don't understand and would greatly appreciate the help thanks


问:
Swift selector function with optional closure?
What am I doing wrong with the #selector assignment when I add the notification observer?

```<code>NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(rawValue: "reloadCollectionData"), object: nil)

func reloadData(completionHandler: ((Bool) -> Void)? = nil ) {
    mainCollectionView.reloadData()

    completionHandler?(true)
}
</code>```

The app crashes whenever I post the notification:

```<code>NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadCollectionData"), object: nil)
</code>```

I have already tried things like #selector(reloadData(completionHandler: nil)

EDIT:
I have tried the selector #selector(reloadData(completionHandler:)) but it still crashes n the line where I post a notification, with the error message:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)

When I change the code as follows everything works fine but it is not really nice to create a function just to call another function

```<code>NotificationCenter.default.addObserver(self, selector: #selector(testCall), name: NSNotification.Name(rawValue: "reloadCollectionData"), object: nil)

func testCall() {
    self.reloadData()
}
</code>```

答:
A completion handler in a notification selector method is nonsensical (and illegal). What do you expect is the object which is supposed to be the receiver of the completion handler ... ?

The syntax of a notification selector is very similar to a target/action selector. The passed parameter must be the type of the affected object (here Notification).

```<code>func reloadData(_ notification : Notification) { ...
</code>```

The alternative is the block based API of Notification which is able to capture values of the enclosing function / method.

The only way to pass custom data in a notification object with specified selector is the (optional) userInfo dictionary.

Body:
What am I doing wrong with the #selector assignment when I add the notification observer?

NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(rawValue: "reloadCollectionData"), object: nil)

func reloadData(completionHandler: ((Bool) -> Void)? = nil ) {
    mainCollectionView.reloadData()

    completionHandler?(true)
}

The app crashes whenever I post the notification:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadCollectionData"), object: nil)

I have already tried things like #selector(reloadData(completionHandler: nil)

EDIT:
I have tried the selector #selector(reloadData(completionHandler:)) but it still crashes n the line where I post a notification, with the error message:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)

When I change the code as follows everything works fine but it is not really nice to create a function just to call another function

NotificationCenter.default.addObserver(self, selector: #selector(testCall), name: NSNotification.Name(rawValue: "reloadCollectionData"), object: nil)

func testCall() {
    self.reloadData()
}

Body:
A completion handler in a notification selector method is nonsensical (and illegal). What do you expect is the object which is supposed to be the receiver of the completion handler ... ?

The syntax of a notification selector is very similar to a target/action selector. The passed parameter must be the type of the affected object (here Notification).

func reloadData(_ notification : Notification) { ...

The alternative is the block based API of Notification which is able to capture values of the enclosing function / method.

The only way to pass custom data in a notification object with specified selector is the (optional) userInfo dictionary.