text:
Q: Showing that $\cos(u_1,u_3)=\cos(u_1,u_2)\cos(u_2,u_3)$ for nearby $u_i$ Edit if we replace rotations with "add isotropic noise", this relation can be proven using Chebychev inequality as shown here. The $\pi/4$ angle seems to be connected to forgetting of starting point. In high dimensions, random rotations seem to keep iterates $u_1,u_2,...,$ roughly along the same line (hence triangle inequality for cosines becomes equality), until $\pi/2$ angle is reached at which point the process becomes ergodic.

Suppose I start with vector $u_1$ in $d$ dimensions and obtain $u_{i+1}$ by performing a sequence of $i$ small rotations in $d$ dimensions. For $d=100$, the following gives a good approximation, within 0.1% of true value in expectation.
$$\cos(u_1,u_4)=\cos(u_1,u_2)\cos(u_2,u_3)\cos(u_3,u_4)$$
where
$$\cos(x,y)=\frac{\langle x, y\rangle}{\|x\| \|y\|}$$
"Small rotation" of $v$ is done by sampling entries $z$ from standard normal, and rotating $v$ in the plane defined by vectors $v,z$ by $\theta$ radians. This identity works for $\theta_i\le\pi/4$ and breaks down for $\theta$ slightly above $\pi/4$.

*

*How can this be justified?

*Why is $\pi/4$ special?

A: EDIT: It turns out I was misunderstanding. This is not a solution to the problem.
Unless I'm misunderstanding, I think this is a corollary of the following fact:
"Theorem": given two uniform random unit vectors $u,v \in \mathbb{R}^d$, for large values of $d$ we usually see that $\langle u, v \rangle \approx 0$.
I put theorem in quotes because I haven't defined "large $d$" and I haven't defined "usually". Another way of stating this theorem is that in high dimension, almost all vectors are almost orthogonal.
The argument for this "theorem" is pretty intuitive. Given two such unit vectors chosen uniformly randomly, we see by the central limit theorem that:
$$\langle u, v \rangle \sim \mathcal{N}(0, \frac{1}{d})$$
That is, the dot product will be distributed as a normal random variable with zero mean and variance $1/d$.
As you can see, as $d \rightarrow \infty$, the variance $\sigma^2 \rightarrow 0$. Hence we "usually" see dot products close to zero.
It immediately follows that both the right hand side and the left hand side of your expression should on average be very close to zero for large $d$. As Brian Tung points out, the ratio may blow up though.


text:
Q: How to implement greatest common divisor to simplify fractions #include <iostream>
using namespace std;

int g_c_d(int n, int d);

class Fraction
{

private:
  //variables to store numerator and denominator
  int num;
  int denom;

public:
  Fraction(){}
  Fraction(int num): num(num) {}
  Fraction(int num, int denom): num(num), denom(denom) {}

  void set_num(int n){ num = n;}
  void set_denom(int d){ denom = d;}

  int get_numerator() const {return num;}
  int get_denominator() const {return denom;}
};

  int g_c_d(int n, int d){
    return d == 0? n : g_c_d(d, n % d);
 }

istream &operator>> (istream &input, Fraction &f)
{
  int n, d;
  char slash;
  input >> n;
  input >> slash;
  input >> d;

  if (d == 0) {n = 0;} //if denom is 0; fraction = 0/0
  f = Fraction(n, d);
  return input;
}

ostream &operator<<(ostream &output, const Fraction &frac)
{
  return output << frac.get_numerator() << "/" << frac.get_denominator();
}

int main()
{
   int n, d;
   Fraction frac;

   int gcd;
   n = frac.get_numerator();
   d = frac.get_denominator();
   gcd = g_c_d(frac.get_numerator() , frac.get_denominator());

   cout << "Enter a fraction" << endl;
   cin >> frac;
   frac.set_num(n/gcd);
   frac.set_denom(d/gcd);
   cout << "your fraction is: ";
   cout << frac << endl;

   return 0;
}

Hi im trying to simplify fractions entered by a user. However everytime I enter a fraction that is to be simplified the output returned is "1/0".
Can some one please help, it'll be massively appreciated!

A: The problem is that you do all your computations on frac before asking the user to input a fraction — and then you overwrite whatever the user inputs. You need to move this bit:
   cout << "Enter a fraction" << endl;
   cin >> frac;

much, much higher up.

A: When you are setting up the code you have:
Fraction frac;

This calls the default constructor for Fraction. Because you never initialized the members in the constructor you get the default initizliation for the int type which is 0. Then:
n = frac.get_numerator();
d = frac.get_denominator();

This makes n and d 0. From that point onwards you are using those values of n and d. These values however are not the values from the user inputted frac but are just the values you get from the defaults. Change your code to read in the user inputted value for frac before you do any calculations.
The main lesson to learn here is to make sure you don't use uninitialized variables. Generally speaking when you compile with all warnings enabled this is the sort of thing that compilers will warn about.

A: You may be diving by zero because the default constructor doesn't assign value to the denominator.  In the case where the denominator is set to zero, the gcd() function will divide by zero, on the first time in main.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP-view filenames without selecting subfolder this is my directory
D:
|--SMUE
  |--a.pdf
  |--b.pdf
  |--file_1
     |--c.pdf
  |--file_2
     |--d.pdf

and below is my coding
<html>
    <head>
        <link rel="shortcut icon" href="images/search_icon.png">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Retrieval System</title>
        <link href="templatemo_style.css" rel="stylesheet" type="text/css" />
        <script language="javascript" type="text/javascript">

        </script>
    </head>
    <body>
        <?php

          foreach (glob("D:/SMUE/*.pdf") as $filename)
          {
            echo "$filename <br/>";
          }
        ?>
    </body>
</html>

I have tried this coding for viewing files name under the SMUE directory and it work but it only view filenames for  a.pdf and b.pdf only.
How can i view the filenames  fro c.pdf and d.pdf file too? is there any solution.?
*i want to view all filenames (that .pdf only) under the SMUE folder


text:
Q: Bind this when using method decorators in React How to bind this with transform-decorators-legacy Babel plugin?
For example I have some simple decorator. Decorator works, but this is undefined on component's method.
fucntion myDecorator(target, name, descriptor) {
    var oldValue = descriptor.value;

    descriptor.value = function() {
        ...// Doing some stuff here I need the decorator for
        ...// (for example logging on every method call)
        return oldValue.apply(null, arguments);
    };

    return descriptor;

}

class MyClass extends React.Component {
    @myDecorator
    myMethod() {
        ...// this.props... is unavailable here(`this` is undefined)
    }
}

If I try to use @myDecorator with some @autobind decorators I get
TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, because

A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

In my example I can not use value() and get().
Binding in the constructor (this.myMethod = thid.myMethod.bind(this)) doesn't seem to be helpful either, because you bind undecorated method.

A: This is how I managed to solve this:
Using code from mentioned @autobind decorator:
function myDecorator(target, key, descriptor) {
    let fn = descriptor.value;

    return {
        configurable: true,

        get() {
            let boundFn = fn.bind(this);
            Reflect.defineProperty(this, key, {
                value: boundFn,
                configurable: true,
                writable: true
            });

            return function() {
                ...// Doing some stuff here I need the decorator for
                ...// (for example logging on every method call)
                return boundFn.apply(this, arguments)
            };
        }
    };
}

A: Is it not the problem with .binding decorated methods.
But there is something that you missed. Even though you did .bind your myMethod inside your constructor to the class, when you invoke it, no matter from where, myDecorator modifies the execution scope.
oldValue.apply(null, arguments)
Basically, you replaced target scope (MyClass) with null.
So what you want is this:
oldValue.apply(this, arguments)
See this fiddle: http://jsfiddle.net/free_soul/0n6v1dtp/


text:
Q: tabs inside a dropdown -twitter bootstrap is that possible?. i'm planning on making one but have no idea how to do it. i'm using bootstrap tho. this is all i have right now

Vehicles

Cars

Vans & Pick-Up

MPVs

Crossover & SUVs

Hybrid

Performance

A: It sounds like this is something like what you're looking for:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    <button class="btn btn-primary dropdown-toggle" id="menu" type="button" data-toggle="dropdown">Dropdown Example
    </button>

HTML

CSS

JavaScript

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Menu 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.

Menu 3

Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Keep in mind that the href attribute of the data-toggle="tab" needs to correspond to the ID of external content.
Hope this helps! :)


text:
Q: WPF application crashes randomly reporting internal error with exit code 80131506 I have an issue with my WPF application crashing randomly (but at least twice per day) leaving the following message in windows Application log:

Application: AppName.exe
  Framework Version: v4.0.30319
  Description: The process was terminated due to an internal error in the .NET Runtime at IP xxxxxxxx (xxxxxxxx) with exit code 80131506.

Just to give you the background, this application runs on an embedded system running Windows Embedded Standard 2009, and together with another process is the only application running on the device (even explorer is disabled since it is not needed).
After some trial-and-error investigation, I have isolated the code triggering the error. It is a hook installed on the mainwindow and used to intercept the HWND messages to know when the monitor goes off or in standby mode.
Since the system is equipped with a touch panel, I cover my application mainwindow with a  panel while the monitor is off so when the user touches the monitor to take it out of standby mode, it won't erroneously click one of the buttons in my mainwindow. When the panel itself gets a "click" event, it closes, disappearing and thus allowing the user to resume normal operativity.
here is how i instantiate the hook and the function that gets called when the hwnd is intercepted:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    WindowInteropHelper helper = new WindowInteropHelper(this);
    HwndSource.FromHwnd(helper.Handle).AddHook(HwndSourceHookHandler);
}

private IntPtr HwndSourceHookHandler(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    handled = false;

    if (msg == WM_SYSCOMMAND && wParam == (IntPtr)SC_MONITORPOWER)
    {
        if (lParam == (IntPtr)MONITOR_OFF || lParam == (IntPtr)MONITOR_STANDBY)
        {
          AppName.Shell.canvasStandBy.Visibility = System.Windows.Visibility.Visible;
        }
    }
    return IntPtr.Zero;
}

If I comment out the code in the Window_Loaded bit the crash does not happen anymore...
Can you point out what is wrong with this code or give me a hint for another way to make it so that the users' clicks on the monitor while it is off do not get to the underlying mainwindow?
Thanks in advance for your help :)

A: Worked out the problem. @HansPassant was right. The REAL problem was not with the hook call, but with an external, third party, DLL (containing some custom controls used in the application) that was using some wrongly signed P/INVOKES. The Hook call was just triggering the problem by somehow forcing the Garbage Collector to intervene at times when nobody was using the device and thus detecting the heap corruption that had been there since the custom controls had been instantiated.
The solution was: obtaining a newer, fixed DLL from the developer, and the problem is no more :)
Thanks everybody for helping.


text:
Q: How to hook up infinitescroll.js with isotope.js for WordPress portfolio I've been working on making a portfolio with wordpress / isotope.js / Lightbox2 and am now trying to add infinitescroll.js to the mix, alas with no avail.
So far I've just got a mess of code...
Secondly, here is some of the code I have running.
//Isotope settings
var $container = jQuery( '#projects' );

$container.imagesLoaded( function() {
    $container.isotope({
        itemSelector : '.isotope',
        resizable : false,
        masonry : { columWidth: $container.width() / 3 }
    });

});

// infinite scroll
$container.infinitescroll({
    navSelector  : '#project-nav',
    nextSelector : '#project-nav a',
    itemSelector : '.isotope',
    loading: {
        finishedMsg: 'No more projects.',
        msgText: "Loading more projects ...",
        img: TEMPLATE_URI + '/images/loader.gif'
    }
},

    function( newElements ) {
        $container.isotope( 'appended', jQuery( newElements ));
    }

);

Thanks for any and all help!


text:
Q: AWS SFTP with custom identity providers, but the template doesn't work I want to create a sftp server that the user and access with BOTH username/password and ssh token.
I am following this tutorial to create a customized identity provider

https://docs.aws.amazon.com/transfer/latest/userguide/custom-identity-provider-users.html

In the section of Lambda function templates, I choose to use "Classic (Cognito) stack template".
My problem is, when I upload this template to Cloudformation, I get this error:

IF: CreateServer error

Can anyone point out if I missed something, or this template doesn't work. If it is the template problem, can anyone help fix it?


text:
Q: Struggling to implement Google Maps Clustering I work at an Alarm systems company and we have an option in our service managing software to export lets say next months alarm system maintenance's that are due to a google map.  Extremely useful for when trying to book everything close by for an engineers day.  My HTML and CSS knowledge is very good however my JS is pretty much guess work and yet to really learn it!
Could one of you very knowledgeable people on here help me out with adding Google Map pin CLUSTERING to this existing exported code?  To save time and space I have only included one location in the example code.  I have spent hours and hours reading up on it but are still struggling.
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <title>Google Maps Multiple Markers</title>

I am basically trying to achieve this:
https://developers.google.com/maps/articles/toomanymarkers/markerclustererfull.png

A: You can try a cluster in php. Basically create a grid and sort the points into the grid cells:http://www.appelsiini.net/2008/introduction-to-marker-clustering-with-google-maps.


text:
Q: Double Click open dialog on ckeditor I'm trying to open the dialog box to a custom plugin via a doubleclick on a placeholder.

        editor.on('doubleclick',
                function (event) {

                    var element = event.data.element;

                    if (element.is('div')) {

                        event.data.dialog = 'sharedcontent';
                    }
                    console.log('clicked!');

                });

Here is the doubleclick function I'm using, and it is currently registering.
So I feel there is a referencing issue with the actual dialog box.
Has anyone else run into this issue and know a way around it ?
Thanks in advance.

A: Error was a reference issue, renamed the reference and now the dialog box appears


text:
Q: What is the maximum number of rows that can be counted by a SOQL count query? I recollect that:
select count() from Contact

will now work for more than 50,000 rows (but can't find documentation on that improvement).
My question is whether or not there is a new (much higher) limit that applies?

A: The COUNT query is a special case of aggregate querying, as covered in the documentation:

Queries that include aggregate functions are still subject to the limit on total number of query rows. All aggregate functions other than COUNT() or COUNT(fieldname) include each row used by the aggregation as a query row for the purposes of limit tracking.
For COUNT() or COUNT(fieldname) queries, limits are counted as one query row, unless the query contains a GROUP BY clause, in which case one query row per grouping is consumed.

(My emphasis)
In that case if you only do a COUNT then it should in principle be able to count any number of rows since it is considered a single query row when it comes to contributing to limits. However, as mentioned by @David Reed, it may be that applying the query to a very large dataset will simply time out.


text:
Q: Соединение на ICMP Всем доброго времени суток. Подскажите, Если слать по очереди несколько пакетов по icmp протоколу, может ли измениться очередность получения этих пакетов на сервере? Я имею в виду, может ли пакет b, добраться до сервера быстрее пакета a, если пакет a отправили раньше?

A: В RFC 792 и 950 об этом afaik ничего не говорится. Доставка пакетов вообще не гарантируется (вспомните команду ping).
Словом, такой гарантии FIFO для пакетов ICMP нет.
На всякий случай оговорюсь еще раз - afaik. Но вряд ли такое требование вообще выполнимо в протоколе без надежной передачи.


text:
Q: why the job has been submitted using qsub is unknown? In regard to create a PBS script file to run long-term jobs on a server with 256 GB of RAM and two CPUs, each with 12 cores and 24 threads, yielding 48 computing unit. I tried to do it, but I think there is something wrong.
I created a PBS script named run_trinity and submitted it to server using qsub command (qsub run_trinity.sh) within the same directory that contain my desired program (trinity) and data, and it returned something like 47.chpc. But when I tried to check the status of job using qstat command, it says: unknown job id 47.chpc. I'm a biology student and really new in this field, could you please help me to figure out what happened? here is my PBS script:
#!/bin/bash
#PBS -N run_trinity
#PBS -l nodes=1:ppn=6
#PBS -l walltime=100:00:00
#PBS -l mem=200gb
#PBS -j oe
#Set stack size to unlimited
ulimit -s unlimited

cd /home/mary/software/trinityrnaseq_r20140717

perl /home/mary/software/trinityrnaseq_r20140717/Trinity.pl --seqType fq --JM 200G --normalize_reads --left reads8_1.fq.gz --right reads8_2.fq.gz --SS_lib_type FR --CPU 6 --full_cleanup --output /home/mary/software/trinityrnaseq_r20140717

Looking forward to hearing your perfect solutions.


text:
Q: JSoup: how to access a cell without class I'm trying to fetch data from a HTML file into my java code. It all goes well when my cell has a class name. Is it possible to get "next cell" or something like that? Here is a part of HTML and my code.

Termin
Dzień, godzina
Przedmiot
Typ
Nauczyciel
Sala

2015-09-30
Śr 07:50 - 09:30
Język obcy
ćwiczenia

public class FetchData {
FetchData() {

    try {
        Document doc = Jsoup.connect("http://planzajec.uek.krakow.pl/index.php?typ=G&id=84721&okres=1").get();
        for (Element table : doc.select("table")) {
            for (Element row : table.select("tr")) {

                Elements termin = row.select("td.termin");
                Elements dzien = row.select("td.dzien");
                Elements przedmiot = row.select("td");

                System.out.println(termin.text() + " " + dzien.text());
                System.out.println(przedmiot.text());

            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

A: You can retrieve them with tags. Use getElementsByTag(yourTag) to retrieve all cells with the specified tag, then loop through them with a for loop.

A: To select elements specifically without a class you can use this:
Elements tds = row.select("td:not([class])");

This uses the pseudo selector :not() implemented by JSoup.

A: Elements elmnts= doc.select("table tr");

for(Element e:elmnts){
   System.out.println(e.select("td:eq(0)").text());
   System.out.println(e.select("td:eq(1)").text());
   System.out.println(e.select("td:eq(2)").text());
   System.out.println(e.select("td:eq(3)").text());
   System.out.println(e.select("td:eq(4)").text());
   System.out.println(e.select("td:eq(5)").text());
}

since you have mentioned 6 column in sample data i have provided for the same


text:
Q: How does a filtering capacitor smoth a changing current? Lets assume,in picture blow, the current be in its peak voltage moment. then when the current begins to fall (assume a moment after the peak moment) we know the current is blocked by diodes (actually two diodes) and then the cap discharge its stored charged to load. my question is why diodes block this current? Why the diode doesn't allow the rest of falling voltage current to go into the load?
Is this because of the fast rate of voltage chaining for this falling voltage current?

A: This is the case of a power supply with AC input and bridge rectifier with a smoothing capacitor.
First thing to note is that the output is a load which is trying to draw DC current all of the time. However the input is a rectified sine wave and so the diodes only conduct when the input sine wave voltage is actually larger than the output voltage.
The current which is flowing into the load when the input voltage is less than the output voltage (when the diodes do not conduct) and when the input voltage actually falls to zero is all current coming out of the capacitor.
The input wave charges up the capacitor very quickly whenever the input volage is larger than the output voltage. This may only be for a brief moment, but it might be a lot of current. Then when the input voltage starts to go to zero, the diodes stop conducting and it is all down to the capacitor to supply the current for the load like a battery. Think of it as regularly charging a battery, but at the same time your load is always discharging the battery.
If the output load is too high then the voltage will fall a lot in between cycles of the AC. The up and down change of the voltage at the output of the power supply for a particular load is called the ripple voltage. Generally you select a capacitor for the load that you expect so that this ripple voltage is not too much. A bigger capacitor will hold more charge and result in less ripple.
If you remove the capacitor then the voltage will be just a full wave rectified sine wave and will fall to zero each half cycle. (Gray trace in your diagram.) It will not be a constant DC value at all.


text:
Q: IMAP - ENVELOPE vs. RFC822 headers, Fetching whole message vs body parts, etc I'm writing an IMAP client and I have a question.
To get Sender, From, To, CC, etc -
I can FETCH RFC822.HEADER , which will give me a long string w/sometimes not relevant information, or I can FETCH ALL / FETCH ENVELOPE, which will give me a nice formatted version of the main info I need, which is Date, Subject, Sender, etc.
To get email message / attachments -
I can FETCH BODY.PEEK[], which will give me a MIME string with every part of the message regardless of whether I want it (nor does it give the MIME boundaries in an easy to read parse format like BODYSTRUCTURE does), or I can FETCH BODYSTRUCTURE / FETCH (BODY ENVELOPE), then parse out the individual parts I want/need, without having to download everything.
My question is whether using the rfc822 headers, or downloading an entire MIME string, is every really necessary in an email client? It seems like BODYSTRUCTURE & ENVELOPE have made this much easier, so is there any reason I would ever need to manually parse the RFC822 headers / MIME message in my email client? I should be able to do everything a client would ever need with ENVELOPE & BODYSTRUCTURE, correct?
Thank you.

A: You can make do with BODYSTRUCTURE, ENVELOPE (and BODY.PEEK[1] etc when you need to fetch bodyparts).
You may find that at some point, before or after 1.0, you may choose to e.g. retrieve BODY.PEEK[HEADER.FIELDS (List-Id)] or other things. But overall you're right, BODYSTRUCTURE and ENVELOPE are enough.


text:
Q: How do I render data from an HTTP GET on the client (with Handlebars) I have a Meteor method that retrieves Google Books data
searchBooks: function (query) {
  this.unblock();
  return Meteor.http.call("GET", "https://www.googleapis.com/books/v1/volumes?q=" + query);
}

which is called like this
Meteor.call("searchBooks", term, function(error, results) {
    console.log(results.content);
});

How do I go about making the results renderable in a template (with handlebars)?

A: Put your results into a reactive variable, for example in Session:
Meteor.call("searchBooks", term, function(error, results) {
    Session.set('books', results.content);
});

Return this variable in a template helper:
Template.booksView.helpers({
  books: function() {return Session.get('books');}
});

Then, in the template use double braces for usual text and in triple braces for html:
<Template name='booksView'>
  {{{books}}}
</Template>

You might have to parse or iterate your data depending on its format and output requirements.


text:
Q: Install Mono in red hat 5 I have been looking in the mono-project website the dependencies to install mono and the sources but I haven't found anything.
Does anyone know how to install mono udner a red hat linux 5 32-bit environment? Maybe the sources are deprecated.
Thank you in advance.

A: I have found how to do it. All the mono repository is in:
http://download.mono-project.com/sources/mono/
And then you follow this guideline:
Install Mono and Monodevelop on CentOS 5.x/6.x


text:
Q: How can I use subprocess.Popen in a for loop? I'm trying to use subprocess.Popen to run a command, and I've chosen this over subprocess.run, as I need the output from the command printed to the shell.
I'm calling the commands in a for loop, and modifying the environment for each iteration, but python only runs the first command, and not the other 6.
I'm pretty sure this is a bug as I can't find anything else like this, but I thought I'd check before I submit the "bug".
The relevant code looks like this
input_file = Path("input.json").open()

for thread in threads:
    new_env = default_env
    new_env["OMP_NUM_THREADS"] = str(thread)
    print("Starting run for {} threads".format(thread))
    process = subprocess.Popen(
        benchmark_command, env=new_env, stdin=input_file, stdout=subprocess.PIPE)
    lines = []
    for line in process.stdout:
        print(line.decode(), end='')
    results.append(Result(lines, thread))
    print("Completed run for {} threads".format(thread))

and the current output is this
❯ python python/plot_results.py
Starting run for 1 threads
<expected output from running command>
Completed run for 1 threads
Starting run for 2 threads
Completed run for 2 threads
Starting run for 4 threads
Completed run for 4 threads
Starting run for 8 threads
Completed run for 8 threads
Starting run for 16 threads
Completed run for 16 threads
Starting run for 32 threads
Completed run for 32 threads
Starting run for 56 threads
Completed run for 56 threads

but should look like this
❯ python python/plot_results.py
Starting run for 1 threads
<expected output from running command>
Completed run for 1 threads
Starting run for 2 threads
<expected output from running command>
Completed run for 2 threads
Starting run for 4 threads
<expected output from running command>
Completed run for 4 threads
Starting run for 8 threads
<expected output from running command>
Completed run for 8 threads
Starting run for 16 threads
<expected output from running command>
Completed run for 16 threads
Starting run for 32 threads
<expected output from running command>
Completed run for 32 threads
Starting run for 56 threads
<expected output from running command>
Completed run for 56 threads

A: First of all I would say that unless your level of expertise in the language is far beyond senior, or the nature of your problem is extremely uncommon, it is unlikely that your problem is a bug, and rather, it is probably some misconception you have regarding how the language is doing things.
In your case, Popen does not block your main thread. Your problem is that the main thread is starting all processes... and eventually starts reading output from stdout and prints it.
Simple solution would be using subprocess.check_output to wait the commands to finish, but it doesn't allow env parameter so we'll go for communicate() method after the call to Popen, which will also block your main thread and wait for the process to terminate:
for thread in threads:
    new_env = default_env
    new_env["OMP_NUM_THREADS"] = str(thread)
    print("Starting run for {} threads".format(thread))
    output = subprocess.Popen(
        benchmark_command, env=new_env, stdin=input_file, stdout=subprocess.PIPE)
    stdout, stderr = output.communicate()
    lines = []
    for line in stdout:
        print(line.decode(), end='')
    results.append(Result(lines, thread))
    print("Completed run for {} threads".format(thread))

A: Per @jasonharper's suggestion, I needed to make a new open file object for each iteration.
input_file = Path("input.json")

for thread in threads:
    new_env = default_env
    new_env["OMP_NUM_THREADS"] = str(thread)
    print("Starting run for {} threads".format(thread))
    process = subprocess.Popen(
        benchmark_command, env=new_env, stdin=input_file.open(), stdout=subprocess.PIPE)
    lines = []
    for line in process.stdout:
        print(line.decode(), end='')
    results.append(Result(lines, thread))
    print("Completed run for {} threads".format(thread))


text:
Q: Выборочный экспорт из БД Добрый день!
Столкнулся с маленькой проблемой, есть 2 БД , с одинаковыми таблицами;
рассмотрим таблицу i_block_elements в первой БД
в которой существуют  5ть полей с данными.
необходимо экспортировать данные из этой таблицы по этим полям. не программно, а в пределах возможности phpmyadmin
выбираю sql запросом: SELECT  pole1, pole2, pole3, pole4, pole5 FROM i_block_elements WHERE id=11
 у нас выберается все что мы хотели, но как это экспортировать?, нажимал на экспорт он мне всю таблицу скачивает.
Далее, после того как мы все таки экспортируем выбранные поля, необходимо импортировать во 2ю базу с такой же таблицей и с 2мя из 5ти полями pole1, и pole2 с данными.
Необходимо импортировать так, чтобы те данные что были в pole1 и pole2 обновились (то есть добавились не достающие)а pole3,  pole4 и pole5 добавились  полностью
PS
конец рабочего дня , мозг кипит, надеюсь доступно расписал.заранее огромное спасибо!
A: ну почему же, можно через view ;)
CREATE view tmp_my_view AS SELECT album_id from album_data;
CREATE TABLE new_materialized_view SELECT album_id, 0 as fld1, '' as fld2, null as fld3 from tmp_my_view;

смысл: делаем view, туда заносим нужные данные, потом создаем таблицу на основе Вашего view ;)
A: через pma по-моему нельзя делать экспорт определенных столбцов. Во всяком случае я не нашел.
По второй проблеме: в расширенных настройках экспорта есть список "Использовать оператор при сохранении данных:". Выбирите UPDATE.


text:
Q: Selenium IDE getting id from url parameter? I am struggling with getting the id from a url in selenium ide please could you assist me Thanks. When I echo the store location it removes the equals? PLease see the comments for the output below. Thanks for any help given.
When I run the ide tests I run it through webdriver and on internet explorer but i dont think this should make much difference.

    // gets http//website.co.uk/index.php?main_detail_id=123456789123456
    storeLocation
    loc

    //prints http//website.co.uk/index.php?main_detail_id123456789123456
    echo
    ${loc}

    //no errors have also tried split '?'
    storeEval
    "${loc}".split('=')[2]
    mainid

    //prints nothing.
    echo
    ${mainid}

A: Below is code with help of that you can get ID from URL

    store
    http//website.co.uk/index.php?main_detail_id=123456789123456
    test

    store
    1
    delimiter

    store
    javascript{storedVars['test'].split('=')[storedVars['delimiter']]}
    vv

    echo
    ${vv}


text:
Q: Error: Use instance member on type In the below code, I have an "instance member on type" error when I am trying to call the matchTravellerWithLocal function and assign the return value to message. Any idea on how to solve this error?
var travellerInformation: Traveller{
    return Traveller(destination: location, travellingPreference: preference)
}

let message = matchTravellerWithLocal(travellerInformation)

func matchTravellerWithLocal(traveller: Traveller) -> String {
    var message = ""
    let location =  traveller.destination.rawValue
    let type = traveller.travellingPreference.rawValue
    let locals = LocalsInformation().locals
    for (name, information) in locals{
        let city = information["City"]
        let preference = information["Preference"]
        if city == location{
            message = "Meet your local: \(name), a local of \(city)"
            print(message)
        }else{
            message = "Apologies, there aren't in \(city) on LocalRetreat. Try again soon!"
            break
        }
        if preference == type{
            message += "who is also a \(preference)"
            print(message)
        }
    }
    return message
}


text:
Q: Annotation position is not updated as the series scrolls I am using Annotation and AnnotationCallout to create labels on a series. But the problem I have is that their positions are not updating as new data is added to the chart. The series scrolls, but the Annotation / AnnotationCallout stay in the same place.
I set the Annotation and AnnotationCallout with the following code:
Anno.setLeft(aSeries.calcXPos(iIndex)-51);
Anno.setTop(aSeries.calcYPos(iIndex)+100);

Callout.setXPosition(aSeries.calcXPos(iIndex));
Callout.setYPosition(aSeries.calcYPos(iIndex));

Is there a way to attach them to point on a series or am I using the wrong tool for the job?

A: Annotations are positioned either on pixel positions or relative positions on the chart depending on how you define the Scaling property.
That's how Annotation works. So once you have defined the position of the annotation it sticks there.
If you want labels sticked on the points, look at Series.Marks.
When you add points to the series you can add a label text like:

AddXY(xPos,yPos,'Hello',clGreen);

Set Series.Marks.Visible := True to show the mark labels. To customize the label text on the fly, look at the event TChartSeries.OnGetMarkText.
Explore all Series.Marks properties to customize the look to your preference.
Update :
In order to hide some marks on your series data, set the label text to empty string during the OnGetMarkText event.
An example how to use OnGetMarkText:
...
Series1.OnGetMarkText := Self.Series1GetMarkText;  // Define the OnGetMarkText event
...

procedure TMyForm.Series1GetMarkText(Sender: TChartSeries;
  ValueIndex: Integer; var MarkText: string);
begin
  if ValueIndex=3 then  // Just an example how to set the selection criteria
    MarkText := 'Hello'
  else
    MarkText := '';
end;


text:
Q: variable scope in AJAX calls one question I always ask myself is how is it possible that javascript has still a reference in a callback function of a AJAX request when the variable was declared in the function which isssues the AJAX call. Here an example
var loadMask = {name:"test"};

form.submit({
  url: 'request.php',
  timeout : 180000,
  success: function(the_form, action_object)
  {
    console.log(loadMask);
  }
});

despite the fact that loadMask was declared outside of the success function it is still visible (and defined) inside.
How is this possible?

A: This is possible using something called closures. There are many resources for this:
Here's a few from a google:
http://www.webreference.com/programming/javascript/rg36/
http://jibbering.com/faq/notes/closures/


text:
Q: Parsing an non-compliant JSON data with Python I am getting JSON data from a hardware device in a Python script. The JSON data is not 100% valid: some base 10 integers have leading zeros, which is apparently forbidden. This makes the Python JSON module throw an exception.
Is there any way to ask the parser to be more permissive? Or am I condemned to do all the parsing myself?
I have already sent a mail to the hardware device manufacturer but they don't seem to care...

A: According to the documentation for JSONDecoder,

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

So, just write some code that handles leading zeros. (Note: In C a leading zero indicates that the number is an octal literal. Since you're mentioning a hardware device, you should confirm whether the numbers you are receiving are base 8 or 10 or 16 or 2 or ...?)
def parse_00int(strval):
    stripped = strval.lstrip('0')
    return 0 if stripped == '' else int(stripped)


text:
Q: What is the correct way to write this javascript function? I'm trying to understand javascript and javascript functions. This function is used to change the look of a button.
function changeButton(){
    btn.style.backgroundColor = btn.style.backgroundColor == "black" ? "white" : "black";
    btn.style.color = btn.style.color == "white" ? "black" : "white";
    btn.innerHTML = btn.innerHTML == 'GOOD JOB' ? 'CLICK ME' : 'GOOD JOB';
}

It works just fine. But when I look at this function I see a lot of repetition. The basic structure seems to be element = element == value1 ? value2 : value1
So in my mind this should work:
function toggleValue(elem, val1, val2){
    elem = elem == val1 ? val2 : val1
}

function changeButton(){
    var x = btn.style.backgroundColor
    var y = btn.style.color
    var z = btn.innerHTML
    toggleValue(x, 'white', 'black')
    toggleValue(y, 'black', 'white')
    toggleValue(z, 'CLICK ME', 'GOOD JOB')
}

But it does not work and I don't understand why. Can someone tell me why this doesn't work? And is there a way to make it work?

A: It does not work, because you hand over a primitive value an not a reference to the property.
function toggleValue(elem, prop, val1, val2){
    elem[prop] = elem[prop] == val1 ? val2 : val1
}

function changeButton(){
    toggleValue(btn.style, 'backgroundColor', 'white', 'black')
    toggleValue(btn.style, 'color', 'black', 'white')
    toggleValue(btn, 'innerHTML', 'CLICK ME', 'GOOD JOB')
}

A: Because you are passing the String which is immutable.
You can create one more argument - property.
function toggleValue(elem, prop, val1, val2){
    elem[prop] = elem[prop] == val1 ? val2 : val1
}

function changeButton(){
    var x = btn.style;
    var y = btn.style;
    var z = btn;
    toggleValue(x, "backgroundColor", 'white', 'black');
    toggleValue(y, "color", 'black', 'white');
    toggleValue(z, "innerHTML", 'CLICK ME', 'GOOD JOB');
}

A:

function toggleValue(elem, val1, val2, ButtonStyleType) {
        elem = elem == val1 ? val2 : val1;
        if (ButtonStyleType == 'backgroundColor')
            btn.style.backgroundColor = elem;
        else if (ButtonStyleType == 'color')
            btn.style.color = elem;
        else if (ButtonStyleType == 'innerHtml')
            btn.innerHTML = elem;
    }
    function changeButton() {
        var x = btn.style.backgroundColor;
        var y = btn.style.color;
        var z = btn.innerHTML;
        toggleValue(x, 'green', 'yellow', 'backgroundColor');
        toggleValue(y, 'black', 'Orange', 'color');
        toggleValue(z, 'Default', 'GOOD JOB', 'innerHtml');
    }
<button id="btn" style="background-color:green; color:black;">Default</button>

        Click here to update button style

A: You have to understand the difference between pass by value and pass by reference
to know more about that click here


text:
Q: Error when trying to install Django CMS in virtualenv w/ MySQL on Mac OSX I am getting the following error when I try to install django CMS with MySQL using virutalenv:
RuntimeError: maximum recursion depth exceeded

/Users/ethan/Sites/env/build/mysql-python/distribute-0.6.28-py2.7.egg

Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/Users/ethan/Sites/env/build/mysql-python/setup.py", line 7, in <module>

    use_setuptools()

  File "distribute_setup.py", line 145, in use_setuptools

    return _do_download(version, download_base, to_dir, download_delay)

  File "distribute_setup.py", line 125, in _do_download

    _build_egg(egg, tarball, to_dir)

  File "distribute_setup.py", line 116, in _build_egg

    raise IOError('Could not build the egg.')

IOError: Could not build the egg.

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /Users/ethan/Sites/env/build/mysql-python

The command I am using for the install is the following:
env/bin/pip install --download-cache=~/.pip-cache -r reqs.txt

And the reqs.txt file looks like this:
django-cms==2.4.1
Django==1.5.1
django-classy-tags==0.4
South==0.8.1
html5lib==1.0b1
django-mptt==0.5.2
django-sekizai==0.7
six==1.3.0
Pillow==2.0.0
django-filer==0.9.4
cmsplugin-filer==0.9.5
django-reversion==1.7
mysql-python==1.2.4

I'm a novice to django (just going through the tutorial) and I cannot find anything in a search that seems to resolve this issue. Anyone have any ideas?

A: mysql-python v. 1.2.4 has a hard dependency on distribute version 0.6.28. It might not be picking the right version of distribute.
Run this after the virtual env is activated:
easy_install distribute==0.6.28

and you should be good to proceed with
env/bin/pip install --download-cache=~/.pip-cache -r reqs.txt

A: change requirement to mysql-python==1.2.5 also worked for me on OS X mavericks with pip install

A: Change your requirement to mysql-python==1.2.5, I had the same problem on a CentOS 6.3 server.


text:
Q: sort table using $_get['sort'] , error Unexpected T_STRING I tried to sort a table by clicking the th of the table using $_get['sort'] function
this is my code
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "");

//connect to database
//select the database
mysql_select_db("fak_databases");

//submit button
if($_POST['formSubmit'] == "Submit")
{
    $country = $_POST['country'];
}

//query the database
if($country == TRUE) {
    // query to get all AL records
    $query = mysql_query("SELECT * FROM auip_wipo_sample WHERE applicant1_country='$country'");
    if ($_GET['sort'] == 'city')
    {
        $query .= " ORDER BY wipo_applicant1_city";
    }
    elseif ($_GET['sort'] == 'address')
    {
        $query .= " ORDER BY applicant1_addr1";
    }
}

//fetch the result
Print "
";
Print "
";
Print "City	";
Print "Address	";
Print "
";

while($row = mysql_fetch_array($query))
{

    Print "
";
    Print "".$row['wipo_applicant1_city'] . "	";
    Print "".$row['applicant1_addr1'] . "
";
}

Print "
";
?>

but I got an error
syntax error, unexpected T_STRING

which the line is
Print "City	";

anyone can fix this issue?
and  I need to be able to click head table and sort alphabetically...
and I have a question, is $_get['sort'] function only sort ascending??or both ascending and descending?? if only sort ascending, is any function that can sort ascending and descending while I click on the table head??
thanks

A: The reason is that you are not escaping your double quotes and hence PHP ends the string where it encounters second double quote in your string
Print "City	";
                ---^---               ---^---

OR use ' quotes around your string, you can us this safely here as you are not having any variables inside your string
print 'City	';

I would suggest you, not to print HTML using PHP, just separate them like

     City
     Address

<?php
  //PHP Code Here
?>

A: You can't use double quotes in way you did this. It should be:
Print 'City	';

A: try it
   <?php
  //connect to server
   $connect = mysql_connect("localhost", "root", "");

 //connect to database
 //select the database
  mysql_select_db("fak_databases");

 //submit button
   if($_POST['formSubmit'] == "Submit")
   {
  $country = $_POST['country'];
   }

  //query the database
   if($country == TRUE) {
 // query to get all AL records
     $query = mysql_query("SELECT * FROM auip_wipo_sample WHERE    applicant1_country='$country'");
if ($_GET['sort'] == 'city')
{
    $query .= " ORDER BY wipo_applicant1_city";
}
elseif ($_GET['sort'] == 'address')
{
    $query .= " ORDER BY applicant1_addr1";
}
 }

//fetch the result
   Print "
";
  Print "
";
  Print 'City	';
  Print 'Address	';
  Print "
";

  while($row = mysql_fetch_array($query))
  {

Print "
";
Print "".$row['wipo_applicant1_city'] . "	";
Print "".$row['applicant1_addr1'] . "
";
  }

Print "
";
 ?>


text:
Q: Content doesn't update on route change When I change route, from say /set/1 to /set/2, then it still shows the information from /set/1 until I manually refresh the page, I've tried adding $route.refresh to the ng-click of the links to these pages, but that didn't work either. Any ideas?
Below is the routing code, this works fine, all routing is done via links, just <a> tags that href to the route.
angular.module('magicApp', ['ngRoute']).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
        templateUrl: 'pages/home.html'
    }).when('/set', {
        redirectTo: '/sets'
    }).when('/set/:setID', {
        controller: 'SetInformationController',
        templateUrl: 'pages/set.html'
    }).when('/card', {
        redirectTo: '/cards'
    }).when('/card/:cardID', {
        controller: 'CardInformationController',
        templateUrl: 'pages/card.html'
    }).when('/sets', {
        controller: 'SetListController',
        templateUrl: 'pages/sets.html'
    }).when('/cards', {
        controller: 'CardListController',
        templateUrl: 'pages/cards.html'
    }).when('/search/:searchterm', {
        controller: 'SearchController',
        templateUrl: 'pages/search.html'
    }).otherwise({
        redirectTo: '/'
    });
}]);

Below is the code for the SetListController, it uses the routeParams to grab the correct information from a service, which works, when I go to /set/1 then it returns the right information, if I then go back then go to /set/2 it still shows the information from set 1, until I refresh the page.
.controller('SetInformationController', function($scope, $routeParams, $route, SetInformationService, CardSetInformationService) {
$scope.set = [];
$scope.cards = [];

function init() {
    SetInformationService.async($routeParams.setID).then(function(d) {
        $scope.set = d;
    });
    CardSetInformationService.async($routeParams.setID).then(function(d) {
        $scope.cards = d;
    })
}

init();
})

The HTML itself has no reference to the controller, or anything like that, just the objects in the scope, namely set and cards.

A: I figured it out! The problem wasn't actually with the routing it was with my service, here was the service before:
.factory('SetInformationService', function($http) {
  var promise;
  var SetInformationService = {
    async: function(id) {
      if ( !promise ) {
          // $http returns a promise, which has a then function, which also returns a promise
          promise = $http.get('http://api.mtgdb.info/sets/' + id).then(function (response) {
           // The then function here is an opportunity to modify the response
           console.log("Set Information");
           console.log(response);
           // The return value gets picked up by the then in the controller.
           return response.data;
           });
      }
      // Return the promise to the controller
      return promise;
    }
  };
  return SetInformationService;
})

where it should have been:
.factory('SetInformationService', function($http) {
  var promise;
  var SetInformationService = {
    async: function(id) {
      // $http returns a promise, which has a then function, which also returns a promise
      promise = $http.get('http://api.mtgdb.info/sets/' + id).then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log("Set Information");
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return SetInformationService;
})


text:
Q: MySql table size increase We have old Bugzilla installed 2.20 install Debian Sarge 32bit with MySQL 4.0 Server running fine. Unfortunately from Yesterday noon, It started through error stating below.
DBD::mysql::st execute failed: The table '**attachments' is full** [for Statement "INSERT INTO attachments
      (thedata, bug_id, creation_ts, filename, description,
       mimetype, ispatch, isprivate, submitter_id)
      VALUES (?, 8983, '2014-05-07 11:21:05', 'RE  #8983-Tool-form - Bug #9270 (1).msg',
              'Email flows for questions/clarificatios', 'application/octet-stream', 0,
              0, 165)"] at /var/www/1503/attachment.cgi line 943
    main::insert() called at /var/www/1503/attachment.cgi line 94

By the above error I understood that, The attachments table is full & checked it with command show table status like 'attachments' \G
I want know to how do I fix this issue or increase the size of table. Please help to fix this issue.

A: This is not inherently a MySQL issue as you can see here in the MySQL documentation for the error message.
You will need to determine what the problem is

*

*Check your kernel version (uname -r)

*Check your disk space (df)

*Check other things in the article I link to.

Once you know the cause you can take appropriate action.
You really should upgrade too.


text:
Q: get month and year from date input I have the following html code:
<input type="date" id="myDate"/>

<button type="button" class="btn btn-secondary" id="clickMe">MyButton</button>

And I am trying to use the values from the date input (only month and year) in a js function like this:
function myFunction() {
    function function1(a,b)
    {
      //do something with a and b values
    }

    function function2()
    {
        var a = document.getElementById('myDate').value.month;  //this values are not good
        var b = document.getElementById('myDate').value.year;

        function1(a,b)
    }

    var el = document.getElementById("clickMe");
    if (el.addEventListener)
        el.addEventListener("click", function2, false);
    else if (el.attachEvent)
        el.attachEvent('onclick', function2);
})();

Bassicaly when the button is pressed I want to save the values of the input date as int values (for example 7 and 2020 - month and year) and these values will be transmitted in the js function2 that will call function1 with those parameters.
The problem is that right know my a and b variables are null. Is there any way I can fix this?
I did a debug for those values (a and b) and I get the following error: "TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them"

A: Convert the string to a Date object:
new Date(input).getYear()
(input being the value of your date input)


text:
Q: Multiple regression - High adjusted R^2 but the residuals are high I used the multiple regression models to derive the outcomes after using AIC pairwise comparison and deleted the outliers, high leverage points.
And it seems good, the adjusted R^2 acheived 0.9543, see below:
Call:
lm(formula = P ~ V + EF + W + H, data = PS)

Residuals:
Min      1Q     Median      3Q     Max
-22.448 -14.576   2.949  12.524  26.034

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -2.186e+03  5.209e+02  -4.196 0.000201 ***
V           1.511e-01  1.033e-02  14.633 9.96e-16 ***
EF           1.183e+01  3.239e+00   3.653 0.000917 ***
W           -1.135e+00  4.205e-01  -2.698 0.011028 *
H            3.192e+01  8.482e+00   3.763 0.000678 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 15.79 on 32 degrees of freedom
(13 observations deleted due to missingness)
Multiple R-squared:  0.9593, Adjusted R-squared:  0.9543
F-statistic: 188.8 on 4 and 32 DF,  p-value: < 2.2e-16

However, when I was inspecting the residuals, they are fairly high.
With the R^2 higher than 0.95. I expect the residuals should be around 5% but actually not. It's kind of weird. See below for the (actual - fitted)/actual.
tidy((PS$P-fitted(fita2))/PS$P)
         x
1   0.01778472
2  -0.19525412
3  -0.01824948
4  -0.24418585
5  -0.06475068
6   0.65211477
7   0.58158990
8  -0.14876657
9  -0.27050744
10  0.15220738
11  0.14239352
12  0.02274694
13  0.10920921
14  0.04696290
15 -0.07793881
16 -0.32173830
17 -0.60332883
18 -1.47499192
19 -0.70576325
20 -0.04088402
21 -1.11266825
22 -1.13704286
23 -0.72987082
24 -0.50573858
25  0.38938329
26  0.57790490
27  0.21233140
28 -0.42890622
29  0.27630390

Plot of Residuals vs Fitted:

Normal Q-Q plot:

A: I don't see a clear basis for your assessment that the residuals are "fairly high."  Certainly "high" is in the eye of the beholder and is context-dependent, but in most non-physics contexts an R-square of 95% indicates a very accurate model.  If you changed the y-axis of your "Residuals vs Fitted" graph to match the x-axis, the residuals would show up as very small indeed.
It should help if you keep several quantities distinct:

*

*The residual, (observed - fitted)

*The standardized residual, (residual/[standard deviation of residuals])

*Your (idiosyncratic?) metric, the residual as a % of the
observed value:  (residual/observed).

Each of these has its own scale and needs to have its magnitude judged accordingly.  I don't see a mean of 5% as a standard or reliable benchmark to judge the "goodness" of any of the 3.
R-squared itself does not relate directly to any of the 3;  it's an indicator of the regression sum of squares in relation to (divided by) the residual sum of squares.
Some other notes:  4 decimal places is excessive precision to report when your df is only 32.  Also, your Normal Q-Q plot does indicate something potentially "off" about this regression, but it concerns not the mean size of the (standardized) residuals but rather the way they are distributed at the tails.  This regression produces a few more that are relatively extreme than would be ideal.  This really shows up just as well in the "Residuals vs Fitted" graph, where fitted values at the low and high end are paired with some particularly high residuals.  The bottom line is that this model seems to predict substantially better for some types of cases (those with fitted values between 140 and 320) than for others.


text:
Q: Clearing tkinter canvas content doesn't work I have a tkinter canvas where a label and a matplotlib plot are shown. I want to update the content of the canvas and therefore delete what was shown before. To do this I found that canvas.delete('all') is the way to do this. According to the code below the canvas is filled with content and afterwards deleted. But instead of getting an empty window the content is shown. What am I doing wrong?
import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# data for plot
x1 = [1, 2, 3]
y1 = [1, 2, 3]

root = tk.Tk()
canvas = tk.Canvas(root, background="grey")
plot_title = tk.Label(canvas, text="plot", font=("Arial 24 bold"), background="grey")

# plot
fig = plt.Figure(figsize=(5, 5))
fig.set_facecolor("grey")
plot1 = fig.add_subplot(111)
plot1.scatter(x1, y1)
chart1 = FigureCanvasTkAgg(fig, canvas)
chart1.get_tk_widget().grid(row=0, column=1)

canvas.grid(row=0, column=0)
plot_title.grid(row=0, column=0, padx=5, pady=5)
canvas.delete('all')

root.mainloop()

A: when using FigureCanvasTkAgg you have to clear the figure instead of the canvas using fig.clear().
if you want to clear all the data in the canvas then you should destroy it with canvas.destroy() then create another canvas in its place, alternatively if you want to delete the label specifically you can just call plot_title.grid_forget() or plot_title.destroy()
Edit: to keep this information out of comments for future readers, as noted by @acw1668 a label is not a canvas item and so it cannot be removed by .delete("all"), and only items in tk item types in the documentation can be removed by it https://tkdocs.com/tutorial/canvas.html


text: Q: R console does not show output The Rstudio on my mac does not show output in the console.For instance, after I run a R script, and type the name of a parameter in the console, there is no output. However, there is no such issue on a window system. What goes wrong?


text:
Q: Extreme points of a body in $\mathbb{R} ^{n}$ let $K\subseteq\mathbb{R}^{n}$ be a body, and suppose that $x,y\in K$ satisfy $\left|\left|y-x\right|\right|_{2}=diam_{\left|\left|\cdot\right|\right|_{2}}\left(K\right)$. Show that $x$ and $y$ are extreme points in $K$.
So my thought on how to approach this was to fix $y$ and you can see that $x$ must be the most distant point to it in $K$, and it cannot happen unless $x$ is an extreme point.
Now I'm stuck on how to formalize it. I can see the intuition behind it very well, if $x$ is not an extreme point then we can get a larger diameter on $K$, with contradicts the fact that $\left|\left|y-x\right|\right|_{2}=diam_{\left|\left|\cdot\right|\right|_{2}}\left(K\right)$.
I tried to suppose by contradition that $x$ is not an extreme point. Thus, there exists $a,b \in \mathbb{R}^{n}$ (different than $x$) such that $x \in [a, b]$, and therefore we can write $x = a+t(b-a)$ for some $0<t<1$ (if $t=1$ or $t=0$ we get $x=b$ or $x=a$, in contradition), but I got stuck here and couldn't see how I get the contradition. Would be glad for some help.


text:
Q: Access to constructor not allowed Hi I encountered this error when I created a custom backbone app for my application. What it does is to send to its parent constructor a target container where the fragment will be installed. The custom class is simply zero-arg constructor and supers an integer to its a parent which stores the targetContainer. But when I ran my application I get a runtime exception.
Here is my code:
Here is a custom class specific to the app I plan to build:
public class NoteActivity extends BackboneActivity
{
    public NoteActivity()
    {
        super(R.id.fragmentContainer);
        addFragment(new NoteFragment());
    }

}

Now here is backbone app so I can add fragments at will. I want a dynamic control over the app and fragment using this class:
public class BackboneActivity extends ActionBarActivity
{
    private FragmentManager fragmentManager;
    private int targetContainer = -1;

    public BackboneActivity(int target)
    {
        super();
        targetContainer = target;
    }

    protected boolean addFragment(Fragment fragment)
    {
        if(fragment == null) return false;

        fragmentManager.beginTransaction()
            .add(targetContainer, fragment)
            .commit();

        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(targetContainer);

        fragmentManager = getSupportFragmentManager();
    }
}

I am still in the learning process for Android and Java and I have a bit of programming experience so I am not quite sure what I have been missing.
The error I get is access to Constructor is not allowed. Is this technically different than other post here which describes access to class not allowed?
I admit I feel so &&(& dumb with this error.
Thanks.

A: Can you not do something like:
public NoteActivity()
{
    super();
    addFragment(new NoteFragment());
}

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(targetContainer);
    // you will have to put a getter/setter in BackboneActivity or change access modifiers
    this.setTargetContainer(R.id.fragmentContainer);
    fragmentManager = getSupportFragmentManager();
}


text:
Q: How to add and use a custom font in my xcode project I am trying to add and use a font within my app. I've followed this post for reference but I can't get it to work.
I've added the font Frutiger95UltraBlack.ttf as a supporting file and then added it to my {app-name}-Info.plist.
Then tried to use it in my app delegate to change my UINavegationBar but nothing happens.
What am i missing??
 [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                          [UIColor whiteColor], UITextAttributeTextColor,
                                                          [UIFont fontWithName:@"Frutiger95UltraBlack" size:16.0], UITextAttributeFont,nil]];

A: (From my above comment:)
[UIFont fontWithName:...] requires the PostScript name of the font as parameter, that might be different from the file name.

A:
make sure that your font is in your Copy Bundle Resources.

if we not adds font to target then sometimes it happens that your font not automatically adds in Copy Bundle Resources.

also make sure that your font name is same that you have used. you can
  make this sure by opening font in fontBook.

if you have different fonts like Regular/Bold/italic,then you have to attach this name to your font name like this-Frutiger95UltraBlack-Bold
install your font on mac system.iterate your all fonts programatically , write NSLog for fontName, by this way you can make sure the name of font i.e. PostScriptName.

A: Just an FYI, UITextAttributeTextColorand UITextAttributeFont were deprecated in iOS 7.0.
Instead replace UITextAttributeTextColor with NSForegroundColorAttributeName and UITextAttributeFont with NSFontAttributeName


text:
Q: CURL POST не работает Здраствуйте. Хочу с помощью курла отправить пост запрос чтобы перейти по ссылке(внешне ссылка выглядит так
Далее

Передаю пост - запрос :
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS,'некий пост-текст').

Все данные запроса который отправляется взят из firebug, там четко указано что это пост метод. Но в результате сервер возвращает

HTTP/1.1 405 Method Not Allowed
  Allow: OPTIONS, TRACE, GET, HEAD
  Content-Length: 1564 Content-Type: text/html
  Server: Microsoft-IIS/6.0
  X-Powered-By: ASP.NET
  Date: Thu, 01 Sep 2016 16:45:55 GMT

то есть метод POST не разрешен. Не могу понять,в чем проблема: или я не правильно задаю запрос, или действительно здесь не метод пост нужен,может есть другой способ перейти по ссылке?

A: Полагаю, вам следует передавать правильный Content-Type и корректный CURLOPT_POSTFIELDS


text:
Q: Can i make site myself? I like this Wordpress template
Can I make a working site from it myself - I need the same result like this template, would it be as beautiful?
I am novice, and didn't try it yet.

A: You can, after a lot of practice and studying ofcourse. If you really need a proper working website for a company in short terms, you might better forget to attempt. If it is as a hobby, get to work with your best friend.
But questions like these are not really apriciated on Stack Overflow. You are asking about our opinion on a personal matter. Best of luck anyway!


text:
Q: SQL Why count CHAR in MySQLWorkbanch between Server was different I am trying to query the messages from the server to send out with line notify but I already using auto space as my script and showing well in Workbench but when bringing this code into the server the result not same as testing by Workbench so Can anyone advise me on this?
Background :
Workbench using the same database with the server
I trying to change the type from Char to NChar but the system can't change
Query from Server

Query by Workbench

Code
SELECT
    MAX(T1.ID) as ID,
    T1.site_id as user_id,
    tank_product,
    volume,
    ullage,
    water_volume,
    site.sfl_limit,
    timestamp,
    concat('\n', 'Inventory Report') as Title,
    concat ((site.name),'\n','Inventory Report ','\n',current_date(),' ',current_time(),'\n\n','Tank ',space(2),'Product Name',space(4),'Volume',space(2),
    site.sfl_limit*'100','%',' Ullage',space(2),'Water',space(6),'Times',
    group_concat(concat(
                    '\n',

                    space(1),IF (length(format(tank.number,0)) > 2,format(tank.number,0),concat(format(tank.number,0),space(2 - length(format(tank.number,0))))), space(4),
                    IF (length(tank.name) > 17,tank.name,concat(tank.name,space(17 - length(tank.name)))),
                    IF (length(format(T1.volume,0)) > 8,format(T1.volume,0),concat(format(T1.volume,0),space(8 - length(format(T1.volume,0))))),space(1),
                    IF (length(IF(format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0)>0,format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0),0)) > 8,
                            IF(format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0)>0,format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0),0),
                                concat(IF(format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0)>0,format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0),0),
                                    space(8 - length(IF(format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0)>0,format (((tank.max_or_lable * site.sfl_limit) - T1.volume),0),0))))),space(3),
                    IF (length(format(T1.water,0)) > 8,format(T1.water,0),concat(format(T1.water,0),space(8 - length(format(T1.water,0))))),
                    timestamp
                    )

                    order by tank_product))
                    as Message

                    FROM inventory as T1

                    INNER JOIN  tank on T1.site_id = tank.site_id and T1.tank_product = tank.number
                    INNER JOIN site on T1.site_id = site.ID
                    INNER JOIN user_information ON user_information.ID = site.ID
                    where T1.site_id = 3 and T1.tank_product in(1,2,3,4,5,6,7,8,9) order by tank_product and line_access_token IS NOT NULL


text:
Q: Confusion Between Which vs That I am having a doubt between the usage of which and that.
Which one of the following is correct and why?
The cougar is a member of the cat family that grows around 8 feet in length.
or
The cougar is a member of the cat family which grows around 8 feet in length.
Hope you can clarify it ASAP.

A: To understand the use of "that" & "which" like the way you sentenced, you need to know about restrictive/nonrestrictive modifiers.

For example, the following two sentences are both correct. But conveys totally different meaning.

The cars that are expensive often get stolen.

  The cars, which are expensive, often get stolen.

A restrictive modifier restricts the scope of the noun to a subset. This is where "that" comes into play. In the first statement, "The cars that are expensive often get stolen" it means only those cars that are expensive get stolen. Not all cars! We are pointing out a subset of cars called "expensive cars".

A non-restrictive modifier adds more information to the noun. Even if you remove the modifier the core meaning stays the same. In our example, "The cars, which are expensive, often get stolen" it means all cars are expensive and they get stolen. And it also means all cars get stolen.
Both of the below statement means the same. But the first merely adds more information.

The cars, which are expensive, often get stolen.
  The cars often get stolen.

 Also a non-restrictive modifier needs to be set off from the noun it modifies by commas. Whereas restrictive modifier should not have any commas. This is also a prime differentiating factor.

The cars that are expensive often get stolen.

  The cars, which are expensive, often get stolen.

A: I have two tests. [1] Bear in mind that 'that' defines, while 'which' describes. To remember this you can mutter to yourself the phrase: "This is the house that Jack built."
[2] The comma test; if you would be inclined to put commas round the clause then 'which' is likely to be more appropriate.
"The cougar is a member of the cat family that grows around 8 feet in length."  Does not need commas, so 'that' can stand. The phrase suggest that at 5 foot the cat cannot be a cougar.
The cougar, which frequently grows to around 8 feet in length, is a member of the cat family. This can take commas and 'which'. (Unfortunate the borderline is indistinct.)


text:
Q: How to make Dart Editor find referenced packages In the Dart Editor (x64), I create a new project from the "Polymer Web Application" template.
Immediately after creation, Dart Editor runs pub get command, executes building workspace.
Then for every import directive, like
import 'package:polymer/polymer.dart';

I got the following error:
Target of URI does not exist: 'package:polymer/polymer.dart'
How can I make Dart Editor understand references for standard libraries?

A: I assume your pub-cache is corrupted which can usually be fixed by running pub cache repair from command line.


text:
Q: propertygrid adding two models in a form I've a problem:
I've an item which is called: ServerStatus
This item i am adding with this.propertyGrid1.SelectedObject = item; to my propertygrid.
But I've 2 WCF Services and wanna add to this propertygrid (=> in that my item is) an other modelitem (can't use +=);
is there a way to do this ? or do i need to make a model for both modelitems ?

A: Not sure what your requirement is but a PropertyGrid is capable of displaying common properties for several instances. If you modify a property, the value will be assigned to all selected target instances. If a property has different values for the target instances, a blank field will be displayed.
myGrid.SelectedObjects = new object[] { item1, item2 };


text:
Q: Is there a notification code when cursor position changes in Edit Control MFC? Is there a notification code sent when the cursor position changes in an Edit Control MFC? I want to display the cursor (character) position for the user

A: There is no EN_... notification sent by the Edit control itself when the caret position changes.
However, you can use SetWinEventHook() to register for EVENT_OBJECT_LOCATIONCHANGE notifications for your app's process ID and UI thread ID.

EVENT_OBJECT_LOCATIONCHANGE
  0x800B
An object has changed location, shape, or size. The system sends this event for the following user interface elements: caret and window objects. Server applications send this event for their accessible objects.

You can then have your callback function filter the notifications by checking if the provided hwnd is your Edit control and the provided idObject is OBJID_CARET.

OBJID_CARET
The text insertion bar (caret) in the window.

When detected, you can get the actual caret position by sending an EM_GETSEL message to the Edit control.

Gets the starting and ending character positions (in TCHARs) of the current selection in an edit control.

Or, if you are using the CEdit class, use its GetSel() method.

Call this function to get the starting and ending character positions of the current selection (if any) in an edit control, using either the return value or the parameters.


text:
Q: Is the druid boy Mordred? Earlier in the series Merlin comes across a group of Druids and a young boy who telepathically talks to him and refers to his magical name "Emrys". on a few occasions when this boy is in danger the Dragon tell Merlin not to help him as the boy will one day ally himself with Morganna and pose a great threat to Arthur, a warning (like a fair few) Merlin ignores.
The final season is Mordred is introduced and at first Merlin seems fearful since Mordred knows his name as Emrys however at first Mordred shows he is on Arthur's side until he betrays the kingdom and allies with Morganna.
Now i am wondering, is Mordred the druid boy and if so, how many years have elapsed in the series since their first meeting?

A: From the very last scene when he first appears in 1x08, "The Beginning of the End":

Adult Druid: "We are forever indebted to you, Arthur Pendragon, for returning the boy to us."
Arthur: "You must not let it be known that it was I who brought him to you."
Adult Druid: "We will tell no one.  You have my word."
(Starts to walk away)
Arthur: "Wait!  I don't even know your name.  At least tell me your name."
(Stops and looks back at Arthur)
Adult Druid: "It's all right."
Mordred: "My name is Mordred."
Arthur: "Good luck, Mordred."

As for Mordred's age, one fan broke down the calendar references in the series to come up with 10 years passing between the start and end of the series.  The re-casting of Mordred from someone born in 1997 to someone born in 1988 makes a lot more sense in this case:

*

*The Great Purge happened 20 years before Merlin came to Camelot, and right after Arthur's birth.

*Year 1: Series 1

*Year 2: Series 2

*Year 3: One Year Gap

*Year 4: Series 3

*Year 5: One Year Gap

*Year 6: Series Four

*Year 7, 8, 9 : Three Year Gap

*Year 10: Series Five

So although Season 5 aired 5 years after Season 1, the characters have all aged 10 years, and a 5-year-older Mordred would have been too young.  All the other actors were fine because at their age, a few missing years isn't as visible, but with how young Mordred was in his first appearance, the original actor wouldn't have aged enough.


text:
Q: Examples/classification of algebraic symplectomorphisms I'm curious about examples of algebraic automorphisms of complex varieties which are symplectomorphism. For instance, can we classify the algebraic symplectomorphisms of $\mathbb{P}_{\mathbb{C}}^n$ with regard to the Fubini-Study form? Or can we give large classes thereof for $\mathbb{P}_{\mathbb{C}}^n$ or other complex algebraic varieties? If understand a comment on this question correctly, there ought to be an ample supply....

A: A general remark about Kahler manifolds is that a biholomorphic automorphism is symplectomorphic if and only if it is an isometry. (Generally, if a diffeomorphism preserves two out of three structures given by a Kahler metric: hermitian, symplectic, complex, then it preserves all three.) In the case of $CP^n$ with the FS-metric, the group of biholomorphic isometries is easily seen to be equal to $PU(n+1)$. As for more general examples, you can consider  biholomorphic isometries of compact hermitian symmetric spaces (these spaces will be algebraic). Helgason's book
Helgason, Sigurdur, Differential geometry, Lie groups, and symmetric spaces, Pure and Applied Mathematics, 80. New York-San Francisco-London: Academic Press. XV, 628 p.  (1978). ZBL0451.53038.
contains a description of these groups (I do not remember the details). For general smooth algebraic varieties, describing the groups of biholomorphic isometries will be difficult. On general grounds, all you can say that this group will be a compact Lie group.


text:
Q: Proof $||\vec x||_\infty = \max\{|x_i|\}$ I know that the norm of vector $x$ is defined to be $||x||_n=\sqrt[n]{\sum_{i=1}^m|x_i|^n}$
How using that i can show that the inf norm is max?

A: Hint:$$\lim_{n \to \infty}\sqrt[n]{2^n+3^n+5^n}=\\\lim_{n \to \infty}\sqrt[n]{5^n((\frac 25)^n+(\frac 35)^n+1)} \to 5$$You can facotr $max\{|x_i|\}$ in radical ,to proove what you need
$$||\vec x||_\infty=\lim_{n \to \infty}\sqrt[n]{\sum_{i=1}^m|x_i|^n} $$take $max\{|x_i|\}=M$ so $M \geq \underbrace{|x_i|}_{i=1,2,3,...m}$
now
$$\lim_{n \to \infty}\sqrt[n]{\sum_{i=1}^m|x_i|^n}=\\\lim_{n \to \infty}\sqrt[n]{|x_1|^n+|x_2|^n+...+M^n+...+|X_m|^n}=\\
\lim_{n \to \infty}M\sqrt[n]{(\frac{|x_1|}{M})^n+(\frac{|x_2|}{M})^n+...+(\frac{M}{M})^n+...+(\frac{|x_m|}{M})^n}=\\
M\sqrt[n]{0+0+...+1+0+0+..}=\\M=max\{|x_i|\}$$
$\bf{Remark}:$If two or more of $|x_i|$ are equal to M we have the same result, let's say that $k\in\mathbb{N}$ is the number of parts that are equal to M$$\lim_{n \to \infty}\sqrt[n]{\sum_{i=1}^m|x_i|^n}=\\\lim_{n \to \infty}\sqrt[n]{|x_1|^n+|x_2|^n+...+M^n+...+M^n+...+|X_m|^n}=\\
\lim_{n \to \infty}M\sqrt[n]{(\frac{|x_1|}{M})^n+(\frac{|x_2|}{M})^n+...+(\frac{M}{M})^n+...+(\frac{M}{M})^n+...+(\frac{|x_m|}{M})^n}=\\
M\lim_{n \to \infty}\sqrt[n]{0+0+...1+...+1+0+0+..}=\\M\lim_{n \to \infty}\sqrt[n]{k}=\\
M\lim_{n \to \infty}k^{\frac 1n}\to M\times 1\\M=max\{|x_i|\}$$


text:
Q: PCI-E Sound Card not Appearing in Device Manager I have a HP EliteDesk 800 G1 SFF desktop computer running Windows 7 x64. The onboard sound card doesn't allow separate outputs for front and rear audio ports and they all output the same channel. I want to be able to use my speakers and have them connected to the rear audio panel and have my headset connected to the front audio panel with 2 separate sound outputs. The driver that comes with this computer doesn't allow separate outputs.
To fix this I bought an ASUS Xonar DGX PCI-E sound card. When I plug this sound card into the motherboard it fits fine and the computer boots up. However in Device Manager I do not see the new sound card.
I have checked the BIOS settings and the PCI slot is enabled and I even tried disabling the onboard sound with no luck. I tried this sound card in two other HP EliteDesk 800 G1 SFF's and I ran into the same issue. I tried the card in a HP Compaq 6200 Pro SFF and it works just fine which tells me the card isn't defective. Upon trying several other HP EliteDesk 800 G1 SFF's this also tells me the PCI slot isn't defective.
I have also updated the BIOS to the latest version which didn't work and the other machines I tried had older versions of the BIOS which also didn't work.
So what are my options?

*

*I haven't tried booting a different operating system to see if it detects the card yet

*Could there be a BIOS setting that I am not seeing?

*Maybe the card isn't compatible with this machine?

*Could there be a jumper or cable that needs to be unplugged on the motherboard? One thing to note is when I unplug the cable from the motherboard for the front panel and plug it into the sound card the BIOS gives me an error upon boot saying "917 - Front Audio Not Connected" and I have to press F1.

*Is there a different sound driver that I can use that would allow 2 separate outputs for the rear and front audio ports?
POSSIBLE SOLUTION
The HP Compaq 6200 Pro SFF also has a Realtek onboard sound card that is a little older. The driver software that comes with that allows you to have separate audio outputs, unlike the newer driver that comes with the HP EliteDesk 800 G1 SFF.
The older drivers interface looks like this and it gives you this option whereas the newer one does not:

The newer Realtek audio driver is called DTS Audio Control Panel and it lacks the feature mentioned above in the Realtek HD Audio Manager.
Does anyone know of a way to use this older version of the driver? That would fix my problem and it would eliminate the need for a separate sound card.


text:
Q: how to split the below datas with reg exp? I have try so many times to split the below data into separate numbers and texts, but always failed.
0                '£22,000 per annum'
1      '£30,000 - £35,000 per annum'
2        '£250.00 - £350.00 per day'
3            '£250 - £280 per annum'
4      '£30,000 - £35,000 per annum'

is it possible to split the data into this format with one reg expression?
22000           per-annum
30000  35000    per-annum
250     350     per-day
30000  35000    per-annum

A: Why not just pop value at those positions instead, especially since when they maintain set intervals. I don't know if the actual data holds the same format though. I'd push regular expression away as much as I can.