问:
Open app activity if clicked on a specific file in file browser
I want to open my activity if user clicks a specific text file in file browser like deep link.
Here is my code

```<code><activity
        android:name=".debug.DebugActivity"
        android:label="@string/debug_label"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="file" />
            <data android:host="*/*" />
            <data android:pathPattern =".*\\.txt" />
            <data android:host="*" />
        </intent-filter>
    </activity>
</code>```

How can I do that?
Thanks in Advance

答:
```<code><intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="file" />
            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:mimeType="text/html" />
            <data android:mimeType="text/plain" />
            <data android:mimeType="application/xhtml+xml" />
        </intent-filter>
</code>```

I got the solution with this

Body:
I want to open my activity if user clicks a specific text file in file browser like deep link.
Here is my code

<activity
        android:name=".debug.DebugActivity"
        android:label="@string/debug_label"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="file" />
            <data android:host="*/*" />
            <data android:pathPattern =".*\\.txt" />
            <data android:host="*" />
        </intent-filter>
    </activity>

How can I do that?
Thanks in Advance

Body:
<intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="file" />
            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:mimeType="text/html" />
            <data android:mimeType="text/plain" />
            <data android:mimeType="application/xhtml+xml" />
        </intent-filter>

I got the solution with this


来源: stackexchange

问:
Scenarios where automated testing is unhelpful
What are some situations where unit testing and TDD and the like are more trouble than they're worth?

Some things I've come up with are:

When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When the only practical way of verifying correctness of the code is to run it.

When you're testing visual elements of the design.

What are some other cases?

答: I think Michael summed it up quite nicely: "things that cannot really be formally specified". Turns out there are lots of things that cannot be formally specified. Usability is one example (although once you decided which behavior is usable, you can and should of course test that behavior!). Somewhat paradoxically, lots of numbercrunching tasks cannot be formally specified: Take for example a weather forecast. The goal is of course to predict tomorrow's weather, but that's not a formal specification. So you can either test if the algorithms you use do what they should do (calculating averages, inverting matrices, stuff that can be formally specified), but then your weather forecast program could pass all the tests and still be wrong 90% of the time. Or you could use lots of historical data to test if the algorithm yields good predictions, but this is dangerous, because it can easily lead to an algorithm that's only accurate for the historical data you used, not in general. And it would probably mean that your unit tests take hours or days to run. Even worse, your algorithm might have parameters that have to be "tweaked" e.g. for the measurement instruments used, and the optimal parameters might not be the same ones for every algorithm, so the unit-tests would need manual interaction for finding good parameters. Possible in theory, but probably not very useful. I guess the same arguments would apply to OCR, ICR, many signal processing task, face recognition (and many other image processing tasks), typical photoshop tools like "red eye removal", or search engine ranking algorithms (just to name a few examples).</p>

OwnerDisplayName: Shalmanese

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Niki

LastEditorDisplayName: Niki


问:
PrimeFaces gmap not rendering
Using PrimeFaces 2.2.RC2 in a JSF 2.0 project.

I'm trying to get a basic Google Map to render with the gmap component.  No errors show up just blank page where the map should be.

My .xhtml file

```<code><?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.prime.com.tr/ui">

    <h:head>
        <script src="http://maps.google.com/maps/api/js?sensor=false"
              type="text/javascript"></script>
    </h:head>
    <h:body>
        <f:view contentType="text/html">
            <h1>Google Map</h1>
            <p:gmap center="41.381542, 2.122893" zoom="15" type="HYBIRD"
                    style="width:600px;height:400px" />
        </f:view>
    </h:body>
</html>
</code>```

Not had any issues getting other PrimeFaces components to render in this project and the example on the PrimeFaces website renders in my browser just fine.

Any ideas ?

Update:

I changed the view tag to <f:view contentType="text/html">, now I get a grey box where the map should be and when I hover over the box the curser turns to white hand to grab and move the map around, but still no map shows.

答:
<f:view contentType="text/html"> is needed for it to work in Safari/Chrome

My other problem was HYBRID was spelled wrong, the following works:

```<code><h1>Google Map 1</h1>
<p:gmap center="41.381542, 2.122893" zoom="15" type="HYBRID"
  style="width:600px;height:400px" />
</code>```

Spelling was never my strong suit.

Title: PrimeFaces gmap not rendering

Body:
Using PrimeFaces 2.2.RC2 in a JSF 2.0 project.

I'm trying to get a basic Google Map to render with the gmap component.  No errors show up just blank page where the map should be.

My .xhtml file

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>

    </h:head>
    <h:body>
        <f:view contentType="text/html">

Google Map

        </f:view>
    </h:body>

Not had any issues getting other PrimeFaces components to render in this project and the example on the PrimeFaces website renders in my browser just fine.

Any ideas ?

Update:

I changed the view tag to <f:view contentType="text/html">, now I get a grey box where the map should be and when I hover over the box the curser turns to white hand to grab and move the map around, but still no map shows.

Body:
<f:view contentType="text/html"> is needed for it to work in Safari/Chrome

My other problem was HYBRID was spelled wrong, the following works:

<h1>Google Map 1</h1>
<p:gmap center="41.381542, 2.122893" zoom="15" type="HYBRID"
  style="width:600px;height:400px" />

Spelling was never my strong suit.


问:
SwiftyJson parse oData response

I am trying to parse a oData web service using SwiftyJSON

Here is my oData response:

```<code>{
  "odata.metadata":"http://url.com/odata/$metadata#Updates","value":[
    {
      "ID":1,"msgTitle":"Testing","reportedBy":"testUser"
    }

  ]
}
</code>```

Here is my Swift code:

```<code> Alamofire.request(URL, method: .get).responseString { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                self.activityIndicator.stopAnimating()
                let swiftyJsonVar = JSON(responseData.result.value!)
                print(swiftyJsonVar)
                if let resData = swiftyJsonVar["value"].arrayObject {
                    if let dict = resData as? [Dictionary<String, AnyObject>] {
                        for obj in dict {
                            let announce = announcement(fileDict: obj)
                            self.Announcements.append(announce)
                        }

                        self.tableView.reloadData()
                        self.tableView.isHidden = false
                    }
                }
            }
        }
</code>```

The problem is that resData is returning null.  What I am doing wrong to get the JSON within the value array?

I have also tried swiftyJsonVar[0]["value"].arrayObject without success.

答:
After consulting the swiftyJSON documentation, I was able to figure this out using the following syntax:</p>

```<code>Alamofire.request(URL, method: .get).responseString { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                self.activityIndicator.stopAnimating()
                //log.info("Response: \(responseData.result.value)")
                let jsonObj = responseData.result.value!
                if let dataFromString = jsonObj.data(using: .utf8, allowLossyConversion: false) {
                    let json = JSON(data: dataFromString)
                    print(json)
                    if let resData = json["value"].arrayObject {
                        if let dict = resData as? [Dictionary<String, AnyObject>] {
                            for obj in dict {
                                let announce = announcement(fileDict: obj)
                                self.Announcements.append(announce)
                            }

                            self.tableView.reloadData()
                            self.tableView.isHidden = false
                        }
                    }
                }
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: SwiftyJson parse oData response

Body:
I am trying to parse a oData web service using SwiftyJSON

Here is my oData response:

{
  "odata.metadata":"http://url.com/odata/$metadata#Updates","value":[
    {
      "ID":1,"msgTitle":"Testing","reportedBy":"testUser"
    }

  ]
}

Here is my Swift code:

 Alamofire.request(URL, method: .get).responseString { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                self.activityIndicator.stopAnimating()
                let swiftyJsonVar = JSON(responseData.result.value!)
                print(swiftyJsonVar)
                if let resData = swiftyJsonVar["value"].arrayObject {
                    if let dict = resData as? [Dictionary<String, AnyObject>] {
                        for obj in dict {
                            let announce = announcement(fileDict: obj)
                            self.Announcements.append(announce)
                        }

                        self.tableView.reloadData()
                        self.tableView.isHidden = false
                    }
                }
            }
        }

The problem is that resData is returning null.  What I am doing wrong to get the JSON within the value array?

I have also tried swiftyJsonVar[0]["value"].arrayObject without success.

Body:
After consulting the swiftyJSON documentation, I was able to figure this out using the following syntax:

Alamofire.request(URL, method: .get).responseString { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                self.activityIndicator.stopAnimating()
                //log.info("Response: \(responseData.result.value)")
                let jsonObj = responseData.result.value!
                if let dataFromString = jsonObj.data(using: .utf8, allowLossyConversion: false) {
                    let json = JSON(data: dataFromString)
                    print(json)
                    if let resData = json["value"].arrayObject {
                        if let dict = resData as? [Dictionary<String, AnyObject>] {
                            for obj in dict {
                                let announce = announcement(fileDict: obj)
                                self.Announcements.append(announce)
                            }

                            self.tableView.reloadData()
                            self.tableView.isHidden = false
                        }
                    }
                }
            }
        }


问:
Promise.map and callback on each resolved
I have an array of URLs which I am mapping (with bluebird's Promise.map) to http GET requests with max concurrency set:

```<code>const fetchingPages = Promise.map(urls, async url => {
  const data = await fetchPage(url)
  return data
}, { concurrency: 100 })
const pages = await fetchingPages
</code>```

How can I listen to each promise being resolved and do some side effect in an organized manner, i.e. don't put side effects inside .map callback?

Ideally, I would like to have array of "empty/dummy" promises ahead of time, so I can set callback to any of them before corresponding GET request is even sent.

I can do it like this:

```<code>const pagesUtils = urls.map((url) => {
  let resolve, reject
  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })
  return {
    url,
    promise,
    resolve,
    reject,
  }
})

const pagesPromises = pagesUtils.map(x => x.promise)

Promise.map(urlsFinal, async (url, i) => {
  const data = await fetchPageData(url)
  pagesUtils[i].resolve(data)
  return data
}, { concurrency: CONCURRENCY })

pagesPromises.forEach(p => {
  p.then((result) => {
    // side-effect
    console.log(result)
  })
})

const results = await Promise.all(pagesPromises)
</code>```

How can this be done in ideal way? Thanks.

答:
From your comment, it seems like you're bothered about putting a lot of code in the map callback. You don't have to, put the various bits of logic into discrete, composable functions as normal, and call them. E.g.:

```<code>const fetchingPages = Promise.map(urls, async url => {
  let data = await fetchPage(url)
  data = await doThis(data)
  if (/*...some condition...*/) {
    data = await doThat(data)
  }
  return data
}, { concurrency: 100 })
const pages = await fetchingPage
</code>```

(Naturally, you only have to await doThis or doThat if they're also asynchronous.)

Or in promise terms insted of async/await:

```<code>const fetchingPages = Promise.map(urls, url => {
  return fetchPage(url)
    .then(doThis)
    .then(data => /*...some condition...*/ ? doThat(data) : data)
}, { concurrency: 100 })
const pages = await fetchingPage
</code>```

Body:
I have an array of URLs which I am mapping (with bluebird's Promise.map) to http GET requests with max concurrency set:

const fetchingPages = Promise.map(urls, async url => {
  const data = await fetchPage(url)
  return data
}, { concurrency: 100 })
const pages = await fetchingPages

How can I listen to each promise being resolved and do some side effect in an organized manner, i.e. don't put side effects inside .map callback?

Ideally, I would like to have array of "empty/dummy" promises ahead of time, so I can set callback to any of them before corresponding GET request is even sent.

I can do it like this:

const pagesUtils = urls.map((url) => {
  let resolve, reject
  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })
  return {
    url,
    promise,
    resolve,
    reject,
  }
})

const pagesPromises = pagesUtils.map(x => x.promise)

Promise.map(urlsFinal, async (url, i) => {
  const data = await fetchPageData(url)
  pagesUtils[i].resolve(data)
  return data
}, { concurrency: CONCURRENCY })

pagesPromises.forEach(p => {
  p.then((result) => {
    // side-effect
    console.log(result)
  })
})

const results = await Promise.all(pagesPromises)

How can this be done in ideal way? Thanks.

Body:
From your comment, it seems like you're bothered about putting a lot of code in the map callback. You don't have to, put the various bits of logic into discrete, composable functions as normal, and call them. E.g.:

const fetchingPages = Promise.map(urls, async url => {
  let data = await fetchPage(url)
  data = await doThis(data)
  if (/*...some condition...*/) {
    data = await doThat(data)
  }
  return data
}, { concurrency: 100 })
const pages = await fetchingPage

(Naturally, you only have to await doThis or doThat if they're also asynchronous.)

Or in promise terms insted of async/await:

const fetchingPages = Promise.map(urls, url => {
  return fetchPage(url)
    .then(doThis)
    .then(data => /*...some condition...*/ ? doThat(data) : data)
}, { concurrency: 100 })
const pages = await fetchingPage


问:
Prolog operator errors in Pereira
Using SWI Prolog 7.7.2 in Ubuntu Linux, I am trying to run the "talk"
module from Pereira and Schieber (Appendix A,
http://www.mtome.com/Publications/PNLA/prolog-digital.pdf).

After copying, pasting into a text editor (Sublime), and adjusting
line breaks to (mostly) match the original, running swipl, and then
['talk.P'], I am encountering over two dozen "Syntax error: Operator
expected" errors, e.g. (with directory location replaced by [...]):

Lines 15-20:

```<code>main_loop :-
    write(’>> ’),       % prompt the user
    read_sent(Words),   % read a sentence
    talk(Words, Reply), % process it with TALK
    print_reply(Reply), % generate a printed reply
    main_loop.          % process more sentences
</code>```

ERROR: [...]/talk.P:16:15: Syntax error: Operator expected

---Line 38:

```<code>talk(_Sentence, error(’too difficult’)).
</code>```

ERROR: [...]/talk.P:38:25: Syntax error: Operator expected

---Lines 76-77:

```<code>% Replying to some other type of sentence.
reply(_Type, _FreeVars, _Clause, error(’unknown type’)).
</code>```

ERROR: [...]/talk.P:77:42: Syntax error: Operator expected

---Lines 87-91:

```<code>print_reply(error(ErrorType)) :-
    write(’Error: "’), write(ErrorType), write(’."’), nl.

print_reply(asserted(Assertion)) :-
    write(’Asserted "’), write(Assertion), write(’."’), nl.
</code>```

ERROR: [...]/talk.P:91:12: Syntax error: Operator expected

---Note I am also encountering ten singleton variable warnings, but am not sure whether this will prove to be a problem or not, e.g.:

---Lines 59-60:

```<code>reply(query, FreeVars,
    (answer(Answer):-Condition), Reply) :- Warning: [...]/talk.P:59:  Singleton variables:
</code>```

[FreeVars,Condition,FreeVarsˆCondition] Warning: [...]/talk.P:59:
    Singleton variable in branch: FreeVarsˆCondition

---Lines 242-243:

```<code>q(S => ‘answer(X)) -->
    whpron, vp(finite, XˆS, nogap).
</code>```

Warning: [...]/talk.P:242:    Singleton variables: [S,X,XˆS]

What do I need to do to get this module up and running?

答:
There are a couple of problems. The operator values (100, 500 etc) are compatible with older values for the standard operators and should be higher. Also, the back-quote/back-tick (ASCII 96) changed at some point from being a symbol to being a quote character.

I managed to get the files to load in SWI prolog, by changing the operators:

```<code>:- op(1000,xfy,&).
:- op(1010,xfy,=>).
:- op(200,fx,`).
</code>```

and giving the command line parameter --traditional (to make back-quote a symbol instead of a quote character).

```<code>$ swipl --traditional
Welcome to SWI-Prolog (threaded, 64 bits, version 7.4.2)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit http://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- [talk].
true.
</code>```

Title: Prolog operator errors in Pereira

Body:
Using SWI Prolog 7.7.2 in Ubuntu Linux, I am trying to run the "talk"
module from Pereira and Schieber (Appendix A,
http://www.mtome.com/Publications/PNLA/prolog-digital.pdf).

After copying, pasting into a text editor (Sublime), and adjusting
line breaks to (mostly) match the original, running swipl, and then
['talk.P'], I am encountering over two dozen "Syntax error: Operator
expected" errors, e.g. (with directory location replaced by [...]):

Lines 15-20:

main_loop :-
    write(’>> ’),       % prompt the user
    read_sent(Words),   % read a sentence
    talk(Words, Reply), % process it with TALK
    print_reply(Reply), % generate a printed reply
    main_loop.          % process more sentences

ERROR: [...]/talk.P:16:15: Syntax error: Operator expected

---Line 38:

talk(_Sentence, error(’too difficult’)).

ERROR: [...]/talk.P:38:25: Syntax error: Operator expected

---Lines 76-77:

% Replying to some other type of sentence.
reply(_Type, _FreeVars, _Clause, error(’unknown type’)).

ERROR: [...]/talk.P:77:42: Syntax error: Operator expected

---Lines 87-91:

print_reply(error(ErrorType)) :-
    write(’Error: "’), write(ErrorType), write(’."’), nl.

print_reply(asserted(Assertion)) :-
    write(’Asserted "’), write(Assertion), write(’."’), nl.

ERROR: [...]/talk.P:91:12: Syntax error: Operator expected

---Note I am also encountering ten singleton variable warnings, but am not sure whether this will prove to be a problem or not, e.g.:

---Lines 59-60:

reply(query, FreeVars,
    (answer(Answer):-Condition), Reply) :- Warning: [...]/talk.P:59:  Singleton variables:

[FreeVars,Condition,FreeVarsˆCondition] Warning: [...]/talk.P:59:
    Singleton variable in branch: FreeVarsˆCondition

---Lines 242-243:

q(S => ‘answer(X)) -->
    whpron, vp(finite, XˆS, nogap).

Warning: [...]/talk.P:242:    Singleton variables: [S,X,XˆS]

What do I need to do to get this module up and running?

Body:
There are a couple of problems. The operator values (100, 500 etc) are compatible with older values for the standard operators and should be higher. Also, the back-quote/back-tick (ASCII 96) changed at some point from being a symbol to being a quote character.

I managed to get the files to load in SWI prolog, by changing the operators:

:- op(1000,xfy,&).
:- op(1010,xfy,=>).
:- op(200,fx,`).

and giving the command line parameter --traditional (to make back-quote a symbol instead of a quote character).

$ swipl --traditional
Welcome to SWI-Prolog (threaded, 64 bits, version 7.4.2)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit http://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- [talk].
true.


问:
QT Creator: OpenCV dll lib can not be added ("File format not recognized")
I'm trying to get openCV 3.1.0 to work in QT Creator 4.4.1 using this tutorial from their official site.

Right now, I'm setting up my project file. The whole file looks identical to the on in the tutorial apart from the last couple of lines, as my openCV build is in another place and it's a different version This is what I got:

```<code>INCLUDEPATH += C:\opencv\opencv-3.1.0\build\include

LIBS += -LC:\opencv\opencv-3.1.0\build\x64\vc14\bin \
    libopencv_world310d \
</code>```

As far as I understand, the "world" module has been introduced to openCV to unify all the different modules into one.

However, when I try to run this, QT produces the following error:

```<code>C:\opencv\opencv-3.1.0\build\x64\vc14\bin\opencv_world310d.dll:-1: error: file not recognized: File format not recognized
</code>```

What am I doing wrong? In the tutorial there's an alternative way to link the libraries which even explicitly states them as .dll files. Why is this a problem?

答:
You need to link to the .lib contained in the lib folder:

```<code>LIBS += -LC:\opencv\opencv-3.1.0\build\x64\vc14\lib \
</code>```

and put the .dll in the PATH, or the same folder of the .exe

Body:
I'm trying to get openCV 3.1.0 to work in QT Creator 4.4.1 using this tutorial from their official site.

Right now, I'm setting up my project file. The whole file looks identical to the on in the tutorial apart from the last couple of lines, as my openCV build is in another place and it's a different version This is what I got:

INCLUDEPATH += C:\opencv\opencv-3.1.0\build\include

LIBS += -LC:\opencv\opencv-3.1.0\build\x64\vc14\bin \
    libopencv_world310d \

As far as I understand, the "world" module has been introduced to openCV to unify all the different modules into one.

However, when I try to run this, QT produces the following error:

C:\opencv\opencv-3.1.0\build\x64\vc14\bin\opencv_world310d.dll:-1: error: file not recognized: File format not recognized

What am I doing wrong? In the tutorial there's an alternative way to link the libraries which even explicitly states them as .dll files. Why is this a problem?

Body:
You need to link to the .lib contained in the lib folder:

LIBS += -LC:\opencv\opencv-3.1.0\build\x64\vc14\lib \

and put the .dll in the PATH, or the same folder of the .exe


问:
java regex help
I can have one string with the following two formats:

```<code>"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between changeValue1 and changeValue2";
"[MatchString] between changeValue1 and changeValue2";
</code>```

I would like to match if the string have "[MatchString] between" expression.
ANd depending upon which string I match, The changed value format should be one of the following:
The changed format should be :

```<code>"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between chamged1 and changed2"; or
"[MatchString] between changed1 and changed2";
</code>```

I started to match "[MatchString] between" expression and I got stuck over there:
ANy help is appreciated.

答:
This will match both kinds of line examples that you give.

```<code>String inputLine;
String outputLine;

String regex1 = "(\\[MatchString\\] between )changeValue1 and";
String regex2 = "(\\[MatchString\\] between )[^ ]+ and";

do {
    inputLine = readTheInput();

    outputLine = inputLine.replaceFirst(regex1, "$1changed1 and");

    writeTheOutput(outputLine);
} while (thereIsStillInput());
</code>```

The first regex1 looks specifically for changeValue1 while the second regex2 looks for anything following "between" and preceding "and".

This should get you started.

Title: java regex help

Body:
I can have one string with the following two formats:

"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between changeValue1 and changeValue2";
"[MatchString] between changeValue1 and changeValue2";

I would like to match if the string have "[MatchString] between" expression.
ANd depending upon which string I match, The changed value format should be one of the following:
The changed format should be :

"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between chamged1 and changed2"; or
"[MatchString] between changed1 and changed2";

I started to match "[MatchString] between" expression and I got stuck over there:
ANy help is appreciated.

Body:
This will match both kinds of line examples that you give.

String inputLine;
String outputLine;

String regex1 = "(\\[MatchString\\] between )changeValue1 and";
String regex2 = "(\\[MatchString\\] between )[^ ]+ and";

do {
    inputLine = readTheInput();

    outputLine = inputLine.replaceFirst(regex1, "$1changed1 and");

    writeTheOutput(outputLine);
} while (thereIsStillInput());

The first regex1 looks specifically for changeValue1 while the second regex2 looks for anything following "between" and preceding "and".

This should get you started.


问:
Spring Batch StepScope Bean
how the lifecycle of step scoped bean is exactly defined, especially in case when I have partitioned scope?

For example:

gridSize = 4

SimplePartitioner used as a Partitioner (will create 4 partition definitions)

RepositoryItemReader as step scoped bean

The question is: how many parallel steps will be created assuming a simple flow (read, process, write, finish)? 4 parallel steps? Do every step has its own RepositoryItemReader, so in result there will be 4 RepositoryItemReaders?

答: A bean that is step scoped will get one instance per StepExecution.  So using your example you will end up with four RepositoryItemReader instances, one per partition.  This allows the state of each partition to be independent to support things like restartability.

Title: Spring Batch StepScope Bean


问:
FreePascal: How to use GetEnvironmentVariable in non-latin Windows?
I've been writing some code using Lazarus 1.6.4 and FPC 3.0.2 to get USERNAME in Windows and USER in Linux. To achieve this I used SysUtils.GetEnvironmentVariable function. In Linux it works perfect, but in Windows it returns something corrupted that looks like UTF8 string opened in wrong encoding. My USERNAME in Windows has Cyrillic symbols so instead of the actual name GetEnvironmentVariable returns ???????? but it should be Пользователь.
Here my code:

```<code>function GetUserName: string;
{$IFDEF MSWINDOWS}
const
  envVar = 'USERNAME';
{$ENDIF}
{$IFDEF UNIX}
  envVar = 'USER';
{$ENDIF}
begin
  Result := SysUtils.GetEnvironmentVariable(envVar);
{$IFDEF MSWINDOWS}
  { TODO : BUG: Does not work correct for non-latin strings }
  Result := LazUTF8.UTF8ToWinCP(Result)
{$ENDIF}
end;
</code>```

And it returns corrupted strings when it contains non-latain symbols inside.

How can I GetEnvironmentVariable in correct encoding in Windows OS?

答:
Afaik in 3.0+ getenvironmentvariable is overloaded for unicodestring on windows, and that uses the -W variant.

```<code>var res,tag : unicodestring;

begin
  tag:='HOME';
  res:=getenvironmentvariable(tag);
end;
</code>```

Just

```<code>  getenvironmentstring (unicodestring('whatever'));
</code>```

might also work, but make sure you either set utf8 as default encoding, or assign the result to an unicodestring.

Body:
I've been writing some code using Lazarus 1.6.4 and FPC 3.0.2 to get USERNAME in Windows and USER in Linux. To achieve this I used SysUtils.GetEnvironmentVariable function. In Linux it works perfect, but in Windows it returns something corrupted that looks like UTF8 string opened in wrong encoding. My USERNAME in Windows has Cyrillic symbols so instead of the actual name GetEnvironmentVariable returns ???????? but it should be Пользователь.
Here my code:

function GetUserName: string;
{$IFDEF MSWINDOWS}
const
  envVar = 'USERNAME';
{$ENDIF}
{$IFDEF UNIX}
  envVar = 'USER';
{$ENDIF}
begin
  Result := SysUtils.GetEnvironmentVariable(envVar);
{$IFDEF MSWINDOWS}
  { TODO : BUG: Does not work correct for non-latin strings }
  Result := LazUTF8.UTF8ToWinCP(Result)
{$ENDIF}
end;

And it returns corrupted strings when it contains non-latain symbols inside.

How can I GetEnvironmentVariable in correct encoding in Windows OS?

Body:
Afaik in 3.0+ getenvironmentvariable is overloaded for unicodestring on windows, and that uses the -W variant.

var res,tag : unicodestring;

begin
  tag:='HOME';
  res:=getenvironmentvariable(tag);
end;

Just

  getenvironmentstring (unicodestring('whatever'));

might also work, but make sure you either set utf8 as default encoding, or assign the result to an unicodestring.


问:
Load data infile parameter error

LOAD data LOCAL INFILE
    'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/amazon1.xml'
INTO TABLE
    amazonxmlfeeddata
CHARACTER SET 'utf8'
LINES STARTING BY '<item_data>' TERMINATED BY '</item_data>'
(@tmp)
SET
    item_unique_id = ExtractValue(@tmp, '//item_unique_id'),
    item_title = ExtractValue(@tmp, '//item_title'),
    item_long_desc = ExtractValue(@tmp, '//item_long_desc'),
    item_page_url = ExtractValue(@tmp, '//item_page_url');
```

This is basically my query and I wrote this is in ASP.NET C#.
I want to execute this through C# in MySQL.
But if I execute through C# it gives me error of (@tmp) that it should be declared. And even after declaring it still throws the same error.

答:
It seems you need to add AllowUserVariables=true; to the MySql connection string, to allow user variables (@tmp).

See: https://dev.mysql.com/doc/connector-net/en/connector-net-connection-options.html

Title: Load data infile parameter error

Body:
LOAD data LOCAL INFILE
    'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/amazon1.xml'
INTO TABLE
    amazonxmlfeeddata
CHARACTER SET 'utf8'
LINES STARTING BY '<item_data>' TERMINATED BY '</item_data>'
(@tmp)
SET
    item_unique_id = ExtractValue(@tmp, '//item_unique_id'),
    item_title = ExtractValue(@tmp, '//item_title'),
    item_long_desc = ExtractValue(@tmp, '//item_long_desc'),
    item_page_url = ExtractValue(@tmp, '//item_page_url');

This is basically my query and I wrote this is in ASP.NET C#.
I want to execute this through C# in MySQL.
But if I execute through C# it gives me error of (@tmp) that it should be declared. And even after declaring it still throws the same error.


问:
importing a project from Perforce Eclipse Plugin as Java Project
I am trying import a project from Perforce workspace in Eclipse. It is importing it (fetching the files into java package hierarchy) but the problem is it is not importing as "Java project". so i can't edit the "Build path" or there is no classpath or something.

Any idea?

答: You need to make sure to put Eclipse metadata files into your source control system. All files starting with . in the project root along with entire .settings directory need to get checked in along with your source. If you don't do that, Eclipse will loose all knowledge of the type of projects that it is and how it supposed to be configured.</p>


问:
Google Apps Script - Making a url request using sha1 and base64 encode
I have to make a url request with Google Apps Script and for that, I need to enncode my login and password using a sha 1 algorithm and a base64 encoding. In the documantation for the request, I have the following php code :

$string = "loginpassword2017-15-04T09:25:00";
   $hash = sha1($string, true);
   $hash = base64_encode($hash);

So in Google Apps Script, i use the following code :

function GetSHA1(input) {
     var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, input);
     var txtHash = '';
     for (j = 0; j <rawHash.length; j++) {
       var hashVal = rawHash[j];
       if (hashVal < 0)
         hashVal += 256;
       if (hashVal.toString(16).length == 1)
        txtHash += "0";
       txtHash += hashVal.toString(16);
       }
     return txtHash;
   }

and then the function

Utilities.base64Encode

Finally I make the url request but authentication is unsuccessful. Does someone know how to do a php sha1 and base64encode in Google Apps Script ? Thanks

答:
You can pass the Byte[] array returned from the Utilities::computeDigest directly to a Utilities::base64EncodeWebSafe invocation. So you could do something like the following:

```<code>function getLoginHash(loginData) {

    return Utilities.base64EncodeWebSafe(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, loginData));

}
</code>```

Body:
You can pass the Byte[] array returned from the Utilities::computeDigest directly to a Utilities::base64EncodeWebSafe invocation. So you could do something like the following:

function getLoginHash(loginData) {

    return Utilities.base64EncodeWebSafe(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, loginData));

}


问:
how to disable past days in calender in WPF?
i'm developing WPF application in that i'm trying to disable the past days in calender.
any way is there to disable the past days.please let me know.

thanks

答:
In WPF and you want to use MVVM binding to your view model. This approach is more general and lets you do boundary checking within your unit tests.

```<code>   <DatePicker SelectedDate="{Binding SelectedDate}"  DisplayDateStart="{Binding MinAvailDate}" DisplayDateEnd="{Binding MaxAvailDate}"></DatePicker>
</code>```

In the view model....

```<code>private DateTime _minAvailDate= DateTime.UtcNow;
        public DateTime MinAvailDate { get { return _minAvailDate; }
        set { _minAvailDate = value; OnPropertyChanged("MinAvailDate"); }
</code>```

Set MinAvailDate = DateTime.Now, or adjust the default for  your time zone.

Implement MaxAvailDate in a similar way, as well as you binding to the SelectedDate.

Body:
In WPF and you want to use MVVM binding to your view model. This approach is more general and lets you do boundary checking within your unit tests.

   <DatePicker SelectedDate="{Binding SelectedDate}"  DisplayDateStart="{Binding MinAvailDate}" DisplayDateEnd="{Binding MaxAvailDate}"></DatePicker>

In the view model....

private DateTime _minAvailDate= DateTime.UtcNow;
        public DateTime MinAvailDate { get { return _minAvailDate; }
        set { _minAvailDate = value; OnPropertyChanged("MinAvailDate"); }

Set MinAvailDate = DateTime.Now, or adjust the default for  your time zone.

Implement MaxAvailDate in a similar way, as well as you binding to the SelectedDate.


问:
Vec::dedup does not work — how do I deduplicate a vector of strings?
I've parsed a file, split the string by lines and want to leave only unique elements in each vector. I expect vec.dedup() to work like this:

```<code>let mut vec = vec!["a", "b", "a"];
vec.dedup();
assert_eq!(vec, ["a", "b"]);
</code>```

But it fails:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `["a", "b", "a"]`,
 right: `["a", "b"]`', src/main.rs:4:4
```

How can I remove duplicates?

答:
As documented, Vec#dedup only removes consecutive elements from a vector (it is much cheaper than a full deduplication). It would work fine if the vector was vec!["a", "a", "b"], for example.

Of course, there are multiple potential solutions.

In order to obtain a vector with all duplicates removed while retaining the original order of the elements, the itertools crate provides a unique adaptor.

```<code>use itertools::Itertools;

let v = vec!["b", "a", "b"];
let v: Vec<_> = v.into_iter().unique().collect();
assert_eq!(v, ["b", "a"]);
</code>```

If element order is not important, you may sort the elements first and then call dedupe.

```<code>let mut v = vec!["a", "b", "a"];
v.sort_unstable();
v.dedup();
assert_eq!(v, ["a", "b"]);
</code>```

If fast element lookup is important, you may also consider using a set type instead, such as HashSet.

```<code>let v: HashSet<_> = ["a", "b", "a"].iter().cloned().collect();
let v2: HashSet<_> = ["b", "a"].iter().cloned().collect();
assert_eq!(v, v2);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've parsed a file, split the string by lines and want to leave only unique elements in each vector. I expect vec.dedup() to work like this:

let mut vec = vec!["a", "b", "a"];
vec.dedup();
assert_eq!(vec, ["a", "b"]);

But it fails:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `["a", "b", "a"]`,
 right: `["a", "b"]`', src/main.rs:4:4

How can I remove duplicates?

Body:
As documented, Vec#dedup only removes consecutive elements from a vector (it is much cheaper than a full deduplication). It would work fine if the vector was vec!["a", "a", "b"], for example.

Of course, there are multiple potential solutions.

In order to obtain a vector with all duplicates removed while retaining the original order of the elements, the itertools crate provides a unique adaptor.

use itertools::Itertools;

let v = vec!["b", "a", "b"];
let v: Vec<_> = v.into_iter().unique().collect();
assert_eq!(v, ["b", "a"]);

If element order is not important, you may sort the elements first and then call dedupe.

let mut v = vec!["a", "b", "a"];
v.sort_unstable();
v.dedup();
assert_eq!(v, ["a", "b"]);

If fast element lookup is important, you may also consider using a set type instead, such as HashSet.

let v: HashSet<_> = ["a", "b", "a"].iter().cloned().collect();
let v2: HashSet<_> = ["b", "a"].iter().cloned().collect();
assert_eq!(v, v2);


问:
Does multiple action assignment addition run synchronously?
Does the actions run synchronously or asynchronously when using += operator?

```<code>Action actions = () => Console.WriteLine("First Action");

actions += () => Console.WriteLine("Second Action");
actions += () => Console.WriteLine("Third Action");
actions += () => Console.WriteLine("Fourth Action");

actions();
</code>```

This block of code prints:

```<code>First Action
Second Action
Third Action
Fourth Action
</code>```

答:
this actions will run synchronously, just do this:

```<code>Action actions = () => Console.WriteLine("First Action");

actions += () => Console.WriteLine("Second Action");
actions += () => {
                    Thread.Sleep(2000);
                    Console.WriteLine("Third Action")
                 };
actions += () => Console.WriteLine("Fourth Action");
actions();
</code>```

And you can check a Thread waiting to write the last one

Body:
Does the actions run synchronously or asynchronously when using += operator?

Action actions = () => Console.WriteLine("First Action");

actions += () => Console.WriteLine("Second Action");
actions += () => Console.WriteLine("Third Action");
actions += () => Console.WriteLine("Fourth Action");

actions();

This block of code prints:

First Action
Second Action
Third Action
Fourth Action

Body:
this actions will run synchronously, just do this:

Action actions = () => Console.WriteLine("First Action");

actions += () => Console.WriteLine("Second Action");
actions += () => {
                    Thread.Sleep(2000);
                    Console.WriteLine("Third Action")
                 };
actions += () => Console.WriteLine("Fourth Action");
actions();

And you can check a Thread waiting to write the last one


问:
How to get the object from a Django Rest Framework serializer init method?
I have my serializers code set up as follows:

```<code>class ProductSerializer(serializers.ModelSerializer):
    """
     * Serializes Products.
    """
    def __init__(self, *args, **kwargs):
        print kwargs.pop('product_passed')
        super(ProductSerializer, self).__init__(*args, **kwargs)
</code>```

Now, this serializer is being called from a view using the code below:

```<code>product_passed = Product.objects.get(pk=pk)
product_serializer = ProductSerializer(product_passed)
</code>```

What I want to do is call the product_passed from my serializer init method. How can I do this? Right now, my method does not work.

答:
Pass it like this:

```<code>product_serializer = ProductSerializer(product_passed, product_passed= product_passed)
</code>```

And access it from kwargs: kwargs.get('product_passed')

Body:
I have my serializers code set up as follows:

class ProductSerializer(serializers.ModelSerializer):
    """
     * Serializes Products.
    """
    def __init__(self, *args, **kwargs):
        print kwargs.pop('product_passed')
        super(ProductSerializer, self).__init__(*args, **kwargs)

Now, this serializer is being called from a view using the code below:

product_passed = Product.objects.get(pk=pk)
product_serializer = ProductSerializer(product_passed)

What I want to do is call the product_passed from my serializer init method. How can I do this? Right now, my method does not work.

Body:
Pass it like this:

product_serializer = ProductSerializer(product_passed, product_passed= product_passed)

And access it from kwargs: kwargs.get('product_passed')


问:
Replace column names using lookup table, if lookup table contains old column name
I have a data frame that looks like this:

```<code>test <- data.frame("PLOT.ID" = c(1,2,3),
                "Diameter" = c(1,2,3),
                "tag_id" = c(1,2,3),
                "COL_NA" = c(1,2,3))
</code>```

I also have a lookup table with the old column names that I want to change:

```<code>lookup <- data.frame(old = c("PLOT.ID", "Diameter"),
                     new = c("plot_id", "diam"))
</code>```

How can I use the lookup table to replace only the column names in test that appear in lookup$old and leave others as they are?

My method so far removed column names that don't appear in lookup$old and replaces them with blanks:

```<code>test_new <- setNames(test, lookup$new[match(names(test), lookup$old)])
</code>```

答:
You could use the mapvalues function from the plyr package:

```<code>test_new <- test
colnames(test_new) <- plyr::mapvalues(colnames(test),
    as.character(lookup$old),
    as.character(lookup$new))

> test_new
  plot_id diam tag_id COL_NA
1       1    1      1      1
2       2    2      2      2
3       3    3      3      3
</code>```

Body:
I have a data frame that looks like this:

test <- data.frame("PLOT.ID" = c(1,2,3),
                "Diameter" = c(1,2,3),
                "tag_id" = c(1,2,3),
                "COL_NA" = c(1,2,3))

I also have a lookup table with the old column names that I want to change:

lookup <- data.frame(old = c("PLOT.ID", "Diameter"),
                     new = c("plot_id", "diam"))

How can I use the lookup table to replace only the column names in test that appear in lookup$old and leave others as they are?

My method so far removed column names that don't appear in lookup$old and replaces them with blanks:

test_new <- setNames(test, lookup$new[match(names(test), lookup$old)])

Body:
You could use the mapvalues function from the plyr package:

test_new <- test
colnames(test_new) <- plyr::mapvalues(colnames(test),
    as.character(lookup$old),
    as.character(lookup$new))

> test_new
  plot_id diam tag_id COL_NA
1       1    1      1      1
2       2    2      2      2
3       3    3      3      3


问:
Manipulating Angular Material Input Form Styling
I am new to Angular and Angular Material (AM). By default, AM Input Component shows the primary color of your palette until you click on the form, where then it changes the placeholder value and marker line to the accent color. Is there a way to manipulate the form so that the accent color is always showing? In other words, the form will always be highlighted. The issue is that my primary color is dark, and my website page background is also dark, therefore, the placeholder and marker line are barely visible unless the form is clicked on by the user. This would also be a nice color addition to my site's page.

Here is the sample of the required html from the AM docs:

```<code><md-input-container>
  <input mdInput placeholder="Favorite food" value="Sushi">
</md-input-container>
</code>```

You can add color="accent" to the input line, but again, the color only appears when the form is clicked on by the user.

Thank you in advance.

答:
I had a similar problem adjusting with width of my form field.  When investigating found that the answer that referenced Nehal's answer is correct, but also deprecated in the latest version, 5.0.0-rcX, https://angular.io/guide/component-styles.  I continued to double check my CSS selectors but found I needed to change the ViewEncapsulation.

What worked for me was in my css/scss file (of course modify with your own selectors as needed):

```<code>mat-input-container {
    // Your CSS here
}
</code>```

And in my components ts file:

```<code>@Component({
    selector: 'my-component-selector',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.scss'],
    encapsulation: ViewEncapsulation.None
})
</code>```

Without changing the encapsulation, the CSS selector would not get applied.

Good luck!

Body:
I am new to Angular and Angular Material (AM). By default, AM Input Component shows the primary color of your palette until you click on the form, where then it changes the placeholder value and marker line to the accent color. Is there a way to manipulate the form so that the accent color is always showing? In other words, the form will always be highlighted. The issue is that my primary color is dark, and my website page background is also dark, therefore, the placeholder and marker line are barely visible unless the form is clicked on by the user. This would also be a nice color addition to my site's page.

Here is the sample of the required html from the AM docs:

<md-input-container>
  <input mdInput placeholder="Favorite food" value="Sushi">
</md-input-container>

You can add color="accent" to the input line, but again, the color only appears when the form is clicked on by the user.

Thank you in advance.

Body:
I had a similar problem adjusting with width of my form field.  When investigating found that the answer that referenced Nehal's answer is correct, but also deprecated in the latest version, 5.0.0-rcX, https://angular.io/guide/component-styles.  I continued to double check my CSS selectors but found I needed to change the ViewEncapsulation.

What worked for me was in my css/scss file (of course modify with your own selectors as needed):

mat-input-container {
    // Your CSS here
}

And in my components ts file:

@Component({
    selector: 'my-component-selector',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.scss'],
    encapsulation: ViewEncapsulation.None
})

Without changing the encapsulation, the CSS selector would not get applied.

Good luck!


问:
Ignite cluster with mixed persistent/non-persistent cache nodes
In my Apache Ignite 2.3 cluster I want to run one node (probably two in the future for a backup) that has my replicated cache persistent on disk. I need to make sure this node is always up while other cache nodes don't have the persistent configuration and therefore access the cache only in memory. These non-persistent nodes can come and go frequently on demand as they are for computing but not for storing data.

When a non-persistent node is connected, what happens when the persistent node goes down? Ideally the cache should go away for the whole cluster but it doesn't. All nodes continue using the cache in memory it seems. But this means the new data will never be on disk and gone after cluster restart.
Is my configuration with mixed persistent/non-persistent nodes not common? How would I keep this type of cluster consistant?

Any background help appreciated.

答:
You can configure your cache to be stored on a single node only. So, when it goes down, the cache stops functioning. It can be done by using node attributes and a node filter.

But in this configuration every request will be sent to a single node, making work of additional nodes slower. If you want to avoid it, consider using a near cache.


问:
No implementation for play.modules.reactivemongo.ReactiveMongoApi was bound
I'm working on a back-end project using Scala, the Play Framework, and the IntelliJ IDE just to practice, I'm new to these technologies.

I added the Reactive Mongo dependency to the build.sbt

```<code>libraryDependencies ++= Seq(
  "org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"
)
</code>```

What I get is this error :

```<code>No implementation for play.modules.reactivemongo.ReactiveMongoApi was bound
</code>```

When I hover the mouse on

```<code>"org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"
</code>```

This little text displays:

Unknown artifact. Not resolved or indexed.

What am I doing wrong ?

UPDATE:

When i refresh the project by hitting option + enter on the dependency, the "Event log" shows this :

[warn] Found version conflict(s) in library dependencies; some are suspected to be binary incompatible: [warn] * com.google.guava:guava:22.0 is selected over 19.0 [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 22.0) [warn] +- com.google.inject:guice:4.1.0 (depends on 19.0) [warn] * com.typesafe.akka:akka-stream_2.12:2.5.6 is selected over 2.4.19 [warn] +- com.typesafe.play:play-streams_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-http-core_2.12:10.0.10 (depends on 2.4.19) [warn] * com.typesafe.akka:akka-actor_2.12:2.5.6 is selected over {2.4.14, 2.4.19} [warn] +- com.typesafe.akka:akka-stream_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-slf4j_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-parsing_2.12:10.0.10 (depends on 2.4.19) [warn] +- org.reactivemongo:reactivemongo_2.12:0.12.6 () (depends on 2.4.14) [warn] Run 'evicted' to see detailed eviction warnings

答:
This looks like error from dependency injection. Have you followed the tutorial you referenced fully including the "Setup" part?

Thus, the dependency injection can be configured, so that the your controllers are given the new ReactiveMongo API. First, Add the line bellow to application.conf:

```<code>play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
</code>```

Body:
I'm working on a back-end project using Scala, the Play Framework, and the IntelliJ IDE just to practice, I'm new to these technologies.

I added the Reactive Mongo dependency to the build.sbt

libraryDependencies ++= Seq(
  "org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"
)

What I get is this error :

No implementation for play.modules.reactivemongo.ReactiveMongoApi was bound

When I hover the mouse on

"org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"

This little text displays:

Unknown artifact. Not resolved or indexed.

What am I doing wrong ?

UPDATE:

When i refresh the project by hitting option + enter on the dependency, the "Event log" shows this :

[warn] Found version conflict(s) in library dependencies; some are suspected to be binary incompatible: [warn] * com.google.guava:guava:22.0 is selected over 19.0 [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 22.0) [warn] +- com.google.inject:guice:4.1.0 (depends on 19.0) [warn] * com.typesafe.akka:akka-stream_2.12:2.5.6 is selected over 2.4.19 [warn] +- com.typesafe.play:play-streams_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-http-core_2.12:10.0.10 (depends on 2.4.19) [warn] * com.typesafe.akka:akka-actor_2.12:2.5.6 is selected over {2.4.14, 2.4.19} [warn] +- com.typesafe.akka:akka-stream_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-slf4j_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-parsing_2.12:10.0.10 (depends on 2.4.19) [warn] +- org.reactivemongo:reactivemongo_2.12:0.12.6 () (depends on 2.4.14) [warn] Run 'evicted' to see detailed eviction warnings

Body:
This looks like error from dependency injection. Have you followed the tutorial you referenced fully including the "Setup" part?

Thus, the dependency injection can be configured, so that the your controllers are given the new ReactiveMongo API. First, Add the line bellow to application.conf:

play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"


问:
How to use WCF service
We have 2 projects in our company, the 2nd calls the 1st through the WCF service that is hosted by ASP.NET web site.

My idea was to deploy asp.net with hosted WCF service and the 2nd team will add 'service reference' to their project. and using auto-generated classes will instantiate client for service and call its methods.

But, they insist me to create a DLL that will contains a interface (contract) implemented by WCF service and they will add reference to those DLL. And only using this interface from dll they are going to communicate.

What is a correct approach for 'consuming' WCF service?

P.S. I've read a lot about how to consume/host WCF service, but still can see a best approach for that.

P.P.S. We are working under VS 2008, .NET 3.5, but ideas for VS2010 and .NET 4.0 are also welcome.

答: So team 2 wants you to create a client implementation they can include in their project?  Seems like laziness to me.  Sounds like you guys need to hash out what your corporate SOA strategy is.  If there is no strategy (or hope of getting one).  Team 2 should create their own project, with a facade they can reference if needed.</p>

Title: How to use WCF service


问:
driver.executeScript() returns NullPointerException for simple javascript
js.executeScript("return document.title") works fine as expected but I'm not sure why my code returns null pointer error. what is wrong here?

```<code>   String testJs= "function test() {arr = 111; return arr;}; test();";
   JavascriptExecutor js = (JavascriptExecutor) driver;
   int a = (Integer) js.executeScript(testJS);
</code>```

答:
Yeah, the key thing is not to forget insert the return, f.e.:

```<code>Long dateNow = (Long) jse.executeScript("return Date.now()");
</code>```

Body:
js.executeScript("return document.title") works fine as expected but I'm not sure why my code returns null pointer error. what is wrong here?

   String testJs= "function test() {arr = 111; return arr;}; test();";
   JavascriptExecutor js = (JavascriptExecutor) driver;
   int a = (Integer) js.executeScript(testJS);

Body:
Yeah, the key thing is not to forget insert the return, f.e.:

Long dateNow = (Long) jse.executeScript("return Date.now()");


问:
Find out the training error after fit()
I'm training a LinearSVC model and I want to get the training error of it. Is it possible to get it w/o evaluating it manually? </p>

<p>Thanks  </p>

答:
sklearn is using liblinear for this task.

You can take a quick glance into the sources here:

```<code>self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear(
    X, y, self.C, self.fit_intercept, self.intercept_scaling,
    self.class_weight, self.penalty, self.dual, self.verbose,
    self.max_iter, self.tol, self.random_state, self.multi_class,
    self.loss, sample_weight=sample_weight)
</code>```

which shows that only coefficients, intercepts and number of iterations are processed by sklearn's python-API. Whatever else is available in liblinear's output is not grabbed. You can't directly read out the training-error without changing the internal code.

There might be a possible hack turning on verbose-mode, redirect the output and parse additional info available there. But this assumes the info you look for is available there and it's also hacky and i won't recommend it.

Just use the score-method. It won't be too costly compared to fitting.

Title: Find out the training error after fit()

Body:
I'm training a LinearSVC model and I want to get the training error of it. Is it possible to get it w/o evaluating it manually?

Thanks

Body:
sklearn is using liblinear for this task.

You can take a quick glance into the sources here:

self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear(
    X, y, self.C, self.fit_intercept, self.intercept_scaling,
    self.class_weight, self.penalty, self.dual, self.verbose,
    self.max_iter, self.tol, self.random_state, self.multi_class,
    self.loss, sample_weight=sample_weight)

which shows that only coefficients, intercepts and number of iterations are processed by sklearn's python-API. Whatever else is available in liblinear's output is not grabbed. You can't directly read out the training-error without changing the internal code.

There might be a possible hack turning on verbose-mode, redirect the output and parse additional info available there. But this assumes the info you look for is available there and it's also hacky and i won't recommend it.

Just use the score-method. It won't be too costly compared to fitting.


答:
The answer to your question is short and simple: actions run synchronously. Just like event handles, actions are executed sequentially, one after another, in the order they are assigned / subscribed.

As you could have noticed, the block has been printed with all the strings in sequence. If you define something like this:

```<code>Action actions = () => Console.WriteLine("2");
actions += () => Console.WriteLine("3");
actions += () => Console.WriteLine("1");
actions += () => Console.WriteLine("4");
</code>```

You will always see 2 3 1 4 being printed, no matter what happens.

Title: Does multiple action assignment addition run synchronously?

Body:
The answer to your question is short and simple: actions run synchronously. Just like event handles, actions are executed sequentially, one after another, in the order they are assigned / subscribed.

As you could have noticed, the block has been printed with all the strings in sequence. If you define something like this:

Action actions = () => Console.WriteLine("2");
actions += () => Console.WriteLine("3");
actions += () => Console.WriteLine("1");
actions += () => Console.WriteLine("4");

You will always see 2 3 1 4 being printed, no matter what happens.


问:
Should I upload css + maps to the server? And does it slow down the website?
I have two issues that need support, whether to upload the scss file, and the map file to the server after the job has finished? And does it increase page load time?</p>

答:
I personally use a build system (gulp) and a repo for maintaining sites. I don't include the .css files, those are all .gitignored to prevent conflicts. So when an update is pushed live, I just pull it down, and run a gulp task to build the .css file and maps. So I end up having both the sass, and the map file on the production server.

Having the sass file doesn't affect load time. The browser doesn't actually load that, it will load your .css sheet. The map files do increase the load time though, as they are being called, but its extremely minimal. You're looking at maybe 150kb and 70ms depending on the size of the css which directly effects the size of the map.

I wouldn't worry about it, but it's up to you how important that 70ms is.


问:
Why argument conversion is not considered when calling a templated function?
I have a template class and a friend operator* function

```<code>StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)
</code>```

I use it with TE=float but I need to multiply a StereoSmp<float> * double
I think that should be possibile because it should converts double to float automatically and works but I get the error:

```<code>no match for ‘operator*’ (operand types are ‘StereoSmp<float>’ and
    ‘__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type {aka double}’)
deduced conflicting types for parameter ‘TE’ (‘float’ and ‘double’)
</code>```

Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

答:
Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

This isn't a conversion problem, it's a template parameter inference issue. Since the declaration is of the form:

```<code>StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)
</code>```

... and the operands are of type StereoSmp<float> and double, the C++ inference rules do not work, because they do not take into account that a double is convertible to a float. These rules are specified by the language specification; the reason why they don't take potential conversions into account is probably because "it would make deduction very complicated, otherwise". The rules are already complex enough!

You can of course cast your double parameter to a float and it will work fine. Also, you could make the operator* a member function of StereoSmp, or you could independently parameterise the types of the type parameters:

```<code>template <class TE, class U> StereoSmp<TE> operator* (const StereoSmp<TE>& a, U b);
</code>```

Body:
I have a template class and a friend operator* function

StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)

I use it with TE=float but I need to multiply a StereoSmp<float> * double
I think that should be possibile because it should converts double to float automatically and works but I get the error:

no match for ‘operator*’ (operand types are ‘StereoSmp<float>’ and
    ‘__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type {aka double}’)
deduced conflicting types for parameter ‘TE’ (‘float’ and ‘double’)

Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

Body:
Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

This isn't a conversion problem, it's a template parameter inference issue. Since the declaration is of the form:

StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)

... and the operands are of type StereoSmp<float> and double, the C++ inference rules do not work, because they do not take into account that a double is convertible to a float. These rules are specified by the language specification; the reason why they don't take potential conversions into account is probably because "it would make deduction very complicated, otherwise". The rules are already complex enough!

You can of course cast your double parameter to a float and it will work fine. Also, you could make the operator* a member function of StereoSmp, or you could independently parameterise the types of the type parameters:

template <class TE, class U> StereoSmp<TE> operator* (const StereoSmp<TE>& a, U b);


问:
Efficient Packet types/transfer protocol
Using boost::asio in C++, I'm trying to determine the best way to encrypt packets in my program. I thought of defining packets all by myself by type number, each with different fixed packet sizes. The system reads the header (type, and quantity of entries for lists of data) and creates the appropriate structure to receive the data, then it reacts according to the data received.

However, when I look at this method, I wonder if there would be a simpler way to accomplish this without sacrificing efficiency.

These packets are to be sent between different applications trough TCP. Ideally, I'm aiming at both applications using as least bandwidth and CPU as possible while also being as simple to modify as possible. Any suggestions?

答:
TCP uses streams of data, not packets. I highly suggest thinking of your data transmission as a stream of data instead of sequence of packets. This will make it easier to abstract into your code. Take a look at Boost.Serialization or Google Protocol Buffers.

Boost.Asio has SSL encryption capabilities, so it's trivial to encrypt the stream of data. It also has an example using serialization.


问:
How returning a string when using jitclass from numba?
I'm trying to return a string when I call a function in a class that uses jitclass but I get an error:

```<code>numba.errors.InternalError: Failed at nopython (nopython mode backend)
cannot convert native const('Something') to Python object
[1] During: resolving callee type: BoundFunction((<class 'numba.types.misc.ClassInstanceType'>, 'get_Names') for     instance.jitclass.myclass#3f2d488<A:float64,B:float64>)
[2] During: typing of call at <string> (3)
</code>```

I'm using this code to test the function:

```<code>from numba import jitclass
from numba import boolean, int32, float64,uint8

spec = [('A' ,float64),
        ('B' ,float64)]

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return "Something"

mC = myclass()
print(mC.get_Names())
</code>```

Does somebody know How I could return a string?

答:
You can sort of work around this by using an array of bytes to represent the string, as shown below.

That said, I think this is pretty ugly/hard to maintain.  Assuming it fits the problem, I think you are better off using a plain python class with jit functions for speedups as necessary, or dropping into something like cython which has richer support for extension types.

```<code>from numba import jitclass, float64

SOMETHING = np.frombuffer(b"Something", dtype='uint8')

spec = [('A' ,float64),
        ('B' ,float64)]

def get_jitclass_str(val):
    return bytes(val).decode('utf-8')

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return SOMETHING
</code>```

Usage

```<code>In [16]: mc = myclass()

In [17]: get_jitclass_str(mc.get_Names())
Out[17]: 'Something'
</code>```

Body:
I'm trying to return a string when I call a function in a class that uses jitclass but I get an error:

numba.errors.InternalError: Failed at nopython (nopython mode backend)
cannot convert native const('Something') to Python object
[1] During: resolving callee type: BoundFunction((<class 'numba.types.misc.ClassInstanceType'>, 'get_Names') for     instance.jitclass.myclass#3f2d488)
[2] During: typing of call at <string> (3)

I'm using this code to test the function:

from numba import jitclass
from numba import boolean, int32, float64,uint8

spec = [('A' ,float64),
        ('B' ,float64)]

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return "Something"

mC = myclass()
print(mC.get_Names())

Does somebody know How I could return a string?

Body:
You can sort of work around this by using an array of bytes to represent the string, as shown below.

That said, I think this is pretty ugly/hard to maintain.  Assuming it fits the problem, I think you are better off using a plain python class with jit functions for speedups as necessary, or dropping into something like cython which has richer support for extension types.

from numba import jitclass, float64

SOMETHING = np.frombuffer(b"Something", dtype='uint8')

spec = [('A' ,float64),
        ('B' ,float64)]

def get_jitclass_str(val):
    return bytes(val).decode('utf-8')

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return SOMETHING

Usage

In [16]: mc = myclass()

In [17]: get_jitclass_str(mc.get_Names())
Out[17]: 'Something'


问:
is it possible to activate a div when clicked without javascript?
Just wondering if a div can be called without using javascript.

such as

```<code>my_div:hover{ add new layout}
</code>```

is there a version for click eg

```<code>my_div:click{add new layout}
</code>```

Thanks

答:
Not directly, but you can fake it using checkboxes:

input[type=checkbox] {
  display: none;
}
.content {
  display: none;
  padding: 20px;
  background-color: #dadada;
}
input[type=checkbox]:checked+label+.content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="check">
<label for="check">Click me</label>
<div class="content">
  <h3>Content</h3>
  <p>lorem20</p>
</div></code>```

Body:
Just wondering if a div can be called without using javascript.

such as

my_div:hover{ add new layout}

is there a version for click eg

my_div:click{add new layout}

Thanks

Body:
Not directly, but you can fake it using checkboxes:

input[type=checkbox] {
  display: none;
}
.content {
  display: none;
  padding: 20px;
  background-color: #dadada;
}
input[type=checkbox]:checked+label+.content {
  display: block;
}

<input type="checkbox" id="check">
<label for="check">Click me</label>
<div class="content">
  <h3>Content</h3>
  <p>lorem20</p>
</div>


问:
EF comparing Expression<Func<T, bool>> with T
How can we compare Expression<Func<T, bool>> with T in Entity Framework?

For example:

```<code>Expression<Func<Book, bool>> exp = getYellowBooksExpr();
var v = context.Books.Where(exp).ToList();
</code>```

This above code would run well, but how can we run a query like this:

```<code>var v = context.Students.Where(x => x.Book == exp).ToList();
</code>```

答:
You cannot do this in general without rewriting your Where expression. But you can use external library, like LinqKit, to do that rewriting for you. Install LinqKit nuget package, then you can do:

```<code>var v = context.Students.AsExpandable()
          .Where(x => exp.Invoke(x.Book)).ToList();
</code>```

This will work for more complex cases too:

```<code>var v = context.Students.AsExpandable()
          .Where(x => x.Name == "something" || exp.Invoke(x.Book)).ToList();
</code>```

Body:
How can we compare Expression<Func<T, bool>> with T in Entity Framework?

For example:

Expression<Func<Book, bool>> exp = getYellowBooksExpr();
var v = context.Books.Where(exp).ToList();

This above code would run well, but how can we run a query like this:

var v = context.Students.Where(x => x.Book == exp).ToList();

Body:
You cannot do this in general without rewriting your Where expression. But you can use external library, like LinqKit, to do that rewriting for you. Install LinqKit nuget package, then you can do:

var v = context.Students.AsExpandable()
          .Where(x => exp.Invoke(x.Book)).ToList();

This will work for more complex cases too:

var v = context.Students.AsExpandable()
          .Where(x => x.Name == "something" || exp.Invoke(x.Book)).ToList();


答:
You might use the following

Edited based on the comment below

```<code>var students = context.Students.Where(t=>context.Books
                     .Where(exp).Contains(t.Book));
</code>```

Hope this will help you

Title: EF comparing Expression<Func<T, bool>> with T

Body:
You might use the following

Edited based on the comment below

var students = context.Students.Where(t=>context.Books
                     .Where(exp).Contains(t.Book));

Hope this will help you


问:
How do I write a route that allows for underscores in ASP.NET MVC?
I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?

You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)

```<code>01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }
</code>```

You implement a controller named HomeController that includes methods with the following
signatures.

```<code>public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)
</code>```

You need to add a route to meet the following requirements:

The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.

User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?

A. Replace line 05 with the following code segment.

```<code>routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );
</code>```

B. Replace line 05 with the following code segment.

```<code>routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );
</code>```

C. At line 04, add the following code segment.

```<code>routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );
</code>```

D. At line 04, add the following code segment.

```<code>routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );
</code>```

答:
C is right.

For B, if you replace line 05, then all your other routes won't work.
You also need to insert at line 04 because if not, the line 05 route will catch it before it even gets a chance.

Body:
I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?

You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)

01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }

You implement a controller named HomeController that includes methods with the following
signatures.

public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)

You need to add a route to meet the following requirements:

The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.

User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?

A. Replace line 05 with the following code segment.

routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );

B. Replace line 05 with the following code segment.

routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );

C. At line 04, add the following code segment.

routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );

D. At line 04, add the following code segment.

routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );


问:
C# Selenium : Test Fails intermittently
I have been using C# selenium for automating the application. I am facing the problem of intermittent failure on executing the Tests.

Sometime the Test pass & sometimes it fails.

Failure states that element/Frame/Window is NOT available.

I have been using the below code for wait

```<code>WebDriverWait wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(100));
            IWebElement elementToWait = wait.Until<IWebElement>((d) =>
            {
                return Driver.Instance.FindElement(By.Id("Element ID")); ;
            });
</code>```

Is this inconsistency due to the webdriver wait used ? What is the best practice to be followed in order to avoid this ?

答:
The problem you refer is because after 100 seconds, your element is still not appearing on the DOM, please, send us your log, but I am sure it's because of that.

The way that the Implicit/Explicit Wait work it's that after the time you setup, if the element does not exist, an exception is raised with a message of timeout (after 100 seconds in you case).

But again, provide more information please.

Title: C# Selenium : Test Fails intermittently

Body:
I have been using C# selenium for automating the application. I am facing the problem of intermittent failure on executing the Tests.

Sometime the Test pass & sometimes it fails.

Failure states that element/Frame/Window is NOT available.

I have been using the below code for wait

WebDriverWait wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(100));
            IWebElement elementToWait = wait.Until<IWebElement>((d) =>
            {
                return Driver.Instance.FindElement(By.Id("Element ID")); ;
            });

Is this inconsistency due to the webdriver wait used ? What is the best practice to be followed in order to avoid this ?


问:
Map one JSON schema to a different JSON schema
I have a bunch of JSON files, thousands of different schemas. Using GenSON (the Python JSON schema generator), I managed to create schema files for each of the input files. Now, what I'd like to do is standardize all these different files to one defined schema. Here's an example:

Input

```<code>{
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
}
</code>```

Output

```<code>{
     "names": ["Bob Odenkirk"],
     "occupations": ["Software Engineer"],
     "locations": ["San Francisco, CA"]
}
</code>```

Essentially, I am looking for a language agnostic method (i.e., I don't care what programming language is used) of defining how an input JSON file should be parsed to an output JSON file.

答:
I think the best, fastest, easiest way to parse many JSON files together is using python.

I was doing something similar to your project and ran into the same problem.
I found this site which teaches how to use python to actually parse JSON files together. Turns out there is a library on python called json(use pip to download json dependencies) which enables JSON file processing. If you already have a python editor, This method would be easier and faster then using Jolt
Check This website for more info: https://code.tutsplus.com/tutorials/how-to-work-with-json-data-using-python--cms-25758.

You can also use JS, which is again faster than Jolt. this is the website: https://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript . It is very easy as you can use JSON.parse() function

Body:
I have a bunch of JSON files, thousands of different schemas. Using GenSON (the Python JSON schema generator), I managed to create schema files for each of the input files. Now, what I'd like to do is standardize all these different files to one defined schema. Here's an example:

Input

{
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
}

Output

{
     "names": ["Bob Odenkirk"],
     "occupations": ["Software Engineer"],
     "locations": ["San Francisco, CA"]
}

Essentially, I am looking for a language agnostic method (i.e., I don't care what programming language is used) of defining how an input JSON file should be parsed to an output JSON file.


答:
Although Yakk's answer is probably the best in this particular scenario, I want to point out that you can prevent this deduction conflict and get your expected result (pass StereoSmp<float>, deduce TE as float) by making the other argument ineligible for use in deduction:

```<code>StereoSmp<TE> operator* (const StereoSmp<TE>& a, remove_reference<TE>::type b)
</code>```

Related reading: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3766.html

Title: Why argument conversion is not considered when calling a templated function?

Body:
Although Yakk's answer is probably the best in this particular scenario, I want to point out that you can prevent this deduction conflict and get your expected result (pass StereoSmp<float>, deduce TE as float) by making the other argument ineligible for use in deduction:

StereoSmp<TE> operator* (const StereoSmp<TE>& a, remove_reference<TE>::type b)

Related reading: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3766.html


问:
How to get rid of denominator in numerator and denominator in mathematica
I have the following expression

```<code>(-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B))
</code>```

How can I multiply both the denominator and numberator by p^(A+B), i.e. to get rid of the denominators in both numerator and denominator? I tried varous Expand, Factor, Simplify etc. but none of them worked.

Thanks!

答:
I must say I did not understand the original question.  However, while trying to understand the intriguing solution given by belisarius I came up with the following:

```<code>expr = (-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B));

Together@(PowerExpand@FunctionExpand@Numerator@expr/
 PowerExpand@FunctionExpand@Denominator@expr)
</code>```

Output (as given by belisarius):

Alternatively:

```<code>PowerExpand@FunctionExpand@Numerator@expr/PowerExpand@
 FunctionExpand@Denominator@expr
</code>```

gives

or

```<code>FunctionExpand@Numerator@expr/FunctionExpand@Denominator@expr
</code>```

Thanks to belisarius for another nice lesson in the power of Mma.

Body:
I have the following expression

(-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B))

How can I multiply both the denominator and numberator by p^(A+B), i.e. to get rid of the denominators in both numerator and denominator? I tried varous Expand, Factor, Simplify etc. but none of them worked.

Thanks!

Body:
I must say I did not understand the original question.  However, while trying to understand the intriguing solution given by belisarius I came up with the following:

expr = (-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B));

Together@(PowerExpand@FunctionExpand@Numerator@expr/
 PowerExpand@FunctionExpand@Denominator@expr)

Output (as given by belisarius):

Alternatively:

PowerExpand@FunctionExpand@Numerator@expr/PowerExpand@
 FunctionExpand@Denominator@expr

gives

or

FunctionExpand@Numerator@expr/FunctionExpand@Denominator@expr

Thanks to belisarius for another nice lesson in the power of Mma.


问:
AEM Dispatcher - cache rules
I am looking to get an understanding on a part of AEM dispatcher configuration. This will go under /cache /rules section

It looks like something below

```<code>/rules
        {
        # initial blanket deny
          /0000
          {
            /glob "*"
            /type "deny"
          }
          /0100
          {
           /glob "*.html"
           /type "deny"
          }
        }
</code>```

Does rule 100 mean that the dispatcher is not caching any html pages?

答:
Here is the simple explanation:

```<code>/rules
       {
        # initial blanket deny
          /0000
          {
            /glob "*"
            /type "deny"
          }
          /0100
          {
           /glob "*.html"
           /type "deny"
          }
        }
</code>```

/0000 -- rule will not allow anything to be cached.

if you want something to be cached just mention allow as per the below:

```<code>/rules

      /0100
      {
       /glob "*.html"
       /type "allow"
      }
</code>```

Title: AEM Dispatcher - cache rules

Body:
I am looking to get an understanding on a part of AEM dispatcher configuration. This will go under /cache /rules section

It looks like something below

/rules
        {
        # initial blanket deny
          /0000
          {
            /glob "*"
            /type "deny"
          }
          /0100
          {
           /glob "*.html"
           /type "deny"
          }
        }

Does rule 100 mean that the dispatcher is not caching any html pages?

Body:
Here is the simple explanation:

/rules
       {
        # initial blanket deny
          /0000
          {
            /glob "*"
            /type "deny"
          }
          /0100
          {
           /glob "*.html"
           /type "deny"
          }
        }

/0000 -- rule will not allow anything to be cached.

if you want something to be cached just mention allow as per the below:

/rules

      /0100
      {
       /glob "*.html"
       /type "allow"
      }


问:
Modal event before hide
I have a problem. I need to show toastr informing that changes are not saved when someone wants to hide modal. I need to trigger toastr before modal hide, and when the user tries again to dismiss modal allow this. I tried something like this:

```<code>declare let jQuery: any;
declare let $: any;
declare let toastr: any;

@Component({
  selector: 'app-trigger',
  templateUrl: './trigger.component.html',
  styleUrls: ['./trigger.component.scss']
})
export class TriggerComponent implements OnInit {

  name: string

  private canHideModal = true;

  constructor() {
  }

ngOnInit(){
      const self = this;
      $('#triggerModal').on('hide.bs.modal', () => {
        if (self.canHideModal) {
          //hide modal here  <---------
        } else {
          toastr['warning']('You have unsaved changes');

          self.canHideModal = true;
           return false
        }
       });
    }

 fireModal(changes : {action:string, name:string}){
   changes.action  = 'show';
   changes.name = 'test';
   this.name = changes.name
   $('#triggerModal').modal(changes.action);
 }

}
</code>```

and it works fine for first time, after this hide event seems to be overwriten and function $('#triggerModal').on('hide.bs.modal', () => { doesn't trigger anymore.

HTML:

```<code><div class="modal fade" id="triggerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="display: none;" aria-hidden="true">
    <div class="modal-dialog modal-lg px-4" role="document">

        <!--Content-->
        <div class="modal-content">

            <!--Header-->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
            </div>

            <!--Body-->
            <div class="modal-body mb-0">

                <!--Grid row-->
                <div class="row d-flex justify-content-center mb-4">

                    <!--Grid column-->
                    <div class="col-md-6">

                        <!--Name-->
                        <div class="md-form">
                            <input type="text" id="triggerStartName" (input)="canHideModal = false" class="form-control" #triggerName [value]="name">
                            <label for="triggerStartName" [ngClass]="{ 'active': name }">Trigger name</label>
                        </div>

                    </div>
                    <!--Grid column-->

                </div>
                <!--Grid row-->

            </div>

            <!--Footer-->
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-primary waves-effect waves-light" data-dismiss="modal">Close</button>
            </div>

        </div>
        <!--/.Content-->

    </div>
</div>
</code>```

答:
You can do it with the ng-bootstrap Modal component, by assigning a method to its beforeDismiss option, as illustrated in this plunker:</p>

```<code>import {Component} from '@angular/core';

import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'ngbd-modal-basic',
  templateUrl: 'src/modal-basic.html'
})
export class NgbdModalBasic {
  closeResult: string;
  private canHideModal = false;

  constructor(private modalService: NgbModal) {}

  open(content) {
    this.canHideModal = false;
    const options : NgbModalOptions = {
      beforeDismiss: () => {
        if (this.canHideModal) {
          return true;
        } else {
          alert('You have unsaved changes');
          this.canHideModal = true;
          return false;
        }
      }
    };
    this.modalService.open(content, options).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }
  ...
}
</code>```

Title: Modal event before hide

Body:
I have a problem. I need to show toastr informing that changes are not saved when someone wants to hide modal. I need to trigger toastr before modal hide, and when the user tries again to dismiss modal allow this. I tried something like this:

declare let jQuery: any;
declare let $: any;
declare let toastr: any;

@Component({
  selector: 'app-trigger',
  templateUrl: './trigger.component.html',
  styleUrls: ['./trigger.component.scss']
})
export class TriggerComponent implements OnInit {

  name: string

  private canHideModal = true;

  constructor() {
  }

ngOnInit(){
      const self = this;
      $('#triggerModal').on('hide.bs.modal', () => {
        if (self.canHideModal) {
          //hide modal here  <---------
        } else {
          toastr['warning']('You have unsaved changes');

          self.canHideModal = true;
           return false
        }
       });
    }

 fireModal(changes : {action:string, name:string}){
   changes.action  = 'show';
   changes.name = 'test';
   this.name = changes.name
   $('#triggerModal').modal(changes.action);
 }

}

and it works fine for first time, after this hide event seems to be overwriten and function $('#triggerModal').on('hide.bs.modal', () => { doesn't trigger anymore.

HTML:

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                            <input type="text" id="triggerStartName" (input)="canHideModal = false" class="form-control" #triggerName [value]="name">
                            Trigger name

                <button type="button" class="btn btn-primary waves-effect waves-light" data-dismiss="modal">Close</button>

Body:
You can do it with the ng-bootstrap Modal component, by assigning a method to its beforeDismiss option, as illustrated in this plunker:

import {Component} from '@angular/core';

import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'ngbd-modal-basic',
  templateUrl: 'src/modal-basic.html'
})
export class NgbdModalBasic {
  closeResult: string;
  private canHideModal = false;

  constructor(private modalService: NgbModal) {}

  open(content) {
    this.canHideModal = false;
    const options : NgbModalOptions = {
      beforeDismiss: () => {
        if (this.canHideModal) {
          return true;
        } else {
          alert('You have unsaved changes');
          this.canHideModal = true;
          return false;
        }
      }
    };
    this.modalService.open(content, options).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }
  ...
}


问:
C++ passing 4 random characters back to main and forming an array
I am looking to use a function to generate a random character, pass that to the main. The function must be called four times to eventually get an array of 4 chars.

I'm not sure how to call the function multiple times and how to form an array using the chars.

```<code>char GenChar(char &c))
{
int i;
char c;
for (i=0; i <5; i++)  {
c =  rand( ) % 26 + 65;
return c;
    }
}
</code>```

答:
Maybe, you want to use strings instead of single characters:

```<code>std::string GenRandomString()
{
  std::string text;
  for (int i = 0; i < 5; ++i)
  {
    text += (rand() % 26) + 'A';
  }
  return text;
}
</code>```

In C++ there is a concept difference between single characters and multiple characters.  Multiple characters are called a string.

You could also pass by reference:

```<code>void GenRandomString(std::string& text)
{
  text.clear();
  for (int i = 0; i < 5; ++i)
  {
    text += (rand() % 26) + 'A';
  }
}
</code>```

Body:
I am looking to use a function to generate a random character, pass that to the main. The function must be called four times to eventually get an array of 4 chars.

I'm not sure how to call the function multiple times and how to form an array using the chars.

char GenChar(char &c))
{
int i;
char c;
for (i=0; i <5; i++)  {
c =  rand( ) % 26 + 65;
return c;
    }
}

Body:
Maybe, you want to use strings instead of single characters:

std::string GenRandomString()
{
  std::string text;
  for (int i = 0; i < 5; ++i)
  {
    text += (rand() % 26) + 'A';
  }
  return text;
}

In C++ there is a concept difference between single characters and multiple characters.  Multiple characters are called a string.

You could also pass by reference:

void GenRandomString(std::string& text)
{
  text.clear();
  for (int i = 0; i < 5; ++i)
  {
    text += (rand() % 26) + 'A';
  }
}


答:
Yes, if you add tabindex="0" to your div, you make it clickable and can then use the :focus pseudo-class to apply styles.

```<code><div class="clickable" tabindex="0"></div>

.clickable {
  height: 100px;
  background: blue;
}

.clickable:focus {
  background: red;
}
</code>```

Codepen example. Clicking the div should give it focus and apply the :focus CSS to it. Clicking away from it will unfocus (blur) it and reset the default styles.

Title: is it possible to activate a div when clicked without javascript?

Body:
Just wondering if a div can be called without using javascript.

such as

my_div:hover{ add new layout}

is there a version for click eg

my_div:click{add new layout}

Thanks

Body:
Yes, if you add tabindex="0" to your div, you make it clickable and can then use the :focus pseudo-class to apply styles.

<div class="clickable" tabindex="0"></div>

.clickable {
  height: 100px;
  background: blue;
}

.clickable:focus {
  background: red;
}

Codepen example. Clicking the div should give it focus and apply the :focus CSS to it. Clicking away from it will unfocus (blur) it and reset the default styles.