问:
Trouble controlling the loops
If pressed delet , All images are deleted ,I do not want that.
I just want to delete one image.</p>

```<code>$get_img = "SELECT * FROM img";
$run_img = mysqli_query($db,$get_img);

while ($row_img= mysqli_fetch_array($run_img)){
    if (isset($_POST['delete'])){
        $delete= "DELETE FROM img WHERE id = {$row_img['id']} ";
        $query = mysqli_query ($db , $delete);
    }

    echo '
        <div style="width:200px; height:200px;  border: 5px solid red; margin:10px; float: right;">
            <img src="images/'.$row_pro['c_img'].'" width="200" height="200" /><br />
            <form action="get.php" method="POST">
                <input type="submit" name="delet" value="delet" />
            </form>
        </div>
    ';
}
</code>```

答:
Grab your isset and delete query out of while
Something like that. I did not checked all details but maybe it's good for inspiration.

```<code>$get_img = "SELECT * FROM img";
$run_img = mysqli_query($db, $get_img);

while ($row_img = mysqli_fetch_array($run_img))
{
  echo '<div>
          <img src="images/' . $row_pro['c_img'] . '" /><br />
        </div>';
}

echo '<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <input type="submit" name="delete" value="delete" />
      </form>';

if (isset($_POST['delete']))
{
  $delete= "DELETE FROM img WHERE id = :id", ['id'=>$row_pro['id']];
  $query = mysqli_query($db, $delete);
}
</code>```

Hope you'll figured out.

Title: Trouble controlling the loops

Body:
If pressed delet , All images are deleted ,I do not want that.
I just want to delete one image.

$get_img = "SELECT * FROM img";
$run_img = mysqli_query($db,$get_img);

while ($row_img= mysqli_fetch_array($run_img)){
    if (isset($_POST['delete'])){
        $delete= "DELETE FROM img WHERE id = {$row_img['id']} ";
        $query = mysqli_query ($db , $delete);
    }

    echo '

            <form action="get.php" method="POST">
                <input type="submit" name="delet" value="delet" />
            </form>

    ';
}

Body:
Grab your isset and delete query out of while
Something like that. I did not checked all details but maybe it's good for inspiration.

$get_img = "SELECT * FROM img";
$run_img = mysqli_query($db, $get_img);

while ($row_img = mysqli_fetch_array($run_img))
{
  echo '<div>
          <img src="images/' . $row_pro['c_img'] . '" /><br />
        </div>';
}

echo '<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <input type="submit" name="delete" value="delete" />
      </form>';

if (isset($_POST['delete']))
{
  $delete= "DELETE FROM img WHERE id = :id", ['id'=>$row_pro['id']];
  $query = mysqli_query($db, $delete);
}

Hope you'll figured out.


来源: stackexchange

问:
Swift 4 String index offset by too slow while processing a large string
I'm processing a csv file with last column not being always same format.
Each row has this structure:

```<code>"Root/Word1","some string","some string","some œ0'fqw[å”ƒ#”≠§
\nfw@\tfa0j
"
"Root/Word2","some string","some string","some string"
...
</code>```

So 6 columns and the last can contain \n. Which makes it hard to split by components.
Another restriction is that all the strings can be any possible special character. Which makes it hard to use regex.

I decided to solve the problem brute force first. (Yes I have seen that index offset by is O(n). But can't come up with an alternative.)

```<code>static func importData(_ db: DB) {
    let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!

    let totalCharCount = csvString.count
    print("total: \(totalCharCount)")
    for i in 0..<totalCharCount {
        print(i)
        if i+5 >= totalCharCount {
            continue
        }
        let index = csvString.index(csvString.startIndex, offsetBy: i)
        let endIndex = csvString.index(csvString.startIndex, offsetBy:i+5)

        let part = csvString[index ..< endIndex]
        if part == "Root/" {
            let accum = lookInside(i: i, totalCharCount: totalCharCount, csvString: csvString)

            var rows = accum.components(separatedBy: "\",\"")

            if var lastt = rows.last {
                lastt.removeLast()
                lastt.removeLast()
                rows[rows.count-1] = lastt
            }
        }
    }
}

static func lookInside(i:Int, totalCharCount: Int, csvString: String) -> String {
    var accum = ""
    var found = false
    var j = i+5
    while !found {

        if j+5 >= totalCharCount {
            found = true
        }
        let index2 = csvString.index(csvString.startIndex, offsetBy: j)
        let endIndex2 = csvString.index(csvString.startIndex, offsetBy:j+5)

        if csvString[index2 ..< endIndex2] == "Root/" {
            found = true
            accum.removeLast()
        } else {
            accum += String(csvString[index2])
        }
        j += 1
    }

    return accum
}
</code>```

Basically I'm traversing the whole string looking for a pattern "Root/".
When found, I advance from this moment to the next occurrence of the pattern.

Problem is that the csv results in a string 200k chars long and when I run this on simulator it lasts too much time (~30min).

So now I'm asking some help here because according to Instruments all the time is consumed in String.index(offset by) method which is called too many times.

答:
Shlemiel gets a job as a street painter, painting the dotted lines
  down the middle of the road. On the first day he takes a can of paint
  out to the road and finishes 300 yards of the road. “That’s pretty
  good!” says his boss, “you’re a fast worker!” and pays him a kopeck.

The next day Shlemiel only gets 150 yards done. “Well, that’s not
  nearly as good as yesterday, but you’re still a fast worker. 150 yards
  is respectable,” and pays him a kopeck.

The next day Shlemiel paints 30 yards of the road. “Only 30!” shouts
  his boss. “That’s unacceptable! On the first day you did ten times
  that much work! What’s going on?”

“I can’t help it,” says Shlemiel. “Every day I get farther and farther
  away from the paint can!”

Quote from Joel on Software

You need to understand how strings work. Poor string handling was slow in 2001 when Joel Spolsky wrote the above story. With proper Unicode handling, things have become even more expensive.

You aren't really traversing the string. You start all over again and again by using String.startIndex.

Instead use functions that return a String.Index result. That's an efficient index into the string. Use it to save your last position and then work relative to this position. Your code will be faster if you use String.Index only once at the beginning.

ContentLicense: CC BY-SA 3.0

Body:
I'm processing a csv file with last column not being always same format.
Each row has this structure:

"Root/Word1","some string","some string","some œ0'fqw[å”ƒ#”≠§
\nfw@\tfa0j
"
"Root/Word2","some string","some string","some string"
...

So 6 columns and the last can contain \n. Which makes it hard to split by components.
Another restriction is that all the strings can be any possible special character. Which makes it hard to use regex.

I decided to solve the problem brute force first. (Yes I have seen that index offset by is O(n). But can't come up with an alternative.)

static func importData(_ db: DB) {
    let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!

    let totalCharCount = csvString.count
    print("total: \(totalCharCount)")
    for i in 0..<totalCharCount {
        print(i)
        if i+5 >= totalCharCount {
            continue
        }
        let index = csvString.index(csvString.startIndex, offsetBy: i)
        let endIndex = csvString.index(csvString.startIndex, offsetBy:i+5)

        let part = csvString[index ..< endIndex]
        if part == "Root/" {
            let accum = lookInside(i: i, totalCharCount: totalCharCount, csvString: csvString)

            var rows = accum.components(separatedBy: "\",\"")

            if var lastt = rows.last {
                lastt.removeLast()
                lastt.removeLast()
                rows[rows.count-1] = lastt
            }
        }
    }
}

static func lookInside(i:Int, totalCharCount: Int, csvString: String) -> String {
    var accum = ""
    var found = false
    var j = i+5
    while !found {

        if j+5 >= totalCharCount {
            found = true
        }
        let index2 = csvString.index(csvString.startIndex, offsetBy: j)
        let endIndex2 = csvString.index(csvString.startIndex, offsetBy:j+5)

        if csvString[index2 ..< endIndex2] == "Root/" {
            found = true
            accum.removeLast()
        } else {
            accum += String(csvString[index2])
        }
        j += 1
    }

    return accum
}

Basically I'm traversing the whole string looking for a pattern "Root/".
When found, I advance from this moment to the next occurrence of the pattern.

Problem is that the csv results in a string 200k chars long and when I run this on simulator it lasts too much time (~30min).

So now I'm asking some help here because according to Instruments all the time is consumed in String.index(offset by) method which is called too many times.


问:
How to enable Android O WiFi Hotspot programmatically
We've been using the WifiManager hidden API to enable Wifi tethering and create an access point. The problem now with API 26 on Android is that the tag @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) was added to the setWifiApEnabled function and now that invocation returns false and the following log is printed:

W/WifiManager: PACKAGE_NAME attempted call to setWifiApEnabled enabled = true

Reading the new documentation, it says that the function is deprecated and will be removed in an upcoming release and to instead use ConnectivityManager#startTethering if the caller has proper permission but this approach has the same problem with no TETHER_PRIVILEGED permissions. One other option presented on the documentation is the use of LocalOnlyHotspot but this is no use to the project since the hotspot created has no Internet connectivity.

I've also tested with the startSoftAp function from the hidden API but with no successful results since the following exception is thrown:

WifiService: Neither user 10164 nor current process has android.permission.NETWORK_STACK

Is there any workaround to activate a Wifi hotspot on newer APIs? I've also searched for alternatives to Wifi tethering but the only viable alternative seems to be Bluetooth tethering with the downside of only getting 3G speed. Wifi Aware and Wifi P2P were also considered but these have the problem of the Internet connectivity not being shared between the devices.

Any suggestions on how to approach this?

答:
This has been answered many times. As, Snehashish Agarwal said, setWifiApEnabled() and startThethering() methods are private APIs. They are  annotated with @hide which means they are private. Third party applications should not be invoking private APIs directly. There is no guarantee that they will work in future. As in your case.

Also, startLocalOnlyHotspot will not have the internet access. It is a local only hotspot to communicate between devices connected to the Wifi hotspot and this method will not have Internet access.

Currently, there are no official API call for enabling the Mobile hotspot.


问:
How to print text from textarea?
I want to print text from text area.

I have a textarea which text can be updated by user. When user update text from textarea and then print the updated text can be print on page. And this text can be print on print page without textarea.

Please suggest any solution.

Thanks

答:
I think I got what you are asking for. Give it a try:

```<code><html>
  <head>
    <title>Print TextArea</title>
    <script type="text/javascript">
      function printTextArea() {
        childWindow = window.open('','childWindow','location=yes, menubar=yes, toolbar=yes');
        childWindow.document.open();
        childWindow.document.write('<html><head></head><body>');
        childWindow.document.write(document.getElementById('targetTextArea').value.replace(/\n/gi,'<br>'));
        childWindow.document.write('</body></html>');
        childWindow.print();
        childWindow.document.close();
        childWindow.close();
      }
    </script>
  </head>
  <body>
    <textarea rows="20" cols="50" id="targetTextArea">
      TextArea value...
    </textarea>
    <input type="button" onclick="printTextArea()" value="Print Text"/>
  </body>
</html>
</code>```

Basically this will open another child window and execute javascript print on that so that the textarea and other things don't get printed.

ContentLicense: CC BY-SA 2.5

Title: How to print text from textarea?

Body:
I think I got what you are asking for. Give it a try:

<html>
  <head>
    <title>Print TextArea</title>
    <script type="text/javascript">
      function printTextArea() {
        childWindow = window.open('','childWindow','location=yes, menubar=yes, toolbar=yes');
        childWindow.document.open();
        childWindow.document.write('<html><head></head><body>');
        childWindow.document.write(document.getElementById('targetTextArea').value.replace(/\n/gi,'<br>'));
        childWindow.document.write('</body></html>');
        childWindow.print();
        childWindow.document.close();
        childWindow.close();
      }
    </script>
  </head>
  <body>
    <textarea rows="20" cols="50" id="targetTextArea">
      TextArea value...
    </textarea>
    <input type="button" onclick="printTextArea()" value="Print Text"/>
  </body>
</html>

Basically this will open another child window and execute javascript print on that so that the textarea and other things don't get printed.


问:
How to release a Python application that uses API keys to the public?
I would like to release the code for an application I made in Python to the public, just as a pastebin link. However, the app needs a client ID, secret and user agent to access the API (for reddit in this case).

How can I store the key strings in the python code without giving everyone free reign on my api access? Maybe a hashing function or similar?

答:
You probably don't want to provide the actual keys and other private information at all, hashed or otherwise. Besides being a security issue, it probably violates all sorts of agreements you implicitly made with the provider.

Anyone using the application should be able to get their own key in the same manner you did. You can (and should) provide instructions for how to do this.

Your application should expect the key information in a well documented format, usually a configuration file, that the user must provide once they have obtained the keys in question. You should document the exact format you expect to read the key in as well.

Your documentation could also include a dummy file with empty or obvious placeholder values for the user to fill in. It may be overkill, but I would recommend making sure that any placeholders you use are guaranteed not to be valid keys. This will go a long way to avoiding any accidents with the agreements you could violate otherwise.


问:
Need help formatting/parsing this list
I'm not a developer so sorry if this is a dumb question or if my terminology is incorrect. I'm writing a script to make calls to our CMDB's API but i'm not sure how to handle the data that is being sent back from it. It appears to be a list type but I can't reference anything by key names. Is there a way to convert it to something that i can easily manipulate and pull data out of?

Here is my code:

```<code>import requests
import json

r=requests.post('API.URL', data={'grant_type': 'password', 'client_id':'#######', 'username': 'user', 'password': 'password'})
json_data = json.loads(r.content)
token = json_data['access_token']
data ={
  "filters": [
    {
      "fieldId": "937905400191ae67dd03ab4b79968fcbaa264b1a75",
      "operator": "eq",
      "value": "hostname"
    }
  ],
  "fields":[
    '9426b6ddf3cb971488517145e39efc5aa7f16fec46',
    '9343f8800b3917f26533954918a6388ae8c863507f',
    '9379053db492ece14816704ef5a9e3e567e217511b',
    '9343f93fc4c8422bcf24e74a9a86035bb7d0248b00',
    '941ba290776d6f51ce35664246927b958330a753b2'
  ],
  "association": "Configuration Item",
  "busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8",
  "includeAllFields": 'false',
  "pageNumber": 0,
  "pageSize": 300,
  "scope": "Global",
  "scopeOwner": "(None)",
  "searchName": "APItest"
}
payload = json.dumps(data)
headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization':'bearer '+token}
search=requests.post('http://API.URL', headers=headers, data=payload)
search_json = json.loads(search.content)
bo = search_json['businessObjects']
print(bo)
</code>```

Here's the response:

```<code>[
    {
        "busObRecId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1",
        "hasError": false,
        "links": [
            {
                "url": "http://URL",
                "name": "Delete Record"
            }
        ],
        "fields": [
            {
                "displayName": "Business Sponsor",
                "name": "Business Sponsor",
                "value": "",
                "html": null,
                "dirty": false,
                "fieldId": "9426b6ddf3cb971488517145e39efc5aa7f16fec46"
            },
            {
                "displayName": "Owned By",
                "name": "Owned By",
                "value": "John Doe",
                "html": null,
                "dirty": false,
                "fieldId": "9343f8800b3917f26533954918a6388ae8c863507f"
            },
            {
                "displayName": "Asset Status",
                "name": "Asset Status",
                "value": "Active",
                "html": null,
                "dirty": false,
                "fieldId": "9379053db492ece14816704ef5a9e3e567e217511b"
            },
            {
                "displayName": "Description",
                "name": "Description",
                "value": "Automation Server",
                "html": null,
                "dirty": false,
                "fieldId": "9343f93fc4c8422bcf24e74a9a86035bb7d0248b00"
            },
            {
                "displayName": "Data Center Location",
                "name": "Data Center Location",
                "value": "",
                "html": null,
                "dirty": false,
                "fieldId": "941ba290776d6f51ce35664246927b958330a753b2"
            }
        ],
        "errorMessage": null,
        "busObPublicId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1",
        "busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8",
        "errorCode": null
    }
]
</code>```

type() shows the object bo as a list and len() says it only has one element so I'm not sure how to pull data out of it without hacking away at it stripping out characters.

答:
The reason why you cannot reference anything by key names is the fact that your output is a list. A list which is only containing one single dictionary element. If you print out

```<code>bo[0]
</code>```

you get the whole data, without the [ and ] symbols. As for the dictionary now we can access different elements by keys, e.g.:

```<code>print(bo["busObId"])
</code>```

will return the following value:

```<code>93dada9f640056ce1dc67b4d4bb801f69104894dc
</code>```

Let's say you would want to print out the fieldId of the first element of "fields". You can do it the following way:

```<code>print(bo[0]["fields"][0]["fieldId"])
</code>```

Hope this helped.

Title: Need help formatting/parsing this list

Body:
I'm not a developer so sorry if this is a dumb question or if my terminology is incorrect. I'm writing a script to make calls to our CMDB's API but i'm not sure how to handle the data that is being sent back from it. It appears to be a list type but I can't reference anything by key names. Is there a way to convert it to something that i can easily manipulate and pull data out of?

Here is my code:

import requests
import json

r=requests.post('API.URL', data={'grant_type': 'password', 'client_id':'#######', 'username': 'user', 'password': 'password'})
json_data = json.loads(r.content)
token = json_data['access_token']
data ={
  "filters": [
    {
      "fieldId": "937905400191ae67dd03ab4b79968fcbaa264b1a75",
      "operator": "eq",
      "value": "hostname"
    }
  ],
  "fields":[
    '9426b6ddf3cb971488517145e39efc5aa7f16fec46',
    '9343f8800b3917f26533954918a6388ae8c863507f',
    '9379053db492ece14816704ef5a9e3e567e217511b',
    '9343f93fc4c8422bcf24e74a9a86035bb7d0248b00',
    '941ba290776d6f51ce35664246927b958330a753b2'
  ],
  "association": "Configuration Item",
  "busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8",
  "includeAllFields": 'false',
  "pageNumber": 0,
  "pageSize": 300,
  "scope": "Global",
  "scopeOwner": "(None)",
  "searchName": "APItest"
}
payload = json.dumps(data)
headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization':'bearer '+token}
search=requests.post('http://API.URL', headers=headers, data=payload)
search_json = json.loads(search.content)
bo = search_json['businessObjects']
print(bo)

Here's the response:

[
    {
        "busObRecId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1",
        "hasError": false,
        "links": [
            {
                "url": "http://URL",
                "name": "Delete Record"
            }
        ],
        "fields": [
            {
                "displayName": "Business Sponsor",
                "name": "Business Sponsor",
                "value": "",
                "html": null,
                "dirty": false,
                "fieldId": "9426b6ddf3cb971488517145e39efc5aa7f16fec46"
            },
            {
                "displayName": "Owned By",
                "name": "Owned By",
                "value": "John Doe",
                "html": null,
                "dirty": false,
                "fieldId": "9343f8800b3917f26533954918a6388ae8c863507f"
            },
            {
                "displayName": "Asset Status",
                "name": "Asset Status",
                "value": "Active",
                "html": null,
                "dirty": false,
                "fieldId": "9379053db492ece14816704ef5a9e3e567e217511b"
            },
            {
                "displayName": "Description",
                "name": "Description",
                "value": "Automation Server",
                "html": null,
                "dirty": false,
                "fieldId": "9343f93fc4c8422bcf24e74a9a86035bb7d0248b00"
            },
            {
                "displayName": "Data Center Location",
                "name": "Data Center Location",
                "value": "",
                "html": null,
                "dirty": false,
                "fieldId": "941ba290776d6f51ce35664246927b958330a753b2"
            }
        ],
        "errorMessage": null,
        "busObPublicId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1",
        "busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8",
        "errorCode": null
    }
]

type() shows the object bo as a list and len() says it only has one element so I'm not sure how to pull data out of it without hacking away at it stripping out characters.

Body:
The reason why you cannot reference anything by key names is the fact that your output is a list. A list which is only containing one single dictionary element. If you print out

bo[0]

you get the whole data, without the [ and ] symbols. As for the dictionary now we can access different elements by keys, e.g.:

print(bo["busObId"])

will return the following value:

93dada9f640056ce1dc67b4d4bb801f69104894dc

Let's say you would want to print out the fieldId of the first element of "fields". You can do it the following way:

print(bo[0]["fields"][0]["fieldId"])

Hope this helped.


问:
Shutting down daemon thread properly
I've created my own thread class that will be used in a threadpool as follows:

```<code>class SendFilesThread(threading.Thread):
    execute = True

    def __init__(self, port, rate, fileQueue):
        self.daemon = True
        self.fileQueue = fileQueue
        #Other initialization

    def run(self):
        while SendFilesThread.execute == True or not self.fileQueue.empty():
            self.filename = self.fileQueue.get()
            #some file processing
            self.fileQueue.task_done()

    @staticmethod
    def terminate():
        SendFilesThread.execute = False
</code>```

In the main thread of the program, after I have processed all of my files, I try and shut down the threadpool as follows:

```<code>SendFilesThread.terminate()
for t in threadPool:
    if t.is_alive():
        t.join()
exit()
</code>```

My understanding is that if I call join() it will block the calling thread, in this case the main thread, from continuing until the joined thread finishes processing. My issue is that despite the thread completing, it never returns to the main thread and the program just hangs. Am I doing anything wrong when shutting down my threadpool?

答:
There are two things. First, from a design standpoint it's a bit odd to have the execute flag be at the class-level. It's usually better to have it be a flag on each class instance.

Second, you have a race condition. The execute flag is accessed by more than one thread, and not protected by a synchronization primitive, such as a mutex. This means that the terminate() call can be run (and the flag set) after any worker thread checks the flag, but before that thread tries to dequeue the next filename. Because you're calling get() without a timeout, the worker thread will hang here, and the main thread will block in the t.join() call. Deadlock ensues.

There are many ways around this. You can use a thread-synchronization primitive such as a mutex to protect the execute flag, or use a threading.Event object in place of a simple boolean.

Another, and in my opinion simpler, solution is to send a "sentinel" value on the same queue, which indicates that the thread should quit. It looks like you're sending string filenames, so an empty string could be a good choice. (None is also commonly used.)

The work-loop for each thread now looks like this:

```<code>def run(self):
    while True:
        self.filename = self.fileQueue.get()
        if self.filename == '':
            return
        # Process file
</code>```

Rather than the terminate() static method, the main thread places an empty string (i.e., fileQueue.enqueue('')) for each worker thread you have.

Title: Shutting down daemon thread properly

Body:
I've created my own thread class that will be used in a threadpool as follows:

class SendFilesThread(threading.Thread):
    execute = True

    def __init__(self, port, rate, fileQueue):
        self.daemon = True
        self.fileQueue = fileQueue
        #Other initialization

    def run(self):
        while SendFilesThread.execute == True or not self.fileQueue.empty():
            self.filename = self.fileQueue.get()
            #some file processing
            self.fileQueue.task_done()

    @staticmethod
    def terminate():
        SendFilesThread.execute = False

In the main thread of the program, after I have processed all of my files, I try and shut down the threadpool as follows:

SendFilesThread.terminate()
for t in threadPool:
    if t.is_alive():
        t.join()
exit()

My understanding is that if I call join() it will block the calling thread, in this case the main thread, from continuing until the joined thread finishes processing. My issue is that despite the thread completing, it never returns to the main thread and the program just hangs. Am I doing anything wrong when shutting down my threadpool?

Body:
There are two things. First, from a design standpoint it's a bit odd to have the execute flag be at the class-level. It's usually better to have it be a flag on each class instance.

Second, you have a race condition. The execute flag is accessed by more than one thread, and not protected by a synchronization primitive, such as a mutex. This means that the terminate() call can be run (and the flag set) after any worker thread checks the flag, but before that thread tries to dequeue the next filename. Because you're calling get() without a timeout, the worker thread will hang here, and the main thread will block in the t.join() call. Deadlock ensues.

There are many ways around this. You can use a thread-synchronization primitive such as a mutex to protect the execute flag, or use a threading.Event object in place of a simple boolean.

Another, and in my opinion simpler, solution is to send a "sentinel" value on the same queue, which indicates that the thread should quit. It looks like you're sending string filenames, so an empty string could be a good choice. (None is also commonly used.)

The work-loop for each thread now looks like this:

def run(self):
    while True:
        self.filename = self.fileQueue.get()
        if self.filename == '':
            return
        # Process file

Rather than the terminate() static method, the main thread places an empty string (i.e., fileQueue.enqueue('')) for each worker thread you have.


问:
Realm - write from different threads - RxJava
I want to use Realm and I need to write data from different threads. I read post about Realm. Realm is similar as Git. Can you explain how merge of data with conflicts works in Realm? Thanks </p>

答:
Can you explain how merge of data with conflicts works in Realm?

If we are talking about the Realm local database (Realm Mobile Database), and NOT about the Realm Mobile Platform:

Transactions are blocking across threads and processes, so there can only be one write transaction at a time. Therefore when that is committed, that will become the new version. Merge scenario is impossible. When a write transaction is open, then in the transaction, you see the latest state of the database at all times, and it is impossible to see an older version.

If we are talking about the Realm Mobile Platform:

When multiple offline transactions occur on the same data where they only get synced later, the conflict resolution happens based on rules of the operational transform:

Deletes always win: If one side deletes an object it will always stay deleted, even if the other side has made changes to it later on.

Last update wins. If two sides update the same property, the value will end up as the last updated.

Inserts in lists are ordered by time. If two items are inserted at the same position, the item that was inserted first will end up before the other item.


问:
Get values from array and calculate average then store in array
I have recently learned about two dimensional arrays. The problem is within the AverageScores function. I am trying to calculate the average for each student, then store the value calculated into a different array and then print it. I am having trouble but I understand that I need to sum the row of values and calculate the average, print, then move onto the next student.

edit : When I run the program, the program does not calculate the average at all, but rather it prints the number of tests and a negative incorrect value.
ex. if there are 2 tests and 2 students, the program will print -9.25596e+61 twice for the first student and then twice again for the second.

```<code>#include <iostream>
#include <iomanip>
#include <conio.h>

using namespace std;

//constant declarations
const int MAX_STUDENTS = 30; //maximum number of students
const int MAX_TESTS = 10; //maximum number of tests
                          //function prototypes
void intro();
void ReadScores(double[][MAX_TESTS], int&, int&);
void PrintScores(const double[][MAX_TESTS], int, int);
void AverageScores(const double[][MAX_TESTS],
    int,
    int,
    double[]);

int main()
{
    //variable declarations
    double scores[MAX_STUDENTS][MAX_TESTS],//array of test scores
        studentAvgs[MAX_TESTS];
    int numberOfStudents; //number of students in a class
    int numberOfTests; //number of tests written
    intro();
    //read the each student’s test scores into an array scores
    ReadScores(scores, numberOfStudents, numberOfTests);
    //print each student’s scores
    PrintScores(scores, numberOfStudents, numberOfTests);
    AverageScores(scores, numberOfStudents, numberOfTests, studentAvgs);

    _getch();
    return 0;
}

void ReadScores(double scores[][MAX_TESTS], //array of test scores
    int& numberOfStudents, //number of students read
    int& numberOfTests) //number of tests read
{
    int student; //row index used for students
    int test; //column index used for tests
              //prompt for and read the number of students and the number of tests
    cout << "Enter the number of students(up to " << MAX_STUDENTS << ") :";
    cin >> numberOfStudents;
    cout << "Enter the number of tests(up to " << MAX_TESTS << ") : ";
    cin >> numberOfTests;
    //read the test scores into the array scores
    for (student = 0; student < numberOfStudents; student++)
    {
        cout << "Enter the " << numberOfTests
            << " test scores for student# " << (student + 1) << endl;
        for (test = 0; test < numberOfTests; test++)
            cin >> scores[student][test];
    }
}

void PrintScores(const double scores[][MAX_TESTS],
    int numberOfStudents,
    int numberOfTests)
{
    int student;
    int test;
    for (student = 0; student < numberOfStudents; student++)
    {
        cout << "The test scores for student# " << (student + 1)
            << " are: " << endl;
        for (test = 0; test < numberOfTests; test++)
            cout << setw(3) << scores[student][test];
        cout << endl << endl;
    }
}

void intro() {
    cout << setw(46) << "Welcome\n\n";
}

void AverageScores(const double scores[][MAX_TESTS],
    int numberOfStudents,
    int numberOfTests,
    double studentAvgs[]){

    int student,
        test,
        accumilator = 0;

    for (student = 0; student < numberOfStudents; student++)
    {
        cout << "The average test score for student# " << (student + 1)
            << " is: " << endl;
        for (test = 0; test < numberOfTests; test++) {
            accumilator += scores[numberOfStudents][numberOfTests];
            studentAvgs[test] = accumilator / numberOfTests;
            cout << studentAvgs[numberOfTests] << endl;
        }
    }
}
</code>```

答:
The same but using STL (for giggles):

```<code>#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <numeric>

int main()
{
    std::vector<std::pair<std::string, std::vector<double>>> studentScores;

    studentScores.push_back(std::make_pair(std::string("Bob"), std::vector<double>{ 1.23, 3.23, 0.55 }));
    studentScores.push_back(std::make_pair(std::string("John"), std::vector<double>{ 2.09, 2.22, 4.55, 1.28, 4.99 }));
    studentScores.push_back(std::make_pair(std::string("Mary"), std::vector<double>{ 4.11, 0.2, 0.55, 3.88}));

    for (auto studentScore : studentScores)
    {
        std::cout << studentScore.first << "'s average score is: ";
        std::cout << std::accumulate(studentScore.second.begin(), studentScore.second.end(), static_cast<double>(0)) / static_cast<double>(studentScore.second.size()) << std::endl;
    }

    return 0;
}
</code>```

Prints

```<code>Bob's average score is: 1.67
John's average score is: 3.026
Mary's average score is: 2.185
</code>```

Body:
I have recently learned about two dimensional arrays. The problem is within the AverageScores function. I am trying to calculate the average for each student, then store the value calculated into a different array and then print it. I am having trouble but I understand that I need to sum the row of values and calculate the average, print, then move onto the next student.

edit : When I run the program, the program does not calculate the average at all, but rather it prints the number of tests and a negative incorrect value.
ex. if there are 2 tests and 2 students, the program will print -9.25596e+61 twice for the first student and then twice again for the second.

#include <iostream>
#include <iomanip>
#include <conio.h>

using namespace std;

//constant declarations
const int MAX_STUDENTS = 30; //maximum number of students
const int MAX_TESTS = 10; //maximum number of tests
                          //function prototypes
void intro();
void ReadScores(double[][MAX_TESTS], int&, int&);
void PrintScores(const double[][MAX_TESTS], int, int);
void AverageScores(const double[][MAX_TESTS],
    int,
    int,
    double[]);

int main()
{
    //variable declarations
    double scores[MAX_STUDENTS][MAX_TESTS],//array of test scores
        studentAvgs[MAX_TESTS];
    int numberOfStudents; //number of students in a class
    int numberOfTests; //number of tests written
    intro();
    //read the each student’s test scores into an array scores
    ReadScores(scores, numberOfStudents, numberOfTests);
    //print each student’s scores
    PrintScores(scores, numberOfStudents, numberOfTests);
    AverageScores(scores, numberOfStudents, numberOfTests, studentAvgs);

    _getch();
    return 0;
}

void ReadScores(double scores[][MAX_TESTS], //array of test scores
    int& numberOfStudents, //number of students read
    int& numberOfTests) //number of tests read
{
    int student; //row index used for students
    int test; //column index used for tests
              //prompt for and read the number of students and the number of tests
    cout << "Enter the number of students(up to " << MAX_STUDENTS << ") :";
    cin >> numberOfStudents;
    cout << "Enter the number of tests(up to " << MAX_TESTS << ") : ";
    cin >> numberOfTests;
    //read the test scores into the array scores
    for (student = 0; student < numberOfStudents; student++)
    {
        cout << "Enter the " << numberOfTests
            << " test scores for student# " << (student + 1) << endl;
        for (test = 0; test < numberOfTests; test++)
            cin >> scores[student][test];
    }
}

void PrintScores(const double scores[][MAX_TESTS],
    int numberOfStudents,
    int numberOfTests)
{
    int student;
    int test;
    for (student = 0; student < numberOfStudents; student++)
    {
        cout << "The test scores for student# " << (student + 1)
            << " are: " << endl;
        for (test = 0; test < numberOfTests; test++)
            cout << setw(3) << scores[student][test];
        cout << endl << endl;
    }
}

void intro() {
    cout << setw(46) << "Welcome\n\n";
}

void AverageScores(const double scores[][MAX_TESTS],
    int numberOfStudents,
    int numberOfTests,
    double studentAvgs[]){

    int student,
        test,
        accumilator = 0;

    for (student = 0; student < numberOfStudents; student++)
    {
        cout << "The average test score for student# " << (student + 1)
            << " is: " << endl;
        for (test = 0; test < numberOfTests; test++) {
            accumilator += scores[numberOfStudents][numberOfTests];
            studentAvgs[test] = accumilator / numberOfTests;
            cout << studentAvgs[numberOfTests] << endl;
        }
    }
}

Body:
The same but using STL (for giggles):

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <numeric>

int main()
{
    std::vector<std::pair<std::string, std::vector<double>>> studentScores;

    studentScores.push_back(std::make_pair(std::string("Bob"), std::vector<double>{ 1.23, 3.23, 0.55 }));
    studentScores.push_back(std::make_pair(std::string("John"), std::vector<double>{ 2.09, 2.22, 4.55, 1.28, 4.99 }));
    studentScores.push_back(std::make_pair(std::string("Mary"), std::vector<double>{ 4.11, 0.2, 0.55, 3.88}));

    for (auto studentScore : studentScores)
    {
        std::cout << studentScore.first << "'s average score is: ";
        std::cout << std::accumulate(studentScore.second.begin(), studentScore.second.end(), static_cast<double>(0)) / static_cast<double>(studentScore.second.size()) << std::endl;
    }

    return 0;
}

Prints

Bob's average score is: 1.67
John's average score is: 3.026
Mary's average score is: 2.185


问:
Comparing 40 million lines in a file with 6 million list items in Python
I have a file with 40 million entries in the form of:

```<code>#No Username
</code>```

And I have a list with 6 million items, where each item is a username.

I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far:

```<code>import os
usernames=[]
common=open('/path/to/filf','w')
f=open('/path/to/6 million','r')
for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)
#noOfUsers=len(usernames)
for l in f:
    l=l.split(' ')
    if(l[1] in usernames):
        common.write(l[1]+'\n')
common.close()
f.close()
</code>```

How can I improve the performance of this code?

答:
If this is an operation you will perform more than once, may I suggest threading? The following is some pseudo-code.

First, split the files up into 100,000 line files in Linux:

```<code>> split -l 100000 usernames.txt usernames_
</code>```

Then, spawn some threads to do this parallel-wise.

```<code> import threading
 usernames_one = set()
 usernames_two = set()
 filereaders = []

 # Define this class, which puts all the lines in the file into a set
 class Filereader(threading.Thread):
  def __init__(self, filename, username_set):
    # while 1:
    # read a line from filename, put it in username_set
  ...

 # loop through possible usernames_ files, and spawn a thread for each:
 # for.....
 f = Filereader('usernames_aa', usernames_one)
 filereaders.append(f)
 f.start()
 # do the same loop for usernames_two

 # at the end, wait for all threads to complete
 for f in filereaders:
     f.join()

 # then do simple set intersection:
 common_usernames = usernames_one ^ usernames_two

 # then write common set to a file:
 common_file = open("common_usernames.txt",'w')
 common_file.write('\n'.join(common_usernames))
</code>```

You'll have to check if set addition is a thread-safe procedure. If not, you can of course create a list of sets (one for each file processed by the thread), and at the end union them all before intersecting.

Body:
I have a file with 40 million entries in the form of:

#No Username

And I have a list with 6 million items, where each item is a username.

I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far:

import os
usernames=[]
common=open('/path/to/filf','w')
f=open('/path/to/6 million','r')
for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)
#noOfUsers=len(usernames)
for l in f:
    l=l.split(' ')
    if(l[1] in usernames):
        common.write(l[1]+'\n')
common.close()
f.close()

How can I improve the performance of this code?

Body:
If this is an operation you will perform more than once, may I suggest threading? The following is some pseudo-code.

First, split the files up into 100,000 line files in Linux:

> split -l 100000 usernames.txt usernames_

Then, spawn some threads to do this parallel-wise.

 import threading
 usernames_one = set()
 usernames_two = set()
 filereaders = []

 # Define this class, which puts all the lines in the file into a set
 class Filereader(threading.Thread):
  def __init__(self, filename, username_set):
    # while 1:
    # read a line from filename, put it in username_set
  ...

 # loop through possible usernames_ files, and spawn a thread for each:
 # for.....
 f = Filereader('usernames_aa', usernames_one)
 filereaders.append(f)
 f.start()
 # do the same loop for usernames_two

 # at the end, wait for all threads to complete
 for f in filereaders:
     f.join()

 # then do simple set intersection:
 common_usernames = usernames_one ^ usernames_two

 # then write common set to a file:
 common_file = open("common_usernames.txt",'w')
 common_file.write('\n'.join(common_usernames))

You'll have to check if set addition is a thread-safe procedure. If not, you can of course create a list of sets (one for each file processed by the thread), and at the end union them all before intersecting.


问:
Defining Exponent in Fortran
I've been having some trouble with variables precision in my code...
For a while i've been declaring variables as real(kind=8) :: var and I now understand that this is not very portable and has some other complications, but basically I'm getting a lot of imprecision in numerical calculations.

Now I'm using:

```<code>INTEGER,  PARAMETER :: R8 = SELECTED_REAL_KIND (30, 300)
with variable declaration: real(R8) :: var1,var2.
</code>```

Before I usually initialized variables as var1 = 1.0D0 and now I'm using var1 = 1.0_R8 but what should I do with var1 = 1.0D-20? I've run a simple code which proved that 1.0D-20 won't give me an accurate result but something like 10.0_r8**(-20.0_r8) will. Is there an easier way to define the variable? I know that 1D-20 is very small but the code I'm using really needs 30 decimal case precision.

Thank you for your help!

答:
There's really two things happening here. First, declaring an exponent using d notation is the same as declaring it as type double precision.

Second, the r8 variable you declare requires more precision than most (all?) 8-byte representations. So you're actually declaring most of your variables as quad, then initializing them as double, which is the source of your problem.

As mentioned in the comments, the answer to your explicit question is to declare exponents using the following notation

```<code>real(mytype) :: a = 1.23e-20_mytype
</code>```

This notation is cumbersome but easy to get used to for constant declaration.

Here's a little sample code I used to test your types:

```<code>program main
   use ISO_FORTRAN_ENV, only : REAL64 => REAL64, REAL128
   implicit none

   INTEGER,  PARAMETER :: R8 = SELECTED_REAL_KIND (30, 300)
   real(r8) :: x, y, z
   real(REAL64) :: a, b, c

   x = 1.23d-20
   y = 1.23e-20_r8
   z = 1.23_r8*(10._r8**-20)

   write(*,*) x
   write(*,*) y
   write(*,*) z

   a = 1.23d-20
   b = 1.23e-20_REAL64
   c = 1.23_REAL64*(10._REAL64**-20)

   write(*,*) a
   write(*,*) b
   write(*,*) c

   write(*,*) 'Types: ', REAL64, R8, REAL128

end program main
</code>```

for Intel 16.0, this gives:

```<code>mach5% ifort main.f90 && ./a.out
  1.230000000000000057423043720037598E-0020
  1.230000000000000000000000000000000E-0020
  1.230000000000000000000000000000002E-0020
  1.230000000000000E-020
  1.230000000000000E-020
  1.230000000000000E-020
 Types:            8          16          16
</code>```

Title: Defining Exponent in Fortran

Body:
I've been having some trouble with variables precision in my code...
For a while i've been declaring variables as real(kind=8) :: var and I now understand that this is not very portable and has some other complications, but basically I'm getting a lot of imprecision in numerical calculations.

Now I'm using:

INTEGER,  PARAMETER :: R8 = SELECTED_REAL_KIND (30, 300)
with variable declaration: real(R8) :: var1,var2.

Before I usually initialized variables as var1 = 1.0D0 and now I'm using var1 = 1.0_R8 but what should I do with var1 = 1.0D-20? I've run a simple code which proved that 1.0D-20 won't give me an accurate result but something like 10.0_r8**(-20.0_r8) will. Is there an easier way to define the variable? I know that 1D-20 is very small but the code I'm using really needs 30 decimal case precision.

Thank you for your help!

Body:
There's really two things happening here. First, declaring an exponent using d notation is the same as declaring it as type double precision.

Second, the r8 variable you declare requires more precision than most (all?) 8-byte representations. So you're actually declaring most of your variables as quad, then initializing them as double, which is the source of your problem.

As mentioned in the comments, the answer to your explicit question is to declare exponents using the following notation

real(mytype) :: a = 1.23e-20_mytype

This notation is cumbersome but easy to get used to for constant declaration.

Here's a little sample code I used to test your types:

program main
   use ISO_FORTRAN_ENV, only : REAL64 => REAL64, REAL128
   implicit none

   INTEGER,  PARAMETER :: R8 = SELECTED_REAL_KIND (30, 300)
   real(r8) :: x, y, z
   real(REAL64) :: a, b, c

   x = 1.23d-20
   y = 1.23e-20_r8
   z = 1.23_r8*(10._r8**-20)

   write(*,*) x
   write(*,*) y
   write(*,*) z

   a = 1.23d-20
   b = 1.23e-20_REAL64
   c = 1.23_REAL64*(10._REAL64**-20)

   write(*,*) a
   write(*,*) b
   write(*,*) c

   write(*,*) 'Types: ', REAL64, R8, REAL128

end program main

for Intel 16.0, this gives:

mach5% ifort main.f90 && ./a.out
  1.230000000000000057423043720037598E-0020
  1.230000000000000000000000000000000E-0020
  1.230000000000000000000000000000002E-0020
  1.230000000000000E-020
  1.230000000000000E-020
  1.230000000000000E-020
 Types:            8          16          16


问:
C - How to get string from user when using typedef?
I have the following typedef in my code:

```<code>typedef char * string;
</code>```

And I need to have the user input a string so that I can then parse it and use the contents later. If I am just declaring a string with this definition it works, like this:

```<code>string bob = "My name is bob!;
printf("%s\n", bob);
</code>```

What should I use to get user input when using this, scanf() and fgets()
both give me Segmentation fault (core dumped) errors when I try to use them.

This is for school, which is why I need to use the typedef this way.

答:
you can typedef a pointer variable but must be taken care while using or accessing that typedefed pointer variable because normally you won't see * symbol in declaration and definition may be somewhere else and you may treat as a normal variable.

If you want to take input for pointer variable from runtime or from file first you should allocate the memory.

```<code>int main()
    {
            typedef char * string;// now string also a char pointer
            string bob;// bob is pointer variable
            printf("enter the string\n");
            scanf("%s",bob);//bob is uninitialized pointer .. u can't put any data
            printf("%s\n", bob);
          //once job is done free dynamically allocated memory using free function
    }
</code>```

Above code will cause segmentation fault,So allocate the memory dynamically first.

```<code>        string bob;
        bob = malloc(SIZE);//how much memory you want , mention in SIZE variable.
        printf("enter the string\n");
        scanf("%s",bob);
        printf("%s\n", bob);
</code>```

Body:
I have the following typedef in my code:

typedef char * string;

And I need to have the user input a string so that I can then parse it and use the contents later. If I am just declaring a string with this definition it works, like this:

string bob = "My name is bob!;
printf("%s\n", bob);

What should I use to get user input when using this, scanf() and fgets()
both give me Segmentation fault (core dumped) errors when I try to use them.

This is for school, which is why I need to use the typedef this way.

Body:
you can typedef a pointer variable but must be taken care while using or accessing that typedefed pointer variable because normally you won't see * symbol in declaration and definition may be somewhere else and you may treat as a normal variable.

If you want to take input for pointer variable from runtime or from file first you should allocate the memory.

int main()
    {
            typedef char * string;// now string also a char pointer
            string bob;// bob is pointer variable
            printf("enter the string\n");
            scanf("%s",bob);//bob is uninitialized pointer .. u can't put any data
            printf("%s\n", bob);
          //once job is done free dynamically allocated memory using free function
    }

Above code will cause segmentation fault,So allocate the memory dynamically first.

        string bob;
        bob = malloc(SIZE);//how much memory you want , mention in SIZE variable.
        printf("enter the string\n");
        scanf("%s",bob);
        printf("%s\n", bob);


问:
Laravel (5.2) Blade - How to prevent a Blade Directive in an email address from being parsed?
Update This is a bug in Laravel 5.2 & 5.3

I've got a weird one here. A user's email address on our client's system has a domain with the following substring in it '@parent'. I am not including the whole thing just for the sake of privacy.

Because @parent is a Blade directive, Laravel seems to either process or ignore the @parent and strips it out of the rendered email address on the page.

For example, let's say the email address is john@parentstuff.com. Laravel will render the following on the page: johnstuff.com. See how it removes @parent from the email?

What I've tried to fix it:

```<code>1. {!! $user->email !!}

2. {{ e($user->email) }}
</code>```

I know that this is an issue with Blade as AJAX & jQuery rendered content with this same email address is displayed just fine elsewhere on the site.

UPDATE

Upon further investigation, it appears this may be a bug in how Blade processes the @parent directive. I set up 3 new Laravel projects for the following versions: 5.2, 5.3 and 5.4. The project in question is a Laravel 5.2 project, FYI.

I created the following setup for each of the above mentioned versions to test the bug.

Route

```<code>Route::get('/test', function () {
    $foo = 'john@parentingstuff.org';

    return view('test')->with('foo', $foo);
});
</code>```

Templates

Base

```<code><html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>
</code>```

Test View

```<code>@extends('test-base')

@section('content')
    {{$foo}}
@endsection
</code>```

Outputs

L5.2: johningstuff.org

L5.3: johningstuff.org

L5.4: john@parentingstuff.org

Theories

One very interesting case I noticed while running these tests was that having the {{$foo}} variable inside of a @section directive vs moving it outside of the @section directive led to two different outputs.

Example

```<code>{{$foo}}

@section('content')
    {{$foo}}
@endsection
</code>```

The output of this was...

john@parentingstuff.org

johningstuff.org

Conclusion
So, does anyone know how to patch this bug in Laravel 5.2 or Laravel 5.3? Currently, upgrading to L5.4 is not an option for our client.

Anyone have any clever tricks they can think of that might help?

答:
This is a bug in Laravel verions prior to 5.4. See the following:

https://github.com/laravel/framework/issues/10068

https://github.com/laravel/framework/pull/16033

Body:
Update This is a bug in Laravel 5.2 & 5.3

I've got a weird one here. A user's email address on our client's system has a domain with the following substring in it '@parent'. I am not including the whole thing just for the sake of privacy.

Because @parent is a Blade directive, Laravel seems to either process or ignore the @parent and strips it out of the rendered email address on the page.

For example, let's say the email address is john@parentstuff.com. Laravel will render the following on the page: johnstuff.com. See how it removes @parent from the email?

What I've tried to fix it:

1. {!! $user->email !!}

2. {{ e($user->email) }}

I know that this is an issue with Blade as AJAX & jQuery rendered content with this same email address is displayed just fine elsewhere on the site.

UPDATE

Upon further investigation, it appears this may be a bug in how Blade processes the @parent directive. I set up 3 new Laravel projects for the following versions: 5.2, 5.3 and 5.4. The project in question is a Laravel 5.2 project, FYI.

I created the following setup for each of the above mentioned versions to test the bug.

Route

Route::get('/test', function () {
    $foo = 'john@parentingstuff.org';

    return view('test')->with('foo', $foo);
});

Templates

Base

        <title>App Name - @yield('title')</title>

            @yield('content')

Test View

@extends('test-base')

@section('content')
    {{$foo}}
@endsection

Outputs

L5.2: johningstuff.org

L5.3: johningstuff.org

L5.4: john@parentingstuff.org

Theories

One very interesting case I noticed while running these tests was that having the {{$foo}} variable inside of a @section directive vs moving it outside of the @section directive led to two different outputs.

Example

{{$foo}}

@section('content')
    {{$foo}}
@endsection

The output of this was...

john@parentingstuff.org

johningstuff.org

Conclusion
So, does anyone know how to patch this bug in Laravel 5.2 or Laravel 5.3? Currently, upgrading to L5.4 is not an option for our client.

Anyone have any clever tricks they can think of that might help?


问:
Accessing a public member function from a child window's function
I need to call a parent public member function (myFunction()) from a child dialog function (doStuff()).  The code below more or less does what I need it to do, but I'm running into some issues.

main.cpp

```<code>#include <QApplication>
#include "myapp.h"

int main(int argc, char* argv[])
{
  QApplication a(argc, argv);
  myApp app;  // my main app window
  app.show();
  return a.exec();
}
</code>```

myapp.h

```<code>...

class MyApp : public QMainWindow
{
  Q_OBJECT

public:
  explicit MyApp(QWidget* parent = 0);
  void myFunction();

...
</code>```

myapp.cpp

```<code>...

MyApp::MyApp(QWidget* parent)
  : QMainWindow(parent)
  {
    // constructor
  }

MyApp::void myFunction() {
// do some stuff
}
</code>```

mydialog.h

```<code>...

class MyDialog : public QDialog
{
  Q_OBJECT

public:
  explicit MyDialog(QWidget* parent = 0);
  ~MyDialog();

private:
  void doStuff();

  ...
</code>```

mydialog.cpp

```<code>MyDialog::MyDialog(QWidget* parent) :
  QDialog(parent, QDialog().windowFlags() & ~Qt::WindowContextHelpButtonHint)

{
  //constructor
}

void doStuff() {
  ((MyApp*)(parent()))->myFunction(); // this crashes the application
}
</code>```

Ideally, what I would want to do instead of that cast (((MyApp*)(parent()))->myFunction();) is something like app->myFunction() since I have already created the MyApp app instance in main.cpp. What am I doing wrong here?

答:
I wound up using signals and slots to solve this per Cherkesgiller Tural's comment. Here is what I did:

In mydialog.h, I added the signal I wanted to emit:

```<code>signals:
  void sendMySignal();
</code>```

In mydialog.cpp, I had the doStuff() function emit my signal:

```<code>void doStuff() {
  emit sendMySignal();
}
</code>```

In myapp.h, I added myFunction as a public slot and also created an instance of the myDialog:

```<code>public slots:
  void myFunction();

....

private:
  MyDialog myDialog;
</code>```

In myapp.cpp, I added the connect line to the constructor:

```<code>connect(&myDialog, SIGNAL(sendMySignal()), this, SLOT(myFunction()));
</code>```

This connect listens for the sendMySignal() signal within the myDialog object. When the signal is emitted and it is received by myApp app (myapp.cpp), it runs the myFunction() function, just as I wanted.

Thank you all for the help.

Body:
I need to call a parent public member function (myFunction()) from a child dialog function (doStuff()).  The code below more or less does what I need it to do, but I'm running into some issues.

main.cpp

#include <QApplication>
#include "myapp.h"

int main(int argc, char* argv[])
{
  QApplication a(argc, argv);
  myApp app;  // my main app window
  app.show();
  return a.exec();
}

myapp.h

...

class MyApp : public QMainWindow
{
  Q_OBJECT

public:
  explicit MyApp(QWidget* parent = 0);
  void myFunction();

...

myapp.cpp

...

MyApp::MyApp(QWidget* parent)
  : QMainWindow(parent)
  {
    // constructor
  }

MyApp::void myFunction() {
// do some stuff
}

mydialog.h

...

class MyDialog : public QDialog
{
  Q_OBJECT

public:
  explicit MyDialog(QWidget* parent = 0);
  ~MyDialog();

private:
  void doStuff();

  ...

mydialog.cpp

MyDialog::MyDialog(QWidget* parent) :
  QDialog(parent, QDialog().windowFlags() & ~Qt::WindowContextHelpButtonHint)

{
  //constructor
}

void doStuff() {
  ((MyApp*)(parent()))->myFunction(); // this crashes the application
}

Ideally, what I would want to do instead of that cast (((MyApp*)(parent()))->myFunction();) is something like app->myFunction() since I have already created the MyApp app instance in main.cpp. What am I doing wrong here?

Body:
I wound up using signals and slots to solve this per Cherkesgiller Tural's comment. Here is what I did:

In mydialog.h, I added the signal I wanted to emit:

signals:
  void sendMySignal();

In mydialog.cpp, I had the doStuff() function emit my signal:

void doStuff() {
  emit sendMySignal();
}

In myapp.h, I added myFunction as a public slot and also created an instance of the myDialog:

public slots:
  void myFunction();

....

private:
  MyDialog myDialog;

In myapp.cpp, I added the connect line to the constructor:

connect(&myDialog, SIGNAL(sendMySignal()), this, SLOT(myFunction()));

This connect listens for the sendMySignal() signal within the myDialog object. When the signal is emitted and it is received by myApp app (myapp.cpp), it runs the myFunction() function, just as I wanted.

Thank you all for the help.


问:
Keras categorical model
I'm trying to create a Keras deep learning algorithm to identify coniferous and leafed trees from a false-colour orthophoto. I have extracted around 4 500 training/validation images which are considered to be correct, such as here and here. The pixel size in real-world is 0,5 meters so these are not really high-res images. All images are fixed-size 31x31 px. The following model is a product of googling, especially Keras' own documentation site.

```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

# dimensions of our images.
img_width, img_height = 30, 30

train_data_dir = 'treedata/train'
validation_data_dir = 'treedata/validation'
nb_train_samples = 4000
nb_validation_samples = 533
epochs = 50
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Dropout(0.5))

model.add(Activation('relu'))
model.add(Dense(2)) # number of classes
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
          optimizer='rmsprop',
          metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save('treetypes.h5')
</code>```

From epoch 2 onwards, the accuracy claims to be > 0.99 and loss < 0.02, which I find odd. After creating the model, I try to go through an orthophoto and decide if one 30x30 px sub-image contains a tree of given type.

```<code>import numpy as np
import cv2
from keras.models import load_model
from keras.preprocessing import image

model = load_model('treetypes.h5')
roi = cv2.imread('roi.jpg')
sy, sx = img.shape[:2]
px_apart = 10 # start sub-images 10 px apart
s = 30 # sub-image size

for starty in range(1, sy-img_height, px_apart):

    for startx in range(1, sx-img_width, px_apart):

        subimg = img[starty:starty+s, startx:startx+s]
        x = image.img_to_array(subimg)
        x = np.expand_dims(x, axis=0)
        is_tree = model.predict(x, batch_size=1, verbose=0) # predict classes
</code>```

This is where I get lost. First and foremost, there seems not to be a choice that a sub-image is neither a coniferous nor leafed tree (all sub-images get predicted either is_tree = [[0, 1]] or is_tree = [[1, 0]]). There are not for example predictions [[0.1, 0.02]], which would suggest that this sub-image is not a tree at all. Thus, two main questions:

1) Have I understood correctly that the model should output probabilities for belonging to class 1 (coniferous) and class 2 (leafed)? Why it does give only "binary" results? I read somewhere that softmax scales sum of probabilities to 1.

2) Is my model anywhere near usable? Or is it even viable to use NN for this, given coarse sample resolution? I suspect some overfitting for my model...

Thanks in advance if anyone has time to take on this!

答:
I assume that you have only two classes in your dataset. So I'd like to propose you an interesting technique called channel inhibited softmax in order to have an additional maybe category which you may read about here. In order to use this category you need to add the additional 3rd output from network to softmax layer which is constantly equal to 0. Now you have two options here:

You could retrieve the input to softmax from your model and add an artificial 0 to it:

```<code>logits_model = Model(model.input, model.layers[-2].output)
data = logits_model.predict(x)
final_probs = numpy.exp(x) / (numpy.sum(numpy.exp(x), axis = 1) + 1)
</code>```

The advantage of this way is that you don't need to train a new model but use an existing one.

You could train a new model:

```<code>def channel_inhibited_softmax(x):
    e = K.exp(x - K.max(x, axis=1, keepdims=True))
    s = K.sum(e, axis=1, keepdims=True) + K.exp(-K.max(x), axis=1)
    return e / s

model.add(Activation('relu'))
model.add(Dense(2)) # number of classes
model.add(Lambda(channel_inhibited_softmax))
</code>```

Now you could retrain your model with additional not sure class.

Thanks to solutions above - you could add an uncertainty to your model and check if it's likely that a given picture doesn't belong to any of classes.

Title: Keras categorical model

Body:
I'm trying to create a Keras deep learning algorithm to identify coniferous and leafed trees from a false-colour orthophoto. I have extracted around 4 500 training/validation images which are considered to be correct, such as here and here. The pixel size in real-world is 0,5 meters so these are not really high-res images. All images are fixed-size 31x31 px. The following model is a product of googling, especially Keras' own documentation site.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

# dimensions of our images.
img_width, img_height = 30, 30

train_data_dir = 'treedata/train'
validation_data_dir = 'treedata/validation'
nb_train_samples = 4000
nb_validation_samples = 533
epochs = 50
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Dropout(0.5))

model.add(Activation('relu'))
model.add(Dense(2)) # number of classes
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
          optimizer='rmsprop',
          metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save('treetypes.h5')

From epoch 2 onwards, the accuracy claims to be > 0.99 and loss < 0.02, which I find odd. After creating the model, I try to go through an orthophoto and decide if one 30x30 px sub-image contains a tree of given type.

import numpy as np
import cv2
from keras.models import load_model
from keras.preprocessing import image

model = load_model('treetypes.h5')
roi = cv2.imread('roi.jpg')
sy, sx = img.shape[:2]
px_apart = 10 # start sub-images 10 px apart
s = 30 # sub-image size

for starty in range(1, sy-img_height, px_apart):

    for startx in range(1, sx-img_width, px_apart):

        subimg = img[starty:starty+s, startx:startx+s]
        x = image.img_to_array(subimg)
        x = np.expand_dims(x, axis=0)
        is_tree = model.predict(x, batch_size=1, verbose=0) # predict classes

This is where I get lost. First and foremost, there seems not to be a choice that a sub-image is neither a coniferous nor leafed tree (all sub-images get predicted either is_tree = [[0, 1]] or is_tree = [[1, 0]]). There are not for example predictions [[0.1, 0.02]], which would suggest that this sub-image is not a tree at all. Thus, two main questions:

1) Have I understood correctly that the model should output probabilities for belonging to class 1 (coniferous) and class 2 (leafed)? Why it does give only "binary" results? I read somewhere that softmax scales sum of probabilities to 1.

2) Is my model anywhere near usable? Or is it even viable to use NN for this, given coarse sample resolution? I suspect some overfitting for my model...

Thanks in advance if anyone has time to take on this!

Body:
I assume that you have only two classes in your dataset. So I'd like to propose you an interesting technique called channel inhibited softmax in order to have an additional maybe category which you may read about here. In order to use this category you need to add the additional 3rd output from network to softmax layer which is constantly equal to 0. Now you have two options here:

You could retrieve the input to softmax from your model and add an artificial 0 to it:

logits_model = Model(model.input, model.layers[-2].output)
data = logits_model.predict(x)
final_probs = numpy.exp(x) / (numpy.sum(numpy.exp(x), axis = 1) + 1)

The advantage of this way is that you don't need to train a new model but use an existing one.

You could train a new model:

def channel_inhibited_softmax(x):
    e = K.exp(x - K.max(x, axis=1, keepdims=True))
    s = K.sum(e, axis=1, keepdims=True) + K.exp(-K.max(x), axis=1)
    return e / s

model.add(Activation('relu'))
model.add(Dense(2)) # number of classes
model.add(Lambda(channel_inhibited_softmax))

Now you could retrain your model with additional not sure class.

Thanks to solutions above - you could add an uncertainty to your model and check if it's likely that a given picture doesn't belong to any of classes.


问:
WPF .png overlay using DrawingVisual
I'm using this example - I found around here - to overlay two .png images and then save the result as a third .png image.

The input images are:

The output image should (in my dreams) be:

And instead I get this:

Here is the code:

```<code>    public static void Test()
    {
        // Loads the images to tile (no need to specify PngBitmapDecoder, the correct decoder is automatically selected)
        BitmapFrame frame1 = BitmapDecoder.Create(new Uri(@"D:\_tmp_\MaxMara\Test\Monoscope.png"), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
        BitmapFrame frame2 = BitmapDecoder.Create(new Uri(@"D:\_tmp_\MaxMara\Test\OverlayFrame.png"), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

        // Gets the size of the images (I assume each image has the same size)
        int imageWidth = 1920;
        int imageHeight = 1080;

        // Draws the images into a DrawingVisual component
        DrawingVisual drawingVisual = new DrawingVisual();
        using (DrawingContext drawingContext = drawingVisual.RenderOpen())
        {
            drawingContext.DrawImage(frame1, new Rect(0, 0, imageWidth, imageHeight));
            drawingContext.DrawImage(frame2, new Rect(0, 0, imageWidth, imageHeight));
        }

        // Converts the Visual (DrawingVisual) into a BitmapSource
        RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 300, 300, PixelFormats.Pbgra32);
        bmp.Render(drawingVisual);

        // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmp));

        // Saves the image into a file using the encoder
        using (Stream stream = File.Create(@"D:\_tmp_\MaxMara\Test\Result.png"))
            encoder.Save(stream);
    }
</code>```

Note: if i use 100 dpi as in:

```<code>RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 100, 100, PixelFormats.Pbgra32);
</code>```

I get the correct result (meaning: the result I want).

I don't understand why. All images are 300 DPI

Can anyone shed some light on the topic please?
Thank you for your time

Orf

答:
Do not use the PixelWidth and PixelHeight (i.e. your imageWidth and imageHeight values) of the bitmaps for drawing them into a DrawingContext.

Use their Width and Height values instead, because these give the bitmap size in device-independent units (1/96th inch per unit) as required for drawing.

```<code>using (var drawingContext = drawingVisual.RenderOpen())
{
    drawingContext.DrawImage(frame1, new Rect(0, 0, frame1.Width, frame1.Height));
    drawingContext.DrawImage(frame2, new Rect(0, 0, frame2.Width, frame2.Height));
}
</code>```

Title: WPF .png overlay using DrawingVisual

Body:
I'm using this example - I found around here - to overlay two .png images and then save the result as a third .png image.

The input images are:

The output image should (in my dreams) be:

And instead I get this:

Here is the code:

    public static void Test()
    {
        // Loads the images to tile (no need to specify PngBitmapDecoder, the correct decoder is automatically selected)
        BitmapFrame frame1 = BitmapDecoder.Create(new Uri(@"D:\_tmp_\MaxMara\Test\Monoscope.png"), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
        BitmapFrame frame2 = BitmapDecoder.Create(new Uri(@"D:\_tmp_\MaxMara\Test\OverlayFrame.png"), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

        // Gets the size of the images (I assume each image has the same size)
        int imageWidth = 1920;
        int imageHeight = 1080;

        // Draws the images into a DrawingVisual component
        DrawingVisual drawingVisual = new DrawingVisual();
        using (DrawingContext drawingContext = drawingVisual.RenderOpen())
        {
            drawingContext.DrawImage(frame1, new Rect(0, 0, imageWidth, imageHeight));
            drawingContext.DrawImage(frame2, new Rect(0, 0, imageWidth, imageHeight));
        }

        // Converts the Visual (DrawingVisual) into a BitmapSource
        RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 300, 300, PixelFormats.Pbgra32);
        bmp.Render(drawingVisual);

        // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmp));

        // Saves the image into a file using the encoder
        using (Stream stream = File.Create(@"D:\_tmp_\MaxMara\Test\Result.png"))
            encoder.Save(stream);
    }

Note: if i use 100 dpi as in:

RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 100, 100, PixelFormats.Pbgra32);

I get the correct result (meaning: the result I want).

I don't understand why. All images are 300 DPI

Can anyone shed some light on the topic please?
Thank you for your time

Orf

Body:
Do not use the PixelWidth and PixelHeight (i.e. your imageWidth and imageHeight values) of the bitmaps for drawing them into a DrawingContext.

Use their Width and Height values instead, because these give the bitmap size in device-independent units (1/96th inch per unit) as required for drawing.

using (var drawingContext = drawingVisual.RenderOpen())
{
    drawingContext.DrawImage(frame1, new Rect(0, 0, frame1.Width, frame1.Height));
    drawingContext.DrawImage(frame2, new Rect(0, 0, frame2.Width, frame2.Height));
}


问:
Rails form not persisting data after update_attributes fails?
I have the following

```<code>@account = Account.find(4)
respond_to do |format|
 format.html { render :action => "edit" }
end
</code>```

which render a form

```<code><%= form_for(@account,:html => {:id => "account" }) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :amount %>
  <%= f.text_field :amount %>
<% end %>
</code>```

which sends an update to

```<code>@account = Account.find(params[:id])
@account.update_attributes(Account.params(params))
respond_to do |format|
 format.html { render :action => "edit" }
end
</code>```

I have function in  Account model

```<code>def self.params(params)
    params.require(:account).permit!
end
</code>```

When the account fails to update.
I see the errors but the form does not persist the data I tried to update account with?
I tried using

```<code><%= form_for(@account,:html => {:id => "account" }) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name, :value => params[:user][:name] %>
  <%= f.label :amount %>
  <%= f.text_field :amount, :value => params[:user][:amount]  %>
<% end %>
</code>```

but when I load the edit page those fail.

Thanks

答:
The issue that was happening was for one reason. The code was inheriting  from a class that had:

```<code>slef.reload
</code>```

in one of the function that were being called during validations.

so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.
So when it came time to display the old values are gone.
Thanks everyone for the help

Body:
I have the following

@account = Account.find(4)
respond_to do |format|
 format.html { render :action => "edit" }
end

which render a form

<%= form_for(@account,:html => {:id => "account" }) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :amount %>
  <%= f.text_field :amount %>
<% end %>

which sends an update to

@account = Account.find(params[:id])
@account.update_attributes(Account.params(params))
respond_to do |format|
 format.html { render :action => "edit" }
end

I have function in  Account model

def self.params(params)
    params.require(:account).permit!
end

When the account fails to update.
I see the errors but the form does not persist the data I tried to update account with?
I tried using

<%= form_for(@account,:html => {:id => "account" }) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name, :value => params[:user][:name] %>
  <%= f.label :amount %>
  <%= f.text_field :amount, :value => params[:user][:amount]  %>
<% end %>

but when I load the edit page those fail.

Thanks

Body:
The issue that was happening was for one reason. The code was inheriting  from a class that had:

slef.reload

in one of the function that were being called during validations.

so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.
So when it came time to display the old values are gone.
Thanks everyone for the help


问:
Core Data NSPredicate checking for BOOL value
I am currently having an issue pulling all data from db whereby i.e 1 parameter is TRUE.

I am using NSPredicate and below is a sample code

```<code>NSManagedObjectContext *context = managedObjectContext_;

if (!context) {
    // Handle the error.
    NSLog(@"ERROR CONTEXT IS NIL");
}

NSEntityDescription *entity = [NSEntityDescription entityForName:@"tblcontent" inManagedObjectContext:managedObjectContext_];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bookmarked == YES"];

[request setPredicate:predicate];
</code>```

I tried setting predicatewithformat to almost everything but it still does not pull out bookmarks which have a YES value.

I even tried (@"bookmarked == %d",YES) but with not luck. I don't want to have to get the whole array and then filter it manually by doing if(object.bookmarked == YES) .....blabla.

I will really appreciate some help.

Many thanks.

答:
Sneaking in with the Swift 3/4 answer:

```<code>let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
</code>```

We have to use NSNumber apparently because a literal bool is not acceptable per Apple.

Stolen from here ;)

Body:
I am currently having an issue pulling all data from db whereby i.e 1 parameter is TRUE.

I am using NSPredicate and below is a sample code

NSManagedObjectContext *context = managedObjectContext_;

if (!context) {
    // Handle the error.
    NSLog(@"ERROR CONTEXT IS NIL");
}

NSEntityDescription *entity = [NSEntityDescription entityForName:@"tblcontent" inManagedObjectContext:managedObjectContext_];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bookmarked == YES"];

[request setPredicate:predicate];

I tried setting predicatewithformat to almost everything but it still does not pull out bookmarks which have a YES value.

I even tried (@"bookmarked == %d",YES) but with not luck. I don't want to have to get the whole array and then filter it manually by doing if(object.bookmarked == YES) .....blabla.

I will really appreciate some help.

Many thanks.

Body:
Sneaking in with the Swift 3/4 answer:

let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))

We have to use NSNumber apparently because a literal bool is not acceptable per Apple.

Stolen from here ;)


问:
Provision certficate to LAMP EC2, which are autoscaled on AWS
I need to design a solution, where the AWS EC2 has LAMP installed . The EC2s are autoscalled . The EC2 should have HTTPS for LAMP . The certificate can be self signed , but the private key should be protected. That is the private key should not be hardcoded on EC2 instance ( which is not best practice) . Also the HTTPS  should originate from EC2 and not from ELB,CloudFront,ACM etc. </p>

<p>Can someone help me in suggesting best practices ? </p>

答:
For your scenario: Amazon best practices is to store your SSL server certificate in IAM.

IAM securely encrypts your private keys and stores the encrypted version in IAM SSL
  certificate storage. IAM supports deploying server certificates in all
  regions, but you must obtain your certificate from an external
  provider for use with AWS. You cannot upload an ACM certificate to
  IAM. Additionally, you cannot manage your certificates from the IAM
  Console.

Working with Server Certificates

Are taking an Amazon cerfication? If I remember correctly, this was a question on one of the exams (maybe the SAA).

Body:
I need to design a solution, where the AWS EC2 has LAMP installed . The EC2s are autoscalled . The EC2 should have HTTPS for LAMP . The certificate can be self signed , but the private key should be protected. That is the private key should not be hardcoded on EC2 instance ( which is not best practice) . Also the HTTPS  should originate from EC2 and not from ELB,CloudFront,ACM etc.

Can someone help me in suggesting best practices ?


问:
Why doesn't type inference work the same on lambdas and method references in Java?
The code should not compile but it does!

```<code>public class MyClass {

...........

    private void setEndDateOfValidStatusToCurrentTime(List<LifecycleStatus> oldStatuses, Date currentTime)
    {
        oldStatuses.stream()
            .filter(oldStatus -> isValidNow(oldStatus, currentTime))
            .findFirst().ifPresent(oldStatus -> oldStatus.setValidToDate(currentTime));
    }

    private boolean isValidNow(LifecycleStatus lifecycleStatus, Date currentTime)
    {
        Date start = lifecycleStatus.getValidFromDate();
        Date end = lifecycleStatus.getValidToDate();
        Date startTime = Optional.ofNullable(start).orElse(new Date(0L)); // BEGINNING OF TIME
        Date endTime = Optional.ofNullable(end).orElse(new Date(Long.MAX_VALUE)); // END OF TIME

        return startTime.before(currentTime) && endTime.after(currentTime);
    }

}
</code>```

Reason:
I am using isValidNow() in a lambda in order to target the Predicate interface since the filter method requires it. But isValidNow() is a 2-argument method and test() in Predicate expects only 1 argument!

I do know the Java compiler has the power of type inference. With such power, perhaps the smart compiler internally breaks down isValidNow(), determines that it can safely put aside the second argument (currentTime) and come up with an implementation that satisfies test() in Predicate by using only the first argument (oldStatus).

Then why doesn't type inference work when I try to use a method reference instead? Interestingly, if I replace

```<code>filter(oldStatus -> isValidNow(oldStatus, currentTime))
</code>```

with

```<code>filter(this::isValidNow)
</code>```

I see these compiler errors:

```<code>- The method filter(Predicate<? super LifecycleStatus>) in the type Stream<LifecycleStatus> is not applicable for the arguments
 (this::isValidNow)
- MyClass does not define isValidNow(LifecycleStatus) that is applicable here
</code>```

答:
oldStatus -> isValidNow(oldStatus, currentTime) is the predicate/lambda here, and only takes one argument.  That lambda is effectively equivalent to:

```<code>new Predicate<LifecycleStatus> {
    boolean test(LifecycleStatus oldStatus) {
        return isValidNow(oldStatus, currentTime);
    }
}
</code>```

(where currentTime is a local variable from the enclosing scope.)

That's certainly not the same as this::isValidNow, which is why the latter doesn't compile.

Body:
The code should not compile but it does!

public class MyClass {

...........

    private void setEndDateOfValidStatusToCurrentTime(List<LifecycleStatus> oldStatuses, Date currentTime)
    {
        oldStatuses.stream()
            .filter(oldStatus -> isValidNow(oldStatus, currentTime))
            .findFirst().ifPresent(oldStatus -> oldStatus.setValidToDate(currentTime));
    }

    private boolean isValidNow(LifecycleStatus lifecycleStatus, Date currentTime)
    {
        Date start = lifecycleStatus.getValidFromDate();
        Date end = lifecycleStatus.getValidToDate();
        Date startTime = Optional.ofNullable(start).orElse(new Date(0L)); // BEGINNING OF TIME
        Date endTime = Optional.ofNullable(end).orElse(new Date(Long.MAX_VALUE)); // END OF TIME

        return startTime.before(currentTime) && endTime.after(currentTime);
    }

}

Reason:
I am using isValidNow() in a lambda in order to target the Predicate interface since the filter method requires it. But isValidNow() is a 2-argument method and test() in Predicate expects only 1 argument!

I do know the Java compiler has the power of type inference. With such power, perhaps the smart compiler internally breaks down isValidNow(), determines that it can safely put aside the second argument (currentTime) and come up with an implementation that satisfies test() in Predicate by using only the first argument (oldStatus).

Then why doesn't type inference work when I try to use a method reference instead? Interestingly, if I replace

filter(oldStatus -> isValidNow(oldStatus, currentTime))

with

filter(this::isValidNow)

I see these compiler errors:

- The method filter(Predicate<? super LifecycleStatus>) in the type Stream<LifecycleStatus> is not applicable for the arguments
 (this::isValidNow)
- MyClass does not define isValidNow(LifecycleStatus) that is applicable here

Body:
oldStatus -> isValidNow(oldStatus, currentTime) is the predicate/lambda here, and only takes one argument.  That lambda is effectively equivalent to:

new Predicate<LifecycleStatus> {
    boolean test(LifecycleStatus oldStatus) {
        return isValidNow(oldStatus, currentTime);
    }
}

(where currentTime is a local variable from the enclosing scope.)

That's certainly not the same as this::isValidNow, which is why the latter doesn't compile.


问:
Entity Framework & WPF Application Design Guidance
Entity Framework Layer Guidance

I'm in the design stage of a WPF business application.  The first stage of this application will be a WPF/Desktop application.  Later iterations may include a browser based mini version.

I envision creating a dll or 2 that contain the domain model & dbcontext that all applications(Desktop or Browser) will use.

My intention is to ride or die with EF.  I'm not worried about using DI/Repository patterns etc for flexibility.  The benefits of using them don't outweigh the added complexity in my opinion for this project.  My plan is to use a model, and a derived dbcontext.

Having said that, I'm looking for input on where to put certain types of method code.

An example will hopefully make my question more clear:

Let's say I have the following two entities..

Entity: Employee

Entity: PermissionToken

Inside of these two entities I have a ManyToMany relationship resulting in me creating another entity for the relationship:
EmployeesPermissionTokens

For clarity, the PermissionToken Entity's Primary Key is an Enum representing the permission..

In the application, lets say the current user is Administering Employees and wants to grant a permission to an Employee.

In the app, I could certainly code this as:

```<code>var e = dbcontext.Employees.Find(1);
var pt = new PermissionToken
{
    PermissionID=PermissionTypeEnum.DELETEUSER";
    ...
}

e.PermissionTokens.Add(pt)
</code>```

But it seems to me that it would be more convenient to wrap that code in a method so that one line of code could perform those actions from whatever application chooses to do so.  Where would a method like that live in all of this?

I've thought about adding a static method to the EF Entity:

In The employee class:

```<code>public static void GrantPermission(PermissionToken token)
{
    e.PermissionTokens.Add(token);
}
</code>```

Going further, what would be really convenient for the app would be the ability to write a line like this:

```<code>Permissions.GrantToEmployee(EmployeeID employeeId, PermissionTypeEnum
permissionId);
</code>```

Of course that means that the method would have to be able to access the DbContext to grab the Employee Object and the PermissionObject by ID to do its work.  I really want to avoid my entities knowing about/calling DbContext because I feel long term the entities get stuffed full of dbcontext code which in my opinion shouldn't even be in the Model classes.

So Where would a method like this go?

My gut tells me to put these sorts of code in my derived DbContext since in order to do these sorts of things, the method is going to need access to a DbContext anyway.

Does this make sense, or am I missing something?  I hate to write oodles of code and then figure out 3 months later that I went down the wrong road to start with.  Where should these types of methods live?  I know there is probably a purist answer to this, but I'm looking for a clean, real world solution.

答:
First of all you are making a good decision to not abstract EF behind a repository.

With the EF Context you have a class supporting the  Unit Of Work pattern which is handling your data access needs.No need to wrap it up in repository.

However this does not mean you should call the Context directly from your controller or viewmodel.

You could indeed just extend the DbContext however I suggest to use services to mediate between your controllers/view models and your dbcontext.

If e.g. in your controller you are  handling a user request (e.g. the user has clicked a button) then your controller should call a service to archive what ever "Use Case" is behind the button.

In your case this could be a PermissionService, the PermissionService would be the storage for all operations concerning permission.

```<code>public class PermissionService
{

     PermissionService(DbContext context)
     {
     }

     public bool AddPermission(Employee e, PermissionType type) { }
     public bool RemovePermission(Employee e, PermissionType type) {}
}
</code>```

Your service ofcourse needs access to the DbContext.

It makes sense to use DI here and register the DbContext with a DI Container.

Thus the context will be injected into all your services. This is pretty straight forward and I do not see any extra complexity here.

However, if you don't want to do this you can simply new up up the Db Context inside your services. Of course this is harder / impossible to mock for testing.

Body:
Entity Framework Layer Guidance

I'm in the design stage of a WPF business application.  The first stage of this application will be a WPF/Desktop application.  Later iterations may include a browser based mini version.

I envision creating a dll or 2 that contain the domain model & dbcontext that all applications(Desktop or Browser) will use.

My intention is to ride or die with EF.  I'm not worried about using DI/Repository patterns etc for flexibility.  The benefits of using them don't outweigh the added complexity in my opinion for this project.  My plan is to use a model, and a derived dbcontext.

Having said that, I'm looking for input on where to put certain types of method code.

An example will hopefully make my question more clear:

Let's say I have the following two entities..

Entity: Employee

Entity: PermissionToken

Inside of these two entities I have a ManyToMany relationship resulting in me creating another entity for the relationship:
EmployeesPermissionTokens

For clarity, the PermissionToken Entity's Primary Key is an Enum representing the permission..

In the application, lets say the current user is Administering Employees and wants to grant a permission to an Employee.

In the app, I could certainly code this as:

var e = dbcontext.Employees.Find(1);
var pt = new PermissionToken
{
    PermissionID=PermissionTypeEnum.DELETEUSER";
    ...
}

e.PermissionTokens.Add(pt)

But it seems to me that it would be more convenient to wrap that code in a method so that one line of code could perform those actions from whatever application chooses to do so.  Where would a method like that live in all of this?

I've thought about adding a static method to the EF Entity:

In The employee class:

public static void GrantPermission(PermissionToken token)
{
    e.PermissionTokens.Add(token);
}

Going further, what would be really convenient for the app would be the ability to write a line like this:

Permissions.GrantToEmployee(EmployeeID employeeId, PermissionTypeEnum
permissionId);

Of course that means that the method would have to be able to access the DbContext to grab the Employee Object and the PermissionObject by ID to do its work.  I really want to avoid my entities knowing about/calling DbContext because I feel long term the entities get stuffed full of dbcontext code which in my opinion shouldn't even be in the Model classes.

So Where would a method like this go?

My gut tells me to put these sorts of code in my derived DbContext since in order to do these sorts of things, the method is going to need access to a DbContext anyway.

Does this make sense, or am I missing something?  I hate to write oodles of code and then figure out 3 months later that I went down the wrong road to start with.  Where should these types of methods live?  I know there is probably a purist answer to this, but I'm looking for a clean, real world solution.

Body:
First of all you are making a good decision to not abstract EF behind a repository.

With the EF Context you have a class supporting the  Unit Of Work pattern which is handling your data access needs.No need to wrap it up in repository.

However this does not mean you should call the Context directly from your controller or viewmodel.

You could indeed just extend the DbContext however I suggest to use services to mediate between your controllers/view models and your dbcontext.

If e.g. in your controller you are  handling a user request (e.g. the user has clicked a button) then your controller should call a service to archive what ever "Use Case" is behind the button.

In your case this could be a PermissionService, the PermissionService would be the storage for all operations concerning permission.

public class PermissionService
{

     PermissionService(DbContext context)
     {
     }

     public bool AddPermission(Employee e, PermissionType type) { }
     public bool RemovePermission(Employee e, PermissionType type) {}
}

Your service ofcourse needs access to the DbContext.

It makes sense to use DI here and register the DbContext with a DI Container.

Thus the context will be injected into all your services. This is pretty straight forward and I do not see any extra complexity here.

However, if you don't want to do this you can simply new up up the Db Context inside your services. Of course this is harder / impossible to mock for testing.