gdb could not be started - DDD to a remote inferior debugger

Question: Im trying to attach DDD to gdb on a remote machine. I have configured rsh to not require a pass for my machine & username.
ddd opens with "rtx5:1234: not found" and a pop-up with "GDB could not be started". From calling ddd --host rtx5:2159 --trace --no-exec-window /home/murray/beer-process
<code>#  Running GDB (pid 2826, tty /dev/pts/1)...
#  Current language: C/C++
#  Searching "vsllib/ddd.vsl"...
#  Trying "/home/murray/.ddd/vsllib/ddd.vsl"
#  Trying "/usr/share/ddd-3.3.12/vsllib/ddd.vsl"
#  Searching "vsllib/ddd.vsl"..."/usr/share/ddd-3.3.12/vsllib/ddd.vsl".
<- "sh: line 0: exec: rtx5:2159: not found\n"
#  Running GDB (pid 2826, tty /dev/pts/1)...Exit 127.
</code>
The PID of GDB started by ddd from the trace logs are 4-digits. However, all the PIDs that I can see from the rtx(target) are 8-digit. I can not see gdb as a process yet the trace log indicates otherwise. Is the documentation out of date and I am invoking it incorrectly? How could I test if ddd is correctly rsh-ing?
I have addressed the caveats of the docs 2.4.1:

Beer-process binary is in the home dir of my username on the target.
Checked the path of gdb in /usr/bin/gdb
rtx5 does not have xterm therefore include --no-exec-window flag

Thanks in advance
Comment: If you did some research on your own, please share it too. If you try to do something first and ask more specific questions, your post will be more welcomed.
Answer: TLDR: Had a firewall on the host interfering only with ddd's rsh connection. I also had to substitute "rtx5" for "'rsh rtx5'". It wont find the program I pass it, even though its in the home directory of the remote target. I can however use ddd-gui to find, load, and debug it.
I could rsh to rtx5 without a password, then call gdb.
I could not do "rsh rtx5 gdb" and have gdb start.  This is due to rsh. When rsh is called without a command it operates out of 514. If rsh in called with a command it communicates and attempts to move to a different port number. This is where my firewall was blocking it.
Wireshark showed me from local to target after rsh connection:
<code>destination unreachable (host administratively protected)
</code>
ddd still has issues primarily that I can not load a binary which is in my remote home directory. This extends problem extends to attaching to running processes on the remote host. In both cases I can load/connect via the gui once the connection is established.
Furthermore I have to call ddd with 'rsh ' prepended to the remote-host name. This seems wrong. I'll update when I have more.


how to pass two arrays from model file to controller file

Question: I want to return two arrays in a single function in the model and post the result in view but it gives an error.
And also I want to output a certain element of an array.
  public function index(){
     $this->load->model("model");

     $array['thisarray'] =  $this->model->Hello();

     $arrayy['yep'] = $this->model->Hello();

     $this->load->view("viewfile",$array);

     $this->load->view("viewfile",$arrayy);
          }

below is my model.php file.
   public function Hello()
            {
            return ['title' => 'My Title','heading' => 'My Heading'];

             return ['a'=> "helo",'b' =>"yello", 'c' =>"mello"];
            }

below is my view file
 <?php
echo "
";
print_r($thisarray);
print_r($yep)
echo "
"
?>

it gives an error saying yep is undefined variable.
Answer: this is impossible
a possible solution would be
your model
public function Hello()
{
    return
        [
            'yep' => ['title' => 'My Title','heading' => 'My Heading'],
            'thisarray' => ['a'=> "helo",'b' =>"yello", 'c' =>"mello"]
        ];
}

your controller
public function index()
{
    $this->load->model("model");
    $this->load->view("viewfile",$this->model->Hello());
}

and your view stays the same
Answer: you need to just change just your controller like this and you are all set.
public function index()
{
     $this->load->model("model");

     $array['thisarray'] =  $this->model->Hello();

     $array['yep'] = $this->model->Hello();

     $this->load->view("viewfile", $array);
}

After modifying your controller like given above, you will be able to access you array as you are accessing it in your view.


Initialize string producer from CSV

Question: I have a CSV file that contains pairs of filenames of images and a label. I would like to load those images.
# Queue for reading input pairs
filename_queue = tf.train.string_input_producer([MY_CSV_FILE])

# Read CSV input pairs and label
pair_list_reader = tf.TextLineReader()
pair_list_key, pair_list_value = pair_list_reader.read(filename_queue)
record_defaults = [[''], [''], [-1]]
img1_path, img2_path, label = tf.decode_csv(pair_list_value, record_defaults=record_defaults)

# Load image 1
img1_filename_queue = tf.train.string_input_producer(img1_path)

As you can see, I read in the CSV file line-by-line and then try to initialize a second input producer using the filename I get from the CSV decoder.
I get an error in the last line, though:
  File "tensorflow/python/training/input.py", line 138, in string_input_producer
    "fraction_of_%d_full" % capacity)
  File "tensorflow/python/training/input.py", line 106, in _input_producer
    enq = q.enqueue_many([input_tensor])
  File "tensorflow/python/ops/data_flow_ops.py", line 192, in enqueue_many
    batch_dim = ret.inputs[1].get_shape()[0]
  File "tensorflow/python/framework/tensor_shape.py", line 427, in __getitem__
    return self._dims[key]
IndexError: list index out of range

Why is that?
Thank you in advance.
Answer: This is an error due to the incompatible shapes of img1_path (a 0-D, or scalar, Tensor) and the expected string_tensor argument to tf.train.string_input_producer (a 1-D, or vector, Tensor).
Fortunately, the solution is simple, using tf.expand_dims to convert img1_path to a (one-element) vector:
# Convert img1_path from a scalar to a 1-element vector.
img1_path = tf.expand_dims(img1_path, 0)

Keeping track of the shapes of tensors can be tricky, so TensorFlow provides the Tensor.get_shape() method, which you can call to get information about the shape of any tensor object. For example:
print img1_path.get_shape()
# ==> "TensorShape([])" (a 0-dimensional tensor, or scalar)
img1_path = tf.expand_dims(img1_path, 0)
print img1_path.get_shape()
# ==> "TensorShape([Dimension(1)])" (a 1-dimensional tensor with length 1)

Comment: Thank you very much. How do I find out the dimensionality of a tensor?
Comment: I updated the answer to show how to use the `Tensor.get_shape()` method.
Comment: Excellent. Thanks a lot.

Initialize string producer from CSV


What is NFFT used in fft() function in matlab?

Question: I have a audio signal sample at the rate of 10Khz, I need to find fourier coefficients of my signal. I saw one example in mathwork's website where they are using following code to do the fft decomposition of a signal y:
NFFT = 2^nextpow2(L);
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);

where L is the length of the signal, I don't really understand why its defining the variable NFFT the way shown in the code above? Can't I just chose any value for NFFT? Also why are we taking Fs/2 in third line of the code above?
Comment: Last line should have been `linspace(0, Fs/2, NFFT/2+1)` -- what's the point of using the function that minimizes rounding error, and then introducing rounding error?
Answer: NFFT can be any positive value, but FFT computations are typically much more efficient when the number of samples can be factored into small primes. Quoting from Matlab documentation:

The execution time for fft depends on the length of the transform. It is fastest for powers of two. It is almost as fast for lengths that have only small prime factors. It is typically several times slower for lengths that are prime or which have large prime factors.

It is thus common to compute the FFT for the power of 2 which is greater or equal to the number of samples of the signal y. This is what NFFT = 2^nextpow2(L) does (in the Example from Matlab documentation y is constructed to have a length L).
When NFFT > L the signal is zero padded to the NFFT length.
As far as fs/2 goes, it is simply because the frequency spectrum of a real-valued signal has Hermitian symmetry (which means that the values spectrum above fs/2 can be obtained from the complex-conjugate of the values below fs/2), and as such is completely specifies from the first NFFT/2+1 values (with the index NFFT/2+1 corresponding to fs/2). So, instead of showing the redundant information above fs/2, the example chose to illustrate only the spectrum up to fs/2.
Answer: Output of FFT is complex for real valued input. That means for a signal sampled at Fs Hz, The fourier transform of this signal will have frequency components from -Fs/2 to Fs/2 and is symmetric at zero Hz. (Nyquist criterion states that if you have a signal with maxium frequency component at f Hz, you need to sample it with atleast 2f Hz .
You may wonder what does negative frequency mean here. If you are a mathematician you may care about the negative frequency but if you are an engineer, you may choose to ignore the notion of negative frequency and focus only on frequencies from 0 to Fs/2. (Max freq component for a signal sampled at Fs Hz is Fs/2)
Using FFT to learn more about frequency components present in your signal is cumbsrsome. You can use the function pwelch function in MATLAB to learn more frequencies present in your signal and also the power of these signals.  MATLAB will automatically compute the NFFT required and return the frequencies present in your signal along with the power at each frequency. Use this syntax:
[p,f] = pwelch(x,[],[],[],Fs)
Look at the documentation of pwelch for more information.


c# convert from object to model type

Question: I have an empty list with models of type 'audi_b9_aismura' which I want to populate with an object which I retrieve from another list.
I know this object is of the type specified (audi_b9_aismura) but I cannot add it to the list, using Convert.Changetype does not work either. The code below throws (at design time) the following error: Cannot convert from 'object' to '.audi_B9_aismura'.
List<audi_b9_aismura> dataList = new List<audi_b9_aismura>();

if (obj.GetType().Equals(typeof(audi_b9_aismura)))
                    {
                        dataList.Add(Convert.ChangeType(obj, typeof(audi_b9_aismura)));
                    }

I also tried, which does not work either.
audi_b9_aismura testVar = Convert.ChangeType(obj, typeof(audi_b9_aismura));

And, which converts it ok, but when adding it says again it is of the type object.
var testVar = Convert.ChangeType(obj, typeof(audi_b9_aismura));
dataList.Add(testVar);

If I retrieve the object type by filling it in a string, it returns the correct type (audi_b9_aismura)
string result = Convert.ChangeType(obj, typeof(audi_b9_aismura)).GetType().ToString();

Comment: `Convert.ChangeType()` returns an object, you still need to cast it to the correct type, as casting is ALL you need to do in this case, `Convert.ChangeType` serves no purpose.
Comment: If you just want to cast items from one type to another, you can use LINQ's Cast<> or OfType<> operators
Comment: I find it strange, that the string result gets filled with the correct type. I am new to programming in C#, so probably I understand wrongly, but if I retrieve the type from the "object" and it is set to the type (audi_b9_aismura) which I want, how come it is not really set to the type when I try to fill a variable with it?
Answer: Why not do a simple cast :
if (obj is audi_b9_aismura)
{
    dataList.Add((audi_b9_aismura)obj);
}

As Ben Robinson said in his comment, Convert.ChangeType() returns an object that still has to be cast to the right type.
Comment: Well, that works! Thanks! However, I don't get why converting it to a different type doesn't work, but this does. Anyone care to explain?
Comment: Makes sense, but it is a shame that by defining the custom type to convert to, it does not really convert to the custom type. Edit: Ohh you removed your comment...
Comment: Yes, this didn't come from that, but from what Ben Robinson said in his comment.
Comment: LINQ already provides Cast and OfType operators, no need to create the temporary list or for the type check and cast.
Answer: LINQ provides the Cast<> and OfType<> methods that allow you to cast or filter object by a speficic type respectively.
To retrieve items of a specific type as a list you can write:
var dataList=sourceList.OfType<audi_b9_aismura>().ToList();

If you are sure that the source contains only items of the specific type, you can write:
var dataList=sourceList.Cast<audi_b9_aismura>().ToList();

Answer: Try:
List<audi_b9_aismura> dataList = new List<audi_b9_aismura>();

if (obj is audi_b9_aismura)
{
    dataList.Add((audi_b9_aismura)obj);
}

c# convert from object to model type


Is it possible to change the column and record delimiter in sqoop2?

Question: Is it possbile to change the default column delimiter (comma) to a different character in Sqoop2?  I read in some mail archives that it is not supported yet.
If no, how can we specify the enclosed-by and escaped-by chars so that Sqoop properly extracts columns with values containing comma and quotes?  Does this work by default or need to turn it on by setting any options?
Answer: Like I doubted, changing the delimiter is not yet supported in Sqoop2. Refer below:
http://grokbase.com/t/cloudera/cdh-user/137q954ffz/sqoop2-import-field-delimiter

By default, the column delimiter is comma
String fields should be enclosed within single quotes (this takes care of fields with comma in them)
If the field contains single quote in itself then escape it with backslash \


Internet Explorer 11 detection

Question: I know IE 11 has different user agent string than all other IE
 Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko

I have tried to detect IE 11 with answer specified for this question'
Jquery fail to detect IE 11
Thats !!navigator.userAgent.match(/Trident\/7\./)
But I am getting error
Object not found and needs to be re-evaluated.
Then I openede developer console in IE11 and tried to access some predefined javascript objects, I am still getting same error.
I have tried
navigator.userAgent
window.navigator
console.log('test');
Anyone have any idea about it ?
Comment: @Bobkhin I have mentioned above my issue. getting error `Object not found and needs to be re-evaluated.`
Comment: possible duplicate of [How to detect IE 11 with javascript in Asp.net](http://stackoverflow.com/questions/18871760/how-to-detect-ie-11-with-javascript-in-asp-net)
Comment: possible duplicate of [How to detect IE11?](http://stackoverflow.com/questions/17907445/how-to-detect-ie11)
Answer: Edit 18 Nov 2016
This code also work (for those who prefer another solution , without using ActiveX)
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  // true on IE11
  // false on Edge and other IEs/browsers.

Original Answer
In order to check Ie11  , you can use this :  ( tested)
(or run this)
!(window.ActiveXObject) && "ActiveXObject" in window
I have all VMS of IE :

Notice : this wont work for IE11 :
as you can see here , it returns true :

So what can we do :
Apparently , they added the machine bit space  :
ie11 :
"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

ie12 :
"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

so we can do:
/x64|x32/ig.test(window.navigator.userAgent)

this will return true only for ie11.
Comment: Does **not** work for my IE 11.0.9600.19431 on Windows 7 Enterprise. There is no `window.MSInputMethodContext`.
Comment: Wait, there's an IE12? I thought IE11 was the last one and that we soon won't have to worry about that stupid browser anymore! ☹
Comment: `x64` returns both Chrome and Edge
Comment: @Jan. yes. only IE11 would return true for this whole condition. I just showed that <11 return false.
Comment: @IanSteffy This is just to show the result(!) of the operation. You can open a HTML file and add script tag and run the command inside that script. [Here run this](http://jsbin.com/remuya/1/edit?html,css,js,output).
Comment: Doesn't that also result in other IE's?
Comment: Could you please try it in developer console and let me know
Comment: @MiqdadAli Didn't you see my pics ?
Comment: Worked for me with Developer Console compatibility mode in IE11. Thanks, Namir!
Comment: Just wondering: in your screenshots you only show !(window.ActiveXObject) and not the "ActiveXObject in window" part.. so does the whole thing returns true in IE11?
Comment: That may work as suggested. Just keep in mind that future IE12 may also return true.
Comment: No browser ive tried on windows or mac seems to allow the live 'javascript:!(window.ActiveXObject)' to be added to the url
Comment: Why are you using 2 "!" in your first code? Is that used to force returning a boolean value?
Comment: There is no IE12!  Why is nobody apart from Michael Scheper questioning this response?  Does the poster, Royi Namir, mean IE11 or Edge rather than IE12??  Or is this supposed to be some hypothetical future version of IE?
Answer: To detect MSIE (from version 6 to 11) quickly:
if(navigator.userAgent.indexOf('MSIE')!==-1
|| navigator.appVersion.indexOf('Trident/') > -1){
   /* Microsoft Internet Explorer detected in. */
}

Comment: Shouldn't the second `indexOf()` be `> -1`?
Comment: Yeah, I don't know why it's >0 and not >-1, but "Trident/" shows up much farther into the appVersion string anyways-
Comment: This answer does not detect IE 11 specifically which is what the OP asked
Comment: Why not both `>= 0` or `> -1` ? Should be the same outcome but more readable / straightforward.
Comment: Note that appVersion is deprecated: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/appVersion
Answer: I use the following function to detect version 9, 10 and 11 of IE:
function ieVersion() {
    var ua = window.navigator.userAgent;
    if (ua.indexOf("Trident/7.0") > -1)
        return 11;
    else if (ua.indexOf("Trident/6.0") > -1)
        return 10;
    else if (ua.indexOf("Trident/5.0") > -1)
        return 9;
    else
        return 0;  // not IE9, 10 or 11
}

Answer: All of the above answers ignore the fact that you mention you have no window or navigator :-)

Then I openede developer console in IE11

and thats where it says

Object not found and needs to be re-evaluated.

and navigator, window, console, none of them exist and need to be re-evaluated. I've had that in emulation. just close and open the console a few times.
Comment: Worked for me too. This is why there will be partying around the world when IE dies.
Comment: goodness gracious THANK YOU for actually reading the question and answering the problem with re-evaluation.
Comment: Closing and opening the console worked for me. Strange behavior compared to Firefox or Chrome (but it's IE, so that figures.)
Answer: A pretty safe & concise way to detect IE 11 only is
if(window.msCrypto) {
    // I'm IE11 for sure
}

or something like this
var IE11= !!window.msCrypto;

msCrypto is a prefixed version of the window.crypto object and only implemented in IE 11.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
Comment: Thanks, I used the reverse: `if(window.crypto)` since `msCrypto` wasn't detected in `@types`
Answer: Okay try this, simple and for IE11 and IE below 11 version
browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;

navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 for IE 11 version
navigator.userAgent.toUpperCase().indexOf("MSIE") != -1 for IE below 11 version

browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;

console.log('Is IE Browser : '+ browserIsIE)
Answer: And how I implemented this

Comment: !! pretty much means 'Coerce to boolean'.
Comment: I think you have a typo in your function. First, you do the condition check, which is not used. Second, perhaps you mean `&& "ActiveXObject" in window`. Third: what the trick with double negation `!!` ?
Answer: This link was helpful . It contains the javascript code to detect all versions of IE up to IE11.  I tested the script with IE11 emulator. To find the IE11 emulator, right-click on the web browser click "Inspect element". At the bottom-left of the page, scroll down the navigation bar and click the desktop icon. The "User Agent String" dropdown box contains options to emulate IE6-11.
It works. I just used it some minutes before writing this answer. Cannot post snapshots - not enough reputation.

This is the code - follow the link to view it again:

// Get IE or Edge browser version
var version = detectIE();

if (version === false) {
  document.getElementById('result').innerHTML = '<s>IE/Edge</s>';
} else if (version >= 12) {
  document.getElementById('result').innerHTML = 'Edge ' + version;
} else {
  document.getElementById('result').innerHTML = 'IE ' + version;
}

// add details to debug result
document.getElementById('details').innerHTML = window.navigator.userAgent;

/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
function detectIE() {
  var ua = window.navigator.userAgent;

  // Test values; Uncomment to check result …

  // IE 10
  // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

  // IE 11
  // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

  // Edge 12 (Spartan)
  // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

  // Edge 13
  // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

  var msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }

  var trident = ua.indexOf('Trident/');
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }

  var edge = ua.indexOf('Edge/');
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  }

  // other browser
  return false;
}
@import url(https://fonts.googleapis.com/css?family=Fira+Mono|Fira+Sans:300);
body {
  color: black;
  background-color: white;
  font-family: "Fira Sans", sans-serif;
  font-weight: 300;
  margin: 0;
  padding: 3rem;
}

h1 {
  color: darkgrey;
  text-align: center;
  font-weight: 300;
  font-size: 1.5rem;
  line-height: 2rem;
}

h2 {
  text-align: center;
  font-weight: 300;
  font-size: 4rem;
}

p {
  color: darkgrey;
  text-align: center;
  font-family: "Fira Mono", monospace;
  font-size: 1rem;
  line-height: 1.5rem;
}

Detect IE/Edge version with JavaScript.
 Updated to recognize Internet Explorer 12+ aka Edge.

detecting…

n/a

Answer: Using this RegExp seems works for IE 10 and IE 11:
function isIE(){
    return /Trident\/|MSIE/.test(window.navigator.userAgent);
}

I do not have a IE older than IE 10 to test this.
Answer: For a minimal approach and untill IE officially dies on the August 17th 2021 ✌ I'm using the IE conditional statement in reverse .

Answer: Use Navigator:-
The navigator is an object that contains all information about the client machine's browser.
navigator.appName returns the name of the client machine's browser.

navigator.appName === 'Microsoft Internet Explorer' ||  !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie === 1) ? alert("Please dont use IE.") : alert("This is not IE")

Comment: appName is Netscape on IE 11. They did everything they could to trick developers.
Answer: I found IE11 is giving more than one user agent strings in different environments.
Instead of relying on MSIE, and other approaches, It's better to rely on Trident version
const isIE11 = userAgent => userAgent.match(/Trident\/([\d.]+)/) ? +userAgent.match(/Trident\/([\d.]+)/)[1] >= 7;

Hope this helps :)

Internet Explorer 11 detection


vb.net's AddHandler is what? A method of some call?

Question: In VB.net, I have to use AddHandler (to add handler function dynamically) without the brackets.
However if I use brackets like:
AddHandler(MyBtn.Click, AddressOf MyBtn_Click)

It does not work. The call must be without brackets.
Is there any equivalent syntax for calling AddHandler using brackets?
Is AddHandler different from subroutine or a function (method) of some class?
Answer: It's a statement, not a function call.  Just like Return.
You wouldn't do
Return(x)


What is the best way to mine the user's well-being, recent activity, and other useful info

Question: In a Mobile APP, what are the best practices for mining the user's well being
( how are you feeling, does it hurt here, and here ? ), recent activity ( when were you last physically active and what type of activity ), and a few other health related indicators and questions ( mostly subjective ).
This is without using any sensor input info.
Comment: You could just ask them?
Comment: Already been done: [https://www.trackyourhappiness.org/](https://www.trackyourhappiness.org/)
Answer: I worked on a project aiming to do just this. Project Ginsberg tracks a user's wellbeing by recording their responses to a set of self-selected subjective questions designed to track aspects of their wellbeing.
The user is able to pick questions that they feel contribute most to their wellbeing:

They are then asked those questions on a regular basis:

The application also tracks objective measures (such as time spent exercising and sleeping) using connected 3rd party applications and attempts to find patterns and correlations between objective and subjective measures.
To answer the question, the only way to get insight into a user's wellbeing is to ask them. You can "mine" objective data from other applications and trackers which can be connected to your application. Subjective data is much trickier and users are a lot less likely to be tracking their mood than they are their sleep for example.
I would suggest that the best practice around trying to access personal information about the user is to be very clear about the information you're taking and how (maybe why too). Asking up front, rather than "mining" for it, might actually be more appropriate.


How to upload file to DHC-REST/HTTP API with Selenium

Question: I'm trying to send POST request with Chrome extension DHC https://chrome.google.com/webstore/detail/dhc-resthttp-api-client/aejoelaoggembcahagimdiliamlcdmfm?hl=en (I know that there are a lot of tools to send http requests, but I need to use this one).
I wrote following code:
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

# Add Option to be able to use DHC extension
chrome_options = Options()
chrome_options.add_extension('/usr/lib/firefox/browser/extensions/aejoelaoggembcahagimdiliamlcdmfm-0.8.6.2-www.Crx4Chrome.com.crx')
# Start browser session
dr = webdriver.Chrome(chrome_options=chrome_options)
# Open Extension page
dr.get('chrome-extension://aejoelaoggembcahagimdiliamlcdmfm/dhc.html')
# Close update pop-up if exists
try:
    dr.find_element_by_xpath('//a[@class="btn btn-info"]').click()
except:
    pass
# Change HTTP request type to POST
request_type = dr.find_elements_by_xpath('//input[@class="gwt-TextBox"]')[1]
request_type.clear()
request_type.send_keys("POST")
# Choose body type 'file'
dr.find_element_by_xpath('//div[@class="pane-head"]').click()
dr.find_elements_by_xpath('//li[@class="dropdown right"]')[1].click()
dr.find_element_by_xpath('//a[contains(text(), "file")]').click()
# Set path to file I want to send
dr.find_element_by_xpath('//input[@class="gwt-FileUpload"]').send_keys('/path/to/file/dummy3gb')

After last step name of uploaded file appears, but actual file size is 0 bytes and I can't send request as content is not recognized
while if to choose file manually from upload prompt proper file size is displayed and I can send request
Am I doing something wrong? Any ideas?
Answer: When you are want to test your API from DHC for the post method. there has an option for input type like first one is test and second one is file. According to the image.

When you select the file from drop down you can post your file for your web service.


htaccess redirect failed when using htpasswd authentication

Question: I have a problem which is bugging me for over a day now, and I really have no idea where to look.
I have a website set up with a sub directory called cms, which is using a basic htpasswd login.
All requests to the main site are redirected to index.php using htaccess, except requests to the cms-folder, images and so on.
This results in the following htaccess in www_root:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\.domain\.nl [NC]
RewriteRule ^(.*)$ https://www.domain.nl/$1 [R=301,L]

RewriteCond %{REQUEST_URI}  !^/cms
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.css|\.js|favicon\.ico|\.svg|\.pdf|\.ino)$ [NC]
RewriteCond %{REQUEST_URI}  !^/robots.txt$ [NC]
RewriteCond %{REQUEST_URI}  !^/BingSiteAuth.xml$ [NC]
RewriteCond %{REQUEST_URI}  !^/apple-app-site-association$ [NC]
RewriteRule (.*)  framework/index.php [L]

Inside the cms-folder is a separate htaccess, containing only the authentication stuff:
AuthName "CMS"
AuthUserFile /path/to/.htpasswd
AuthGroupFile /dev/null
AuthType Basic

require valid-user

The problem is, when I request cms/index.php, the request gets redirected to framework/index.php instead of cms/index.php, like RewriteCond %{REQUEST_URI}  !^/cms isn't in the main htaccess, except when I remove cms/.htaccess, in which case everything is acting normal and I'm able to reach the (now unprotected) CMS.
The site is running on a Redhat Linux server, using Apache 2.4.16 and PHP 5.6.
Answer: Try turning on debug logging to watch what's going on:
RewriteLog "/tmp/debug.log"
RewriteLogLevel 6

As you step through the URLs on the site, the log will show you what rules are matching, and why.
For example when I set it up and watched /tmp/debug.log, I could see that this request (/somedirectory) was rewritten:
(4) RewriteCond: input='/somedirectory' pattern='!^/cms' => matched
(2) rewrite '/somedirectory' -> 'framework/index.php'
(2) local path result: framework/index.php

and this request (/cms) was not rewritten:
(2) init rewrite engine with requested uri /cms/index.php
(3) applying pattern '(.*)' to uri '/cms/index.php'
(4) RewriteCond: input='/cms/index.php' pattern='!^/cms' => not-matched
(1) pass through /cms/index.php


How do I increase the amount of stone that spawns vertically in a Minecraft world?

Question: So I'm starting an SMP where everyone works mainly underground, so we need a lot more underground to work with vertically speaking. Is there a way to basically generate the world a lot higher on the Y axis, so there's a lot more stone and stuff underneath? I looked through the customization settings in 1.12.2 but I'm not sure what exactly the stuff on the last two pages do. I kind of want to world to look something like this: https://ibb.co/n8VXssK
Comment: You probably need a mod.
Answer: I think I may have found a solution for what you are asking. I went into the world creation menu and changed the World Type to Superflat. From there, click Customize below it and then click the Presets button and select Tunnelers dream. This gives one layer of grass blocks, followed by 5 layers of dirt, then 230 layers of stone, and finally one layer of bedrock. Since this is superflat it would generate a completely flat top but it does give you a looooot more under ground to work with. Heres a screenshot of the layer settings I mentioned to give visual aid.
Comment: I'm not sure superflat will do. We still want biomes and oceans and stuff, but I'll experiment around with it.


Can I use my computer's Wi-Fi connection with the DeSmuME core in OpenEmu?

Question: I'm using the emulator-conglomerating application OpenEmu, and to emulate the Nintendo DS it uses the DeSmuME core. I've been able to find tutorials online to use the computer's Wi-Fi connection with the standalone DeSmuME application, but is there any way to accomplish the same within OpenEmu?
Comment: I'm not entirely sure. I know that official DeSmuME builds do not support wifi, but there are builds you can download that have it enabled. [More information.](http://linkbun.ch/02es5)
Comment: Ah, I see, I hadn't realized those were instructions for non-official builds. That information makes it highly unlikely that it would be possible to enable it in Open Emu until it is officially supported, as the cores are custom-built for the program. Should this question be closed, then?
Answer: If you are going to want the DSEMU core I would suggest using it itself. Unless you can find a video saying that It is for OpenEmu because certain setup steps would be required.


Combination of continuous and discontinuous functions

Question: I know that combining two continuous functions gives a continuous function, i.e., if $f(x)$ and $g(x)$ are continuous, then $f(x)\pm g(x)$, $f(x)\times g(x)$ and $f(x)\div g(x)$ are continuous provided $g(x)\neq 0$. But what if $f(x)$ is continuous and $g(x)$ are discontinuous and we want to determine what type of function $f(x)\times g(x)$ is.
I have tried something out to prove that it will be discontinuous.

Let $h(x)=f(x)\times g(x)$.
   Thus,  $g(x)=\frac{h(x)}{f(x)}$, where $f(x)\neq 0$
If $h(x)$ is continuous, then $g(x)$ is also continuous. But this is contrary to our assumption.
So, $h(x)$ must be discontinuous.
  So, $f(x)\times g(x)$ must be discontinuous.

This is alright but when I asked my teacher he said that the multiplication can yield both sort of functions, continuous and discontinuous. So, what have I missed in my derivation?
Should I have considered something else as well or was my conclusion wrong?
Comment: f(x) = 0 will yield a continuous function after multiplication.
Comment: Careful. Let f=1 and g=x. Is f/g everywhere continuous? oops i see you ruled out g = 0...nevermind. How did you derive g(x)?
Comment: @drawnonward as you can see, I did not derive $g(x)$. All I did was to try to represent it in terms of two functions whom I can say are continuous. My doubt in the proof is that, what are the exceptions and how can they be accounted for in this proof.
Answer: You have proven that if $f(x)\neq 0$ and $g$ is not continuous, then $f(x)\cdot g(x)$ is not continuous. Your proof is correct.
However, if $f(x)$ can be allowed to have zero values, all bets are off. For example, if $f(x)=0$ for all values of $x$, then $f\cdot g$ will be continuous no matter what the function $g$ is.
Comment: Exactly. It yields a discontinuous function if $f\neq 0$, and a continuous if $f\equiv 0$, for example.
Comment: Does that mean that the multiplication operation may yield a continuous as well as a discontinuous function depending on the situation ?
Answer: You remark in your proof that $f(x)\neq 0$, but it's perfectly reasonable that $f(x)=0$.
Comment: @Ris97: Exactly :) And the proof you did produce gives you a bonus fact: the only way that a discontinuous point $x$ of $g$ can become a continuous point of $h$ is if $f(x)=0$.
Comment: I did that because it was coming as a denominator.
Comment: Yes, you did it because you'd be wrong if you didn't--- because as you said, you put it in a denominator. But the fact remains that it's entirely possible that $f(x)=0$, because $f(x)$ didn't *start out* in a denominator. My answer is the same as 5xnum's so if you understand eir's better then you're not missing out. (Except, he said and I should have: your proof is totally valid, it just doesn't prove what you wanted it to prove.)
Comment: Oh okay! I think I understand now. So if I do not assume anything out of the blue, then the the type of function depends on the situation.
Answer: Well! Its not necessary that one of the functions must be zero.
For ex- take |x| as f(x) and sgn(x) as g(x). Now their product is |x|sgn(x) which is continuous. U can check its continuity on 0 as its the only suspicious point. And their left hand side limit and right hand side limit will come same.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Please avoid using abbreviations like  "U" for "you" :)
Comment: Ohh..OK. thanks.
Comment: But here the function $f(x)=|x|$ is $0$ at $x=0$, which is the point that we are interested in. So indeed $f$ need not be equal to $0$ everywhere, but at those "suspicious points".


Why do I get zero when pushing_back floats to a vector?

Question: While I was testing someting, I have created a vector of type float, and put the values 1/i into that vector;however, while reading the values, the output is printed as integers and not as float.
#include <stdio.h>
#include <vector>
#include <iterator>

int main(int argc, char const *argv[])
{
    std::vector<float> testVec;
    for (int i = 1; i < 5; ++i)
    {
        float v = 1/i;
        testVec.push_back(v);
    }

    std::vector< float >::iterator it = testVec.begin();
    for (; it!=testVec.end(); ++it)
    {
        printf("The value of the iterator: %f, *it);
    }
    return 0;
}

So, what is the problem with this ? Is it related with the iterator ? I mean I have not much experienced with them.
Comment: `1/i` where `i` is of type integer is **integer arithmetic**.
Comment: `1` is an `int`, `i` is an `int`, so `1/i` is an `int`.
Comment: @AditiRawat Oh, I see. Thanks for pointing out.
Comment: @AditiRawat I advise you to post your comment as answer.
Comment: So it's not that you "can't puhback" as said in the title, but that you can pushback and are not happy with what you can find back...
Comment: @Christophe That is actually turned out to be the case :)
Answer: The reason behind your issue is that 1/i where i is of type integer is integer arithmetic and will give integer as output.
1.0 in place of 1 would help you. :)


what does '__getnewargs__' do in this code

Question: class NavigableString(unicode, PageElement):

    def __new__(cls, value):
        if isinstance(value, unicode):
            return unicode.__new__(cls, value)
        return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)

    def __getnewargs__(self):#this line
        return (NavigableString.__str__(self),)

Answer: Try this:
x = NavigableString('foop')
y = pickle.dumps(x)
z = pickle.loads(y)
print x, z

I.e.: __getnewargs__ tells pickle.dumps to pickle x in such a way that a pickle.loads back from that string will use NavigableString.__new__ with the proper argument.


Android: Cannot set gravity of TableLayout to Right

Question: I know there are tons of questions about this already floating around SO but I've read a bunch of them and still cannot get my 3rd column to align to the right.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:background="#FFFFFF"
  android:stretchColumns="2"
 >
  <TableRow>

 <ImageView
  android:src="@drawable/blue_light"
  android:layout_height="48px"
  android:layout_width="48px"
  android:padding="3dp"
  android:layout_margin="3dp"
  android:layout_column="1"/>

   <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginLeft="10px"
   android:layout_gravity="center_vertical"
   android:layout_column="2">

   <TableRow>
    <TextView
     android:id="@+id/row_title"
     android:textColor="#000000"
     android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textStyle="bold" />
   </TableRow>

   <TableRow>
    <TextView
     android:id="@+id/row_author"
     android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textColor="#9E9E9E"
      android:textStyle="italic|bold"/>
   </TableRow>

   </TableLayout>

   <TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_column="3"
    android:layout_gravity="center_vertical|right"
  android:gravity="center_vertical|right"
   >

   <TableRow>
    <TextView
     android:textColor="#1F9C29"
     android:textSize="15dp"
     android:id="@+id/row_txt1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textStyle="bold" />
   </TableRow>

   <View
    android:layout_height="1dp"
    android:background="#000000"
    android:layout_marginRight="3dp"
    />

   <TableRow>
    <TextView
     android:textColor="#1B27D1"
     android:id="@+id/row_txt2"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textStyle="bold"/>
   </TableRow>

   </TableLayout>
  </TableRow>
</TableLayout>

What am I doing wrong?
Answer:
cannot get my 3rd column to align to the right.

Off the cuff, I suspect that nested TableLayout widgets will not work terribly well. While TableLayout was designed to mimic the HTML table "API", there are limits to the analogy.
If you want the "3rd column to align to the right", put everything into the outer TableLayout, then try android:layout_gravity="right" on all widgets in that column.
Comment: Yup that was it. I moved to using nested LinearLayouts within  the TableLayout to simplify the XML. Thanks!
Answer: I had the same problem, and solved it with the following:
Inside the TableRow attributes add the two following lines:
android:layout_gravity="center"
android:gravity="right"

If you use the Layout_gravity = right, for some reason it does not work at all.
Enjoy,
Adrian.


Qt three ComboBoxes for a date

Question: I have been looking around Google and Stackoverflow, but I have yet to find out if there is any simple solution to auto-filling three comboboxes to represent a correct date (like YYYY-MM-DD). I would presume it would be related to QCalendarWidget. Any ideas?
I want to be able to scroll through current time to dates from X years ago, it shouldn't have non-existant dates like February 29, 2011. Not sure if this is asking for too much.
Comment: For that you have to add those dates manually to combo boxes.Use some simple logic in loop. I don't think there is too much to be done in implementing it this way
Comment: Why would you need three combo-boxes with identical content? I would recommend using QDateEdit instead of QComboBox
Comment: One box is YYYY, one is MM, one is DD. I will look into QDateEdit.
Answer: Now i get what's your idea.
The answer is simple. Make three combo boxes: Day (1 - 31), Month (1 - 12) and Year (i.e. 1999 - 2012). Create "OK" button. No ultra-logic is needed.
After button being pressed just validate the date by creating QDate object with three numbers given by user and calling QDate::isValid(). If it isn't, create some warning prompt and ask user to change something in input.
The best way to validate the data entered by user is to override QDialog::done() method.
void Dialog::done(int r)
{
    if(r == QDialog::Accepted) {
        QDate date;
        //Create QDate from comboboxes' values
        ...
        if(!date.isValid()) {
            //Some warning to user.
            return;
        }
    }
    QDialog::done(r);
}

Comment: Just my personal opinion: An alternative way would be to make the available days dependent from the month currently being selected, so if you select "February", you can only select the days 1..28 or 29, depending on the year. But this would be not as easy to use as you might think, because if you start selecting the day (while the month is at "February"), you might not be able to select the day you want to, so you would *have to start with the year*, then the month and finally the day. This will restrict the user.
Answer: int X = 2;
QDate date = QDate::currentDate(), lastDate = date.addYears(-X);
for(; date > lastDate; date = date.addDays(-1))
    ui->comboBox->addItem(date.toString("yyyy-MM-dd"));

Comment: I'm sorry, I misunderstood the question... I thought author expects three comboboxes like this one. Now i see he meant one for day, one for month and one for year...

Qt three ComboBoxes for a date


How to switch between maven and local build dependencies

Question: My title isn't exactly clear so I'll describe my situation before asking the question:
I have a number of libraries (~15), some of which depend on each other and a number of apps (~5) that depend on various subsets of these libraries. The libraries are hosted on an internal maven site. Most of these apps function within the same domain and there's an overlap in functionalities as well as data models used. Sometimes, adding a feature means making changes to a library in the middle of the hierarchy tree, providing support for it upstream (libs towards the root of the dependency tree), and then utilizing the changes upstream (applications as well as libraries that use the changed libraries).
I want to:

Fetch these libraries from Maven when I'm working on application code
Edit and compile these libraries from within my project while I'm working on changes that affect libraries

My current process is a bit tedious:

Checkout the source for the library(ies) and place it beside my application code (workspace/app_code, workspace/lib1_code, workspace/lib2_code, etc.)
I add include ':lib1_code', include ':lib2_code', etc. to my settings.gradle (I have these commented out so I just toggle them on and off as needed)
I replace the
implementation "com.packages:lib1:1.2.3" with implementation project(':lib1_code') (and so on)
I do the same in the dependent libraries too.

As you can see, it's a lot of work and nobody on my team (myself included) likes the process.
I want to be able to just do all of the above with a set of properties like buildLib1UseLocal=true
Questions:

How common is my scenario?
Does gradle have support for something like this?
Is there another build system that does?
Answer: Gradle is based on Groovy, so it provides full scripting support. You can just evaluate the property on your own:
dependencies {
    if (buildLib1UseLocal) {
        implementation project(':lib1_code')
    } else {
        implementation 'com.packages:lib1:1.2.3'
    }
}

Gradle even provides a feature called dependency substitutions. It allows you to define your dependencies in the regular way, but to resolve them from other sources:
dependencies {
    implementation 'com.packages:lib1:1.2.3'
}

configurations.all {
    resolutionStrategy.dependencySubstitution {
        if (buildLib1UseLocal) {
             substitute module('com.packages:lib1:1.2.3') with project(':lib1_code') because '<some reason>'
        }
    }
}

Comment: I would have to replicate this code in all the library codes too, right?
The good thing, though, would be that if App A includes libs 1, 2, 3, the dependency substitution will propagate to the libs too (whichever is built locally), correct?
Comment: As always, you may wrap some piece of Gradle configuration inside a `allprojects` closure of your root project to apply it for all projects at one place.


How does Ability Power affect the damage of skills?

Question: I know that Ability Power increases the damage of the skill that your champion can use. However, I am not sure how it works. For example, does your skill's damage increase by 1 for every 1 point of Ability Power? If not, what is the rate of increasing damage per ability power? And does ability power affects skills that stuns or slows, or passive skills as well?
Answer: Scaling by stats
Not all skills are increased by ability power, some are increased by other values like Health, Attack Damage, Armor and / or Magic Resist.
Here are 2 examples for different scaling:
Galio's Runic skin (passive)
Galio gains bonus ability power equal to 50% of his total magic resistance
Lux's Illumination (passive)
Lux's damaging spells mark any enemies with light energy for 6 seconds. Her autoattacks or Final Spark.png Final Spark will consume the mark, dealing 10 + (8 × Lux's level) (+ 20% AP) magic damage to the target.
Scaling ratio
The ratio for the specific skill differs per skill.
All the abilities are unique, and therefore have their own scaling.
For example, let's take Lux:
Passive: Illumination
Lux's damaging spells mark any enemies with light energy for 6 seconds. Her autoattacks or Final Spark.png Final Spark will consume the mark, dealing 10 + (8 × Lux's level) (+ 20% AP) magic damage to the target.
Q: Illumination
MAGIC DAMAGE: 60 / 110 / 160 / 210 / 260 (+ 70% AP)
SECOND TARGET MAGIC DAMAGE: 30 / 55 / 80 / 105 / 130 (+ 35% AP)
W: Prismatic Barrier
SHIELD STRENGTH: 80 / 105 / 130 / 155 / 180 (+ 35% AP)
E: Lucent Singularity
SLOW: 20 / 24 / 28 / 32 / 36%
MAGIC DAMAGE: 60 / 105 / 150 / 195 / 240 (+ 60% AP)
R: Final Spark
MAGIC DAMAGE: 300 / 400 / 500 (+ 75% AP)
CC Scaling
Ability power (and other stats) may increase stuns, slows and passives, according on the skill. (however, this is not always the case and the scaling is, because the skills are unique, always different)
For example:
Janna's Zephyr (W skill)
PASSIVE: Janna is aided by a wind elemental, gaining movement speed and ignoring unit collision.
MOVEMENT SPEED BONUS: 4 / 6 / 8 / 10 / 12% (+ 2% AP)
ACTIVE: Janna launches the elemental to deal magic damage and Slow icon slow an enemy's movement speed for 3 seconds (capped at 80% total). She loses the ability's passive benefits while it is on cooldown.
MAGIC DAMAGE: 60 / 115 / 170 / 225 / 280 (+ 50% AP)
SLOW: 24 / 28 / 32 / 36 / 40% (+ 6% AP)

Source: Lol Wikia
CC = Crowd Control (Slow, stun, fear)
Comment: A lot of useful information here, but wasn't exactly what I was looking for... but still great for reference!
Answer: The ratio between the AP and the damage dealt (or special effects) is defined on a spell by spell basis. This wiki excerpt explains it better than I could:

For example, if a spell deals 100 (+20% AP) damage and a champion has 50 ability power, the spell's damage will increase by 10.
  In-game, spell descriptions do not display the percentage, but do display the resulting bonus; the previous example would display as 100 (+10).

The spell description appears on muse over and extra damage is color coded:
1. Green - scales with AP
2. Orange - ... AD
3. Red - ... HP
4. Blue - ... Mana
5. Yellow - ... Armor
6. Magneta - ... Magic Resist
Some skills have things other than damage augmented by AP, like Janna's Zephyr.
The skill's tooltip should always tell you when this is happening. A good wiki or guide site could also tell you the ratio, that's obscured in the game for some reason I don't entirely understand.
Comment: I would like to add some useful tip, but I have no reputations yet to comment.

Upon mouse-over on the specific skill, you may notice that there are some texts/values that are in green, it means that the skill damage(or damage reduction, or speed increase, or whatever) scales with AP. Other skills does not increase damage even if AP is increased.

Here are some other details for the color scheme:

Green - scales with AP
Orange - ... AD
Red - ... HP
Blue - ... Mana
Yellow - ... Armor
Magneta - ... Magic Resist
From: ChinoCarlo
Answer: I would like to add some useful tip, but I have no reputations yet to comment.
Upon mouse-over on the specific skill, you may notice that there are some texts/values that are in green, it means that the skill damage(or damage reduction, or speed increase, or whatever) scales with AP. Other skills does not increase damage even if AP is increased.
Here are some other details for the color scheme:

Green - scales with AP
Orange - ... AD
Red - ... HP
Blue - ... Mana
Yellow - ... Armor
Magneta - ... Magic Resist


Modify a substring without altering the string in Bash

Question: I have this string:
14-Nov-2018 10:14:44.775 client IP1#59098: view internal: query: DOMAIN IN A + (IP2)

I want to parse it to delete minutes and seconds from the hour. The result would be the next:
14-Nov-2018 10 client IP1#59098: view internal: query: DOMAIN IN A + (IP2)

I get this string from a file, so It would be perfect if It is achieved with a pipe. My current line is as follows:
cat $dns_logs | grep "$date" | HERE WOULD BE YOUR SOLUTION > $temp_queries

Thanks!
Answer: sed -r 's/(:[0-9]{2}){2}\.[0-9]{3} //'

Comment: Thanks! I modify your solution and It works: sed -r 's/:[0-9]{2}:[0-9]{2}.[0-9]{3} / /g'.
Answer: If you are ok with awk then could you please try following.
echo "14-Nov-2018 10:14:44.775 client IP1#59098: view internal: query: DOMAIN IN A + (IP2)" |
awk '
  match($0,/[0-9]+:[0-9]+:[0-9]+\.[0-9]+/){
  print substr($0,1,RSTART-1),substr(substr($0,RSTART,RLENGTH),1,2),substr($0,RSTART+RLENGTH+1)
  next
}
1'

Comment: Wow thanks! That is interesting since I didn't know how to match inside AWK. Thanks again!
Comment: @Miguel.G, your welcome, you could try to encourage people by up-voting their helpful answers too on SO.
Answer: The whole line can be done as
awk -v d="$date" '($0 ~ d){$2=substr($2,1,2); print}' "$dns_logs"


How to avoid other Ingress players to steal items when I am exchanging items with others?

Question: It is very annoying that when I am dropping capsules to other Ingress members, someone steal it. I lose many items from this problem and I don't know what to do to prevent it.
Answer: Fundamentally, you can't. Arrange to meet the people you want to trade with somewhere quiet so you can be reasonably sure there's nobody else around.


JavaScript outputting [object, object] instead of string

Question: I am trying to output the correct answers of the quiz it outputs the correct number of questions that are correct but when trying to output the text of the question I get [object,object] anyone know why its doing this?
HTML

Next

Prev

 Start Over

Whatswhatquiz.js file
(function() {
  var questions = [{
    question: "what browser feature would you use to find information on the Internet? (Click on Circle)",
    choices: ["Web Form", "Link", "Button", "Navigation Bar", "Search Bar"],
    correctAnswer: 4
  }, {
    question: "Where would you find the main links of each page on a website?",
    choices: ["Button", "Search Bar", "Web Form", "Navigation Bar"],
    correctAnswer: 3
  }, {
    question: "What feature will you use when entering personal details to a website? ",
    choices: ["Link", "Button", "Web form", "Search bar"],
    correctAnswer: 2
  }, {
    question: "What feature is used to hold a large list of information?",
    choices: ["Button", "Link", "Search Bar", "Dropdown Menu/List"],
    correctAnswer: 3
  }, {
    question: "What box are you most likely to select when giving permission to a website?",
    choices: ["Select Box", "Tick Box", "Check Box", "Grey box", ],
    correctAnswer: 2
  }];

  var questionCounter = 0; //Tracks question number
  var selections = []; //Array containing user choices
  var quiz = $('#quiz'); //Quiz div object
  var correct = [];
  var wrong = [];

  // Display initial question
  displayNext();

  // Click handler for the 'next' button
  $('#next').on('click', function(e) {
    e.preventDefault();

    // Suspend click listener during fade animation
    if (quiz.is(':animated')) {
      return false;
    }
    choose();

    // If no user selection, progress is stopped
    if (isNaN(selections[questionCounter])) {
      alert('Please make a selection!');
    } else {
      questionCounter++;
      displayNext();
    }
  });

  // Click handler for the 'prev' button
  $('#prev').on('click', function(e) {
    e.preventDefault();

    if (quiz.is(':animated')) {
      return false;
    }
    choose();
    questionCounter--;
    displayNext();
  });

  // Click handler for the 'Start Over' button
  $('#start').on('click', function(e) {
    e.preventDefault();

    if (quiz.is(':animated')) {
      return false;
    }
    questionCounter = 0;
    selections = [];
    displayNext();
    $('#start').hide();
  });

  // Animates buttons on hover
  $('.button').on('mouseenter', function() {
    $(this).addClass('active');
  });
  $('.button').on('mouseleave', function() {
    $(this).removeClass('active');
  });

  // Creates and returns the div that contains the questions and
  // the answer selections
  function createQuestionElement(index) {
    var qElement = $('
', {
      id: 'question'
    });

    var header = $('
Question ' + (index + 1) + ':
');
    qElement.append(header);

    var question = $('
').append(questions[index].question);
    qElement.append(question);

    var radioButtons = createRadios(index);
    qElement.append(radioButtons);

    return qElement;
  }

  // Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('
');
    var item;
    var input = '';
    for (var i = 0; i < questions[index].choices.length; i++) {
      item = $('
');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += questions[index].choices[i];
      item.append(input);
      radioList.append(item);
    }
    return radioList;
  }

  // Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }

  // Displays next requested element
  function displayNext() {
    quiz.fadeOut(function() {
      $('#question').remove();

      if (questionCounter < questions.length) {
        var nextQuestion = createQuestionElement(questionCounter);
        quiz.append(nextQuestion).fadeIn();
        if (!(isNaN(selections[questionCounter]))) {
          $('input[value=' + selections[questionCounter] + ']').prop('checked', true);
        }

        // Controls display of 'prev' button
        if (questionCounter === 1) {
          $('#prev').show();
        } else if (questionCounter === 0) {

          $('#prev').hide();
          $('#next').show();
        }
      } else {
        var scoreElem = displayScore();
        quiz.append(scoreElem).fadeIn();
        $('#next').hide();
        $('#prev').hide();
        $('#start').show();
      }
    });
  }

  function buildList(arr) {
    var listHTML = '
';
    for (var i = 0; i < arr.length; i += 1) {
      listHTML += '
' + arr[i] + '
';
    }
    listHTML += '
'
    return listHTML;
  }

  // Computes score and returns a paragraph element to be displayed
  function displayScore() {
    var score = $('
', {
      id: 'question'
    });

    var numCorrect = "0";
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
        correct.push(questions);
      } else {
        wrong.push(questions);
      }
    }

    score.append('You got ' + numCorrect + ' questions out of ' +
      questions.length + ' right!!!' + buildList(correct));
    return score;
  }
})();

Comment: Is `var question = $('').append(questions[index].question);` the line that's giving you problems?
Comment: Please be more specific. What part of your code is outputting this?
Comment: The function displayScore() is outputting this? It computes the correct answers and displays 'You got 3 answers out of 5 correct' And then underneath it displays a list of 1. [object, object] 2. [object, object] 3. [object, object] so it is recognising that it should be displaying the 3 questions that are right but not showing the question text.
Comment: Please post html so we can test this code
Comment: It likely means you're trying to output an array of objects,
Comment: I have posted the HTML
Comment: Once thing to mention is that you may want to use `` instead of `` in the result page, so the numbers in the correct answers list doesn't get confused by the actual index of the question.
Comment: Oh yes, you are right. Thanks Man.
Answer: UPDATE: I've found your problem, you were pushing the entire array of objects into correct and/or wrong array. Also, in your buildList function you were returning the object at a position which is why you were getting [object object]. So specify the property you want from the object.
function buildList(arr) {
    var listHTML = '
';
    for (var i = 0; i < arr.length; i += 1) {
        listHTML += '
' + arr[i].question + '
';
    }
    listHTML += '
'
    return listHTML;
}

var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
    if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
        correct.push(questions[i]);
    } else {
        wrong.push(questions[i]);
    }
}

Comment: what's the relevance of this ?
Comment: Title: JavaScript outputting [object, object] instead of string.
Comment: What he wants is to know why the code is wrong and not a way to convert the an array of objects to string.
Comment: You should judge the other guys answer.
Comment: Even after you edited it no I shouldn't. He written: "Then try to iterate myJSON." which you didn't.
Comment: I found his problem now. It makes sense. I'm saying to judge the other guy because he had the same answer as I did initially. I listened and learned.
Comment: Luis yes its working now, thanks for the explanation appreciate it!


Refactor class method to property using Pycharm

Question: I have the following class:
class Dogs(object):
    def __init__(self):
        self.names = []
        self.breeds = set()

    def number(self):
        return len(self.names)

I want to change number to being a property. This means I also want to change all of it usages. Does PyCharm have this built into it's refactoring tools? It seems to be according to this issue.
At this point, I'm doing "find all usages" and then manually fixing each instance. If there isn't a specific refactoring tool for changing a method to a property, is there some way to use "find all usages" more effectively?
Answer: Yes, you can refactor a method to a property in PyCharm. Strangely, this does not correspond to any entry in the "Refactor" menu.
Just place the editor cursor on the name of the method and press Alt+⏎ shortcut to show the available Intentions.
Then, select "Convert method to property".

You can also trigger the global action search with Ctrl+Shift+A and select the intention from there.
Comment: Strangely, the inverse operation isn't available :)


How do I run Maltego after installing it?

Question: I installed Maltego from Paterva's website and it successfully installed. Now, how do I run it? I typed "maltego" on the terminal a zillion times and it comes back with "command not found". I tried entering "sudo apt-get install maltego" and get back with "maltego is already the newest version". There is no icon on the desktop or applications menu, but the Ubuntu Software Center reports that it was successfully installed. What do I do??
Edit: I found the icon but it doesn't respond to any command
Comment: Welcome to Ask Ubuntu! **;-)** Could you please give us a bit more information by [edit]ing your question and telling us: what version of Ubuntu you're running? What the output to `locate maltego` is?  Please [edit] your question and add this information... (Please help us help you!) Then leave a comment @Fabby.
Answer: To make sure it installed properly check to see if /usr/bin/maltego_community exists. You should be able to run this file to open Maltego.
You need superuser access for this:
To add the shortcut, make a new file called maltego-community.desktop
Open the file with a text editor and paste in the following:
[Desktop Entry]
Version=4.0
Type=Application
Name=Maltego Community
GenericName=Maltego Classic
Comment=Visualise, Map and Mine Data
Exec=/usr/bin/maltego_community
Icon=maltego_community

Terminal=false

Actions=ConfigureMemory;ShowWebsite;

[Desktop Action ConfigureMemory]
Name=Configure Memory
Exec=/usr/bin/maltego_community_memory_config

[Desktop Action ShowWebsite]
Name=Paterva Website
Exec=x-www-browser https://www.paterva.com

If Maltego doesn't run, it may be because you don't have Java installed.
Install it by running sudo apt install default-jre


sudo service networking start doesn't work

Question: I just configured dns-nameservers in /etc/network/interfaces.
To make it take effect instantly, I typed sudo service networking stop, the desktop seems to kill some processes, anyway the UI is down...
Then I switch to Ctrl+Alt+F1 and type sudo service networking start.
It prompts that networking stop/waiting.
I've tried several times and can't figure out what's the reason. Can anyone help me with this?
Thank you!
Answer: The commands to start, stop and restart network manager are
sudo service network-manager stop

sudo service network-manager start

sudo service network-manager restart

You set the dns-nameservers in network manager and not /etc/network/interfaces unless you are not using network manger because network manger will overwrite what is in /etc/network/interfaces.


I ask for your help in this crazy modal/dialog flow

Question: CONTEXT

We are sending companies to the clients from a draft list.
The draft list can be viewed and reviewed by clients, who have to decide if they like or not these companies
When clients like a company, the company is saved
When clients don't like a company, we ask with a dialog why and then we archive the company

PROBLEM W/ THE DIALOG

The dialog asks: "Why did you pass on this company?"

There are two selectable reasons, once selected, the user can:

Write more feedback about that reason and then click on CTA,

Just click on the CTA without providing more feedback.

Users in general don't provide more information, and just click the CTA (totally understandable in terms of usability)

The company wants that written feedback, so we want to incentive users to write input without making that action mandatory.

POSSIBLE SOLUTION
I've thought of a two-step modal.

First step: select the reason.
Second step: a new view of the modal with a text input asking for more info. This is optional, and the user can directly click the CTA or write more info and then click the CTA.

In general, I don't like two-step dialogs, but adding the text input under the selected reason after being selected is failing, and I think that adding that extra step focused on the (optional) text input will get more written feedback from clients.
Answer: I think that before you come up with a solution, you need to understand a little more about the problem(s), which you can do with user research (via a quick survey, or even by calling 5-10 clients who regularly don't fill out the feedback and just asking them.) There are several things you can try, but here are a few potential problems and solutions to get started:
The problem: "What's in it for me?" Most people don't give feedback unless they feel a need to do so. It's just another thing to do in their day, and if it's optional, they'll skip it.
The solution: Provide a reason. You could add a small line at the top of the dialog that says, "Your response will help us pick a better company for you next time." If they know that their feedback makes a difference, they'll be more likely to give it.
The problem: "I don't have time to write an essay about this company that I don't like." Open-ended feedback is often seen as a lengthy chore.
The solution: Provide a one-click multiple choice answer set with an "Other" option. Find 5-8 of the most common reasons why companies aren't being selected through your research, and list them. Let the user still have the option to write something in if their problem isn't a fit.
The problem: Rejecting is awkward. You stated that you're potentially sharing negative feedback with a company that was just rejected by a potential client. It's human nature to not want to hurt others' feelings, especially if there's a sense that it won't be anonymous.
The solution: Create psychological safety in the process. If your clients know that you're sharing their feedback, ensure them that it's anonymous and that you won't share verbatims with the companies. Broaden it into larger categories, like cost, or not enough experience.
The problem: "It's not really their business what I think of them, just send me someone else." When people are in a position of power over another, they don't feel that an explanation of their decisions is owed to that person or entity. If you decide not to buy a car and the dealer calls to ask why not, you're not entitled to give an answer. That's just a norm in many cultures.
The solution: Don't tell your clients that you're sharing the info with the companies. Make it all about optimizing their future results with you.


How do I make scheduled snapshots of an authenticated webpage?

Question: How can I, as an Ubuntu beginner, get a daily snapshot of a webpage? The page requires a log in and then displays a bunch of numbers that I'm interested in.
Can I write a script to take care of this?
(I am on a waiting list for college dorm housing and want to keep a close eye on the progression. There's a long list of daily updated info that I would like to store somewhere I can easily flip through it.)
Edit:
so I used Rinzwind's script and did some research on my own; here's what I have so far:
    #!/bin/bash
   filename="kkik"
   url="https://www.kollegierneskontor.dk/default.aspx?func=kkikportal.housingrequests&lang=GB"
   date=` date +%d%m%Y`
   output="$filename-$date.html"
   wget --save-cookies cookies.txt --post-data 'Page_ctl05_Main_ctl04_form_loginUserName=*****&Page$ctl05$Main$ctl04$form$loginPassword=******'
   wget  --load-cookies cookies.txt  $url -O $output

it successfully downloads the 'you don't have permission' page (if I take out the cookies and post stuff it gives me a 'you need to log in' page, which is different).
Am I missing anything obvious? It doesn't seem like an overly complex website.
I'm sure if I get the script to run, I'll figure out how to make a Cron job out of it.
Comment: it depends on what you need to do to get to the website (and my danish is very rusty ;) so it will be hard for me to explain)
Comment: When you say "snapshot" do you mean like a screenshot or just a time-localised copy of the data?
Comment: either would be fine, but time-localised copy is more than enough.
Comment: In a normal browser, when I click 'Ansogning', I need to login (Username and password). I looked into the source and it's a normal 'input type="text"' thing. I took the names/id's off of them and put them in the --post-data section... Right now it's giving me session time out (a third different error page) after adding --keep-session-cookies.
Answer: 1. Downloading a snapshot of a website
You can download the page with some simple commands. Does it require logging in each time? That might require some extra coding but this is a general script that downloads a website (and appends a date to the download)
   #!/bin/bash
   filename="askubuntu"
   url="www.askubuntu.com"
   date=` date +%d%m%Y`
   output="$filename-$date.html"
   wget $url -O $output

Result:

askubuntu-210611.html can be viewed with a browser or a text viewer like gedit.
This can even be altered to add in some sed/grep commands to filter everything that is html out of the result and just save the data you require. Makes it easy to add the data to libreoffice calc for instance.
If you add it to a cron script you can have it do this every x minutes/hours.
2. Making several screenshots of a website
Shutter  can make images from command line with
   shutter --window=.*firefox.*

This will make a screenshot of an instance named firefox and save it with a new name in the folder you save your shutter screenshots.
Add this to a script and have it execute once every time you want and you can have screenshots of your website. As long as you refresh the page with an add-on like refresh every you are set to go.
Shutter also is capable of making an image of a part of the screen with
    shutter -s=100,100,300,300 -e

or capture a screenshot of a website (probably not useable for you if you need to login every time):
    shutter --web=[URL]

Comment: I would use #1 of Rinzwind's and set it up in cron.
Comment: Bugreport and fix on shutter --web not working: https://bugs.launchpad.net/ubuntu/+source/shutter/+bug/793125
Answer: Not sure if it is a solution for you because it does not address all your requirements. However with the ScrapBook Firefox extension you can create snapshots of websites easily. Each time you grab a snapshot it creates an entry in a list sorted by date and you can easily go back a look at any version.
Because you need to login to the site, ScrapBook extension is great because you can login first and then take the snapshot as a logged user.
The only thing that it will not do is automated snapshots because you will need to navigate to the site and save the snapshot manually.
Hope this helps.
Comment: the automation is kind of the point. I can copypaster/save webpage/printscreen manually, but since I want it daily and have very little discipline, I'm bound to forget ;). I'll check it out though!
Answer: @joon I guess you need xdotool.
Xdotool lets you simulate keyboard input and mouse activity, move and resize windows, and much more. Take a check. With this you can do your autentication in the classic "gui" style, then your code can take the screenshot and whatever... I hope this helps you on your way.


Prolog - Multiplication by recursive addition

Question: I am trying to recursively do addition to multiply two numbers in swi-prolog. I am currently learning Prolog and I do not want to use any library like clpfd.
mult(A, B, C) :- A  0, B1 is B - 1, mult(A, B1, A + C). % keep adding
mult(A, B, C) :- B == 0, C is 0. % base case

'C' is supposed to be the result.
This is trying to replicate the following algorithm in Java:
int product(int x, int y)
{
    # first prolog line
    if (x < y)
        return product(y, x);

    # second prolog line
    else if (y != 0)
        return (x + product(x, y - 1));

    # third prolog line
    else
        return 0;
}

However, no matter how I vary the input, the result will always be 'false'. I was able to step through my instructions with :- trace., but I cannot find out how to fix this.
Answer: The problem is the last literal of your second clause: mult(A, B1, A + C).
What you really want is the result of A*B1 to add that to A.
So try replacing this line with:
mult(A, B, C) :- B > 0, B1 is B - 1, mult(A, B1, C1), C is A + C1.