text:
Q: 2020: To quickly and efficiently play an external audio track in sync with a video? To quickly and efficiently play an external audio track in sync with a video?
How to play a video with a different audio track?
https://superuser.com/a/1077106/183467
Tried this, but the last step from:
https://wiki.videolan.org/VLC_HowTo/Play_an_external_audio_track_for_a_video/
does not show up:

Go to Audio -> Audio track -> Track 2.

(If you have more than one track available, pick the one that corresponds to the desired audio overlay.)
This is not working anymore, is too cumbersome and out of date and we would like a simpler cleaner faster method.
PS: OS - Win 8.1 x64

A:
This [VLC solution] is not working anymore[.]

Testing a standard .mp4 and .mp3 file with the current build of VLC 3.0.11 (June 2020) on Windows 7, Track 2 was displayed as an option to hear an external audio file along with the video file playing in VLC, as indicated in the relevant links in your original question.
Also note that the answer in the first link that describes the Track 2 method was apparently conducted successfully under Windows 10. So this method appears to still work, at least in certain cases.

We would like a simpler, cleaner, faster method.

You may want to have a look at MPV then rather than VLC.

*

*The download page for MPV is here, including unofficial binaries for Windows.

*An official online reference manual (HTML) is available, as well as an unofficial PDF version.

Anecdotally, the unofficial Windows builds by shinchiro work well enough and are probably the ones I would generally recommend. Just download the latest version of MPV as a .7z (7-Zip) archive from either the 32bit or 64bit directories on Sourceforge.

Example
Assuming you used a shinchiro build (above), simply extract the .7z archive to wherever you want MPV to live. You can then run ex:
C:\path\to\mpv.exe video.ext -audio-file audio.ext

to play a video file and audio file in sync, with the audio file replacing the audio track of the video during playback.
If you add mpv.exe to your Windows Path, you can shorten this to ex.:
mpv video.ext -audio-file audio.ext

Note that video.ext and audio.ext are the paths to your video and audio files, respectively. Full paths that contain spaces need to be surrounded with double-quotes (""), whether this is the path to mpv.exe, video.ext or audio.ext.

Will we have to resort to command line instead of GUI?

If you check the Wikipedia page for MPV, there are a number of players that are based around MPV/MPlayer (of which MPV is technically a fork), but there are only two (that I am aware of) which potentially support "easy" methods of combining video and audio via their GUIs. These are SMPlayer and Baka MPlayer.

Unfortunately, at the time of this writing, the current version of SMPlayer wasn't working correctly for me (but your experiences may vary).

Baka MPlayer
Using Baka MPlayer to play an external audio file over a video is similar to using VLC but with (slightly) fewer steps. After you download Baka MPlayer and extract the archive:

*

*Open a video file with Baka Mplayer.exe.

*Playback will begin immediately. Pause the video and rewind it to the beginning. Note that Space will toggle video playback and holding the right-arrow key ◄ will rewind the video quickly. You can, of course, use the Pause (||) and/or Rewind (|◄) controls in the GUI as well.

*To add an external audio file to play over the video, open  Playback → Audio Tracks → Add File...:
ex. Loading An External Audio File

*Select the external audio file from the standard Widows file selection dialog that appears.

*You should then be able press Space or Play (►) in the GUI to begin playing the video file with the external audio track (it will be selected automatically).
Notes

*

*SMPlayer should have a similar menu option to Step 3 above (though not an exact duplicate, obviously).

*Baka MPlayer is old. Though its GitHub page apparently isn't entirely dead, it hasn't been updated since 2015. Not exactly a drawback per se (plenty of older Windows programs work fine on modern systems) but if you encounter any issues with it, it seems unlikely they will be fixed anytime soon.


text:
Q: Reading line by line and assigning to array in C I want to read below lines in input.txt file in C program and assign it to variables.
 (1,3) (4,8)
 (3,6) (3,10)
 (2,6) (4,56)

...it has to read more than 100 lines and draw lines with 4 values in each line.
I was using fgets and sscanf, but I am not able to get the value and below was my code.
static const char filename[] = "src/input.txt";
FILE *file = fopen ( filename, "r" );

if ( file != NULL )
{
    char line [ 128 ];
    int i,j,k,l=-1;

    while ( fgets ( line, sizeof line, file ) != NULL )
    {
        fputs ( line, stdout ); /* write a line */
        sscanf (line,"%d" "%d" "%d" "%d", i,j, k,l);
    }
    fclose ( file );
}

A: In scanf replace i, j, k,l with addresses &i, &j,&k,&l

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I Search/Find and Replace in a standard string? How do I replace all occurrences of a substring with another string, for std::strings?
std::string s ("One hello, two hellos.");
s = s.replace("hello", "world");  // something like this

A: Why not implement your own replace?
void myReplace(std::string& str,
               const std::string& oldStr,
               const std::string& newStr)
{
  std::string::size_type pos = 0u;
  while((pos = str.find(oldStr, pos)) != std::string::npos){
     str.replace(pos, oldStr.length(), newStr);
     pos += newStr.length();
  }
}

A: My templatized inline in-place find-and-replace:
template<class T>
int inline findAndReplace(T& source, const T& find, const T& replace)
{
    int num=0;
    typename T::size_t fLen = find.size();
    typename T::size_t rLen = replace.size();
    for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
        num++;
        source.replace(pos, fLen, replace);
    }
    return num;
}

It returns a count of the number of items substituted (for use if you want to successively run this, etc). To use it:
std::string str = "one two three";
int n = findAndReplace(str, "one", "1");

A: In C++11, you can do this as a one-liner with a call to regex_replace:
#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:
Removeallspaces

A: Performant O(n) replace all
Many other answers repeatedly call std::string::replace, which requires the string to be overwritten repeatedly, which results in poor performance. In contrast, this uses a std::string buffer so that each character of the string is only traversed once:
void replace_all(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::string buf;
    std::size_t pos = 0;
    std::size_t prevPos;

    // Reserves rough estimate of final size of string.
    buf.reserve(s.size());

    while (true) {
        prevPos = pos;
        pos = s.find(toReplace, pos);
        if (pos == std::string::npos)
            break;
        buf.append(s, prevPos, pos - prevPos);
        buf += replaceWith;
        pos += toReplace.size();
    }

    buf.append(s, prevPos, s.size() - prevPos);
    s.swap(buf);
}

Usage:
replace_all(s, "text to replace", "new text");

Full example:
#include <iostream>

void replace_all(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::string buf;
    std::size_t pos = 0;
    std::size_t prevPos;

    // Reserves rough estimate of final size of string.
    buf.reserve(s.size());

    while (true) {
        prevPos = pos;
        pos = s.find(toReplace, pos);
        if (pos == std::string::npos)
            break;
        buf.append(s, prevPos, pos - prevPos);
        buf += replaceWith;
        pos += toReplace.size();
    }

    buf.append(s, prevPos, s.size() - prevPos);
    s.swap(buf);
}

int main() {
    std::string s("hello hello, mademoiselle!");
    replace_all(s, "hello", "bye");
    std::cout << s << std::endl;
}

Output:
bye bye, mademoiselle!

Note: Previous versions of this answer used std::ostringstream, which has some overhead. The latest version uses std::string::append instead, as recommended by @LouisGo.

A: The easiest way (offering something near what you wrote) is to use Boost.Regex, specifically regex_replace.
std::string has built in find() and replace() methods, but they are more cumbersome to work with as they require dealing with indices and string lengths.

A: I believe this would work.
It takes const char*'s as a parameter.
//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
   //ASSERT(find != NULL);
   //ASSERT(replace != NULL);
   size_t findLen = strlen(find);
   size_t replaceLen = strlen(replace);
   size_t pos = 0;

   //search for the next occurrence of find within source
   while ((pos = source.find(find, pos)) != std::string::npos)
   {
      //replace the found string with the replacement
      source.replace( pos, findLen, replace );

      //the next line keeps you from searching your replace string,
      //so your could replace "hello" with "hello world"
      //and not have it blow chunks.
      pos += replaceLen;
   }
}

A: #include <string>

using std::string;

void myReplace(string& str,
               const string& oldStr,
               const string& newStr) {
  if (oldStr.empty()) {
    return;
  }

  for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;) {
    str.replace(pos, oldStr.length(), newStr);
    pos += newStr.length();
  }
}

The check for oldStr being empty is important. If for whatever reason that parameter is empty you will get stuck in an infinite loop.
But yeah use the tried and tested C++11 or Boost solution if you can.

A: Why not return a modified string?
std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: "
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: "
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
          << input << std::endl;

Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

A: Using boost::replace_all:
#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");

A: // Replace all occurrences of searchStr in str with replacer
// Each match is replaced only once to prevent an infinite loop
// The algorithm iterates once over the input and only concatenates
// to the output, so it should be reasonably efficient
std::string replace(const std::string& str, const std::string& searchStr,
    const std::string& replacer)
{
    // Prevent an infinite loop if the input is empty
    if (searchStr == "") {
        return str;
    }

    std::string result = "";
    size_t pos = 0;
    size_t pos2 = str.find(searchStr, pos);

    while (pos2 != std::string::npos) {
        result += str.substr(pos, pos2-pos) + replacer;
        pos = pos2 + searchStr.length();
        pos2 = str.find(searchStr, pos);
    }

    result += str.substr(pos, str.length()-pos);
    return result;
}


text:
Q: Forwarding DNS to Cloudflare's DNS-over-TLS via CoreDNS I'm using this Docker image as an example to try to setup secure DNS forwarding over TLS to CloudFlare's resolvers. I'm using CoreDNS 1.5.0 (latest) and my config is this:
# CoreDNS Configuration

.:53 {
  forward . tls://1.1.1.1 tls://1.0.0.1 {
    tls_servername tls.cloudflare-dns.com
    policy sequential
    health_check 5s
  }

  log
}

I'm making requests like so:
root@8ef125545369:/# dig @127.0.0.1 google.com

; <<>> DiG 9.11.3-1ubuntu1.5-Ubuntu <<>> @127.0.0.1 google.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 49802
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: 090b0d7fadcdd8bb (echoed)
;; QUESTION SECTION:
;google.com.                    IN      A

;; Query time: 24 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Apr 08 19:29:30 UTC 2019
;; MSG SIZE  rcvd: 51

I'm not getting answers. The CoreDNS logs look like this:
missioncontrol    | 2019-04-08T19:29:30.778Z [INFO] 127.0.0.1:39615 - 49802 "A IN google.com. udp 51 false 4096" NOERROR - 0 5.02365452s
missioncontrol    | 2019-04-08T19:29:35.759Z [INFO] 127.0.0.1:39615 - 49802 "A IN google.com. udp 51 false 4096" NOERROR - 0 5.00549558s

It's clear that CoreDNS is getting the requests, but I can't determine why this is failing. My image is ubuntu:bionic and ca-certificates is installed. I can also use openssl s_client to connect to 1.1.1.1:443 without issues.
Is there something I'm missing to setup DNS-over-TLS forwarding from CoreDNS to CloudFlare's resolvers?

EDIT
I've tested this on my host operating system outside of a Docker container and I'm seeing the same functionality, namely that it's not working.

A: I tested this again by running it in Travis CI, and it worked; apparently my corporate firewall does not like DNS-over-TLS.
I was able to validate this by installing knot-dnsutils (on Ubuntu 18.04) and trying to query Cloudflare directly:
$ kdig -d @1.0.0.1 +tls-ca +tls-host=cloudflare-dns.com google.com
;; DEBUG: Querying for owner(google.com.), class(1), type(1), server(1.0.0.1), port(853), protocol(TCP)
;; DEBUG: TLS, imported 133 system certificates
;; DEBUG: TLS, received certificate hierarchy:
;; DEBUG:  #1, C=US,ST=California,L=San Francisco,O=Cloudflare\, Inc.,CN=cloudflare-dns.com
;; DEBUG:      SHA-256 PIN: V6zes8hHBVwUECsHf7uV5xGM7dj3uMXIS9//7qC8+jU=
;; DEBUG:  #2, C=US,O=DigiCert Inc,CN=DigiCert ECC Secure Server CA
;; DEBUG:      SHA-256 PIN: PZXN3lRAy+8tBKk2Ox6F7jIlnzr2Yzmwqc3JnyfXoCw=
;; DEBUG: TLS, skipping certificate PIN check
;; DEBUG: TLS, The certificate is trusted.
;; WARNING: TLS, handshake failed (Error in the pull function.)

This is what happened when querying within the corporate network. From Travis CI, I saw:
;; DEBUG: Querying for owner(google.com.), class(1), type(1), server(1.1.1.1), port(853), protocol(TCP)
;; DEBUG: TLS, imported 133 system certificates
;; DEBUG: TLS, received certificate hierarchy:
;; DEBUG:  #1, C=US,ST=California,L=San Francisco,O=Cloudflare\, Inc.,CN=cloudflare-dns.com
;; DEBUG:      SHA-256 PIN: V6zes8hHBVwUECsHf7uV5xGM7dj3uMXIS9//7qC8+jU=
;; DEBUG:  #2, C=US,O=DigiCert Inc,CN=DigiCert ECC Secure Server CA
;; DEBUG:      SHA-256 PIN: PZXN3lRAy+8tBKk2Ox6F7jIlnzr2Yzmwqc3JnyfXoCw=
;; DEBUG: TLS, skipping certificate PIN check
;; DEBUG: TLS, The certificate is trusted.
;; TLS session (TLS1.2)-(ECDHE-ECDSA-SECP256R1)-(AES-256-GCM)
;; ->>HEADER<<- opcode: QUERY; status: NOERROR; id: 59442
;; Flags: qr rd ra; QUERY: 1; ANSWER: 1; AUTHORITY: 0; ADDITIONAL: 1
;; EDNS PSEUDOSECTION:
;; Version: 0; flags: ; UDP size: 1452 B; ext-rcode: NOERROR
;; PADDING: 69 B
;; QUESTION SECTION:
;; google.com.              IN  A
;; ANSWER SECTION:
google.com.             156 IN  A   172.217.5.14
;; Received 128 B
;; Time 2019-04-09 22:03:18 UTC
;; From 1.1.1.1@853(TCP) in 12.8 ms

Clearly the corporate firewall is blocking this access unfortunately.


text:
Q: How to exit (kill) the command cp I have this question: creating an at job that copies all files in your home directory to /var/tmp within half an hour. You may want to create a sub-directory in /var/tmp. A message will appear to indicate that the copying task is successfully done and I try to solve like this :
cp * /var/tmp/ | (try to kill cp )| at now + 30 minute

but I am steel I didn't find command that kill cp?
the question in book and i try to solve it . what i understand that copy all file in home to /var/tmp and if the copy file encroach 30 within half an hour then i should stop it copy

A: You could write a script, assuming you only have one cp command in the script, you could use $$ which returns the PID of the shell script, so ps -ef | grep $$ will return your script as well as the cp command, so ps -ef | grep -E "$$.*cp will return the PID of the cp command, then you simply do kill -15 <pid>. Here is a script that does it all, do NOT put "cp" in the name.
#!/bin/sh

cp -r .* /var/tmp/ &

#sleep 30 minutes then kill cp
sleep 1800 && kill -15 $(ps -ef | grep -E "$$.*cp " | awk '{print $2}') || echo "copy completed as kill failed"

This script you can schedule with at or cron.
You probably would like to do the following if you have to use at to kill the script, name this one myScript.sh:
#!/bin/sh

echo $$ > /tmp/myPID
cp -r .* /var/tmp/
rm /tmp/myPID

A second script named killerQueen.sh for at to kill the process after 30 minutes:
#!/bin/sh

if [ -f /tmp/myPID]; then
  kill -15 $(cat /tmp/myPID)
  echo "Copy not complete." > /tmp/message$$
else
  echo "Copy successful." > /tmp/message$$
fi

run the following:
$ myScript.sh&
Job 1
$ at -f ./killerQueen.sh now + 30 minute

This second example is safer, because we kill the script that performs the copy, if it is still running, else we create a file named /tmp/message<pid_of_killerQueen> with the text "copy succeeded".
EDIT, after reading man at and your comment:
cp -r * /var/tmp& echo "kill -15 \$(ps -ef | grep \"$$.*cp \" | grep -v grep | awk '{print $2}')" | at now + 1 second

A: Firs I would suggest you to use the rsync command to preserve unnecessary copy of unchanged files. Second you could push the rsync process into the background by using the command nohup. Then you can kill the process, using the PID of the job most recently placed into the background !$ (issued by the nohup command) at certain time:
#!/bin/bash
nohup rsync -arqvzh --ignore-errors "$HOME"/* "/var/tmp/" > /dev/null 2>&1 &
echo "kill -9 $!" | at now +30 minutes -M > /dev/null 2>&1

References:

*

*"kill <PID>" not really killing the process, why? | How do I kill processes in Ubuntu?

*How to run nohup and write its pid file in a single bash statement?

*How do I use the nohup command without getting nohup.out?

*How to let 'cp' command don't fire an error when source file does not exist?

*Run command at 5 seconds from now?

*GNU - Bash Reference Manual:Shell Parameters:Special Parameters

Alternatively you could use the timeout command - as @steeldriver have suggested - in this way:
timeout 1800 rsync -arqvzh --ignore-errors "$HOME"/* "/var/tmp/" &

Where:

*

*1800 is the duration of the timeout in seconds.

*& will push the process into the background, thus you could use the current shell.


text:
Q: Passing and accessing Powershell parameters from C# I am trying to pass parameters to Powershell script from a C# class. I am running the script using Process.Start.
string powerShellLocation = @"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe";
ProcessStartInfo psi = new ProcessStartInfo(powerShellLocation);
psi.Arguments = String.Format("{0} {1}", scriptPath, "some_parameter");

The above does not work. Can someone please tell me how to achieve this?

A: You need to set the parameter name. Something like this should work:
string parameters = string.Format("-FILE {0} -parameter1 \"{1}\"", psFilePath, parameter1Value);
Process powershell = new Process()
{
     StartInfo = new ProcessStartInfo("powershell.exe", parameters)
      {
           UseShellExecute = false,
           RedirectStandardOutput = true,
           RedirectStandardError = true
      }
};

A: What you have would work. You have not mentioned what you meant by above does not work and what your script is.
I tried the C# code with the Powershell script:
param([string]$a)

write-host "test"
write-host $a

and it gave the output:
test
some_parameter

as expected. There is no need to specify -File and -paramter1 like the other answer mentions, but will depend on what your script does.

A: Did you set the execution policy to unrestricted or to something that allows you to execute the script. By default Powershell sets scripts to be unrestricted to prevent malicious scripts from running.
Run this command as an administrator when powershell is running:
Get-ExecutionPolicy


text:
Q: Firemonkey TMemo OnChangeTracking strange behavior on Android Does any one had same issue, then on run time created TMemo fires OnChangeTracking only then TMemo is empty (no lines) and only for the first entered symbol. And also then all text is deleted?
If TMemo is created in design time it works as it should.
This behavior is only on Android. iOs and Winows is ok.
Is it a Delphi bug, or maybe there is something I can fix? I use Delphi 10.3 Update 1 at the moment, don't know if problem ocurs on 10.3.3
Here goes a litle video:
https://photos.app.goo.gl/NE4Gd9qkMVMKAnoe9


text:
Q: What trick can I use to apply LIMIT for a multiple fetch? I don't know if I can do what I expect but hey, at least I can ask you guys...
Here's the thing : I'm building a website with some calendars, and we can add some "dates / rendez vous" on them. For some purpose, I want to get the futur (or actual) closest rendez-vous of each calendars.
I'd like to do it with one query instead of using a loop with one query on each iteration (ie for each calendar), and I want to get only ONE rendez-vous for each calendar and not all the futur ones (which could be... a lot).
So far, I started like that :
SELECT p_id, p_cid, p_start, p_end FROM p WHERE p_end >= :date_of_today

I was thinking about using LIMIT, but I can't see how to put a LIMIT (like 0,1 for each calendar)...
I guess I will have to use a loop but if someone could give me an other solution :)
EDIT
With more informations :
I have a table for calendars, which is like c_id, c_title, c_owner, and a table for the rendez-vous, which is like p_id, p_cid, p_uid, p_start, p_end.
The rendez-vous can last more than one day. To be more specific, a "rendez-vous" is at least a day : so p_start and p_end are a date/timestamp like dd-mm-yyyy 00:00:00. They can be equal as they can be two differents days.


text:
Q: dygraphs fails on IE8 when options are used The following HTML does not display a graph on IE8. Works fine on Firefox, Chrome, and IE9 and IE10. On IE8 all I can see are the captions (the dates) and "Barometric Pressure".
dygraph-combined.js is the current version. First six lines are as recommended. If you take the width option out, it works.
Just to make life more interesting, if I replaced width by ylabel:'millibars' it doesn't display the label. Gawds I hate IE.
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">

<title>Real-Time Hydrologic System</title>


text:
Q: What would be the sending and Receiving servers i need to configure? I have company mailid somthing like myname@company.com ,the company is someother palce (offsite),i have a mail client ie Thunderbird for linux ,when i try to create an mail account it is aasking for sending server(SMTP) name and receiving server (POP3) names.
What would be the sending and Receiving servers i need to configure ?

A: I think this is a question for your company's IT team.  You can discover SMTP servers using:
nslookup --query=MX mycompanydomain.com
I'm assuming you're on Linux, so check that syntax as my memory's a little iffy on it.  AFAIK there is no sensible way of discovering POP servers and even the above method for SMTP servers is not good - you'll likely get more than one response and there'll almost certainly be one your IT team want you to use.


text:
Q: gradle showing compatibility error I created android app. i want to show data from my aws mysql database. i wrote following code:
package com.example.yash.car2;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import  java.sql.*;

public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    public Connection CreateDBconn()
    {
        try
        {
            String DRIVER_NAME = "com.mysql.jdbc.Driver";
            String HOST_NAME = "firstdb.cqmpw4u1tyz3.us-west-2.rds.amazonaws.com";
            String PORT_NUMBER = "3306";
            String DB_NAME = "test_master";
            String USER_NAME = "*****";
            String PASSWORD = "*****";
            String URL="jdbc:mysql://firstdb.cqmpw4u1tyz3.us-west-2.rds.amazonaws.com/test_master";
            Class.forName(DRIVER_NAME);
            Connection conn =   DriverManager.getConnection(URL,USER_NAME,PASSWORD);
            return conn;

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public void init() {
try
{
        Connection c=CreateDBconn();
        String query="SELECT * FROM STUD";
        Statement st=c.createStatement();
        ResultSet rs=st.executeQuery(query);

        TableLayout stk = (TableLayout) findViewById(R.id.TL);
        TableRow tbrow0 = new TableRow(this);
        TextView tv0 = new TextView(this);
        tv0.setText(" Sl.No ");
        tv0.setTextColor(Color.WHITE);
        tbrow0.addView(tv0);
        TextView tv1 = new TextView(this);
        tv1.setText(" Last Name ");
        tv1.setTextColor(Color.WHITE);
        tbrow0.addView(tv1);
        TextView tv2 = new TextView(this);
        tv2.setText(" First Name ");
        tv2.setTextColor(Color.WHITE);
        tbrow0.addView(tv2);
        TextView tv3 = new TextView(this);
        tv3.setText(" Age ");
        tv3.setTextColor(Color.WHITE);
        tbrow0.addView(tv3);
        TextView tv4 = new TextView(this);
        tv4.setText(" Branch ");
        tv4.setTextColor(Color.WHITE);
        tbrow0.addView(tv4);
        stk.addView(tbrow0);

        while (rs.next()) {
            TableRow tbrow = new TableRow(this);
            TextView t1v = new TextView(this);
            t1v.setText(rs.getInt("id"));
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            tbrow.addView(t1v);
            TextView t2v = new TextView(this);
            t2v.setText(rs.getString("LastName"));
            t2v.setTextColor(Color.WHITE);
            t2v.setGravity(Gravity.CENTER);
            tbrow.addView(t2v);
            TextView t3v = new TextView(this);
            t3v.setText(rs.getString("FirstName"));
            t3v.setTextColor(Color.WHITE);
            t3v.setGravity(Gravity.CENTER);
            tbrow.addView(t3v);
            TextView t4v = new TextView(this);
            t4v.setText(rs.getInt("Age"));
            t4v.setTextColor(Color.WHITE);
            t4v.setGravity(Gravity.CENTER);
            tbrow.addView(t4v);
            TextView t5v=new TextView(this);
            t5v.setText(rs.getString("Branch"));
            t5v.setTextColor(Color.WHITE);
            t5v.setGravity(Gravity.CENTER);
            tbrow.addView(t5v);
            stk.addView(tbrow);
        }}
catch (Exception e)
{
    e.printStackTrace();
}

    }}

my code is showing following errors:

1:Error:Error converting bytecode to dex: Cause: Dex cannot parse
  version 52 byte code. This is caused by library dependencies that have
  been compiled using Java 8 or above. If you are using the 'java'
  gradle plugin in a library submodule add  targetCompatibility = '1.7'
  sourceCompatibility = '1.7' to that submodule's build.gradle file.
2.Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException:
    com.android.ide.common.process.ProcessException:
    java.util.concurrent.ExecutionException:
    com.android.ide.common.process.ProcessException: Return code 1 for dex
    process

I'm new with this all database thing.
I guess issue is somewhere in import of java.sql but I'm not getting any solution.
Pls Help!

A: You need to use Java 8 as your code depends on Java 8 dependencies.
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Use latest gradle plugin too.
classpath 'com.android.tools.build:gradle:3.3.3'


text:
Q: Cell Selection Methods R1C1 or? I stumbled on this accidently and haven't been able to find an answer online.
These 2 similar looking lines of code give very different results.
I'm ok with the R1C1 version. Can you help me understand and name the other?
Many thanks for your time,
Paul
Sub testcells()

Cells(1, 2).Select
Cells(1)(2).Select

End Sub

A: Just as Cells(1, 2) is shorthand for:
Cells.Item(1, 2)
so Cells(1)(2) is shorthand for:
Cells.Item(1).Item(2)
Cells.Item(1) returns range A1, and the second Item property is relative to A1 so you get A2. It is the same as using:
range("A1").Range("A2")
A couple of things to note:

*

*The start cell doesn't have to be A1 - for example, cells(2)(3)
refers to B3 (the first step gets B1, then the 3 takes you to B3)

*If you only specify one number for the Item property, the result
depends on the width of the original range as the count goes from
left to right and top to bottom.

A: Interesting Question. Not Sure, Just my observation (Maybe later someone will clarify more):
Cells(1,2) is in rowindex,colindex which you are ok with.
Cells(1)(2) is cell number 1 in the respective range, with vertical(row) offset (offset is like 2,3,4... for downward cell or 0,-1,-2,... for upward cell). Without preceding range, Cells(1)(2) becomes number 1 cell in worksheet, with downward offset 1 (not 2!)
Summary:
Cells(1,2) is B1 and Cells(1)(2) is A2
Fun Part: I have tried Cells(1)(2)()().. works every figure inside bracket is treated as offset to previous one!! Except the first (1), of course.


text:
Q: How can I let my React app treat each component instance separately? I am trying to test how TinyMCE handles multiple editors inside React.
In this small example, I just have 3, but there could be up to 100 of them.
My problem is, that I don't think each are being treated as separate instances, but rather one instance.
I don't get any errors, but when I edit one, the edits appears in all 3.
Is there a way to let TinyMCE know which editor is which?
import React from 'react';
import TinyMCEComponent from './TinyMCEComponent';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function BasicExample() {
  return (
    <Router>

            <Link to="/editor_1">Editor One</Link>

            <Link to="/editor_2">Editor Two</Link>

            <Link to="/editor_3">Editor Three</Link>

        <Switch>
          <Route exact path="/editor_1">
            <TinyMCEComponent />
          </Route>
          <Route path="/editor_2">
            <TinyMCEComponent />
          </Route>
          <Route path="/editor_3">
            <TinyMCEComponent />
          </Route>
        </Switch>

    </Router>
  );
}

And this is where TinyMCE is:
import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

const TinyMCEComponent = () => {

const handleEditorChange = (content, editor) => {
    console.log('Content was updated:', content);
}

return (
    <Editor
        apiKey="abc123"
        initialValue="
This is the initial content of the editor
"
        init={{
            height: 500,
            menubar: false,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor'
            ],
            toolbar:
                'undo redo | formatselect | bold italic backcolor | help'
        }}
        onEditorChange={handleEditorChange}
    />
);
}

export default TinyMCEComponent;

Thanks!

A: The simplest solution is to give each a key.
import React from 'react';
import TinyMCEComponent from './TinyMCEComponent';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function BasicExample() {
  return (
    <Router>

            <Link to="/editor_1">Editor One</Link>

            <Link to="/editor_2">Editor Two</Link>

            <Link to="/editor_3">Editor Three</Link>

        <Switch>
          <Route exact path="/editor_1">
            <TinyMCEComponent key="ed1" />
          </Route>
          <Route path="/editor_2">
            <TinyMCEComponent key="ed2" />
          </Route>
          <Route path="/editor_3">
            <TinyMCEComponent key="ed3" />
          </Route>
        </Switch>

    </Router>
  );
}


text:
Q: In ASP.NET Core, how to use sqlite I tried to create a rest api . when I try to change
 services.AddDbContext<WebContext>(options =>

   options.useSqlite(Configuration.GetConnectionString("WebContext")));

when I try to do this I get this error. I installed sqlite nuget.and also Microsoft.EntityFrameworkCore but I still got the problem

error CS1061: 'DbContextOptionsBuilder' does not contain a definition
  for 'UseSqlite' and no extension method 'UseSqlite' accepting a first
  argument of type 'DbContextOptionsBuilder' could be found (are you
  missing a using directive or an assembly reference?

A: Try:
using Microsoft.EntityFrameworkCore;
...
services.AddDbContext<WebContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("WebContext")));
...

And you also need to install the Microsoft.EntityFrameworkCore.Sqlite nuget package.


text:
Q: With pipenv, how to specify the minimum python version in the pipfile? Is there a way in pipenv to specify the minimum version of python in the Pipfile?
Would something like this work?
[requires]
python_version = ">=python 3.5"

A: No, pipenv does not support this.  Per pipenv issue 1050 feature request, the pipenv authors have explicitly chosen not to implement it.
Note that you can specify:
 python_version = "3"

to allow any version of Python 3.  Not exactly what you asked for, but it might be sufficient for some projects.


text:
Q: List only folders of certain depth using Java 8 streams Considering there is the "new" streams API in Java 8 I can use Files.walk to iterate over a folder. How can I only get the child folders of my given directory if using this method or maybe depth=2?
I currently have this working example, which sadly also prints the root path as all "subfolders".
Files.walk(Paths.get("/path/to/stuff/"))
     .forEach(f -> {
        if (Files.isDirectory(f)) {
            System.out.println(f.getName());
        }
     });

I therefore reverted to the following approach. Which stores the folders in memory and needs handling of the stored list afterwards, which I would avoid and use lambdas instead.
File[] directories = new File("/your/path/").listFiles(File::isDirectory);

A: You can make use of the second overload of the Files#walk method to set the max depth explicitly. Skip the first element of the stream to ignore the root path, then you can filter only directories to finally print each one of them.
final Path root = Paths.get("<your root path here>");

final int maxDepth = <your max depth here>;

Files.walk(root, maxDepth)
    .skip(1)
    .filter(Files::isDirectory)
    .map(Path::getFileName)
    .forEach(System.out::println);

A: public List<String> listFilesInDirectory(String dir, int depth) throws IOException {
    try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
        return stream
                .filter(file -> !Files.isDirectory(file))
                .map(Path::getFileName)
                .map(Path::toString)
                .collect(Collectors.toList());
    }
}

A: To list only sub-directories of a given directory:
Path dir = Paths.get("/path/to/stuff/");
Files.walk(dir, 1)
     .filter(p -> Files.isDirectory(p) && ! p.equals(dir))
     .forEach(p -> System.out.println(p.getFileName()));

A: Here is a solution that works with arbitrary minDepth and maxDepth also larger than 1. Assuming minDepth >= 0 and minDepth <= maxDepth:
final int minDepth = 2;
final int maxDepth = 3;
final Path rootPath = Paths.get("/path/to/stuff/");
final int rootPathDepth = rootPath.getNameCount();
Files.walk(rootPath, maxDepth)
        .filter(e -> e.toFile().isDirectory())
        .filter(e -> e.getNameCount() - rootPathDepth >= minDepth)
        .forEach(System.out::println);

To accomplish what you asked originally in the question of listing "...only folders of certain depth...", just make sure minDepth == maxDepth.

A: You can also try with this:
private File getSubdirectory(File file){
    try {
        return new File(file.getAbsolutePath().substring(file.getParent().length()));
    }catch (Exception ex){

    }
    return null;
}

collect file:
File[] directories = Arrays.stream(new File("/path/to/stuff")
          .listFiles(File::isDirectory)).map(Main::getSubdirectory)
                                        .toArray(File[]::new);

A: Agree with Andreas's answer,u can also use Files.list instead of Files.walk
Files.list(Paths.get("/path/to/stuff/"))
.filter(p -> Files.isDirectory(p) && ! p.equals(dir))
.forEach(p -> System.out.println(p.getFileName()));


text:
Q: Local variable name in setup_postdata() I am new in wordpress, I was using setup_postdata() method inside of a template file which was being called via shortcode function. I have not used global $post in my function.
if ( ! function_exists( 'new_shortcode' ) ) :
    function featured_posts_shortcode( $atts, $content = '' ) {
        ob_start();
        get_template_part("page-contents/section","abc");
        return ob_get_clean();
    }
    add_shortcode( 'new', 'new_shortcode' );
endif;

Template file code part:
Not Working:
$my_post = get_post($my_post_id);
setup_postdata($my_post);        // Does not work.

Working:
$post = get_post($my_post_id);
setup_postdata($post);        // Works.

When I use setup_postdata($my_post), it does not set the global post to my post, but when I use setup_postdata($post) it sets the global post to my post.
How can a parameter name can effect a function?
Can anyone explain why this is happening?

A: As noted in the documentation for setup_postdata():

setup_postdata() does not assign the global $post variable so it's important that you do this yourself. Failure to do so will cause problems with any hooks that use any of the above globals in conjunction with the $post global, as they will refer to separate entities.

So the reason $my_post doesn't work is that functions you are using are depending on a variable named $post, but it is not defined. setup_postdata() does not set this variable. You need to do this yourself by defining $post, which should be global $post.


text:
Q: Is there a way to add text to the `y2` axis of a plotly chart in R? I would like to add text to the data points in a plotly chart. See the example below:
df <- data.frame(
  category_value = c("A", "B", "C"),
  bar_value = c(1000, 2000, 15000),
  line_value = c(0.8, 0.9, 0.7)
)

plot_ly(df) %>%
  add_trace(x = ~category_value, y = ~bar_value, type = "bar", name = "bar_value") %>%
  add_trace(x = ~category_value, y = ~line_value, yaxis = "y2", type = "scatter", name = "line_value", mode = "lines+markers") %>%
  layout(xaxis = list(title = var), yaxis2 = list(overlaying = "y", side = "right")) %>%
  add_text(x = ~category_value, y = ~bar_value, text = ~bar_value, textposition = "top right") %>%
  add_text(x = ~category_value, y = ~line_value, text = ~line_value, textposition = "top right")

The problem is that the text for the line chart is too low in the y-dimension.
Something like add_text(x = ~category_value, y2 = ~line_value, text = ~line_value, textposition = "top right") would be helpful, but this does not work.

A: Yes, for sure. If you wanted the text labels for the bars and lines, you don't need four traces, you only need two (Plotly will make the rest.) Instead of "lines+markers" you can use "lines+markers+text", for the bar chart, you simply need to add the argument text.
I moved the legend over as well. The legend was overlapping the axis ticks for y2.
plot_ly(df) %>%
  add_trace(x = ~category_value, y = ~bar_value, type = "bar", name = "bar_value",
            text = ~bar_value, hoverinfo = "x+y", textposition = "top") %>%
  add_trace(x = ~category_value, y = ~line_value, yaxis = "y2", text = ~line_value,
            type = "scatter", name = "line_value", mode = "lines+markers+text",
            textposition = "top") %>%
  layout(xaxis = list(title = var),
         yaxis2 = list(overlaying = "y", side = "right"),
         legend = list(x = 1.05))


text: Q: How to populate a donut chart in highchart for two set of data in single chart with legend for one set of data and pointer for another set of data? I need to generate a donut chart as mentioned below. In this chart, the 'family share' is 100% of the chart and 'individual share' is 50% of chart. 'Your share' and 'Employer share' will be anything between 100%. I am looking for assistance to display family share and individual share pointed in the chart itself and, Your share and Employer share mentioned in the Legend.


text:
Q: save Contact in isolated storage in windows phone 7 c# Can I save Contacts in Isolated Storage in Windows phone 7 ? and How can I access it in c# ? and which is the best way to save it using linq to sql or Files or Values ?

A: No No No, you can NOT save even one Contact Object of type "Microsoft.Phone.UserData.Contact" in the isolated storage. The reason is simple: Contact object is un-serializable.
  I have tried this by myself and did not work, for sure. Consequently, you can NOT save a list of contacts.
Details:
I tried the following scenario: created a contact object, saved it in the isolated storage, tired read it from the isolated storage while the application is running (still alive). The result: it worked and read all the data I previously filled.
BUT
When I closed the application, I tried to retrieve the contact data (contact object that I previously saved) there application crashes and the debugger told me "KeyNotFoundException" which means that no "contact" were stored at all with the same "key" I used to store the "contact" in the first time.
So, why the application can read the stored "contact" in the first time before closing and reopening that application? It was reading form the isolated storage object in the memory not from the one saved on the phone.

A: Yes, you can read contact information (see http://msdn.microsoft.com/en-us/library/hh286416(v=vs.92).aspx) and save it to Isolated Storage in the same way you could save anythign else there.
The "best" way to save it will depend on what you wnat to do with it and how you want to access it.
Remember that you'll have to keep your copy of the contact information in sync with the actual data though. Unless you have a REALLY good reason to keep this copy of the data I'd avoid doing this and just query the actual contact data store when you need it.


text:
Q: JavaScript Fiscal Year issue I need help with my script.
It's supposed to check that month and year is within the current fiscal year (Oct. 2013 - Sep. 2014)
My test date is (Apr 2015) but it's coming up within the current fiscal year which is false.
if ( prevYear == ListYr || (
   ( month == "Oct" || month == "Nov" || month == "Dec" )) ||
   ( curYear == ListYr || (month == "Jan" || month == "Feb" || month == "Mar" ||
   month=="Apr" || month == "May" || month == "Jun" || month == "Jul"
   || month == "Aug" ||  month=="Sep")))
{
       alert("Within Fiscal Year");
} else {
       alert('outwith fiscal year');
}

Any ideas or a better way to make it more efficient?
Thanks!

A: IT's a bit clunky but I think this does what you want..
if ( prevYear == ListYr && (
 ( month == "Oct" || month == "Nov" || month == "Dec" ) ) ||
 ( curYear == ListYr && (month == "Jan" || month == "Feb" || month == "Mar" || month=="Apr" || month == "May" || month == "Jun" || month == "Jul" || month == "Aug" || month=="Sep"))) {
 alert("Within Fiscal Year");
} else {
 alert('outwith fiscal year');
}


text:
Q: back button not working on sencha touch I'm pushing a view from my navigation view (xtype : 'mainPanel') like this. It's an element of  tabbar. In the 2nd view  a back button is displayed in navigation bar,But it's not working. Any idea?
itemtap: function(list, index, target, record) {

                                list.up('mainPanel').push({
                                    xtype: 'newview',
                                    title: 'New',
                                    data: record.data
                                });

}

Main.js
Ext.define('Proj.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
    'Ext.TitleBar','Proj.view.phone.Mainpanel','Proj.view.phone.Home',''
],
config: {
    tabBar: {
        docked: 'bottom',
        layout: {
            pack: 'center'
        }

    },

    items: [

        {
            xtype: 'homePanel'
        },
        {
            xtype: 'mainpanel'
        },

    ]
}

});
Mainpanel.js
Ext.define('Proj.view.phone.MainPanel', {
    extend: 'Ext.navigation.View',
    xtype: 'mainpanel',
    requires : [
        '],
    initialize:function(){

        this.getNavigationBar().add(stuff);

Ext.getCmp('categoryList').setData(jsonObject.info);

    },
    config: {
        title : 'Shop',
        iconCls: 'favorites',
        styleHtmlContent: true,
        scrollable: true,

            items: [

                        {
                            xtype: 'list',
                            fullscreen: true,
                            itemTpl: '{name}',
                            autoLoad: true,
                            id:'categoryList',
                            store: {
                                fields :['active', 'created','description']

                            },
                            listeners: {
                                itemtap: function(list, index, target, record) {

                                    list.up('mainpanel').push({
                                        xtype: 'newview',
                                        title: 'newview',
                                        data: record.data
                                    });

                                }
                            }
                        }
            ]
    },

A: Try overriding the back button event with the following code ::
extend:'Ext.navigation.View',
xtype:'myNavigation',
config:{
    ……
},
onBackButtonTap:function(){
    this.callParent(arguments);
    alert('back button pressed');
}

See if that works. If it does, then you'll know you're handling the back event wrong, and the push isn't working. If it doesn't throw up the alert, then the listener isn't working. Try to programmatically call the back event using a controller method, and see if that works instead

A: I have faced this problem before. Create an initialize function in all views. Add this code in it.
this.callParent(arguments);


text:
Q: SQLite database returning fewer results in terminal than in Jupyter Notebook I have a SQLite database with a little more than 50,000 records. In my Jupyter notebook, I can see:
query = 'select max(id) from table'
c.execute(query)
c.fetchall()

[(50367,)]

In terminal (Ubuntu 16.04), I see:
sqlite> select max(id) from table;
50357

Additionally, queries to return data with IDs between 50357 - 50367 in Jupyter do in fact return data, but they don't in the shell.
Thanks for any help, and let me know in the comments if I should add any specific info to help answer.
EDIT:
I've been getting this message in Jupyter
query = 'delete from table where id > 50357'
c.execute(query)
db.commit()

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-67-b6e7e3eab558> in <module>()
      2 query = 'delete from table where id > 50357'
      3 c.execute(query)
----> 4 db.commit()

OperationalError: disk I/O error

It doesn't happen if I repeat the query a second time, but I'd also never seen it until this issue, if it provides any further clues.


text:
Q: Sklearn or my computer can't handle data set I have a data set of 100,000 rows and 125 features and continuous output. I'm running numpy, pandas, and sklearn on 2013 macbook pro with 16gb ram. Using only 10,000 rows and 5 features to train, the ipython kernel dies when I try to predict only 1,000 rows in the test set using sklearn RandomForestClassifier. Should I be hitting this limit with only 10,000 x 5 to train and 1,000 x 5 to predict?
data
import pandas as pd
import numpy as np
import sklearn as sk
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectKBest

df = pd.read_csv('train.csv')
df2 = pd.read_csv('test.csv')
cat = df.iloc[:,:117]
cont = df.iloc[:,117:df.shape[1]-1]
y = df.iloc[:,df.shape[1]-1]
cat2 = df2.iloc[:,:117]
cont2 = df2.iloc[:,117:df2.shape[1]]

cont_new = SelectKBest(k=5).fit_transform(cont,y)
test = cont2.iloc[:,[6,7,10,12,13]]
rf = RandomForestClassifier(n_jobs=-1,n_estimators=100,max_depth=20)
y = np.asarray(y,dtype="|S6")
rf.fit(cont_new[:10000], y[:10000])
predictions = rf.predict(test[:5000])
print(predictions)

A: Using memory_profiler to Diagnose Memory Usage
Just as Robert Kern's line_profiler package measures CPU usage, the memory_profiler module by Fabian Pedregosa and Philippe Gervais measures memory usage on a line-by-line basis. Understanding the memory usage characteristics of your code allows you to ask yourself two questions:

*

*Could we use less RAM by rewriting this function to work more efficiently?

*Could we use more RAM and save CPU cycles by caching?

memory_profiler operates in a very similar way to line_profiler, but runs far more slowly. If you install the psutil package (optional but recommended), memory_profiler will run faster. Memory profiling may easily make your code run 10 to 100 times slower. In practice, you will probably use memory_profiler occasionally and line_profiler (for CPU profiling) more frequently.
Install memory_profiler with the command pip install memory_profiler (and optionally pip install psutil).
As mentioned, the implementation of memory_profiler is not as performant as the implementation of line_profiler. It may therefore make sense to run your tests on a smaller problem that completes in a useful amount of time.
Overnight runs might be sensible for validation, but you need quick and reasonable iterations to diagnose problems and hypothesize solutions.
The requirement to modify the source code is a minor annoyance. As with line_profiler, a decorator (@profile) is used to mark the chosen function.
When dealing with memory allocation, you must be aware that the situation is not as clear-cut as it is with CPU usage. Generally, it is more efficient to overallocate memory to a process into a local pool that can be used at leisure, as memory allocation operations are relatively expensive. Furthermore, garbage collection is not instant, so objects may be unavailable but still in the garbage collection pool for some time.
The outcome of this is that it is hard to really understand what is happening with memory usage and release inside a Python program, as a line of code may not allocate a deterministic amount of memory as observed from outside the process. Observing the gross trend over a set of lines is likely to lead to better insight than observing the behavior of just one line.
Above is taken from High performance Python by Micha Gorelick and Ian Ozsvald (pp. 42-50).


text:
Q: getThreads() does not read all emails in thread I have 4 emails in the Gmail label "MyLabel".
- 1st thread has 43 email messages
- 2nd thread has 1 email message
- 3rd thread has 2 email messages
- 4th thread has 1 email message
When I use the following code, it appears that I only have 4 emails because my output (which parses correctly) only reads the last email message in each thread instead of all threads. I would like to have 47 rows of output instead of only 4 rows.
  var start = 0;
  var label = GmailApp.getUserLabelByName("MyLabel");
  var threads = label.getThreads();

  var sheet = SpreadsheetApp.getActiveSheet();
  var result = [];

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();

    var content = messages[0].getPlainBody();

Please let me know what I am doing wrong.

A: Thank you, John!! Having a messages.length-1 loop inside my threads loop was the solution. I used the following and got 49 rows instead of 4. So I think it worked!!
for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
for (var j = 0; j <messages.length-1; j++) {

var content = messages[j].getPlainBody();


text:
Q: How can I prevent LaTeX from breaking words and wrapping them to the next line? I want to have my entire document fully justified but without the words being broken up and hyphenated at the end of a line if it is too long. I have come across the \raggedright argument which prevents the hyphenation, but I'm not sure how to then justify the text.

A: Having both no hyphenation and text flush to both sides puts real stress on spacing.  Compare:

Quisque quis  nisl eu nibh  suscipit
rutrum.     Suspendisse     potenti.
Maecenas   quis   neque   ut   velit
pellentesque commodo. Donec et nulla
tortor.
with

Quisque  quis nisl  eu nibh  suscipit
rutrum.  Suspendisse  potenti.  Maec-
enas quis neque ut velit pellentesque
commodo. Donec et nulla tortor.
If you are not using Luatex, try it: good
microtyography can minimise or eliminate hyphenation.  Herbert's answer, usepackage[none]{hyphenat}, can be used together with microtypography.

A: \usepackage[none]{hyphenat}%%%%


text:
Q: Can i add elements programatically to XAML? WPF c# I want to add canvas elements by user input. Something like when a button is clicked, a new <Ellipse/> element is added to the XAML file, inside the Canvas.
<Canvas x:Name="GraphDisplayFrame" Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="3" Grid.RowSpan="4">
            <Ellipse
                Width="50"
                Height="50"
                Stroke="Black"
                StrokeThickness="2"
                Canvas.Left="100"
                Canvas.Top="100" />
</Canvas>

I'm new to WPF, i'm not sure if this is the right way to do this.
The other thing i'm trying is System.Windows.Media but manipulating the XAMl file looks easier and nicer, since then the locations of the drawings are anchored to the canvas. I'm not sure if i can achieve something similar with System.Windows.Media.
So my question is in the title, but I'm open to other suggestions.

A: You probably want to learn about Bindings in WPF. Let's say you want your Ellipses be added by user's input (e.g. on Button click) to your Canvas. I'm not sure about Canvas usage for that purpose (it hasn't auto-alignments for child elements), so I used WrapPanel instead (to allow it align items). And we need 2 Buttons (to Add and Remove Ellipses). And I add a Label to display current amount of Ellipses that we have.
XAML:
<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Name ="mainWindow"
        Title="Main Window"
        Width="800"
        MaxWidth="800"
        Height="450"
        MaxHeight="450">
    <Grid x:Name="MainGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50*"/>
            <ColumnDefinition Width="50*"/>
            <ColumnDefinition Width="50*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="50*"/>
            <RowDefinition Height="50*"/>
            <RowDefinition Height="50*"/>
            <RowDefinition Height="50*"/>
        </Grid.RowDefinitions>
        <Label Content="{Binding ElementName=mainWindow, Path=EllipsesCount, UpdateSourceTrigger=PropertyChanged}"
               HorizontalContentAlignment="Center"
               VerticalContentAlignment="Center"
               Grid.Row="0"
               Background="DimGray"
               Foreground="White"
               Margin="15,35" />
        <Button x:Name="BtnAddEllipse"
                        Content="ADD ELLIPSE"
                        Grid.Row="1"
                        Margin="10, 25" FontSize="22" FontWeight="Bold"
                        Background="LightGreen"/>
        <Button x:Name="BtnRemoveEllipse"
                        Content="REMOVE ELLIPSE"
                        Grid.Row="2"
                        Margin="10, 25" FontSize="22" FontWeight="Bold"
                        Background="IndianRed"/>
        <WrapPanel Orientation="Horizontal"
                   Background="Gainsboro"
                   HorizontalAlignment="Stretch"
                   VerticalAlignment="Stretch"
                   Grid.Column="1"
                   Grid.Row="0"
                   Grid.ColumnSpan="3"
                   Grid.RowSpan="4" >
            <ItemsControl ItemsSource="{Binding ElementName=mainWindow, Path=Ellipses, UpdateSourceTrigger=PropertyChanged}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </WrapPanel>
    </Grid>
</Window>

Here you see that Label.Content property is binded to some EllipsesCount property (you'll see it in code-behind below). Also as WrapPanel is binded to Ellipses property.
Code-behind: (for copypaste purpose)
using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApp2
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        // Text for Label about Ellipses amount in collection
        private object _ellipsesCount = "Current ellipses count: 0";
        public object EllipsesCount
        {
            get => _ellipsesCount;
            set
            {
                _ellipsesCount = "Current ellipses count: " + value;
                // When we set new value to this property -
                // we call OnPropertyChanged notifier, so Label
                // would be "informed" about this change and will get new value
                OnPropertyChanged(nameof(EllipsesCount));
            }
        }

        // Collection for Ellipses
        private ObservableCollection<Ellipse> _ellipses;
        public ObservableCollection<Ellipse> Ellipses
        {
            get => _ellipses;
            set
            {
                _ellipses = value;
                OnPropertyChanged(nameof(Ellipses));
            }
        }

        // Hanlder, which would notify our Controls about property changes, so they will "update" itself with new values
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        // Just for random colors
        private readonly Random random = new Random();

        public MainWindow()
        {
            InitializeComponent();

            // Initialize collection of Ellipses
            Ellipses = new ObservableCollection<Ellipse>();
            // Handle when collection is changed to update Label
            // with a new amount of Ellipses
            Ellipses.CollectionChanged += delegate
            {
                // Update counter of ellipses when new one added or existing removed
                EllipsesCount = Ellipses.Count;
            };

            BtnAddEllipse.Click += delegate
            {
                // Create an Ellipse with random stroke color
                var ellipse = new Ellipse
                {
                    Width = 50,
                    Height = 50,
                    Margin = new Thickness(3),
                    Stroke = new SolidColorBrush(Color.FromRgb((byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255))),
                    StrokeThickness = 3
                };
                // Add to collection of ellipses
                Ellipses.Add(ellipse);
            };
            BtnRemoveEllipse.Click += delegate
            {
                // Check, that Ellipses collection isn't null and empty,
                // so we can remove something from it
                if (Ellipses?.Count > 0)
                    Ellipses.Remove(Ellipses.Last()); // Removing last element
            };
        }
    }
}

So at result you see, actually, "content of collection of Ellipses", without adding Ellipses directly to window. Binding makes WrapPanel to use collection of Ellipses as source of child elements, that should be in that WrapPanel (instead of original my answer, where we add Ellipse to Canvas as Children).

ORIGINAL answer.
Yes, you can. For example (based on your XAML):
XAML (empty window):
<Window x:Class="WPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFApp"
        mc:Ignorable="d">
    <!-- No even Grid here -->
</Window>

Code-behind (check comments also):

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            // Setting Window properties (they not exists in XAML)
            // XAML: <Window ... Title="Main Window" Height="450" Width="800">...
            this.Title = "Main Window";
            this.Height = 450;
            this.Width = 800;

            // Create main Grid and register some its name
            // XAML: ...
            var mainGrid = new System.Windows.Controls.Grid();
            this.RegisterName("MainGrid", mainGrid);

            // Add row and column definitions (as Canvas below needs, at least 4 rows and 3 columns)
            for (int i = 0; i < 4; i++)
            {
                mainGrid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition { Height = new GridLength(50, GridUnitType.Star) });

                if (i < 3) // Needn't 4th column
                    mainGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = new GridLength(50, GridUnitType.Star) });
            }

            // Create Canvas and register its name too
            // XAML: ...
            var canvas = new System.Windows.Controls.Canvas
            {
                // Just to be able see it at Window
                Background = System.Windows.Media.Brushes.LightGray
            };
            this.RegisterName("GraphDisplayFrame", canvas);
            canvas.SetValue(System.Windows.Controls.Grid.ColumnProperty, 1);
            canvas.SetValue(System.Windows.Controls.Grid.RowProperty, 0);
            canvas.SetValue(System.Windows.Controls.Grid.ColumnSpanProperty, 3);
            canvas.SetValue(System.Windows.Controls.Grid.RowSpanProperty, 4);

            // Create Ellipse (child canvas element)
            // XAML: ...
            var ellipse = new System.Windows.Shapes.Ellipse
            {
                Width = 50,
                Height = 50,
                Stroke = System.Windows.Media.Brushes.Black,
                StrokeThickness = 2
            };
            ellipse.SetValue(System.Windows.Controls.Canvas.LeftProperty, 100D);
            ellipse.SetValue(System.Windows.Controls.Canvas.TopProperty, 100D);

            // Add child Ellipse to Canvas
            canvas.Children.Add(ellipse);
            // or you already can find Canvas by its name:
            (this.FindName("GraphDisplayFrame") as System.Windows.Controls.Canvas).Children.Add(ellipse);

            // Add Canvas to MainGrid. Find Grid by its registered name too
            (this.FindName("MainGrid") as System.Windows.Controls.Grid).Children.Add(canvas);

            // Set main Grid as window content
            this.Content = mainGrid;
        }
    }

So, as you can see, XAML markuping is quite more compact, that code-behinded one.


text:
Q: Write fixed length padded lines to file Go For printing, justified and fixed length, seems like what everyone asks about and there are many examples that I have found, like...
package main

import "fmt"

func main() {
    values := []string{"Mustang", "10", "car"}
    for i := range(values) {
        fmt.Printf("%10v...\n", values[i])
    }

    for i := range(values) {
        fmt.Printf("|%-10v|\n", values[i])
    }
}

Situation
But what if I need to WRITE to a file with fixed length bytes?
For example: what if I have requirement that states, write this line to a file that must be 32 bytes, left justified and padded to the right with 0's
Question
So, how do you accomplish this when writing to a file?

A: There are analogous functions to fmt.PrintXX() functions, ones that start with an F, take the form of fmt.FprintXX(). These variants write the result to an io.Writer which may be an os.File as well.
So if you have the fmt.Printf() statements which you want to direct to a file, just change them to call fmt.Fprintf() instead, passing the file as the first argument:
var f *os.File = ... // Initialize / open file

fmt.Fprintf(f, "%10v...\n", values[i])

If you look into the implementation of fmt.Printf():
func Printf(format string, a ...interface{}) (n int, err error) {
    return Fprintf(os.Stdout, format, a...)
}

It does exactly this: it calls fmt.Fprintf(), passing os.Stdout as the output to write to.
For how to open a file, see How to read/write from/to file using Go?
See related question: Format a Go string without printing?


text:
Q: Having problems with a Rewrite rule I have an application most of it is still in development that's why i need to block access on all pages but just not two of them.
Suppose i have a.php all requests will be redirected to here except b.php.
So i think there should be 3 rules:
1st: when a.php and b.php are requested they should be visible to user,

2nd: if anything other than those two is requested,
     it should be redirected to a.php.

3rd: for external css,javascript and image files
     there should be an access rule

Since i dont have much experience with server administration, i believe i'm totally lost:)
This is what i tried:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !^/b.php
RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ a.php

A: I am not sure what you means about #3 but see from what you are trying, I guess you means, all js,ico,... are to be redirect to a.php. Is that right?
If so, that means, a => a.php (with parameter), b => b.php (with parameter) and other => a.php. So try this:
RewriteBase /
RewriteRule ^a\.php(.*) /a.php$1
RewriteRule ^b\.php(.*) /b.php$1
RewriteRule ^.*         /a.php

But if you means that all those script and media files are to be accessible normally, try this:
RewriteBase /
RewriteRule ^a\.php(.*)                          /a.php$1
RewriteRule ^b\.php(.*)                          /b.php$1
RewriteRule ^(.*)\.(js|ico|txt|gif|jpg|png|css)$ /$1.$2

Basically, the rewrite rule is the regular expression and $1,$2,... are match-string group (those wrapped with "(" and ")").
Hope this help.

A: In practice you would swap the second and third rule as your second rule would be the default route:
# 1st
RewriteRule ^(a\.php|b\.php)$ - [L]

# 3rd
RewriteRule \.(js|ico|txt|gif|jpg|png|css)$ - [L]

# 2nd
RewriteRule !^a\.php$ a.php [L]

The subsitution - means that the URI is not changed.


text:
Q: How to create a factor from a binary indicator matrix? Say I have the following matrix mat, which is a binary indicator matrix for the levels A, B, and C for a set of 5 observations:
mat <- matrix(c(1,0,0,
                1,0,0,
                0,1,0,
                0,1,0,
                0,0,1), ncol = 3, byrow = TRUE)
colnames(mat) <- LETTERS[1:3]

> mat
     A B C
[1,] 1 0 0
[2,] 1 0 0
[3,] 0 1 0
[4,] 0 1 0
[5,] 0 0 1

I want to convert that into a single factor such that the output is equivalent to fac defines as:
> fac <- factor(rep(LETTERS[1:3], times = c(2,2,1)))
> fac
[1] A A B B C
Levels: A B C

Extra points if you get the labels from the colnames of mat, but a set of numeric codes (e.g. c(1,1,2,2,3)) would also be acceptable as desired output.

A: This solution makes use of the arr.ind=TRUE argument of which, returning the matching positions as array locations.  These are then used to index the colnames:
> factor(colnames(mat)[which(mat==1, arr.ind=TRUE)[, 2]])
[1] A A B B C
Levels: A B C

Decomposing into steps:
> which(mat==1, arr.ind=TRUE)
     row col
[1,]   1   1
[2,]   2   1
[3,]   3   2
[4,]   4   2
[5,]   5   3

Use the values of the second column, i.e. which(...)[, 2] and index colnames:
> colnames(mat)[c(1, 1, 2, 2, 3)]
[1] "A" "A" "B" "B" "C"

And then convert to a factor

A: One way is to replicate the names out by row number and index directly with the matrix, then wrap that with factor to restore the levels:
factor(rep(colnames(mat), each = nrow(mat))[as.logical(mat)])
[1] A A B B C
Levels: A B C

If this is from model.matrix, the colnames have fac prepended, and so this should work the same but removing the extra text:
factor(gsub("^fac", "", rep(colnames(mat), each = nrow(mat))[as.logical(mat)]))

A: You could use something like this:
lvls<-apply(mat, 1, function(currow){match(1, currow)})
fac<-factor(lvls, 1:3, labels=colnames(mat))

A: Elegant solution with matrix multiplication (and shortest up to now):
as.factor(colnames(mat)[mat %*% 1:ncol(mat)])

A: Here is another one
factor(rep(colnames(mat), colSums(mat)))


text:
Q: IValueConverter not getting invoked in some scenarios I am using a collection of texts fetched from a web service, which should be used for a variety of controls.
The easiest and most dynamic way to do this, in my opinion, is to use an IValueConverter to get the given text as follows:
public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null && parameter is string)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(parameter)).Content;
        }

        return null;
    }
}

And then in the XAML I give the ID of the text ('Name') to the converter:
<phone:PhoneApplicationPage.Resources>
    <Helpers:StaticTextConverter x:Name="TextConverter" />
</phone:PhoneApplicationPage.Resources>

<TextBlock Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />

Then to change the text of some control, all that has to be done is to either change the ID in the parameter or change the text itself from some web interface.
My problem is
That the value converter only gets invoked when in some sort of DataTemplate context where the ItemSource has been set, as if the Binding property only works there.
Whenever I use this method anywhere else, the value converter is simply not invoked.
Does anyone have an idea of what I might be doing wrong?

A: Set DataContext="object" for your textblocks where the convertet is not working and the value converter will be invoked.
This workaround will do the trick in your scenario.

A: add source for the binding
use something like that
Text="{Binding  Converter={StaticResource LocalizedStringsConventer} ,ConverterParameter=Wrong, Source=NULL}"


text:
Q: Why does Source for ContextMenuOpening behave differently for Canvas and UserControl? I have a simple window:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:self="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="435" Width="613">
    <StackPanel>
        <Canvas Name="canvas">
            <self:Red />
        </Canvas>
        <UserControl Name="uc">
            <self:Blue />
        </UserControl>
    </StackPanel>
</Window>

Redand Blueare very simple UserControls:
<UserControl x:Class="WpfApplication1.Blue"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Rectangle Fill="Blue" Width="100" Height="100" />
    </Grid>
</UserControl>

I have created some ContextMenus:
public MainWindow()
{
    InitializeComponent();

    canvas.ContextMenu = new ContextMenu();
    canvas.ContextMenuOpening += (sender, e) =>
    {
        System.Diagnostics.Debug.WriteLine(e.Source.GetType());
    };

    uc.ContextMenu = new ContextMenu();
    uc.ContextMenuOpening += (sender, e) =>
    {
        System.Diagnostics.Debug.WriteLine(e.Source.GetType());
    };
}

If I open the context menu on the Canvas, the Source is Red, but if I open it on the UserControl, Source is UserControl.
Any idea why?
I found this on MSDN:

ContextMenu itself is a FrameworkElement derived class, but this event will not be raised from the context menu being opened as a source. The event is raised from the element that "owns" the context menu as a property...

If I understand it correctly Source should be Canvas in the first case, but it isn't.

A: This behavior is covered fairly well in the MSDN documentation for the RoutedEventArgs.OriginalSource property:

Source adjustment by various elements and content models varies from class to class. Each class that adjusts event sources attempts to anticipate which source is the most useful to report for most input scenarios and the scenarios for which the class is intended, and then sets that source as the Source. If this source is not the one that has relevance to your handling of the event, try checking OriginalSource instead to see if it reports a different source that is more suitable.

Which is exactly what the UserControl class does, it patches the Source property in its AdjustBranchSource() method.
So, as hinted by the quoted text, you are perhaps looking for the OriginalSource property to make the code behave similarly, you'll get a reference to the Rectangle in both cases.


text:
Q: include directory in vcs option in Makefile I am working on one makefile let me give you quick view
vcs is tool, +incdir+<dir_path> is syntax
when i do +incdir+${$@_${seed}} its not working
${seed} is variable which I define in starting of my makefile
Regards,
Vinay

A: found the resoultion it should +incdir+{$@_${seed}} ...


text:
Q: What is a sync during kernel boot? If something prevents a Linux system from booting, it is common to see this message:
kernel panic - not syncing: [Error Message]

But what does "not syncing" mean? What exactly isn't syncing?
The only place I have seen sync before is the sync system call, ie., commit buffer cache to disk

A: You are correct in that it is referring to syncing the disks. If the kernel panics, there could be a multitude of reasons - including a software bug in file system code.
Syncing the disks could write corrupt data to the disks, such as if the panic was due to a bug in Ext4, for example - so the kernel plays it safe and doesn't flush anything to disk because it no longer trusts that the data is valid anymore.
Additionally, if the panic occurred due to a hardware issue (e.g. bad RAM), syncing the disks could also write corrupted data from memory to the disk. If the filesystem then became corrupt as a result, the system might refuse to boot after being restarted, or may need to be fsck'ed.
The overall idea is that if the kernel itself has just crashed, don't trust anything anymore and just halt the system.


text:
Q: Upgrade or Fresh Install to Ubuntu 16.04 if I currently have Ubuntu 14.04 I currently have Ubuntu 14.04 installed on my system, which reached its End of Support in April this year. If I want to step up to Ubuntu 16.04, what is my best course of action - should I upgrade(i.e. is there a way to still do that) or should I clean install?
sudo do-release-upgrade -d

Will this step work or will it upgrade to the latest LTS, now that 14.04 has reached End of Support?
Also, whichever be the answer, if you you can guide me to a trustable page with a list of steps, that would be great.
Thanks !

A: Because 14.04 is EOL (End of Life) there are special considerations:

Upgrade or fresh install?
The advantage of upgrading is that you get to keep your current
configuration as is. This is often desirable on production
environments which you want to keep as stable as possible. At the same
time, configuration applicable for older versions might not always
work with newer versions.
If you format partitions when installing a newer version, you have the
option to select a new file system, which might have benefits and
required features compared to the old one. The new installation also
gives you a clean platform to start building your system from; no old
configuration files and potential upgrade-related bugs.
Reinstalling is usually easier and faster, especially if you would
have to upgrade through several releases. It might also help you save
some bandwidth, if that is a concern.

That said if you were to do a clean install you might want to do it on a new partition and keep your old partition intact. This is helpful for migrating settings set many years ago on the old partition but unknown for the new partition. For example you may have custom scripts in /usr/local/bin or custom settings in /etc which you setup many years ago and then forgot about until the new installation isn't working properly.
If you want to upgrade you should consider cloning your old partition to the new partition and run the upgrade on the clone. Then if the upgrade fails, you can reclone, fix the error condition and run the upgrade again.
Please note an upgrade can take 40 minutes (in my case) to a few hours (reported by other users) depending on your system.
A few times a day, a few times a week, month and year I will change different system settings. Over the course of five years I forget all that I've changed. The advantage of upgrading is none get lost. The disadvantage of reinstalling is all get lost.

A: It is in all cases preferred to do a clean install. This is also an opportunity on which your system is thoroughly cleaned.
New editions of Ubuntu adopt new approaches, also in the way things are configured. Upgrading may leave old configuration approaches in place. A small example to illustrate this point (which I have been through): on computers with an SSD disk, Ubuntu used to set up a cronjob to run fstrim automatically on scheduled times (needed to maintain performance of an SSD). At some point, Ubuntu switched to systemd to do this. As I upgraded instead of performing a fresh install, I found myself having two services configured to launch fstrim, so I manually had to removed the cron service. This is an example of how unneeded "relicts" may persist in an upgraded version.
This was a small example just for illustration of potential issues related to an upgrade. A fresh install is by far preferred. The drawback indeed is that you need to reconfigure your own desktop, but the advantage is more system stability and significantly lower chances to incur issues.
If you value stability, your best action is now to do a fresh install of the current Long Term Support Release Ubuntu 18.04. This version will continue to be supported for the next 3.5 year as of December 2019.


text:
Q: How to prompt input dialog for entering matrix elements in matlab? I would like to ask is there any way to let the user to the enter matrix elements (eg. a 3x3 matrix) in a input dialog that has a total 9 boxes in a square manner in matlab. I know matlab got a inputdlg function but the input box will only be in a vertical manner. So I would like to know is there any other option other than using GUI. My concept is like asking the user the matrix size and then I will prompt the corresponding number of boxes for the matrix elements.

A: This is how I have done it (for solving simultaneus equations), however my problem now is using the data in the matrix I dont think this actually creates a matrix because it wont find the det
`
    clear
    clc
prompt={'x:','y:','z:'}
dlg_title='MATRIX A'
num_lines=[1 50]
def={'3','4','8'}
A=inputdlg(prompt,dlg_title,num_lines,def)

dlg_title='MATRIX B'
def={'4','3','-3'}
B=inputdlg(prompt,dlg_title,num_lines,def)

dlg_title='MATRIX C'
def={'5','-4','-2'}
C=inputdlg(prompt,dlg_title,num_lines,def)

D=[A,B,C]'`


text:
Q: Why does my script work when started from console but does not work when started via upstart? I am running Ubuntu 12.04.
Here is what I am trying to do:
I copied and adapted a shell script from here: http://yatse.leetzone.org/redmine/boards/2/topics/2088. It listens to UDP port 9 for Wake-On-LAN packages. When it receives a package, it should start xbmc. Here is the script /home/myusername/.xbmc/autostarter:
#!/bin/bash
UDP_PORT=9          # Change this if you need to run this on a different port

START_PHRASE="E.....@"
START_PHRASE_ESCAPED="E\.\.\.\.\.@"

# The following block checks if the user running this script has the required      privileges to listen on the port specified above
WHO=`whoami`
if [ "$WHO" != "root" ]; then
     echo "Cannot start unless running as root." >> /var/log/xbmc-starter.log
  exit 1
fi

echo "Listening on port $UDP_PORT for start command" >> /var/log/xbmc-starter.log

while [ true ]; do
     # Wait for a packet to come in
     LISTEN=`tcpdump "udp port $UDP_PORT" -A -c 1 2>&1 | grep -o    "$START_PHRASE_ESCAPED"`
     # Make sure that we received the right command
     if [ "$LISTEN" = "$START_PHRASE" ]; then
        echo "Starting XBMC" >> /var/log/xbmc-starter.log
        /usr/bin/xbmc
        echo "test log after command" >> /var/log/xbmc-starter.log
     fi
     # Sleep, to be nice, for unwanted rogue processes writing to our port
     sleep 1
done

When I run this script from command line with sudo and send the WOL package, it works and starts xbmc.
sudo ./autostarter

The log output is:
Listening on port 9 for start command
Starting XBMC
test log after command

But when I run it from an upstart script, it creates the same log output but does not start xbmc. Here is my upstart script xbmc-starter.conf:
# Starts a listener that runs the xbmc start script when a WOL package is received
description     "start xbmc wol listener script"
# runlevels
start on runlevel [2345]
stop on runlevel [!2345]
exec /home/myusername/.xbmc/autostarter

And the log output:
Listening on port 9 for start command
Starting XBMC
test log after command

Why doesn't it start XBMC?

A: I'll take a shot, since no one else has offered an answer.
Try changing your start condition to start on started tty1
My understanding of init systems is that they will happily start programs at weird times if you ask them to.  Asking to start at the run levels could mean at the beginning of those run levels, before anything else has started.  Like before things like any part of the file system have been mounted, and certainly before minimal networking is available.
start on started tty1 will wait till the first terminal is started before starting the program, which is basically the same time that you would be able to run/test things manually.  So your program starts up later in the boot process, but you should get more consistent results.

A: Maybe adding env DISPLAY=:0 to the Upstart job would help? I think XBMC needs to be able to know what display to use, you know?


text:
Q: Ordering of two weak star limits Suppose $\Omega$ be an open subset of $\mathbb R^n$ and $a_h$ be a sequence of $L^\infty(\Omega)$ functions such that there exist two constants $0<c_1\leq c_2$ such that $$c_1\leq a_h(x)\leq c_2$$ for almost any $x\in\Omega$ and any $h\in\mathbb N$.
Suppose moreover that there exists $a,b\in L^\infty(\Omega)$ such that $$\begin{aligned}a_h\rightharpoonup a,\\ \frac{1}{a_h}\rightharpoonup\frac 1b. \end{aligned}$$
in $w^*-L^\infty(\Omega)$.
Prove that in general $b\leq a$ and $b=a$ implies that $a_h\to a$ strongly in $L^2(\Omega)$.
I'm pretty sure this should be aneasy consequence of Banach Steinhaus, however in my computations I always end up with the equality reversed. Probably I'm messing something with limit superiors and inferiors. Can anybody help me?
Edit
Ok so thanks to the comment below the map $x\mapsto \frac 1x$ is CONVEX then by Jensen and the Weak star convergence in $L^\infty(\Omega)$ we now that for almost any $x\in\Omega$ everything is differentiable according to the LEbesgue differentiation theorem and then
$$|B_r|\left(\int_{B_r}a_h\mathrm d\mu\right)^{-1}\leq \frac{1}{|B_r|}\int_{B_r}\frac{1}{a_h}\mathrm d\mu.$$
Passing to the limit as $r\to 0$ around a Lebesgue point we eventually get $b\leq a$. Am I right?


text:
Q: Content pushed down in IE 7 My site looks good in both Firefox, IE 8, and chrome. However in IE 7 the middle content get pushed down.
I don't understand why, can anyone advise me how to fix this? I tried to float both left and right but it didn't work.
Any help appreciated. Thank you in advance!

Hi all, I have solved the issue by adding in some tables. Thanks for all your help!

A: Perhaps it has something to do with doctype declarations? Here's a tutorial on them:
Right here
You might want to read it and give it a try. Perhaps that could solve your problem.
It could also be a CSS compatibility problem. Take a look at this web page:
Here
It shows which CSS elements are compatible with IE 7 and other versions. If you used an element which is incompatible with IE 7, it might be what is causing you trouble.
Hope it helps.

A: It looks as though the margin-left:210px on a few of your DIVs is pushing the content down. Try assigning the following class in your stylesheet:
.head-nav,
.banner,
.sponsorslogo,
.wp_bannerize_sponsors,
#main{
float:left;
}

If that fixes it, it might be worth to rethink the layout of your design slightly where you place the above mentioned elements in a DIV that has a margin-left:210px and then float:left the #header to the left and place it above the new DIV.
Alternatively, if you want a quick fix that only targets the IE7 glitch you can always include the above style in an IE7 only stylesheet:
<!--[if IE 7]>
    <link href="css/ie7.css" rel="stylesheet" type="text/css" media="screen" />
<![endif]-->


text:
Q: CUPS server-error-internal-error I am trying to install a printer in Ubuntu 22.04.
Via the "Settings" app, it tries to download drivers then fails with "Failed to add new printer".
Via system-config-printer-gnome I get
Caught non-fatal exception.  Traceback:
File "/usr/share/system-config-printer/newprinter.py", line 4235, in getNPPPD
    ppd = cups.PPD(f)
RuntimeError: ppdOpenFile failed
Continuing anyway..

in the command line and There was an error during the CUPS operation: server-error-internal-error' in the GUI
I am a member of the lpadmin group.
How can I get more details on why this is failing?


text:
Q: How can I change my resolution to 1280x1024 How can I change my resolution to 1280x1024? I used the info from this link
How set my monitor resolution?
but it didn't work. This is what appears
http://imgur.com/FFlE4G6
How can I fix this?
I'm using a nVidia GTX 660 GPU with the recommended driver.


text:
Q: Is it possible to restrict user/role access to TFS by file extension? My searches are turning up many useless results, so I am hoping someone here might know off hand.  I would like to configure Team Foundation Server so that some members of a team (front end people) can only have write access on .cshtml, .css, .js files (etc) and the back-end developers can have write access on anything.  Is this possible?

A: This is not possible. I personally also do not find it advisable, since it seriously hampers collaboration between team members. If you want go forward in this direction, then setup the solution structure to have folders for separate types of files. These folders are easily secureable.


text:
Q: Selenium and Python on Snow Leopard I'm trying to use the stock Python (2.6.1) on Snow Leopard with Selenium. Being quite new to Python, I'm a at a bit of a loss for what I've done wrong, as this exact same process worked just fine on my ubuntu box:

*

*sudo easy_install -U selenium

*Create a simple test with Firefox Selenium UI, and export it as Python WebDriver (as mytest.py)

*$ python mytest.py (which results in:

This error message:
E

======================================================================
ERROR: test_mytest_py (__main__.MytestPy)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "mytest.py", line 8, in setUp
    self.driver = webdriver.Firefox()
  File "/Library/Python/2.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 45, in __init__
    self.binary, timeout),
  File "/Library/Python/2.6/site-packages/selenium/webdriver/firefox/extension_connection.py", line 46, in __init__
    self.binary.launch_browser(self.profile)
  File "/Library/Python/2.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 41, in launch_browser
    self._start_from_profile_path(self.profile.path)
  File "/Library/Python/2.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 66, in _start_from_profile_path
    Popen([self._start_cmd, "-silent"], stdout=PIPE, stderr=PIPE).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 595, in __init__
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1106, in _execute_child
OSError: [Errno 2] No such file or directory

----------------------------------------------------------------------
Ran 1 test in 0.302s

FAILED (errors=1)

One thing worth noting is that when I ran "sudo easy_install -U selenium", I did get a warning:
$ sudo easy_install -U selenium
Searching for selenium
Reading http://pypi.python.org/simple/selenium/
Reading http://www.openqa.org/
Reading http://code.google.com/p/selenium/
Reading http://seleniumhq.org/
Best match: selenium 2.14.0
Downloading http://pypi.python.org/packages/source/s/selenium/selenium-2.14.0.tar.gz#md5=8de9ee26d699d699f846f14f9a184e60
Processing selenium-2.14.0.tar.gz
Running selenium-2.14.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-yQVlpa/selenium-2.14.0/egg-dist-tmp-svoAjf
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'src_root'
warning: no files found matching 'docs/api/py/index.rst'
Adding selenium 2.14.0 to easy-install.pth file

Installed /Library/Python/2.6/site-packages/selenium-2.14.0-py2.6.egg
Processing dependencies for selenium
Finished processing dependencies for selenium

A: Check your Firefox binary location first. Does it placed at here: /Applications/Firefox.app/Contents/MacOS/firefox
?
For more information, please check this page: http://code.google.com/p/selenium/wiki/FirefoxDriver

A: I know nothing about Selenium but the traceback indicates that it doesn't have a usable path to Firefox.
You will need to change its configuration/profile file to give it a path to an executable version of Firefox.
The profile as it stands probably has the default location of Firefox on a linux box (hence why it works on Ubuntu).  But it wont be at this location on OSX.


text:
Q: Output a string as a sentence I have a lot of strings like these:
x1 <- c("Red", "Green", "Blue")
x2 <- c("Red", "Green", "Orange", "Yellow", "Pink")
x3 <- c("Red", "Green")
x4 <- c("Red")
x5 <- c("Red", "Green", "Orange", "Yellow", "Pink", "Blue", "Green")

I want to convert them to sentences with these characteristics:

*

*lowercase

*"and" separating second last and last element

*otherwise "," separating each element

*if just 2 elements then they should print as "xx and xx"

*if just 1 element they should print as "xx"

So these strings the strings above should be printed like this:
# red, green and blue
# red, green, orange, yellow and pink
# red and green
# red
# red, green, orange, yellow, pink, blue and green

I began to make a function to accomplish the above, this is how far I got:
sentence_string <- function(x){

    x <- tolower(x)

    x <- paste0(x, sep = ,)

    x

}

But cannot figure out how to achieve my desired output. Can anyone help please?

A: Using only base R:
sentence_string <- function(x){
  l <- length(x)
  if (l == 1) {
    tolower(x)
  } else {
    x <- tolower(x)
    y <- paste(x[-l], collapse = ', ')
    paste0(c(y, x[l]), collapse = ' and ')
  }
}

giving:
> sentence_string(x1)
[1] "red, green and blue"
> sentence_string(x2)
[1] "red, green, orange, yellow and pink"
> sentence_string(x3)
[1] "red and green"
> sentence_string(x4)
[1] "red"
> sentence_string(x5)
[1] "red, green, orange, yellow, pink, blue and green"

A: I like to use stringi for these operations,
library(stringi)

get_string <- function(x){
  y <- paste(x, collapse = ', ')
  y1 <- tolower(stri_replace_last_regex(y, ',', ' and'))
  return(y1)
}

get_string(x1)
#[1] "red, green and blue"


text:
Q: Why are native dll's from dependent libraries not included in build output? We are accessing DB2 from C# using IBM's DB2 libraries
https://www.nuget.org/packages/IBM.Data.DB2.Core/
We want to wrap IBM's library in a library of our own, adding DB2 related functionality to application developers.
The problem is that IBM's library is based on native dll's which are included in their package. However these native dll's are not copied to build output folder when IBMs library is only indirectly referenced through our own DB2 wrapper library
I suspect that I need to include the native dll's in our own library. Only I am not sure how to do that.
The nuget package we create of our wrapper library is created from the csproj file
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <Version>1.0.0</Version>
    <PlatformTarget>x64</PlatformTarget>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="IBM.Data.DB2.Core" Version="1.3.0.100" />
  </ItemGroup>

</Project>

A: It's complicated. NuGet has two ways to consume packages, and the two ways work somewhat differently. The original way was with packages.config (PC) and the new way is PackageReference (PR).
NuGet with PC has no concept of runtimes, so they way it's often implemented, and having a quick look at the package, it appears this is the case, the package author bundles MSBuild props and/or targets files in the package, and these targets modifies the build to copy the native files on build. A project using PC, when a package is installed, all dependencies are also installed, so all packages are direct dependencies of the project and any build targets in packages are imported into the project.
Projects using NuGet with PR on the other hand can reference just their direct dependencies, but dependencies of packages come in transitively. NuGet only tells MSBuild to import build targets from direct dependencies, not transitive dependencies. So that explains the behaviour you're seeing.
In NuGet 5.0 (released with Visual Studio 2019, and I can't remember which versions of .NET Core SDK), we added a buildTransitive feature that will pull in build props/targets from transitive packages. However it requires the package author to reauthor their packages to use it.


text:
Q: Add file with comment sharepoint client object model I use following code to add file to SharePoint library using client object model.
   Web web = context.Web;
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = System.IO.File.ReadAllBytes(filePath);
                newFile.Url = destFileName;
                newFile.Overwrite = true;
                List docs = web.Lists.GetByTitle(listName);
                Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
                context.Load(uploadFile);
                context.ExecuteQuery();

Question is, can I include my comment during this routine itself?
As it stands, I have to checkout file again and check in with comments using following code, which makes 2 versions of file which is unnecessary.
if (uploadFile.CheckOutType != CheckOutType.None)
                    {
                        uploadFile.CheckOut();
                        context.ExecuteQuery();
                    }

                    uploadFile.CheckIn(checkinComments, checkinType);
                    context.ExecuteQuery();

A: It is possible to check-in file with comment in one round trip only. Here is the updated code --
Web web = context.Web;
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = System.IO.File.ReadAllBytes(filePath);
                newFile.Url = destFileName;
                newFile.Overwrite = true;
                List docs = web.Lists.GetByTitle(listName);
                Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
                uploadFile.CheckIn("checkinComments", CheckinType.MajorCheckIn);
                context.ExecuteQuery();

Also, You do not require 'uploadFile' to load again. All pending changes will be commited by 'context.ExecuteQuery()'.