text:
Q: Javascript variable names in loop I have a function that creates 6 html input boxes to store my score values, 1 of the boxes being the total score.
var hole1 = prompt("Enter Hole 1 score:");
var hole2 = prompt("Enter Hole 2 score:");
var hole3 = prompt("Enter Hole 3 score:");
var hole4 = prompt("Enter Hole 4 score:");
var hole5 = prompt("Enter Hole 5 score:");

The whole function of addScore():
function addScore() {

            var ni = document.getElementById('myDiv');
            var numi = document.getElementById('theValue');
            var num = (document.getElementById('theValue').value -1)+ 2;
            numi.value = num;

            var newdiv = document.createElement('div');
            var divIdName = 'my'+num+'Div';
            newdiv.setAttribute('id',divIdName);

            // Prompts user for their score
            var hole1 = prompt("Enter Hole 1 score:");
            var hole2 = prompt("Enter Hole 2 score:");
            var hole3 = prompt("Enter Hole 3 score:");
            var hole4 = prompt("Enter Hole 4 score:");
            var hole5 = prompt("Enter Hole 5 score:");

            // Make the boxes for index.html to be displayed
            var makeScoreBoxes ='<input type ="text" placeholder="Hole 1" id="hole1" /> <input type ="text" placeholder="Hole 2" id="hole2" /> <input type ="text" placeholder="Hole 3" id="hole3" /> <input type ="text" placeholder="Hole 4" id="hole4" /> <input type ="text" placeholder="Hole 5" id="hole5" /> <input type ="text" placeholder="Total Score" id="totalScore" />'
            newdiv.innerHTML = makeScoreBoxes;
            ni.appendChild(newdiv);

            // Adds up all scores entered via hole
            totalScore = parseInt(parseFloat(hole1) +
                                                    parseFloat(hole2) +
                                                    parseFloat(hole3) +
                                                    parseFloat(hole4) +
                                                    parseFloat(hole5));

            // Places output of each data value from totalScore into input boxes in index.html
            addTotal = document.getElementById('totalScore').value=totalScore;
            addhole1 = document.getElementById('hole1').value=hole1; // takes prompt number entered in all hole* variables
            addhole2 = document.getElementById('hole2').value=hole2;
            addhole3 = document.getElementById('hole3').value=hole3;
            addhole4 = document.getElementById('hole4').value=hole4;
            addhole5 = document.getElementById('hole5').value=hole5;

            } // Adds up all scores entered via hole
            totalScore = parseInt(parseFloat(hole1) +
                                    parseFloat(hole2) +
                                    parseFloat(hole3) +
                                    parseFloat(hole4) +
                                    parseFloat(hole5));

And it is called here in index.html:

Add score

How do I generate unique variable names for the hole prompt values ( hole1, hole2, hole3, hole4, etc) and html input box ( hole1, hole2, hole3,) values?

A: Here's an example of what can be done with arrays:
var holes = [];

for (var i = 1; i <= 5; i++) {
    holes.push(prompt("Enter Hole " + i + " score:"));
}

var totalScore = 0;

for (var i = 0; i < holes.length; i++) {
    totalScore += parseInt(holes[i], 10);
}

alert("total score: " + totalScore);

Demo: http://jsfiddle.net/EhpPZ/


text:
Q: count amount of rows in per half year with different years I want to count amount of ID's for each month for the last half year, here is my query:
SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE) UNION SELECT `count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 2 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 4 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 5 MONTH);`

Created is the time stamp of the created row.
My problem is getting the fourth, fifth and sixth months. Because they were created in 2013 (different year), my query can't get their result.

A: I would start with something like this:
SELECT MONTH(created), count(*)
FROM `items`
WHERE Created >= LAST_DAY(current_date() - INTERVAL 6 MONTH) + INTERVAL 1 DAY
GROUP BY MONTH(created)

Where LAST_DAY(current_date() - INTERVAL 6 MONTH) + INTERVAL 1 DAY will return the first day of the month where to start the count, you might also want to group by month and year:
SELECT DATE_FORMAT(created, '%Y-%m'), count(*)
FROM `items`
WHERE Created >= LAST_DAY(current_date() - INTERVAL 6 MONTH) + INTERVAL 1 DAY
GROUP BY DATE_FORMAT(created, '%Y-%m')

redpajama_set_name: RedPajamaStackExchange


text:
Q: htaccess rewriterule parent folder only I would like to change the rewrite rule to only apply to the current folder that the htaccess file is in
RewriteEngine on
RewriteRule ^(.*)\.html $1\.php

how do I change this to make that work?
Thanks,

A: If you have a limited number of known sub-directories I would do something like this:
RewriteCond %{REQUEST_URI} (list|of|sub|dirs)
RewriteRule . - [s=1]
RewriteRule ^(.*)\.html $1\.php

That skips the next 1 rule when the condition is true. You could change the [s=1] to match any number of rules you want to not apply to the sub-directories.

A: Restrict your pattern to only match characters other than /:
RewriteRule ^([^/]+)\.html$ $1.php


text:
Q: Rails server not starting - rails 4.0.0.rc1 I am following the tutorial on http://ruby.railstutorial.org/ and now I am not able to start the server. In my gemfile I am using ruby 2.0.0 and rails 4.0.0.rc1 - then I tried changing back to ruby 1.9.3 and rails 3.2.13 - still not working
this is what terminal tells me:
/config/environments/development.rb:1:in `<top (required)>': uninitialized constant FourTest (NameError)
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/engine.rb:591:in `block (2 levels) in <class:Engine>'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/engine.rb:590:in `each'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/engine.rb:590:in `block in <class:Engine>'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/initializable.rb:30:in `instance_exec'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/initializable.rb:30:in `run'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:210:in `block (2 levels) in each_strongly_connected_component_from'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connected_component_from'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:209:in `block in each_strongly_connected_component_from'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/initializable.rb:44:in `each'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/initializable.rb:44:in `tsort_each_child'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:203:in `each_strongly_connected_component_from'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strongly_connected_component'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:180:in `each'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connected_component'
    from /Users/markustorok/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/initializable.rb:54:in `run_initializers'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/application.rb:214:in `initialize!'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/railtie/configurable.rb:30:in `method_missing'
    from /Users/markustorok/Dropbox/2Working/WebDesign/Ruby/rails_projects/speiseplan/config/environment.rb:5:in `<top (required)>'
    from /Users/markustorok/Dropbox/2Working/WebDesign/Ruby/rails_projects/speiseplan/config.ru:3:in `require'
    from /Users/markustorok/Dropbox/2Working/WebDesign/Ruby/rails_projects/speiseplan/config.ru:3:in `block in <main>'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/builder.rb:55:in `instance_eval'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/builder.rb:55:in `initialize'
    from /Users/markustorok/Dropbox/2Working/WebDesign/Ruby/rails_projects/speiseplan/config.ru:in `new'
    from /Users/markustorok/Dropbox/2Working/WebDesign/Ruby/rails_projects/speiseplan/config.ru:in `<main>'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/builder.rb:49:in `eval'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/builder.rb:49:in `new_from_string'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/builder.rb:40:in `parse_file'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/server.rb:277:in `build_app_and_options_from_config'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/server.rb:199:in `app'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/commands/server.rb:48:in `app'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/rack-1.5.2/lib/rack/server.rb:314:in `wrapped_app'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/commands/server.rb:75:in `start'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/commands.rb:80:in `block in <top (required)>'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/commands.rb:75:in `tap'
    from /Users/markustorok/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0.rc1/lib/rails/commands.rb:75:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

A: Do you have any initialisers or lines in config files that make a call to a FourTest class? Because that class can't be found. Start by searching your code for FourTest then check that you've followed naming conventions on the file that contains the class and that it's in a folder that gets loaded by default (models folder) or that you are manually loading it before using it (lib folder, etc).


text:
Q: How can I include a percent sign in QUrl I'm new in c++ from this afternoon and I am having a hard time.
I have the below line:
const QUrl command("http://192.168.11.11/subdomain/letters?t=somekeyword&p=%01")

But when the QUrl "command" is sent used in QNetworkAccessManager, it is actually being sent adding 25 after the % sign.
Now I understand that QUrl is in TolerantMode, and is adding it thinking it's a user input error.
Unwanted result:
http://192.168.11.11/subdomain/letters?t=somekeyword&p=%2501

How would I prevent my url to be modified?
I tried to double my percent sign and inserting a backslash as well.
Any help is appreciated.
Thanks.

A: This turned out to be a tricky problem. Here is the solution I came up with:
Code
QByteArray rawQuery("t=somekeyword&p=%01");
QUrl command("http://192.168.11.11/subdomain/letters");
command.setEncodedQuery(rawQuery);
std::cout << command.toEncoded().data();

Result
http://192.168.11.11/subdomain/letters?t=somekeyword&p=%01
Notes
The solution relies on some behavior described in setEncodedQuery, which states

Sets the query string of the URL to query. The string is inserted as-is, and no further encoding is performed when calling toEncoded().
This function is useful if you need to pass a query string that does not fit into the key-value pattern, or that uses a different scheme for encoding special characters than what is suggested by QUrl.
Passing a value of QByteArray() to query (a null QByteArray) unsets the query completely. However, passing a value of QByteArray("") will set the query to an empty value, as if the original URL had a lone "?".

References

*

*http://qt-project.org/doc/qt-4.8/qurl.html#setEncodedQuery


text:
Q: Set a Scrollable date and time picker in Android I want to make date time picker in my activity which should be scrollable not clickable means the one like titanium in Iphone. So i tried to use Date time picker but didn't work. So if any one has idea or any link of source code please help. Help Appreciated.

A: you can search as drum picker or date slider for android in google.
anyway check this link
https://github.com/sys1yagi/AndroidPractice/tree/master/DrumPicker/trunk


text:
Q: How to model grouping constraint in Knapsack problem? I would like to add a new constraint to a standard Knapsack problem by introducing groups.
My variables are $x_c \in \mathbb{Z}^+,  c\in \mathbb{C}$. Where $\mathbb{C}$ is the set of all items. Each item belongs to a specific group $g_i, i\in \mathbb{G}$ and these groups are mutually exclusive.
I would like to optimize with limiting the number of groups my items belong to. (let's say $k$ groups)
Is it still possible to formulate this as a MIP problem and how?

A: For $i\in \mathbb{G}$, let binary variable $y_i$ indicate whether some item from group $i$ is selected.  Let $\overline{x}_c$ be an upper bound on $x_c$, which you can obtain from the knapsack constraint.  Impose the following linear constraints:
\begin{align}
x_c &\le \overline{x}_c y_i &&\text{for $i\in \mathbb{G}$ and $c \in g_i$}\\
\sum_{i\in G} y_i &\le k
\end{align}
The first constraint enforces $x_c > 0 \implies y_i=1$.  The second constraint limits the number of selected groups to $k$.


text:
Q: How to retrieve a file's share mode? I've opened a file with CreateFileW and set the dwShareMode parameter to 0 (no sharing).
I could try and create a the file again and use GetLastError to check the failure, but is there a method where this can be queried similar to GetFileAttributesExW?


text:
Q: Open the Settings app?
Possible Duplicate:
Opening the Settings app from another app

Can i open the iPhone's Default Settings App from my Application?

A: You can use this on iOS 5.0 and later:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]];


text:
Q: Pinging an IP address using PHP and echoing the result I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.
function pingAddress($ip){
    $pingresult = shell_exec("start /b ping $ip -n 1");
    $dead = "Request timed out.";
    $deadoralive = strpos($dead, $pingresult);

    if ($deadoralive == false){
        echo "The IP address, $ip, is dead";
    } else {
        echo "The IP address, $ip, is alive";
    }

}

When I call this function using the example:
pingAddress("127.0.0.1")

The echo result is always 'dead' - no matter what.
Could someone please help me where I'm going wrong?
And/OR is there a better method of doing this with the same result?
Many thanks.
Update: Have amended code to include the double quotes but still getting the same (incorrect) results.

A: This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);
    if ($status==0) {
    $status = "alive";
    } else {
    $status = "dead";
    }
    $message .= '
';
    $message .= '
The IP address, '.$ip.', is  '.$status.'

';
    return $message;
}
// Some IP Address
pingAddress("192.168.1.1");

This worked perfectly for me, finally.
I referred this from http://www.phpscriptsdaily.com/php/php-ping/
Hope this will help
Well I want to modify this as it is working fine on my localhost but not on my live server
For live server, I got another thing which now works for both local as well as live.
$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }

Then I show the Server is up for 0 and down for 1.
This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79

A: I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.
Implement the following class:
<?php

    class CheckDevice {

        public function myOS(){
            if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
                return true;

            return false;
        }

        public function ping($ip_addr){
            if ($this->myOS()){
                if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
                    return true;
            } else {
                if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
                    return true;
            }

            return false;
        }
    }

    $ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com

    if ((new CheckDevice())->ping($ip_addr))
        echo "The device exists";
    else
        echo "The device is not connected";

A: i just wrote a very fast solution by combining all knowledge gain above
    function pinger($address){
        if(strtolower(PHP_OS)=='winnt'){
            $command = "ping -n 1 $address";
            exec($command, $output, $status);
        }else{
            $command = "ping -c 1 $address";
            exec($command, $output, $status);
        }
        if($status === 0){
            return true;
        }else{
            return false;
        }
    }

A: this works fine for me..
$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);

echo "
$output
"; //for viewing the ping result, if not need it just remove it

if (strpos($output, 'out') !== false) {
    echo "Dead";
}
    elseif(strpos($output, 'expired') !== false)
{
    echo "Network Error";
}
    elseif(strpos($output, 'data') !== false)
{
    echo "Alive";
}
else
{
    echo "Unknown Error";
}

A: For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
 print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}

https://github.com/geerlingguy/Ping

A: NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly
I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.
But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.
<?php
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
    if (0 == $status) {
        $status = "alive";
    } else {
        $status = "dead";
    }
    echo "The IP address, $ip, is  ".$status;
}

pingAddress("127.0.0.1");

A: Based on the great answer of @tiamiyu-saheed-oluwatosin I wrote this small function in shorthand if/else (ternary) style, working on both Windows and Linux, to check if a second PHP server is up and running in my LAN.
function running($ip) {
    exec("ping -{strtolower(PHP_OS)=='winnt'?'n':'c'} 1 $ip", $out, $res);
    return ($res === 0 ? true : false);
}

Use :
if(running('192.168.1.20') {
    // execute some code...
}

A: This works fine with hostname, reverse IP (for internal networks) and IP.
function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return 'OFFLINE';
    } else {
        return 'ONLINE';
    }
}

echo pingAddress($ip);

A: Do check the man pages of your ping command before trying some of these examples out (always good practice anyway). For Ubuntu 16 (for example) the accepted answer doesn't work as the -n 3 fails (this isn't the count of packets anymore, -n denotes not converting the IP address to a hostname).
Following the request of the OP, a potential alternative function would be as follows:
function checkPing($ip){
    $ping = trim(`which ping`);
    $ll = exec($ping . '-n -c2 ' . $ip, $output, $retVar);
    if($retVar == 0){
        echo "The IP address, $ip, is alive";
        return true;
    } else {
        echo "The IP address, $ip, is dead";
        return false;
    }
}

A: This is work with me:
<?php
class CheckDevice {
    public function myOS(){
        if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
            return true;
        return false;
    }
    public function ping($ip_addr){
        if ($this->myOS()){
            if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))return true;
        } else {
            if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
                return true;
        }return false;
    }
}
$ip_addr = "192.168.1.1";
if ((new CheckDevice())->ping($ip_addr))
    echo "The device exists";
else
    echo "The device is not connected";

A: I use this function :
<?php
function is_ping_address($ip) {
    exec('ping -c1 -w1 '.$ip, $outcome, $status);
    preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
    return ( $arr[1] == 100 ) ? false : true;
}


text:
Q: Wifi keeps reconnecting and asking for passphrase in Manjaro XFCE I'm connecting to a local WiFi network with a normal setup (see system specs below), that is a Fritz!Box router and a WiFi repeater to increase range. Usually all is well, I have a normal connection and can access the internet. However, sometimes seemingly at random (but maybe more often after suspension?!), the NetworkManager gui kicks me out of the WiFi and asks me for the passphrase. As it already knows it, I just press enter, but then it keeps asking me again and again. That forces me to press enter repeatedly like 10-20 times. And then, at random again, it connects. This happens like 20-30 times a day and is really distracting. Any idea what the problem is? Maybe it is the WiFi repeater setup where there are two networks with the same name? But even if I'm only in the range of the router itself but not the repeater I get the problem...
Important to add: I don't have this problem with any other device (e.g. mobile phones, tablets, a laptop running windows)
What I found so far: I've found this and this post and I've tried the following:

*

*set /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf to wifi.powersave = 2 (but this breaks NetworkManager, i.e. systemctl status NetworkManager.serviceyields status failed)

*following journalctl -fu NetworkManager to see what errors it gives me

If the connection fails, journalctl -fu NetworkManager gives me:
[...]
device (wlp2s0): supplicant interface state: 4way_handshake -> disconnected
device (wlp2s0): Activation: (wifi) disconnected during association, asking for new key
device (wlp2s0): state change: activated -> need-auth (reason 'supplicant-disconnect', sys-iface-state: 'managed')
dhcp4 (wlp2s0):  canceled DHCP transaction
dhcp4 (wlp2s0): state changed bound -> done
dhcp6 (wlp2s0): canceled DHCP transaction
dhcp6 (wlp2s0): state changed bound -> done
manager: NetworkManager state is now CONNECTING
device (wlp2s0): supplicant interface state: disconnected -> inactive
device (wlp2s0): supplicant interface state: inactive -> scanning
[...]

And when hitting enter to the dialog asking me the passphrase, it states the following:
device (wlp2s0): Activation: (wifi) connection 'my_home_wifi' has security, and secrets exist.  No new secrets needed.
[... some stuff here about "Config: added"]
device (wlp2s0): supplicant interface state: inactive -> associating
device (wlp2s0): supplicant interface state: associating -> associated
device (wlp2s0): supplicant interface state: associated -> 4way_handshake
device (wlp2s0): supplicant interface state: 4way_handshake -> disconnected
device (wlp2s0): Activation: (wifi) disconnected during association, asking for new key
device (wlp2s0): state change: config -> need-auth (reason 'supplicant-disconnect', sys-iface-state: 'managed')

and it begins again asking me for the passphrase...
My system specs: Manjaro 4.19.122-1 with xfce. My wireless card is a Broadcom BCM4313 (running with the broadcom-wl driver)

A: I myself have had this kind of trouble with Broadcom chips in the past. You might try a different driver such as the reverse-engineered b43 driver or brcmfmac. Former should be available on the AUR. Latter should be built into the kernel.
See here for further reading: https://wiki.archlinux.org/index.php/Broadcom_wireless#Installation


text:
Q: Python - Breaking out of inner loop from nested loop 'break' is used to break out of the nested loop.
main_keyword = ["11111", "22222", "333333", "44444", "55555"]

for pro in main_keyword:
    # 1
    for i in range(3):
        if pro == '333333':
            print(pro, "failure")
            break
        else:
            print(pro, "Pass")
            pass

    # 2
    for a in range(3):
        print(a)

However, the #1 for loop escapes, but the #2 for loop is executed.
11111 Pass
11111 Pass
11111 Pass
0
1
2
22222 Pass
22222 Pass
22222 Pass
0
1
2
333333 failure
0
1
2
44444 Pass
44444 Pass
44444 Pass
0
1
2
55555 Pass
55555 Pass
55555 Pass
0
1
2

What I want is if pro == '333333' , then proceed to the next operation of the top-level loop without working on both for loop #1 and #2.
11111 Pass
11111 Pass
11111 Pass
0
1
2
22222 Pass
22222 Pass
22222 Pass
0
1
2
333333 failure
44444 Pass
44444 Pass
44444 Pass
0
1
2
55555 Pass
55555 Pass
55555 Pass
0
1
2

I want the above result. help

A: Set additional flag that skips exec on fail:
main_keyword = ["11111", "22222", "333333", "44444", "55555"]

for pro in main_keyword:
# 1
    failed = 0
    for i in range(3):
        if pro == '333333':
            print(pro, "failure")
            failed = 1
            break
        else:
            print(pro, "Pass")
            pass
    if failed: continue

# 2
    for a in range(3):
        print(a)

A: It looks like you want a multi-level continue.  But Python doesn't support multi-level break or continue.  However, you can achieve the equivalent effect by using a flag:
main_keyword = ["11111", "22222", "333333", "44444", "55555"]

for pro in main_keyword:
    # 1
    fail = False
    for i in range(3):
        if pro == '333333':
            print(pro, "failure")
            fail = True
            break
        else:
            print(pro, "Pass")
            pass

    if fail:
        continue

    # 2
    for a in range(3):
        print(a)

A: This is my take on it:
main_keyword = ["11111", "22222", "333333", "44444", "55555"]

for pro in main_keyword:
    # 1
    error = False
    for i in range(3):
        if pro == '333333':
            print(pro, "failure")
            error = True
            break
        print(pro, "Pass")

    # 2
    if not error:
        for a in range(3):
            print(a)

Result:
11111 Pass
11111 Pass
11111 Pass
0
1
2
22222 Pass
22222 Pass
22222 Pass
0
1
2
333333 failure
44444 Pass
44444 Pass
44444 Pass
0
1
2
55555 Pass
55555 Pass
55555 Pass
0
1
2


text:
Q: During her stay, she will visit "the" garden, historical sites, or local stores - does repetition of "the" affect the meaning? Example 1

During her stay, she will visit the garden, the historical sites, or the local stores.

During her stay, she will visit the garden, historical sites, or local stores.

Are both the sentences in this example correct?
I am using inclusive "or" here, which means she might visit any two or all three places.
Does repeating "the" or not affect the inclusiveness?
Or does repetition of "the" has nothing to do with inclusiveness or exclusiveness at all?
Example 2

A student should learn from their classmates, their teacher, or their friends.

A student should learn from their classmates, teacher, or friends.

Are both the sentences in this example correct?
I am using inclusive "or" here.
Does repeating "the" or not affect the inclusiveness?
Or does repetition of "the" has nothing to do with inclusiveness or exclusiveness at all?


text:
Q: Have border-bottom after grid-row css3 I have a grid container whose css is
.optionsInnerContainer {
        display: grid;
        // grid-template-columns: 1fr 1fr 1fr;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); /* see notes below */
        // grid-auto-rows: minmax(100px, auto);
        -webkit-column-gap: 10px;
        column-gap: 10px;
        row-gap: 2em;
        padding: 10px;
    }

I want to add a border-bottom below every row of grid. I dont know how to do that. Please help.


text:
Q: Replace consecutive repeated characters with one - Column-wise operation - `pandas.DataFrame` How do I remove repeated characters in string and just leave one of them.
e.g:-
"Bertuggggg Mete"

to
"Bertug Mete"

I've just read data like this:
dataFrame = pd.read_excel("C:\\Users\\Bertug\\Desktop\\example.xlsx")

Name
0 Bertuggggg Mete
Input is read from .xlsx file. I have tried split and strip functions but they don't work seem to work as expected.
How I can solve this problem ?

A: Check this out:
Replace column_name with whatever is the column name you want to apply the replacement.
min_threshold_rep = 2
column_name = 'Name'
dataframe[column_name]= dataframe[column_name].str.replace(r'(\w)\1{%d,}'%(min_threshold_rep-1), r'\1')

NOTE: this would replace every min_threshold_rep number of consecutive character with one character.

A: python code :
if __name__ == '__main__':
    s = 'Bertuggggg Mete'
    if len(s) == 0:
        print('wrong!')
        exit()
    r = s[0]
    for c in s:
        if r[len(r) - 1] != c:
            r += c
    print(r)

java code :
public class Test {

public static void main(String[] args) {
    String s = "Bertuggggg Mete";
    StringBuffer sb = new StringBuffer();
    for (int i = 0, j = s.length(); i < j; i++) {
        if (i == 0) {
            sb.append(s.charAt(0));
        }
        if (s.charAt(i) != sb.charAt(sb.length() - 1)) {
            sb.append(s.charAt(i));
        }
    }
    System.out.println(sb);
}

}


text:
Q: QT How to wait in a main programm for one thread (without using sleep/freezing) My QT-program have 4 steps in a loop:

*

*reading n config file

*transmitting values via UART to uC

*recording audio files and receiving values from uC

*stopping recording and writing a header (*.PCM to *.WAV conversion)

*go to n+1 config file and starting again with step 1.

For audio recording I'm using:
m_file.open(QIODevice::WriteOnly); //audio access mode initialisation
writeHeader(); //writing header to convert PCM to *.wav
m_audio->start(&m_file); //start recording
QTimer::singleShot((record_time_sec+4)*1000), this, SLOT(StopRecording()));

QTimer::singleShot() makes a new thread open and while recording (step 3) is working - the main program is still running and I see that the program try to make direct the next steps in a loop without waiting for stopping recording.
How it is possible to wait for ending of recording threads and then following a next steps?
P.S. I was reading about QCoreApplication::processEvents() but I', not sure about, how to use that function!?

void Measure::processMeas(){

    // Declaration xxxxxxx
    // Read config files
    QDir directory("tralala");
    QStringList config_files = directory.entryList(QStringList() << "*.txt", QDir::Files);
    config_files_cnt = config_files.count();

    foreach(QString filename, config_files) { //config loop
        Conf *conf = new Conf(directory.absoluteFilePath(filename));
        qDebug() << "Config file: " << filename << " is processed";

    // Error message xxxxxxxx
    // Prepare measure
        qDebug()<<"Debug: Prepare measure";

        QStringList lines = conf->getConf_lines(); //read all rows of config files

        record_time_100ms = lines.count();
        record_time_sec = record_time_100ms / 10;

        for(i=0; i < (uint32_t)lines.length(); i++){ //prepare single rows of config files

            QString uart;
            QString uart_hex;

                if(i > 5 && i < lines.length()){
                QStringList speed_chunks = lines.at(i).split(","); //split rows by decimal point

                m1 = speed_chunks.at(2).toInt();
                m2 = speed_chunks.at(3).toInt();
                m3 = speed_chunks.at(4).toInt();
                m4 = speed_chunks.at(5).toInt();

                hextest.resize(10);
                hextest[0]=255;
                hextest[1]=m1>>8;
                hextest[2]=m1;
                hextest[3]=m2>>8;
                hextest[4]=m2;
                hextest[5]=m3>>8;
                hextest[6]=m3;
                hextest[7]=m4>>8;
                hextest[8]=m4;
                hextest[9]=238;

                qDebug()<< "Transfer data: " << i << " from " << lines.count()-1 << " rows transmitted";

                m_serial.write(hextest);
                m_serial.waitForBytesWritten(1000);
                QThread::usleep(50000);

                }//if(lines.at(i).contains(",")) end
            }//for end

    // Measurement
            if(stm==0){
                QString path = SAVE_AUDIO_PATH+QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
                m_file.setFileName(path+".log");
                m_audio->StartRecording(path+".wav");
                stm=1;
            }
            qDebug()<<"Measurement takes " << record_time_sec+4 << " seconds";
    // Stop measure
           measure_cnt++;
           // All configs files done
            if(measure_cnt>=config_files_cnt){
                //m_timer->stop();
                qDebug()<<"All measure done";
                // qApp->quit();
            }
        }//foreach

}
*************************************************
void Audio::StartRecording(QString rec_file_path)
{
    m_file.setFileName(rec_file_path); //audio recording path format
    m_file.open(QIODevice::WriteOnly); //audio access mode initialisation

    writeHeader(); //writing header to convert PCM to *.wav (Step 1)

    m_audio->start(&m_file); //start recording

    QTimer::singleShot((15000), this, SLOT(StopRecording()));
}

//Stop recording

void Audio::StopRecording()
{
    m_audio->stop();
    writeHeaderFinal();
    m_file.close();
}

writeHeader(); and writeFinalHeader(); are just functions to convert PCM to *.Wav
I think the big Problem - i try to combine normal code loop with signal-slot principles!? Maybe I have to split my code to different parts and make a slots - and if one part are over, I have to go to next slot? Its a right logic?


text:
Q: Ambiguous method call navigation using Android with Java I am getting the following error:

Ambiguous method call. Both navigateup (NavController, DrawerLayout)
  in NavigationUI and navigateUp (NavController, AppBarConfiguration)
  in NavigationUI match

trying to use this code:
@Override
public boolean onSupportNavigateUp() {
    return NavigationUI.navigateUp(navController, null);
}

I have no idea what I can do to resolve this, any ideas?

A: Cast the null into the version you want to use.  The compiler isn't sure which to call, the cast will tell it.

A: If you're passing in null, you don't need NavigationUI at all. Just call navigateUp on NavController itself:
@Override
public boolean onSupportNavigateUp() {
    return navController.navigateUp();
}


text:
Q: Histogram in R: Converting into numeric Suppose you have character values as the x values. Suppose you want to draw a histogram. How do you convert the character values into numerical values?

A: You can use as.numeric to do this, as in
hist( as.numeric( c("0", "0", "1", "2", "2", "3", "4") ) )


text:
Q: how to copy data from one column to another excluding the first record in same table? col1
1
2
3
4
5
6

output:
col2
2
3
4
5
6
null

A: Use the LEAD analytic function:
SELECT col1,
       LEAD(col1) OVER (ORDER BY col1) AS col2
FROM   table_name;

Which, for the sample data:
CREATE TABLE table_name (col1) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 6;

Outputs:

COL1
COL2

1
2

2
3

3
4

4
5

5
6

6

db<>fiddle here


text:
Q: Constant resolution inside EL variable I wonder if there is some solution for this problem:

*

*I'm using Spring MVC

*I'm having value for attribute where I store some object saved as constant

*I'd like to access model through that constant in JSP, so something like this:

${ <%= ATTR_ALL_TEMPLATES %> }
Don't worry, I don't want to use scriptlets, just for sake of clarification. How can I achieve this?
EDIT:
I want to communicate between Portlet/Servlet and JSP just by constants without the need to know what value they have. And so instead of ${ allMyTemplates } I want to use something like stated above.

A: As per my understanding you need to read Constant from java constant file in jsp using EL.
There is one Jakarta : Unstandard Tag library which is used to read constant from java file.(Maven Repo.)
Use  to read constant from java file.
You need to add jar file for that and include tag lib declaration in your JSP file as below :
<%@taglib uri="http://jakarta.apache.org/taglibs/unstandard-1.0" prefix="un"%>

To read any constant you first need to include below line for particular java constant file for example :
<un:useConstants var="regStatus"com.example.YourConstantsClass"/>

Read constant by below line:
<p>${Constants.MY_CONSTANT_1}</p>

There another tag library which provide same functionality.
May this will help you.


text:
Q: How to use IcollectionView Filter without any specific class for the data Here is the whole query-
I have a WPF application which has a datagrid. Datagrid is binding to IcollectionView after getting the data from database with Autogenerate column as True. While binding the data or in autogeneratingcolumn method, i am creating a header template with filter popup like excel.
When user clicks on any of those column header , a popup will come for the user same as excel filter. Once user check/uncheck a value and click OK, it should filter the data based on the user selection.
Thats where i thought to use the IcollectionView filter capability. But every solution of filter is taking a class to filter the data. like in the below URL( TraceDataItem class is getting used)-
Filtering ObservableCollection with ICollectionView
I can't have a fixed class as datagrid autogenerate column is true and data can be anything. Is there any way to use this filter capability with data having no fixed class as mentioned in all the examples ?
Do let me know for any query you have instead of down voting if need explanation.
Adding the code used-
This is what i am using to get the checked/unchecked value from user in filter popup-
var tempCollection = (from c in CurrentDistictValues where c.IsChecked == true select c);
                    var val = from c in tempCollection select c.Name;
                    List<object> itemsChecked = new List<object>();
                    itemsChecked = val.ToList();
                    string s = String.Join("','", itemsChecked);
                    StringBuilder t = new StringBuilder(s);
                    t.Append("'");
                    t.Insert(0, "'");
                    s = t.ToString();

s will have all the values selected by user separated by comma so that the same can be applied for dataview rowfilter:-
itemSource.RowFilter = "[" + columnName + "]" + " " + " IN " + "(" + s + ")";

Note- itemSource is DataView in present code & column name is the property on which we are applying filter.
So now If we use IcollectionView as ItemSource , what should be the approach ?

A: If you don't know the type of the elements displayed in the ICollectionView, you can still filter them using reflection. Something like this:
string propertyName = "Name"; //property to filter by
string valueToCompareAgainst = "x";
ICollectionView view = ...;
view.Filter = (obj) =>
{
    Type type = obj.GetType();
    System.Reflection.PropertyInfo pi = type.GetProperty(propertyName);
    if(pi != null)
    {
        object value = pi.GetValue(obj);
        return value.Equals(valueToCompareAgainst);
    }
    return false;
};


text:
Q: Rails 7 dry-struct add attribute from method I'm using dry-struct for non-model class Payout - it's basically structured hash response from API call.
module Customer
class Payout < Dry::Struct
attribute :amount, Types::Integer
attribute :reference, Types::String
attribute :settlements, Types::Array

def fetch_settlements
  CustomerApi.fetch_settlements_by_reference(platform_merchant_id, reference)
end

end
end
Is it possible to set attribute :settlements by the fetch_settlements method ? I was trying something like:
attribute :settlements, Types::Array.optional.default(feth_settlements)

but I'm getting an error of

undefined local variable or method `fetch_settlements


text:
Q: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field I am trying to update the status field of the master record (Service Request) to close, when all the subsequent child activities status is closed.
Here is the code:
trigger TriggerSR_StatusUpdate on Activities__c (after update) {
  //Fetching all SR Ids in map
  List<Activities__c> SR_Ids1 = new List<Activities__c>(
    [SELECT ServiceRequest__r.id FROM Activities__c
     where Status__c='Close' and id in :Trigger.newMap.keySet()]);

  Set<Id> SR_Ids = new Set<Id>();
  for(Activities__c act : SR_Ids1)
  {
     SR_Ids.add(act.ServiceRequest__c);
  }
  //fetching status of the activities for the corresponding Service Request
  Map<Id,ServiceRequest__c > SRMap = new Map<Id,ServiceRequest__c >(
    [SELECT id,(select Status__c from Activities__r)
    from ServiceRequest__c where Id IN:SR_Ids]);

  List<ServiceRequest__c> SrStatus =SRMap.values();
}

I am getting an exception:
System.SObjectException: SObject row was retrieved via SOQL
without querying the requested field

What does this mean?

A: You are accessing act.ServiceRequest__c in your for loop
for(Activities__c act : SR_Ids1)
{
   SR_Ids.add(act.ServiceRequest__c);
}

but didn't query for it first in your SOQL.
Change:
List<Activities__c> SR_Ids1= new List<Activities__c>([
    SELECT ServiceRequest__r.id
    FROM Activities__c
    where Status__c='Close' and id in :Trigger.newMap.keySet()]);

To include ServiceRequest__c.
List<Activities__c> SR_Ids1= new List<Activities__c>([
    SELECT ServiceRequest__r.id, ServiceRequest__c /* add that */
    FROM Activities__c
    where Status__c='Close' and id in :Trigger.newMap.keySet()]);

A: How to reproduce the exception:
System.SObjectException: SObject row was retrieved via SOQL without
querying the requested field: Opportunity.stuff__c

Code:
private static Opportunity reloadOpp(Opportunity opp) {
    Id oppId = opp.Id;
    return [Select Id From Opportunity Where Id = :oppId]; //stuff__c not selected here
}

static testmethod void testFoobar() {
    Opportunity opp = new Opportunity();
    opp.Description = 'Carrier';
    opp.Type = 'Other';
    opp.Name = 'foobar';
    opp.StageName = 'PDP';

    try{
        insert opp;
    }
    catch(Exception e){
        System.debug(Logginglevel.Error, '' + e);
    }
    Opportunity opp2 = reloadOpp(opp);
    System.assert(opp2.stuff__c.equals('foobar'));    //so the error thrown here.
}

When you fetch the value opp2.stuff__c, the compiler notices that you never pulled that value from the object returned by the method reloadOpp.  So you get the exception.


text:
Q: Python Ошибка разбора парсеров Имеется код:

 Разместили сегодня (Дата окончания публикации: 18.04.2019 г.)

По сути этот текст относится к div.
Чтобы вытащить этот текст, достаточно:
date = html.cssselect("div.sm.gray")[0].text

Но нет, возвращает None.
Я подумал что оно относится к Img, просто отсутствует завершающий /
date = html.cssselect("div.sm.gray > img")[0]

Вернуло:
 Разместили сегодня (Дата окончания публикации: 18.04.2019 г.)

Значит верно. Берем текст:
date = html.cssselect("div.sm.gray > img")[0].text

Но возвращает также None. Что за?
Поменял парсер с lxml на html.parser, но ошибка осталась

A: Можно так:
tree.cssselect("div.sm.gray")[0].text_content()

# '\n Разместили сегодня (Дата окончания публикации: 18.04.2019 г.)'


text:
Q: java script setInterval setting the delay? We have a use case of running the java script thread once a month. But what we observe is if we provide 3.5 weeks of delay for the setinterval function it does not respect it and starts getting scheduling once a second. is it a bug? does it have any maxiumum limit for giving the delay?
Interestingly same works fine for setTimeOut. -
<!DOCTYPE html>
<html>
<body>

<input type="text" id="clock" />
<script>
    var int=setInterval(function(){clock()},1000*60*60*24*7*3.5);
    function clock()
    {
        var d=new Date();
        var t=d.toLocaleTimeString();
        document.getElementById("clock").value=t;
    }
</script>

<button onclick="int=window.clearInterval(int)">Stop</button>

</body>
</html>

A: 1000*60*60*24*7*3.5 = 0x7e2bce00

Which is awfully close to 0x80000000, I wonder if 32 but signed arithmetic somewhere might be responsible.
I just checked the specification and the timeout for setInterval and setTimeout are both defined as long values which means signed 32 bit. It is unclear how a negativetimeout value would be treated.
From the WhatWG spec :

long setTimeout(Function handler, optional long timeout, any...
  arguments);

From the WebIDL standard :

The long type is a signed integer type that has values in the range
  [−2147483648, 2147483647].

To fix your problem I can make two suggestions:
Since setTimeout works, use it and retrigger at the end of the processing function
Alternatively setInterval of half the period you want and use a toggle to execute your code every other time.


text:
Q: Do I need to add comma in a sentence joined with "and with that" User experience design industry evolved and with that the need for consistent design and centralized design rollouts.
OR
User experience design industry evolved and with that, the need for consistent design and centralized design rollouts.


text:
Q: Using Pusher in Vue for a Chrome Extension I am trying to use Pusher inside a Chrome extension I am writing in Vue.
The problem I have is that Chrome is refusing to load a script used by Pusher's pusher-js library (And I see the same error if I try and utilise the Pusher JS file directly, rather than as part of the library) (Obviously the key and session are shown in full in the actual error!)

pusher.js:1128 Refused to load the script 'https://stats.pusher.com/timeline/v2/jsonp/1?session=XXX%3D&bundle=MQ%3D%3D&key=XXX' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

The culprit is this line in pusher's JS:
head.insertBefore(self.script, head.firstChild);
I have tried lots of different things in my Manifest, including, of course, adding https://stats.pusher.com like this:
"content_security_policy": "script-src 'self' https://stats.pusher.com https://js.pusher.com; object-src 'self'"
But nothing works. It DOES work if I build the same code example outside of a Vue extension as a 'pure Javascript' project, but I would prefer to use Vue if I can. I suspect this happens because:
Firstly: Pusher is calling an external script from within a script rather than calling it directly
Secondly: I am calling the Pusher library outside of a Javascript file
This is my App.vue which is served from popup.js:
<template>

Hello

</template>

Note in the above example I tried copying the Pusher Javacript library in as a local file and setting a path to it in Webpack but I see exactly the same error if I use the official NPM.
Appreciate any help,
Thanks!


text:
Q: Catch InvalidOperationException with empty structure I am trying to catch the InvalidOperationException that can sometimes occur when declaring variables. The following code doesn't work however. Probably because I don't really know how you catch an exception.
public override void Download()
{
    try
    {
        var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
        try
        {
            throw new InvalidOperationException();
        }
        catch (InvalidOperationException exception)
        {
            return;
        }
        catch (Exception exception)
        {
            throw;
        }
    }
}

Any help at all would be very appreciated.

A: You don't need to throw the exception yourself. Just have:
    try
    {
        var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
    }
    catch (InvalidOperationException exception)
    {
        // Error logging, post processing etc.
        return;
    }

You shouldn't really be catching the general exception either unless you have a really good reason to - i.e. your application cannot crash, but if you do you need to be able to recover from it.


text:
Q: Does this makefile make sense? i want to compile this small program:
#include <iostream>
#include <SDL.h>

using namespace std;

int main() {
  if(SDL_Init(SDL_INIT_VIDEO) < 0) {
    cout << "SDL init failed"   << endl;
    return 1;
  }
  cout << "Hello World" << endl;

  return 0;
}

which I can do successfully with:
g++ -o SDL_basic SDL_basic.cpp -I/opt/local/include/SDL2/ -l SDL2 -L/opt/local/lib/

I spent the last hour trying to modify the makefile I usually use to do the same:
CXX=g++
INC=-I/opt/local/include/SDL2/
LIBSEARCHPATH=-L/opt/local/lib/
LIBS=-l SDL2

OBJECTS=$(PROJECT).o
PROJECT=SDL_basic

$(PROJECT) : $(OBJECTS)
        ${CXX} $(CPFLAGS) $(OBJECTS) -o $@ ${INC} ${LIBSEARCHPATH} ${LIBS}

.cpp.o :
        ${CXX} -c ${CPFLAGS} $? ${INC} ${LIBSEARCHPATH} ${LIBS}

clean :
        rm -f $(OBJECTS)

Running make finally works now, but if I run it a second time after a small change in the .cpp, I get the following warning:
clang: warning: -lSDL2: 'linker' input unused [-Wunused-command-line-argument]
clang: warning: argument unused during compilation: '-L/opt/local/lib/' [-Wunused-command-line-argument]

Therefore my question. Does this make sense what I did in the makefile? Do the arguments ${INC} ${LIBSEARCHPATH} ${LIBS} really belong after both .cpp.o : and $(PROJECT) : $(OBJECTS) (Otherwise it does not seem to work)?
I hope somebody can help me.
Thank you a lot and best regards!!
F


text:
Q: Javamail SendFailedException I'm trying to send and email with javamail api. The code is very simple but when I send the mail doesn't work. Show this error message:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Client does not have permissions to send
as this sender

The code is this:
public class Email {

    static Properties mailServerProperties;
    static Session getMailSession;
    static MimeMessage generateMailMessage;
    static String aInc = "scanner@impresia.es";

    public void sendEmail(String a, String c) throws AddressException, MessagingException {

        // Server propierties
        mailServerProperties = System.getProperties();
        mailServerProperties.put("mail.smtp.port", "25");
        mailServerProperties.put("mail.smtp.auth", "true");

        // New mail
        getMailSession = Session.getDefaultInstance(mailServerProperties, null);
        generateMailMessage = new MimeMessage(getMailSession);
        generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(aInc));
        generateMailMessage.setSubject(c);
        generateMailMessage.setContent(a, "text/html");

        // Send Email
        Transport transport = getMailSession.getTransport("smtp");
        transport.connect("10.5.32.40", "scanner@impresia.es", "xxxxxxxx");

        transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());//generateMailMessage.getAllRecipients());
        transport.close();
    }
}

Please, could you help me?
Thanks!

A: You can try sending the mail after setting From address in the MimeMessage.


text:
Q: Create email from Excel-VBA to include Range with Conditional Formatting Background:
I have dug around and learned to create an email per Rob de Bruin's guide, herein "RDB".  In trying to get the contents of my email appropriate, I have found that the RangetoHTM function RDB created does not maintain colors applied via conditional formatting.
I have attempted a suggested workaround altering the existing code to include .Cells(1).PasteSpecial xlPasteAllUsingSourceTheme (suggested here), though that also does not appear to resolve the issue.
I have attempted to move onto using SendKeys, where I cannot get "^V" to work, hoping that there is another way to do this.  I have attempted to step through and manually Ctrl+V and there is no pastable content, despite the spreadsheet having the selected range outlined.

Issue:
When copying a range from Excel, which has basic coloring as well as additional coloring from conditional formatting, I am unable to paste the desired range into an Outlook email via code as the conditional formatting colors are removed.
Making an image (png) of the range is not an acceptable output as there are links that need to be followed in one column of the range to be pasted.

Question:
Additional suggestions would be appreciated, though that would make this a subjective, discussion piece which is Too Broad for StackOverflow... so I'll try to keep this specific to the code I have created/modified.
If anyone is aware how to modify RDB's code to allow conditionally formatted cells, that would also be awesome.
Given I am attempting SendKeys, does anyone know why I cannot get the paste to work?

Code in question:
Note: I had to bastardize module names and remove some content (standard), so pardon the not so specific labels on the private subs being called.  There are five (5) subroutines and one (1) function in the below code, in this order:

*

*Public Sub execute() 'the one that calls the private subs in the preferred order

*Private Sub SheetVals() 'sets the ranges in the excel sheet and values variables

*Private Sub MsgContent() ' Creates the email and uses the sheet vals

*Private Sub SetToNothing() 'set blah = nothing

*Private Function CopyRangeToHTML(ByVal name As Range) 'RDB's code

*Private Sub send_keys_test() ' how i've been attempting to do sendkeys
.
Option Explicit
Private i As Long, legendrng As Range, tablerng As Range, mval As String, sdate As String, bmonth As String, bdate As String
Private msg As Outlook.MailItem, oapp As Outlook.Application

Public Sub execute()
    If ActiveSheet.name <> "NAME" Then Exit Sub
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .Calculation = xlManual
    End With
    '''
    SheetVals
    MsgContent
    send_keys_test 'Very bottom of the code
    SetToNothing
    '''
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .Calculation = xlAutomatic
    End With
End Sub

Private Sub SheetVals()
    Dim lrtable As Long, lrlegend As Long, lc As Long
    With Sheets("Name")
        lc = 9
        lrlegend = .Cells(.Rows.Count, 1).End(xlUp).Row
        lrtable = .Cells(.Rows.Count, lc).End(xlUp).Row
        Set legendrng = .Range(.Cells(lrlegend - 4, 1), .Cells(lrlegend, 1))
        Set tablerng = .Range(.Cells(3, 1), .Cells(lrtable, lc))
        mval = Format(.Cells(.Columns(1).Find(What:="Shalom", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Row + 3, 6).Value, "$#,###")
        sdate = Format(Date, "yyyyMMMdd")
        bmonth = Format(Date, "MMM")
        bdate = Format(Date, "MMM dd, yyyy")
    End With
End Sub

Private Sub MsgContent()
    Set oapp = CreateObject("Outlook.Application")
    Set msg = oapp.CreateItem(olMailItem)
    With msg
        .Display
        .Importance = 2
        .to = ""
        .Subject = "Subject " & sdate
        .HTMLBody = _
            "Content.
"
        '.HTMLBody = .Body & CopyRangeToHTML(tablerng)
        .Attachments.Add ActiveWorkbook.FullName
    End With
End Sub

Private Sub SetToNothing()
    Set msg = Nothing
    Set oapp = Nothing
    i = 0
    Set legendrng = Nothing
    Set tablerng = Nothing
    mval = ""
    sdate = ""
    bmonth = ""
    bdate = ""
End Sub

Private Function CopyRangeToHTML(ByVal name As Range)
    ' Changed by Ron de Bruin 28-Oct-2006
    ' Working in Office 2000-2016
    Dim fso As Object, ts As Object, TempFile As String, TempWB As Workbook
    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
    'Copy the range and create a new workbook to past the data in
    name.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With
    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With
    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    CopyRangeToHTML = ts.ReadAll
    ts.Close
    CopyRangeToHTML = Replace(CopyRangeToHTML, "align=center x:publishsource=", "align=left x:publishsource=")
    'Close TempWB
    TempWB.Close savechanges:=False
    'Delete the htm file we used in this function
    Kill TempFile
    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Private Sub send_keys_test()
    'comments out the .HTMLBody section of task_two with this being the test
    msg.GetInspector.Activate
    SendKeys "{Tab}{Tab}{Tab}{Tab}{Tab}", True
    SendKeys "^{End}", True
    tablerng.Copy
    msg.GetInspector.Activate
    SendKeys "^V", True
End Sub

Edit1: + Edit2:
Testing sendkeys with this code, where I stripped out most of the above code to focus on copying the desired range.  This does not appear to copy due to the copied range in Excel not displaying the signals for a copy (blinking outline of the range) nor does manually pressing ctrl+V paste anything into Word or Outlook:
Option Explicit

Private tablerng As Range

Private Sub fdsa()
    Set tablerng = Range(Cells(3, 1), Cells(47, 9))
    tablerng.Select
    Application.SendKeys "^c", True 'Edit2:  Once i added "Application." sendkeys worked for me
End Sub

So, I have sendkeys working, due to Application., but still having issues with conditional formatting, despite copy/paste.  Hm... Will add some images, before and after conditional formatting...
Before:   After:
The blue color, added from conditional formatting is lost when copy/pasting to Outlook via RDB rangetohtml method.

A: You shouldn't need to resort to SendKeys. a slight change to "RDB" so that you 'PasteAll' and conditional formatting seems to transfer fine. Below is a very much pared down example (assuming you have conditional formatting within cells A1:B10)
Sub CreateEmail()
    Dim oApp As Object: Set oApp = CreateObject("Outlook.Application")
    Dim oMail As Object: Set oMail = oApp.CreateItem(olMailItem)

    Dim wsData As Worksheet: Set wsData = ThisWorkbook.Worksheets("Sheet1")
    Dim rData As Range: Set rData = wsData.Range("A1:B10")

    With oMail
        .To = "Test"
        .HTMLBody = _
            "Content.
"
        .HTMLBody = .HTMLBody & RangetoHTML(rData)
        .Display
    End With

End Sub

Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    Application.ScreenUpdating = False
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial xlPasteAll
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False
    Application.ScreenUpdating = True

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

********* EDIT *********
Not sure why it doesn't work for you. I tested with conditional formatting in place and it copied altered cells into the e-mail.
The RangetoHTML function may be editable to remove the need to copy and paste the range to a new book though [hopefully bypassing the issues as it would use the direct source] (I'm currently at a PC without Outlook though so unable to test my altered code). Please feel free to give it a try and see if it works though.
Function RangetoHTML(rng As Range)
' Altered from code by Ron de Bruin.
    Dim fso As Object, ts As Object
    Dim TempFile As String
    Dim wbSrc As Workbook: Set wbSrc = rng.Worksheet.Parent

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Publish the sheet range to a htm file
    With wbSrc.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=rng.Worksheet.Name, _
         Source:=rng.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set wbSrc = Nothing
End Function

A: I ended up doing something of far more effort to get around this, due to knowing that .Paragraphs(.Paragraphs.Count).Range.PasteExcelTable False, False, False exists in MS Word.
This was a cumbersome workaround, though I'm attempting to utilize Tragamor's solution before I call this the final product... it works, but it ain't pretty.
Private Sub task_two()
    Set wApp = CreateObject("Word.Application")
    Set doc = wApp.Documents.Add
    With doc
        .content.InsertAfter "Content" & vbNewLine & vbNewLine
        wApp.Selection.EndKey unit:=wdStory, Extend:=wdMove
        tablerng.Copy
        .Paragraphs(.Paragraphs.Count).Range.PasteExcelTable False, False, False
    End With
End Sub

Private Sub task_three()
    Set oApp = CreateObject("Outlook.Application")
    Set msg = oApp.CreateItem(olMailItem)
    doc.content.Copy
    With msg
        .Display
        .Importance = 2
        .To = ""
        .Subject = "Subject " & sdate
        .GetInspector.WordEditor.content.Paste
        .Attachments.Add ActiveWorkbook.FullName
    End With
End Sub

Private Sub task_four()
    doc.Close SaveChanges:=wdDoNotSaveChanges
    Set doc = Nothing
    wApp.Quit
    Set wApp = Nothing
    Set msg = Nothing
    Set oApp = Nothing
    i = 0
    Set legendrng = Nothing
    Set tablerng = Nothing
    mval = ""
    sdate = ""
    bmonth = ""
    bdate = ""
End Sub


text:
Q: Is running programs as another user useful? After watching a talk by Douglas Crockford on security where he talks about how browsers got the right answer to the question "Who's interest does the program represent?", I wondered if it was feasible and a good idea to run some programs as another user.
I'm running Debian but I guess this could apply to any OS.
I tend to trust anything coming from the stable, backports and testing repositories (please tell me if I shouldn't) but whenever I install something else, something that isn't on these repositories, I don't really trust it. And I have quite a few of those from Mathematics programs such as Maple to browsers such as Chrome to games such as Heroes of Newerth.
Since that makes me unable to trust my own OS, I boot on a live CD every single time I want to use my credit card.
So I was wondering if just running those programs as a specific user could be of any help. I'm fine with Chrome being able to see everything I do online but that's where it must stop. I'm fine with Heroes of Newerth seeing what mods I installed, updating its files and so on but I don't want it to be able to access the browser's cache or anything else.
From my understanding of how this works, I'd be able to run each not-totally-trusted program as a separate user, giving them the read and write access to only the files they need.
Is this feasible (like, will I be able to still control volume and other per-user things?)? And will it add the kind of security I want?
Thank you in advance for your answers.
P.S.: I've already found this: Execution of possibly harmful program on Linux
But a virtual machine won't work for video games, I'm already doing the live CD thing but it's kind of annoying, the chroot thing seems overly complicated since I'd need to get the libraries etc. and the sandbox is just an upgraded chroot. And he says using users is useless because the files can be accessed if you don't set the proper rights. But I can just remove read access to anyone but me, can't I?

A: Running programs with uid different from the one that owns your data files provides some additional security - the applications shouldn't be able to access the data (or at least to write them if the alternative user is in the same group and you are using umask 0022). On the other hand it's very unlikely to shield you from local exploits - generally you want the alternative user to have a very similar set of rights to your main account. Hence it will be able to attack the system in similar fashion as if it were run with your main uid. If you want it to access your files you basically want to run it under your account.
As far as applications with X11 GUI are concerned, you have to give them access to your X server - which they can misuse. To be safe, you'd have to run those under a separate (e.g. nested) X server.
Using alternative user really won't give you much security (as is also mentioned in the question you are mentioning).
That said, while being paranoid doesn't mean they're not after you, are you sure that your system is the weakest link? You are mentioning emails - are you really in full control of the actual mail accounts? Are these kept on a highly secured server to which only you know the passwords, that is running only a fully patched mail server and kernel, and using only SSL/TLS secured protocols for transferring data to your machine? Have you reviewed the actual implementation of both client and server side of the SSL/TLS libraries? Are you sure your mail client is not spying on you (or at least that it is free of security holes). Your OS and kernel? Your UEFI? Your keyboard? The mail server's UEFI? (I'm intentionally omitting BIOS, since that is as insecure as it can get when it comes to booting.)
On the other hand, do you have a reason to believe that Waterloo Maple or Wolfram Research are putting backdoors into their software? If you are afraid these applications are remotely exploitable, just cut them off from network and that's it.


text:
Q: Remove item by text from QStandardItemModel in QT How can I remove an item with text "something" from a QStandardItemModel that filled with QStandardItem items and shown in a QListView in pyqt.
I made my QStandardItemModel like code shown below:
item = QtGui.QStandardItem("something")
QStandardItemModel.appendRow(item)

A: You will first need to find the items with the matching text, and then remove them from the model:
model = listview.model()
for item in model.findItems('something'):
    model.removeRow(item.row())

A: I believe the solution given only works when findItems returns a single item.
Otherwise the first call to removeRow will invalidate the next items...


text:
Q: Multiple embedded AND in the Where part of a Select in PostgreSQL I use PostgreSQL 10 and I have the following table.
id  name   place
1    20     56
2    21     51
3    21     53
4    21     54

the select I want to do is something like
select id from mytable where place = 51 and place=53 and place=54 and name = 21
I have to end up with id 2 3 4 but I can only use place and name .
I also tried select id from mytable where (place = 51 and name = 21) and (place=53 and name = 21) and (place=54 and name = 21)
but I keep getting an empty set of results.
How can I syntax that?
Thank you

A: Try this
SELECT id
FROM my_table
WHERE place IN (51,53,54) AND name = 21

A: The reason you get empty results is because you have no records where place equals both 51 and 53. Obviously place can only be one value per record.
I assume you are trying to return any results that match any of your criteria? For that try this:
SELECT id FROM mytable WHERE place IN (51, 53, 54) OR name IN (21);

If you want to exclude any results where name is not 21 then use AND instead.
SELECT id FROM mytable WHERE place IN (51, 53, 54) AND name = 21;

OR means return records if it matches either 'condition a' or 'condition b'.
AND means return record only if it matchs 'condition a' AND (as well as) 'condition b'
IN means return record if it matches any of the values IN the list.


text:
Q: Don't close CSS popup when clicking on it I am trying to add a form within a popup, but whenever you click the text box in the popup it closes and you cant type in the text box, is there a way to disable click to close? and only have it so clicking out the pop up it closes rather than within the pop up. I have tried to change the CSS of the myPopup and added 'pointer-events:none' but that disables click to all components within the popup.

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}
/* Popup container - can be anything you want */

.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */

.popup .popuptext {
  visibility: hidden;
  width: 180px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
  height: 200px;
}

/* Popup arrow */

.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */

.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */

@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

Popup

Click me to toggle the popup!
    <input type="text" id="fname" name="fname">

<button>
<button>

A: It's because your entire div and anything that's contained within it is being triggered by the onclick. Create a button with the onclick function and use that to power the opening and closing of the popup.
Also, consider using an eventListener instead of the inline onclick as that's generally discouraged.
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
Which could be written as:
const element = document.getElementById("myBtn");
element.addEventListener("click", function() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
});

// When the user clicks on div, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
/* Popup container - can be anything you want */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */
.popup .popuptext {
  visibility: hidden;
  width: 180px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
  height: 200px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

Popup

    <input type="text" id="fname" name="fname">

    <button onclick="myFunction()">
    Click me to toggle the popup!
    </button>


text:
Q: Does it make sense to use `logit` or `softplus` loss for binary classification problem? With $z$ is the logit, $p \in \{1, 0\}$ is the class. Usually binary classification problem use sigmoid and cross-entropy to compute loss:
$$\mathcal{L_1} = - \sum{p \log \sigma(z) + (1-p) \log (1-\sigma(z))}$$
Now suppose we scaled $y = 2p - 1 \in \{1, -1\}$.
Can we just directly push logit up when class is 1 and down when class is -1 with this loss?
$$\mathcal{L_2} = - \sum{y z}$$
I have seen some code use softplus like this:
$$\mathcal{L_3} = \sum{\log(1 + e^{-y z})}$$
Does it make sense to use these "simpler" losses? Is there any mathematical reasons against using them?
Could you point me to any source (paper, book, blog...) using these "simpler" losses?

A: The loss function measures some "goodness" or "fitness" of the model to the data. Moreover, in the context of optimization by gradient descent, the loss function must provide gradient information for the optimizer. The gradients must also be stable and informative, that is, they are not exploding, vanishing, or saturating.
From a statistical learning point of view, loss function could be built by the principle of maximum likelihood estimation (MLE), resulting in negative log-likelihood loss (NLL), which is equivalent to cross-entropy loss. The specific form of the loss function depends on the modeling of the predicted probability. For classification, the probability is modeled by sigmoid function, resulting in the form $\mathcal{L_1} $.
Directly pushing logits up and down with an unbounded loss function like $\mathcal{L_2} $ is bad, because there is no stopping threshold in optimizing, a right prediction still affects the loss the same way as a  wrong prediction. On contrary, in the softplus loss $\mathcal{L_3} $, already right predictions will contribute less to the loss compared to wrong predictions.
$\mathcal{L_3} $ is actually equivalent to $\mathcal{L_1} $. The first hint is their gradients regarding the score are the same, thus their optimization dynamics are the same. In fact, one can expand their formulas and derive one from another.


text:
Q: Issue with HTML5 Drag and Drop I am a bit new to javascript/web programming  and I've been having some issues that should probably have simple solutions but that I am having an extreme amount of trouble with. I basically just want to drag text from a cell in one table to a cell in another table. My questions are as follows:
I cannot seem to make anything but an (a href) type link drag and drop. If I try to set the draggable=true option on a div it remains undraggable (in firefox). In my searches, I haven't really seen any fixes for firefox ( i have added css rules for webkit, however).
To work around this, I was trying to drag an (a href) -apologies for parentheses, there is a limit on the amount of link tags i can use - item from one table's cell to a text input field in another table's cell and its default action is to just drag the link. What I'd like it to drag would be the contents of the tag (e.g. for  Some Text  I'd like it to return "Some Text" or "draggable" or any other customizable text). I have tried handling this in the ondragstart/ondrop events through e.datatransfer.setData("Text", "My Custom Text") and e.datatransfer.getData("Text") however I still receive the same results. Would anybody have any suggestions for this? I have been looking at this for a while and cannot figure it out at all.
Thank you very much in advance for your help.
EDIT: I do not have access to the computer I was using atm but I'll try to get the basic gist of what I was doing across..
onDrop(e){ //onDrop is assigned to the drophandler of a text input field
    var text = e.dataTransfer.getData('Text');
    this.Text = text;
    e.preventDefault();
}
onDragOver(e){
    e.preventDefault();
}
onDragStart(e){
    e.dataTransfer.setData('Text', 'My String');
}
....

    Text Content

    <input ondrop="onDrop(e)" type="text" />

A: Here's a complete code sample I did that works, based on your skeleton above:

        <title>drag and drop example</title>

                    Text Content

                            <input id="destination" ondragover="onDragOver(event)" ondrop="onDrop(event)" type="text" />

Several things to note:

*

*The format you pass to setData and getData needs to be "text/plain" not "Text" (see: http://dev.w3.org/html5/spec/dnd.html#dom-datatransfer-getdata)

*You needed to actually call OnDragOver and OnDragStart (perhaps this was just missing from the sample you added from memory)

*It would be good to give your input element an ID, as I did, so you can change the value to the dragged item

*To read more about this topic, I wrote a blog you may find helpful: A Drag and Drop Planning Board with HTML5


text:
Q: Java - generate class diagram by myself I am working on a small project in Java described below:
Input:  List of objects for directed graph. ( Nodes with different kind of edges: inheritance, inner-class, friend classes,  etc. )
Output: class diagram, as planar as possible.
My problem is:
I would like to have some 3rd party software that will do it for me or at least have an algorithm of selecting nodes and edges to keep my graph as planar as possible.
EDIT:
I see I may not have written clearly what I want... I don't want to generate class diagram based on Java project with its files, but I am parsing C++ file and get from there list described in above input. Then I want to call some function on that list and get my diagram. I was trying to use JGraph or JGraphT but I unfortunately didn't find any graph-theory functionality which suit my requirements.
Regards,
Daniel

A: If you use Eclipse IDE you can use Soyatec's eUML2 free plugin. Have a look here.


text:
Q: jQuery XML/RSS Scrape Problems I'm using this script to scrape from an rss feed to view on another website:
$.ajax({
    url: "http://www.thriveafricastore.com/rss.php?type=rss",
    type: "GET",
    success: function(d) {
            $('item', d).each(function() {
                var $item = $(this);
                var title = $item.find('title').text();
                var link = $item.find('link').text();
                var description = $item.find('description').text();
                var image = $(description).find('img').attr('src');
                var price = $(description).find('span.SalePrice').text();

                if (price == '') {price = 'See Price'};

            var html = '

';
                html += ''+title+'
';
                html += price+'
';

                $('#store').append($(html));

            });

    }
});

It works locally on my computer but when I try and use it on the live site online it doesn't work and doesn't throw any errors (or at least none that I can find). Any ideas on what I could be doing wrong and how I can get it to work?
Thanks!

A: Pretty sure you're running into problems with the same origin policy, which prohibits client-side data retrieval across domains in many cases (see http://en.wikipedia.org/wiki/Same_origin_policy and http://api.jquery.com/jQuery.ajax/)
Not sure what server-side language you're using (if any), but you may want to set up a server-side script that retrieves the file on your server, prints out its content, and then in turn load that script in your JS. In PHP, this would look something like the following:
<?php

header('Content-Type: text/xml');
$ch = curl_init('http://www.thriveafricastore.com/rss.php?type=rss');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch);

?>

After you've done that, replace the URL in your request with the location of your server-side script (for example, fetcher.php).


text:
Q: Using gamepad-api via events, rather than polling I am building a chrome extension that would enable the use of my 3d-mouse (made by 3d connexion) to scroll web pages. The built-in 3d connexion drivers are worthless, and the 3d mouse presents itself as a 2 button, 6 axis gamepad to the OS.
The implementation is currently working using the below method:
function get3DMouseData() {
    if (document.hasFocus()) {
        var gp = navigator.getGamepads()[0]
        // axis 5 controls scroll speed
        if (gp.axes[5]) window.scrollBy(0,Math.round(gp.axes[5]*10)*10)
    }
}

interval = this.setInterval(get3DMouseData, 50)

It doesn't seem to be the smartest strategy to run get3DMouseData 20 times por second, and an event-based implementation would probably be more efficient.

*

*Is there an event-based methods for the gamepad-api that I can use in the case above?

*This implementation does not work properly in certain sites (like gmail). What I am doing wrong?

A: There is no such events:

Other events:
More discussion needed, on whether to include or exclude axis and
button changed events, and whether to roll them more together
("gamepadchanged"?), separate somewhat ("gamepadaxischanged"?), or
separate by individual axis and button.

Also it is said that proper polling is a best practice:

Best Practice 1: Coordination with requestAnimationFrame() Interactive
applications will typically be using the requestAnimationFrame()
method to drive animation, and will want coordinate animation with
user gamepad input. As such, the gamepad data should be polled as
closely as possible to immediately before the animation callbacks are
executed, and with frequency matching that of the animation. That is,
if the animation callbacks are running at 60Hz, the gamepad inputs
should also be sampled at that rate.

Regarding gmail: I guess that it is due restriction policy set on that site:

This specification defines a policy-controlled feature identified by
the string "gamepad". Its default allowlist is 'self'.

'self'
The feature is allowed in documents in top-level browsing contexts by default, and when allowed, is allowed by default to same-origin domain documents in child browsing contexts, but is disallowed by default in cross-origin documents in child browsing contexts.

https://www.w3.org/TR/gamepad/


text:
Q: Fetching results from more than one IRepository I have a list of Users and Orders.
public class UserRecord
{
    public virtual int UserId { get; set; }
    public virtual string Name { get; set; }
}

public class OrderRecord
{
    public virtual int UserId { get; set; }
    public virtual int OrderId { get; set; }
}

I have two repositories - IRepository and IRepository. How can I join the two and fetch the result, like this?
SELECT UserRecord.UserId, Name, OrderId
FROM UserRecord, OrderRecord
WHERE UserRecord.UserId = OrderRecord.UserId
Thanks.

A: Use the HQL API that is on ContentManager instead. Repository is for simple CRUD operations on a single table.


text:
Q: $f:\mathbb{R}\rightarrow\mathbb{R}$ continuous function with $x^2\leq f(x)$ $\forall x\in \mathbb{R}$. Show that f takes on its absolute minima. I am preparing for my exam and need help with the following task:
Let $f:\mathbb{R}\rightarrow\mathbb{R}$ be a continuous function with the estimation $x^2\leq f(x)$ $\forall x\in \mathbb{R}$. Show that f takes on its absolute minima.
If a function is continuous, then $\lim\limits_{x \rightarrow a}{f(x)}$=$f(a)$.
Our function has an absolute minima in $x_0$ $\in \mathbb{R}$, if $f(x)\geq f(x_0)$ for $x\in \mathbb{R}$.
At first I thought the task is pretty easy. We learned how to prove that if $f:[a,b]\to\mathbb{R}$ is continuous, then f has an absolute maxima and an absolute Minima in [a,b]. The Problem here is, that the domain of our function here is unbounded. Thats why I don't have any idea what I could and should use for the proof. We should probably use the estimation $x^2\leq f(x)$ $\forall x\in\mathbb{R}$. This gives us the information, that $f$ is bounded from below with $f(x)\geq 0$ $\forall x\in \mathbb{R}$. But how does this help me? And what else do we have?
Is there anyone who could give an advice? I would be very grateful.

A: Let $a =f(0) \geq 0$. Then, if $|x|\geq \sqrt{a}$, we have :
$$f(x) \ge x^2 \geq a = f(0) \tag 1$$
As $[-\sqrt a, \sqrt a]$ is compact and $f$ is continuous on it, there is some $x_0 \in [-\sqrt a, \sqrt a]$, such that :
$$f(x_0) = \min_{[-\sqrt a, \sqrt a]} f$$
Clearly,  $f(x_0)\leq f(0)$. Therefore by $(1)$, we have :
$$f(x_0) = \min_{\mathbb R}f$$

A: Since $\lim_{x\to\infty}x^2=\infty$, there is some $M>0$ such that $x\geqslant M\implies x^2>f(0)$, and therefore $x\geqslant M\implies f(x)>f(0)$. And, for the same reason, there is some $N<0$ such that $x\leqslant N\implies f(x)>f(0)$. The restriction of $f$ to $[N,M]$ has a minimum, which is attained at some $x_0\in[N,M]$ and, since $0\in[N,M]$, $f(0)\geqslant f(x_0)$. So, $f$ attains its absolute minimum at $x_0$. In fact, if $x\in\Bbb R$, then either $x$ belongs to $[N,M]$ or it doesn't. If it doesnt, then $f(x)\geqslant f(0)\geqslant f(x_0)$; if it does, then $f(x)\geqslant f(x_0)$.

A: You can prove the claim by contradiction invoking the Bolzano-Weierstrass theorem.
Because of the condition $x^2\leq f(x)$ we know that it exists
$$m := \inf_{x\in\mathbb{R}}f(x) \geq 0$$
Now, assume that the infimum is not a minimum. Then, for each $n\in\mathbb{N}$ you find an $x_n\in\mathbb{R}$ such that
$$m < f(x_n) < m+\frac 1n$$
Because of Bolzano-Weierstrass, the sequence $(x_n)$ must be unbounded. Otherwise this sequence would have a convergent subsequence and the continuity of $f$ would enforce the infimum to be attained.
So, there is an $N \in\mathbb{N}$ such that
$$\color{blue}{m+2 <} x_N^2 \leq f(x_N) < m+ \frac 1N \leq \color{blue}{m + 1 } \color{blue}{\text{  Contradiction!}}$$


text:
Q: Laravel Storage::download File not found at path I'm trying to download files (rapports) I've uploaded but I'm getting a File not found at path error although the path is defined and seems correct. I've already created the symbolic link with the php artisan storage:link command.
Here is how I'm storing the rapports
$rapport = new Rapport;
        $rapport->themeRapport = $request->input('themeRapport');
        $rapport->resume = $request->input('resume');
        $rapport->auteur = $request->input('auteur');
        $rapport->encadrant = $request->input('encadrant');
        $rapport->cycle = $request->input('cycle');
        $rapport->filiere = $request->input('filiere');

        $fichierRapport = $request->file('fichierRapport');
        $fichierRapportName = $request->input('themeRapport') .'.'. $fichierRapport->getClientOriginalExtension();
        $path = $fichierRapport->storeAs('rapports', $fichierRapportName);

     $rapport->fichierRapport = $fichierRapportName;
     $rapport->save();

So here is the rapports table structure
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRapportsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rapports', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('themeRapport');
            $table->string('resume');
            $table->string('auteur');
            $table->string('encadrant');
            $table->string('cycle');
            $table->string('filiere');
            $table->string('fichierRapport'); // File name of the uploaded file
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('rapports');
    }
}

The uploaded files go then to storage/app/public/rapports newly created directory as I set the public disk as the default one.
config/filesystems.php file
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'public'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

];

In order to download, I've tried this :
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Rapport;
use Illuminate\Support\Facades\Storage;

class downloadRapport extends Controller
{

    public function download($id){
        $rapport = Rapport::findOrFail($id);
        $url = Storage::url($rapport->fichierRapport);
        return Storage::download($url, $rapport->fichierRapport);
    }
}

which is getting me this error : File not found at path: http:/localhost/storage/filename
I tried also this
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Rapport;
use Illuminate\Support\Facades\Storage;

class downloadRapport extends Controller
{

    public function download($id){
        $rapport = Rapport::findOrFail($id);
        $url = Storage::disk('public')->url($rapport->fichierRapport);
        return Storage::download($url, $rapport->fichierRapport);
    }
}

I'm getting the same error : File not found at path: http:/localhost/storage/filename
I then tried the following, as files are uploaded in a new created directory rapports
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Rapport;
use Illuminate\Support\Facades\Storage;

class downloadRapport extends Controller
{

    public function download($id){
        $rapport = Rapport::findOrFail($id);
        $url = Storage::disk('public')->url('rapports/'.$rapport->fichierRapport);
        return Storage::download($url, $rapport->fichierRapport);
    }
}

Error : File not found at path: http:/localhost/storage/rapports/filename.
To get the full path, as I found out here, I tried this
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Rapport;
use Illuminate\Support\Facades\Storage;

class downloadRapport extends Controller
{

    public function download($id){
        $rapport = Rapport::findOrFail($id);
        $url = Storage::disk('public')->path('rapports/'.$rapport->fichierRapport);

        return Storage::download($url, $rapport->fichierRapport);
    }
}

error : File not found at path: C:/xampp/htdocs/MonProjet/storage/app/public/rapports/filename
This full path is although where the files are actually located
What can be wrong with the code..? Am I missing something there? It's the first time for me to manipulate files in Laravel, your help would be very appreciated

A: You can simply run the below command:
php artisan storage:link

Your files will shown in root/public/storage/your_folder
You can just write a href to that file.
File Name


text:
Q: Help identify missing component USB power Can anyone help identify the component that is missing from this circuit board? The board is the main controller board for a music keyboard. The keyboard is meant to be able to be powered over USB but due to the missing component (presumably) this doesn't work. The keyboard can also be powered via a separate DC jack, which takes power from a 9V 200mA DC adapter (this does work).
Below is an image of part of the mainboard, the USB connector is centre-bottom. Just above that is the missing component, marked L19. The bottom pad of this is connected to the +5V pin on the USB connector. To the right of the USB connector is the DC jack.
Next to the missing L19 are two components labelled L20 and L21 - I presume these are the same as the missing component, but I don't know what they are. A larger image of these is below.
I have contacted the manufacturer but they won't tell me what the component is, so I'm hoping someone here might be able to help me.

A: The missing component is a ferrite bead. Without a schematic, service manual or bill of materials, we can't possibly know the exact type of component is, and thus the current rating and impedance are unknown, and we can't suggest a replacement.
However, given that we know it only used to filter USB 5V power, feel free to put almost any ferrite bead there that is rated for 1A-2A and does not drop too much voltage. Or just put a 0R resistor, blob of solder, or a piece wire there to bypass it.
Just check first with a multimeter that there is no short circuit if the ferrite bead acted as a fuse and blew itself to pieces. However there is no sign of that, the damage looks purely mechanical, no blown component residue anywhere.

A: You can verify your hypothesis by desoldering L20 (and/or L21) and use LC-meter/component-identifier to identify it (there are cheap ones like this LCR-T4 tester, for example) and buy replacement ones at local electronics components store. If you desolder both, you can compare if they are indeed the same (note that trying to test them while connected to the rest of the board usually won't give correct results)
L is usual marking for inductor, so as Justme said, it is probably ferrite bead used to filter EMI noise.
Also take note of how this element was lost? If it was mechanical incident where it was chipped of, then it is OK to just replace; but if it has blown due to electrical problem, there might be underlying issue causing it to blow again.


text:
Q: Login always fails in my Sql based visual basic simple login application I tried to create a login page in VISUAL BASIC. But the problem is that the login always fails . My program is connected to my sql database and though my password and username is correct through text boxes the output is always login fail!! and I don't know where is screwed up .
Imports System.Data.SqlClient
Public Class login
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim connection1 As New SqlConnection With {.ConnectionString = "Server = VAIOO-PC ; Database = forum ; Integrated Security= true "}
        Dim sqlcommand As New SqlCommand(" Select * from username where username= @username and password =@password", connection1)
        sqlcommand.Parameters.Add("@username", SqlDbType.VarChar).Value = textboxuser.Text
        sqlcommand.Parameters.Add("@password", SqlDbType.VarChar).Value = textboxpassword.Text

        Dim sqldtaadpt As New SqlDataAdapter(sqlcommand) 'passes the command to via the adapter

        Dim table As New DataTable()
        If table.Rows.Count() <= 0 Then
            MsgBox("USERNAME or THE PASSWORD IS INCORRECT")
        Else
            MsgBox("login successful")
        End If

    End Sub
End Class

A: You forgot to fill the datatable.
Use Fill method of DataAdapter.
sqlcommand.Open()
sqldtaadpt.Fill(table)

To get a full example, look at SqlCommand class help.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx