text:
Q: Terence Tao Analysis 1 Excercise 8.3.2 Proof Verification I am working on excercise 8.3.2 in Tao Analysis 1. This is my answer to the excercise.
The question statement is:
Let $A$, $B$, $C$ be sets such that $A \subseteq B \subseteq C$, and suppose that there is an injection $f : C → A$. Define the sets $D_0$, $D_1$, $D_2$,... recursively by setting $D_0 := B\setminus A$, and then $D_{n+1} := f(D_n)$ for all natural numbers $n$. Prove that the sets $D_0$, $D_1$,... are all disjoint from each other (i.e., $D_n ∩ D_m = ∅$ whenever $n \neq m$). Also show that if $g : A → B$ is the function defined by setting $g(x) := f^{−1}(x)$ when $x \in \cup_{n=0}^{\infty}D_n$, and $g(x) := x$ when $x \not \in \cup_{n=0}^{\infty}D_n$, then $g$ does indeed map $A$ to $B$ and is a bijection between the two. In particular, $A$ and $B$ have the same cardinality.
My work:

*

*The first step is to prove all the sets are disjoint from each other. Assume there are two sets $D_{n_0}$ and $D_{m_0}$ are not disjoint. The aim is to prove this contradicts the injectivity of $f$.
Assume without loss of generality that $n_0 > m_0$. Define the two sequences $\{n_{k}:k \in \mathbb{Z}^{+}$} and $\{m_{k}:k \in \mathbb{Z}^{+}$} as follows: $n_k = n-k$, $m_k = m-k$. Consider $D_{n_1}$ and $D_{m_1}$. If they are disjoint, stop here, if not, consider $D_{n_2}$ and $D_{m_2}$ and then $D_{n_3}$ and $D_{m_3}$, etc... until for some $k$, we find that $D_{n_k}$ and $D_{m_k}$ are disjoint (and such a k does exist, because if $D_{n_k}$ and $D_{m_k}$ are not disjoint for all $k<m$, then for $k=m$, we have the two sets $D_{n_m}$ and $D_0$ which are certainly disjoint). Now we have arrived at the following: For the $k$ that was found, $D_{n_{k-1}} \cap D_{m_{k-1}} \neq \phi$ and $D_{n_{k}} \cap D_{m_{k}} = \phi$. So we have an $x$ such that $x \in D_{n_{k-1}}$ and $x \in D_{m_{k-1}}$ and so $x = f(y_1) = f(y_2)$ for some $y_1 \in D_{n_k}$ and $y_2 \in D_{m_k}$. Since $D_{n_{k}} \cap D_{m_{k}} = \phi$, $y_1 \neq y_2$. We have found that $y_1 \neq y_2$ with $f(y_1) = f(y_2)$, contradicting the injectivity of $f$. So all the sets are piecewise disjoint.

*Next, given the function $g: A → B$, need to prove $g$ is both injective and surjective. For injectivity, if $x_1 \neq x_2$, then there are four possible cases:  $\quad$ 1) $x_1 \in \cup_{n=0}^{\infty} D_n$ and $x_2 \in \cup_{n=0}^{\infty} D_n$.  $\quad$ 2) $x_1 \in \cup_{n=0}^{\infty} D_n$ and $x_2 \not \in \cup_{n=0}^{\infty} D_n$  $\quad$ 3) $x_1 \not \in \cup_{n=0}^{\infty} D_n$ and $x_2 \in \cup_{n=0}^{\infty} D_n$  $\quad$ 4) $x_1 \not \in \cup_{n=0}^{\infty} D_n$ and $x_2 \not \in \cup_{n=0}^{\infty} D_n$  In the first case, $g(x_1) = f^{-1}(x_1)$ and $g(x_2) = f^{-1}(x_2)$. Clearly, $g(x_1) \neq g(x_2)$ or else the same element would map to two different images under $f$. In the second case, $g(x_1) = f^{-1}(x_1) \in \cup_{n=0}^{\infty} D_n$ and $g(x_2) = x_2 \not \in \cup_{n=0}^{\infty} D_n$ so $g(x_1) \neq g(x_2)$. The third case is similar to the second case, so its omitted. In the last case, $g(x_1) = x_1$ and $g(x_2) = x_2$ so $g(x_1) \neq g(x_2)$. This proves that $x_1 \neq x_2 \implies g(x_1) \neq g(x_2)$ and $g$ is injective. To prove $g$ is surjective, let $x \in B$. Then  $x \in B \setminus A$ or $x \in A$. If $x \in B \setminus A = D_0$, then $\exists y_1 \in D_1$ such that $f(x)=y_1$ and $x = f^{-1}(y_1)$ so $x = g(y_1)$. If $x \in A$, then $x \in \cup_{n=0}^{\infty} D_n$ or $x \not \in \cup_{n=0}^{\infty} D_n$. If $x \in \cup_{n=0}^{\infty} D_n$, then $x \in D_n$ for some  and there exists a $y \in D_{n+1}$ such that $y = f(x)$ so that $x = f^{-1}(y)$ and $x = g(y)$. If $x \not \in \cup_{n=0}^{\infty} D_n$, then $g(x) = x$. This shows that for every $x \in B$, there exists a corresponding $y \in A$ such that $x = g(y)$, and $g$ is surjective.
Is this correct? Thanks for your time.


text:
Q: STORM CRAWLER : Generate cookie from a separate link via basic authentication and use the cookie to crawl the links in seeds.txt The website that I want to crawl is enabled with an authentication via a third party basic authentication. For example, the url that needs to be crawled is https://intranet.crawl.com
The url first gets redirected to another page : http://auth.intranet.com, that allows a basic authentication, on passing the valid username and password it uses the cookie to login to https://intranet.crawl.com
How can I achieve the above authentication in storm crawler?

A: One option would be to use Selenium and have a custom NavigationFilter to fill the credentials on the redirected URL, see tutorial.
You could also generate the cookie externally prior to the crawling and specify it in the seed metadata using the key set-cookie. You'd need to add that key to metadata.transfer in your conf so that it gets transmitted to the outlinks and persisted to the storage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unrecognizable template declaration/definition I'm trying to implement a heap, but I've got the above error on one of my functions.
Here's my header file:
template <typename E>
class Heap
{
private:
    class Node {
        E data;
        Node * left;
        Node * right;
    };

    Node root;
    int length;

    E * preorder(E * list, int length, Node node);
    E * inorder(E * list, int length, Node node);
    E * postorder(E * list, int length, Node node);
    void clear(Node node);  //Recursively clears all nodes and frees all pointers
public:
    Heap();
    Heap(E * list, int length);
    ~Heap();

    Node * getRoot();
    void buildHeap(E * list, int length);
    E * returnList();
};

And the specific function in question (although there's similar errors on others). There error is on the second line
template <typename E>
Node<E> * Heap<E>::getRoot() {
    return &root;
}

A: The compiler is complaining about Node<E>; there is no template named Node in global scope. The code has to say that it's the member template:
template <typename E>
typename Heap<E>::Node * Heap<E>::getRoot() {
    return &root;
}


text:
Q: Legendre and sums of three squares The Three-Squares-Theorem was proved by Gauss in his Disquisitiones, and this proof was studied carefully by various number theorists. Three years before Gauss, Legendre claimed
to have given a proof in his Essais de theorie des nombres. Dickson just says that Legendre
proved the result using reciprocal divisors.
I am a little bit surprised that I can't seem to find a discussion of Legendre's proof
anywhere. Reading the original is not exactly a pleasure since the material in Legendre's
book is organized, if I dare use this word, in a somewhat suboptimal manner. So before I'll start reading Legendre's work on three squares I'd like to ask whether anyone knows a discussion of his proof (or its gaps).
Edit. I have meanwhile found a thoroughly written thesis from Brazil on
Legendre's work in number theory by Maria Aparecida Roseane Ramos Silvia:
Adrien-Marie Legendre (1752-1833) e suas obras em teoria dos Números, which has, however, preciously little on Legendre's "proof".
One gets a better idea of what Legendre was doing by reading Simerka's article
Die Perioden der quadratischen Zahlformen bei negativen Determinanten, although Simerka is doing his own thing; in particular, he uses Gauss's definition of equivalence and composition of forms and describes parts of Legendre's work in Gauss's language.
BTW I have only recently learned about the existence of this Czech number theorist, who discovered Carmichael numbers long before Korselt or Carmichael, and who factored (10^17-1)/9 using an algorithm based on the class group of quadratic forms discovered long after by Shanks, Schnorr, and others.

A: There is a discussion of this by Andre Weil in "Number theory from Hammurapi to Legendre", where seems to imply that Legendre's proof might have been a bit problematic (p. 332). Weil also gives some nice proofs of the $n$-squares theorems (appendix 2 to the Euler chapter). You can find a link to the Weil book here:
http://dl.dropbox.com/u/5188175/WeilNumbers.pdf


text:
Q: Custom NSButtonCell black background I have a NSButtonCell (a checkbox) in a cell-based NSTableView. I try to set its background color to a semi-transparent color (used tor the rest of the row), but this color fades to black. If the row color has an alpha of zero, the background of the control appears solid black.
Is there a way to mimic transparency on white instead of this (probably) nil color which default to black (0,0,0) ?

A: I think you should use buttons' layer property instead since the gradual NSCell deprecation introduced several years ago already.
self.wantsLayer = true
self.layer.backgroundColor = UIColor.black.CGColor

It's much more easier than messing with a drawRect(:)-method.


text:
Q: Mysql Query: LEFT JOIN List all orders and "balance due" for a customer, if no orders, just list customer. 3 Tables I have a customers table, orders table, and payments table.
From these I am trying to get one table that has for each record: customer#, order#, Balance due. But if a customer has no order then I just want to list the customer# with NULL values for the other fields.
Using a LEFT JOIN I was able to do this with just the customer# and order# but I cannot figure out how to get the balance due in there as well. I am fairly new to Mysql and tried to search the answer but was unable.
Here is what works for just the customer# and order#:
SELECT
    customers.cust_num,
    orders.order_id
FROM customers
LEFT JOIN orders ON customers.cust_num = orders.cust_num

But I am trying to incorporate "orders.invoice_amount - SUM(payments.amount) AS balance_due" as another column where the payments table is related to the orders table by a field called "order_id" in both.
Perhaps something like:
SELECT orders.invoice_amount - SUM(payments.amount) AS balance_due FROM payments, orders WHERE payments.order_id = orders.order_id
Any idea of how I could go about doing that or pointers in the right direction?

A: do an additional LEFT JOIN, but to a sub-query on payments grouped by order.  So, if it finds a record in the prequeried result, you are good to go.  Also, I changed to using table "aliases" for shorter readability, especially if table names get long, or you have to join multiple times to the same table in a query.
SELECT
      c.cust_num,
      coalesce( o.order_id, 0 ) as Order_ID,
      coalesce( o.invoice_amount, 0 ) as InvoiceAmount,
      coalesce( Prepaid.TotalPaid, 0 ) as TotalPaid,
      coalesce( o.invoice_amount - coalesce( PrePaid.TotalPaid, 0 ), 0) as BalanceDue
   FROM
      customers c
         LEFT JOIN orders o
            ON c.cust_num = o.cust_num
            LEFT JOIN
            ( select
                    p.order_id,
                    sum( p.amount ) as totalPaid
                 from
                    payments p
                 group by
                    p.order_id ) as PrePaid
               on o.order_id = PrePaid.order_id

A: you can try something like
SELECT
    customers.cust_num,
    orders.order_id,
      orders.invoice_amount - SUM(payments.amount)
FROM customers
LEFT JOIN orders ON customers.cust_num = orders.cust_num
INNER JOIN payments P ON P..order_id = orders.order_id
group by cust_num,order_id,orders.invoice_amount


text:
Q: AngularJS: Apply ngStyle on Child Element I have a span that has a ng-include that embeds a svg file. How can I style the svg using ng-style? I want to style it based on its index.

    {{ menuItem.name }}

A: ng-include is a simple "Dump this content here". There is really no way (using just ng-include) to accomplish this. My suggestion is to create a directive, and attach a directive scope variable like sub-style which inside your directive will set internal styles.
Call it like so:

Your directive:
app
.directive('svgcont2', function() {
  return {
    restrict: 'C',
    scope: {
      fillInfo: '='
    },
    templateUrl: function(elem, attrs) {
        return attrs.iconUrl
    }
  };
});

In your directive template:
<svg style="{fill: fillInfo}">

Another way, is to do this via styles. If your styles are simple enough, you can add additional classes to your parent span element, which you can propagate to the children inside. See a quick snippet below:
.svgcont2.fill div.childelement
{
     //Your style element
}

A: I got it. still added a fill attribute on the span, then i placed a css style for the svg to inherit the fill of the parent.
.svgcont2 svg {
    fill: inherit;
}


text:
Q: Invalid property value CSS fit-content I want to make my following CSS code cross-browser (Chrome & Fireofx) but it is not working:
width: fit-content;
width: -moz-fit-content;
height: fit-content;
height: -moz-fit-content;

Any help will be appreciated.


text:
Q: How to make pyramid pattern with numbers? How to make this pyramid with recursive in java ?
     1
    222
   33333
  4444444
     .
     .
     .

I made this pattern, but the number of lines increases by 1 instead of 2
    static void recursion(int row, int k, int j,int c){
    if(row>c){
        return;
    }
    else{
        if(k==row){
        System.out.println();
        recursion(++row, 0,0,c);
        }
        else if(c-j>row){
        System.out.print(" ");
        ++j;
        recursion(row, k, j,c);
        }
        else{
        System.out.print(row+" ");
        recursion(row, ++k, j,c);
        }
    }

Result:
     1
    2 2
   3 3 3
  4 4 4 4
 5 5 5 5 5

A: Try this.
static void pyramid(int n, int i) {
    if (i > n) return;
    System.out.println(" ".repeat(n - i) + Integer.toString(i).repeat(i * 2 - 1));
    pyramid(n, i + 1);
}

and
pyramid(5, 1);

result:
    1
   222
  33333
 4444444
555555555

A: Here's a solution using your existing design logic, or as I understood it. I changed some variable names so I could remember what did what. (use meaningful names when you code)
recursion(1, 0, 0, 7);

static void recursion(int row, int space, int num, int total){
    if (space < total-row){
            System.out.print(' ');
            if (total > 9) System.out.print(' ');
            recursion(row, ++space, num, total);
        }else if(num < row*2-1){
            String r = (row < 10 && total > 9)?" "+row:""+row;
            System.out.print(r);
            recursion(row, space, ++num, total);
        }else{
            System.out.println();
            recursion(++row, 0, 0, total);
        }
    }
}


text:
Q: Ruby hash.key error I feel like I'm overlooking something here.  When I try to use the Hash.key(keytolookfor) method, I get an error.
Is this method deprecated?
pete@Vader:~/tmp$ ruby -v
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux]
pete@Vader:~/tmp$ ./hashtest.rb
./hashtest.rb:8: undefined method `key' for {"firstkey"=>"firstvalue", "secondkey"=>"secondvalue"}:Hash (NoMethodError)
pete@Vader:~/tmp$

The script is as follows.
#!/usr/bin/ruby

testHash = Hash.new
testHash["firstkey"] = "firstvalue"
testHash["secondkey"] = "secondvalue"

if testHash.has_value?("secondvalue")
    keyvalue = testHash.key("secondvalue")
    puts "match found with key #{keyvalue}"
else
    puts "no match found"
end

A: My wild guess is that your system ruby /usr/bin/ruby is 1.8.7 which doesn't have Hash#key method. ruby -v most probably shows rvm version which is located in ~/.rvm/..., but first line in your script calls /usr/bin/ruby.

A: Use the heap record for script as follows:
#/usr/bin/env ruby

This picks up the default ruby version specified by the system, rvm, or rbenv. Since Ruby 1.8.7 has no Hash#key, make sure that you're running at least Ruby 1.9.1:
$ /usr/bin/ruby -v
1.9.1p0

Alternatively, use Hash#[] instead:
keyvalue = testHash["secondvalue"]


text:
Q: What is this CronJobs means? I recently study a newsletter system, there is a Cronjobs like this, I really do not contact linux Cronjobs before, anyone can explain it for me? Thank you very much.
wget -O - -q -t 1 http://www.ynhwebdev.de/newsletter/mails/sendAll

A: this command just downloads the web page "http://www.ynhwebdev.de/newsletter/mails/sendAll" which I assume is doing something on the server side (e.g. send some mails?) and sends the result to root (or whoever gets the cron mail)
If you list your cronjobs with
crontab -l

it should show 5 colums like
0 5 * * * wget....

which means it is executed at 05:00 every day.

A: This isn't actually about programming.
Please read the Cron entry on Wikipedia.


text:
Q: Using background images in Slick Carousel divs (responsive) I am using Slick Carousel and its responsive setting.
This code works fine:

        Sample

Anyone knows how to make Slick Carousel work with background images in DIVs?
Here's a demo of it not working properly:
https://jsfiddle.net/62y4h51w/

A: Can you try next modifications and tellme if works as expected (Appears to works on your jsfiddle):
HTML for slider:

        Sample

Add on CSS
.bg-image {
    background-image:url(https://via.placeholder.com/250x300);
    background-position: center; /* Center the image */
    background-repeat: no-repeat; /* Do not repeat the image */
    background-size: cover;
}


text:
Q: Finding possible thresholds for clustering I'm fiddling around with scipys fcluster.
linkage(p, 'single', 'euclidean')
fcluster(Z, t, criterion='distance')

In particular, I am looking for the right value(s) for the threshold parameter t.
I would like to iterate over all threshold values that generate different results.
So far I am sampling the threshold which often leads to generating the same clustering multiple times and there is no guarantee that a clustering isn't missed.
Is there a way to generate all threshold values at which the resulting clustering will change?
I tried using the values from pdist as potential candidates but noticed that there are still duplicates in the resulting clustering.


text:
Q: DistributionNotFound when moving a python pyramid application? How to correctly and safely move a python pyramid application?
SEE BELOW, I updated the details after feedback in the comments.
I first used the following command to prepare the environment:

virtualenv --relocatable ENV

After that, the app was still working correctly.
I then moved the python app to another directory, but get the following error:
[Thu Jul 27 16:09:08.884534 2017] [wsgi:error] [pid 14775] [remote 185.54.183.194:58084] mod_wsgi (pid=14775): Target WSGI script '/home/develop/web/checklist/prod/backend/pyramid.wsgi' cannot be loaded as Python module.
[Thu Jul 27 16:09:08.884660 2017] [wsgi:error] [pid 14775] [remote 185.54.183.194:58084] mod_wsgi (pid=14775): Exception occurred processing WSGI script '/home/develop/web/checklist/prod/backend/pyramid.wsgi'.

 .......

 [Thu Jul 27 16:09:08.886634 2017] [wsgi:error] [pid 14775] [remote
 185.54.183.194:58084] pkg_resources.DistributionNotFound: The 'checklist' distribution was not found and is required by the application

(checklist is the python application).
I changed the path's in the apache config of WSGIDaemonProcess and WSGIScriptAlias to the new location.
And I changed the path in the pyramid.ini file used in WSGIDaemonProcess.
My apache config:
    WSGIApplicationGroup %{GLOBAL}
    WSGIPassAuthorization On
    WSGIDaemonProcess checklistTest user=apache group=apache threads=4 python-path=/home/develop/web/test/checklist/backend:/home/develop/web/test/checklist/backend/env/lib/python3.4/site-packages
    WSGIScriptAlias /bdh-checklist-test /home/develop/web/test/checklist/backend/pyramid.wsgi
    <Directory /home/develop/web/test/checklist/backend>
      WSGIProcessGroup checklistTest
      Require all granted
    </Directory>

I updated the above config after feedback from Graham. I compiled mod_wsgi with the same python version as used by the python app (version 3.4). However, I still can't use the python-home attribute, it results in a timeout error (with the relocatable environment):

Timeout when reading response headers from daemon process
  'checklistTest':

In case I use the python-home, the above DaemonProcess entry looks like:
WSGIDaemonProcess checklistTest user=apache group=apache threads=4 python-home=/home/develop/web/test/checklist/backend/env/lib/python3.4

How to solve this?
Why should I use the python-home instead of python-path?
I have to include the path to the app itself in the python-app attribute, else the apache log will contain an error saying that it can't find the app distribution.


text:
Q: How to join connected sub-paths by eliminate useless point with PaperJS? I have a path that draw a circle whose origin is in the "west" side, then I split by removing the top and bottom. Then I get three sub-paths:

*

*Top-left 1/4 circle

*Right half circle

*Bottom-left 1/4 circle

But even visually 1 and 3 looks like a flipped 2, 1 and 3 are actually two sub-paths. How do I optimize this? I've tried smooth(), flatten() and simplify() and all not work.
Here is the sketch.

A: Based on your simplified case, you just have to build a new path composed of all your sub paths segments.
In order to optimize the resulting path a bit, you can skip the first segment of path B and only keep its handle out, since it's the same than path A last segment.
Depending on your use case, you could also, with the same logic, skip the last segment of path B since it's the same than path A first segment and make sure that the resulting path is set to closed.
Here is a sketch demonstrating a possible implementation.
const compoundPath = project.importJSON(
    ['CompoundPath', { 'applyMatrix': true, 'children': [['Path', { 'applyMatrix': true, 'segments': [[50, 700], [0, 700], [0, 600], [50, 600]] }], ['Path', { 'applyMatrix': true, 'segments': [[50, 600], [100, 600], [100, 700], [50, 700]] }]] }]
);
compoundPath.strokeColor = 'black';
project.activeLayer.addChild(compoundPath);

const subPaths = [];
compoundPath.children.forEach((child, i) => {
    subPaths.push(
        child
            .clone()
            .translate(0, 150)
            .addTo(project.activeLayer)
    );
});

const assembledPath = assembleSubPaths(subPaths);
assembledPath.strokeColor = 'black';

function assembleSubPaths(subPaths) {
    const path = new Path();
    subPaths.forEach((subPath) => {
        subPath.segments.forEach((segment, segmentIndex) => {
            const isFirstSegment = segmentIndex === 0;
            if (path.segments.length === 0 || !isFirstSegment) {
                path.add(segment);
            } else {
                path.lastSegment.handleOut = segment.handleOut;
            }
        });
        subPath.remove();
    });
    return path;
}


text:
Q: C# Dynamically Load An Assembly And Use It And Then Unload it I'm working on a plugin where the shell dll invokes methods in several other function dlls. Because we want to replace these function dlls during updating, the shell dll has to dynamically load those dll, and when updating, dynamically unload them.
I can do the load and unload part with AppDomain, but I can't find any resources about how to create an instance of a type in the loaded dll and invoke method on it. I'd be very much appreciate it if anyone can elaborate on this...
Thanks!


text:
Q: Receiving data from an array within a function PHP I'm fairly new to PHP and having a problem with an array. I have just set up my function with an array in it. Everything is working fine except when I call my array outside the function it seems nothing is inside, (my last for loop prints nothing out) the error displays "Notice: Undefined offset: for each number".
Here is the code:
$col_num = array();

// `getcoleachrow()`: function to get each data in each column row
function getcoleachrow ($col = array(), $value, $html){

  // 220 cells in the table
  for ($value=$value;$value<220;$value+=11){

    //gets the data from a cell then turn it to text and stores it in an array selected
    array_push($col, $html->find('td', $value)->plaintext);
  }

  // 20 rows and 20 data from the table in an array
  for ($rows = 0;$rows<=19;$rows++) {

    //print out array
    echo $col[$rows];
  }

} // getcoleachrow

// Call the `getcoleachrow()` function
getcoleachrow($col_num, $pos, $html);
//getcoleachrow($col_team, $team);

// Goes through every row
for($row = 0;$row<=19;$row++){
  echo $col_num[$row];
}

The last for loop is empty but the getcoleachrow($col_num, $pos, $html); prints out every I want.

A: You can solve your problem using global variable. But I advise you to return the new array and assign it to col_num. Because you modify an array but is only inside the function the instance of that array not out.
try to change your function to return an array like this:
function getcoleachrow($col = array(), $value, $html){

   //220 cells in the table
   for($value=$value;$value<220;$value+=11){

       //gets the data from a cell then turn it to text and stores it in an array selected
      array_push($col, $html->find('td', $value)->plaintext);
   }

   //20 rows and 20 data from the table in an array
   for($rows = 0;$rows<=19;$rows++){

       //print out array
       echo $col[$rows];
   }
   return($col);
}

and call your function in this mode:
$col_num = getcoleachrow($col_num, $pos, $html);

A: Unclear what the issue is.  The function getcoleachrow() iterates through an array & echos the values.  Then what is the final for($row = 0;$row<=19;$row++){ loop for? In fact looking at your code some more it is unclear what $col_num will do since you init it in the first line, send it to the getcoleachrow() function and then have that odd loop after that.  Something is missing.  Reformatted your code for clarity & edited original post to help.
EDIT: Refactoring the example based on the original poster's comment. The function is simply not returning a value.  Have it return a value & you are good to go.
// `getcoleachrow()`: function to get each data in each column row
function getcoleachrow ($col = array(), $value, $html){

  // Initing the array.
  $col_num = array();

  // 220 cells in the table
  for ($value=$value;$value<220;$value+=11){

    //gets the data from a cell then turn it to text and stores it in an array selected
    array_push($col, $html->find('td', $value)->plaintext);
  }

  // 20 rows and 20 data from the table in an array
  for ($rows = 0;$rows<=19;$rows++) {

    //print out array
    $col_num[] = $col[$rows];
  }

  // Return the `$col_num` array.
  return $col_num;

} // getcoleachrow

// Call the `getcoleachrow()` function
$col_num = getcoleachrow($col_num, $pos, $html);
//$col_num = getcoleachrow($col_team, $team);

// Goes through every row
for($row = 0;$row<=19;$row++){
  echo $col_num[$row];
}

A: You are never returning the values. You need to return it and assign it to a variable to be able to use it afterwards. Try this instead:
//function to get each data in each column row
function getcoleachrow($value, $html) {
  $col = array();

  //220 cells in the table
  for($value=$value;$value<220;$value+=11){

    //gets the data from a cell then turn it to text and stores it in an array selected
    array_push($col, $html->find('td', $value)->plaintext);
    }

  // Return it
  return $col;
  }

// No need to pass the array if you follow this path (returning the array)
$col_nums = getcoleachrow($pos, $html);

//Goes through every row
for($row = 0;$row<=19;$row++){
  echo $col_num[$row];
  }

Not sure on your background, but variables do not have global scope by default (nor should normally in PHP) as they do in other languages like javascript, nor the arrays are passed by reference as default like they are in C. However, you can actually return an array in PHP, something that comes very handy (;
Another thing is that you don't need to declare the variable to pass it (you don't need to pass it), so your code could be a bit cleaner.

A: Your $col_num array does not apear in scope:
you could solve this like:
function getcoleachrow(&$col = array(), $value, $html){
-----------------------^ this here
....
}

$col_num=array()
getcoleachrow($col_num, $pos, $html);

but i would not use this!
I would use:
function getcoleachrow($col = array(), $value, $html){
...
return $col // these is my interest
}

and then
$col_num= getcoleachrow($col_num, $pos, $html);

use the returnvalue of the function

A: A few things:

*

*Your optional arguments should only appear at the end of your function declaration, so you should remove the = array() from the first argument:
function getcoleachrow($col, $value, $html)

*Arrays (just like scalars) aren't passed by reference, so you could:
a. indicate that in the function declaration:
function getcoleachrow(&$col, $value, $html)

b. return the array at the end of your function:
function getcoleachrow($col, $value, $html)
{
    // ...
    return $col;
}
$col_num = getcoleachrow($col_num, $pos, $html);

*If you're always calling the function with an empty array, you may wish to drop the argument altogether:
function getcoleachrow($value, $html)
{
    $col = [];
    // ...
    return $col;
}
$col_num = getcoleachrow($pos, $html);

A: You need to have your function return something and then assign a variable to that returned output. In your case I'm thinking the following changes:
return  $col;     add this line at the end of the getcoleachrow function just before the function closing curly bracket.
$col_num = getcoleachrow($col_num, $pos,  $html); subsitute this for the line:
getcoleachrow($col_num, $pos, $html);

A: You added all the values to the array: $col and not the array $col_num.
Thats why you dont get output outside the function.
$col = array(); makes an new array named $col.
change
function getcoleachrow($col = array(), $value, $html){

to
function getcoleachrow($col, $value, $html){

Or just leave it out and use $col_num in the function


text:
Q: automorphisms of the infinite trivalent tree Let $T$ be the infinite trivalent tree.  I want to show that if $\alpha,\beta,\alpha',\beta'$ are vertices of the tree such that the distances $d(\alpha,\beta)$ and $d(\alpha',\beta')$ are equal, then there is an automorphism $g$ of the tree such that $(\alpha^g,\beta^g)=(\alpha',\beta')$.
I think I can prove this, but since the tree is infinite, I want to make sure my argument is complete, and the terminology to use is unclear to me.
Proof:  If $\alpha=x_0,x_1,\ldots,x_\ell=\beta$ and $\alpha'=x_0',x_1',\ldots,x_\ell'=\beta'$ are the unique shortest $\alpha-\beta$ and $\alpha'-\beta'$ paths, respectively, then let $g$ be the map $x_i \mapsto x_i'$.  The two remaining neighbors of $x_0$ can be mapped to the two remaining neighbors of $x_0'$ in any arbitrary manner, and similarly for the two neighbors of $x_\ell$.  Map the unique remaining neighbor of $x_i, i=1,\ldots,\ell-1$ to the unique remaining neighbor of $x_i'$.  This map $g$ can be extended to an automorphism of the infinite tree (does this sentence require further justification?). QED.
I want to prove that the vertices of the tree can be partitioned into two subsets $\Delta$ and $\Delta'$ such that the distance between any pair of vertices in the same subset is even.  I think this follows immediately from the fact that the tree is bipartite, and I wonder if further explanation is required just because the tree happens to be infinite. (This is exercise 1.5.15 from Dixon and Mortimer's Permutation Groups).
(While the above is my question, I would be glad to know if there are any important differences (in results or proofs) between the cases where the tree is finite versus infinite.)


text:
Q: Unwanted coding shown next to inserted images on PDF, have no idea why? Pictures and code shown in description
Have this problem for all images except this one:

I have tried PNG and Jpeg files, same problem.
Here is the code us for the "count final.jpg"
\begin{figure}[htp]
\centering
\includegraphics[width=15cm]{box count final.jpg}
\caption{Box Count Diagrams for Illustrative Purposes}
\label{fig:box counting}
\end{figure}

And here is the code of the Cantor Set image:
\begin{figure}[htp]
\centering
\includegraphics[width=4cm]{cantor.png}
\caption{The Cantor Set}
\label{fig:cantor}
\end{figure}

Any help in this matter will be greatly appreciated, been having this problem for months.


text:
Q: MongoDB Write Concern in context with replication In a Shard MongoDB provide replication to replica set as pull mechanism, my question is if a write operation arrive at the primary with majority write concern then will it be waiting for all the operation in oplog to be replicated to all nodes or will just replicate this write operation to all nodes.

A: Since the oplog is replicated asynchronously the wait will only be for that particular write operation and not for the whole oplog.
Visit http://docs.mongodb.org/manual/core/distributed-write-operations/ for more details.


text:
Q: iOS - How to create recurring calendar events with exclusion occurrences (date)? I'm trying to create a recurrent event into calendar through JSON API,  but with exclusion occurences (/date) I don't know how to do it. I think i create a recurrent event, then I delete occurences.
update:
For example, the event repeats every weekend. However, I removed some of the weekends from the time line, creating an exception to a recurrence rule.
How can I get these excluded dates through the API?
my code:
 1. CreateEvent from api json:
NSDictionary *dicEvent = [self.arrayEvents objectAtIndex:index];

EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = [dicEvent objectForKey:@"RecurrenceRule"];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
event.startDate = [dicEvent objectForKey:@"startDate"];
event.endDate =  [dicEvent objectForKey:@"endDate"];
    EKSpan span = EKSpanFutureEvents;

[self.eventStore saveEvent:self.savedEvent span:span commit:YES error:&error];

2. then with exclusion occurrences, I think I delete occurences.
EventStore *eventStore = [[EKEventStore alloc] init];

NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:calendars];

NSArray *results =  [eventStore eventsMatchingPredicate:predicate];
for (int i = 0; i < results.count; i++) {
 EKEvent *event = [results objectAtIndex:i]
 if ([event.occurencesIdentifier isEqualToString: eventoccurencesIdentifier]) {
    // delete occurencesIdentifier
break;
}

Please help me where I had gone wrong.
Thanks!


text:
Q: SwiftUI Xcode 12.5 with very basic NavigationView layout Issues I have been developing iOS for about a decade and every time I try to take the dive into SwiftUI I spend more time than ever wrestling what should seemingly be a simple task. While working on an app with very simple navigation setup I kept seeing two errors in the console: Unable to present. Please file a bug. and Unbalanced calls to begin/end appearance transitions for <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVVS_22_VariadicView_Children7ElementGVS_18StyleContextWriterVS_19SidebarStyleContext___: 0x7fd913d0bd90>. The first happens when there are at least 3 Views  to navigate from (I don't understand why this is a significant threshold and my end goal uses a LazyVGrid with a ForEach) with navigation links and the second error happens on rotating to landscape and then back to portrait. I believed this to be related to how the phone is presenting the sidebar but even changing to StackNavigationViewStyle produced similar problems.
If this were a UIKit application I can absolutely solve for the Unbalanced calls situation but SwiftUI really takes away some of the lower level capabilities that I am used to having control of when it comes to building Views and navigation stacks.
I finally attempted to just start a new project from scratch and place the minimal amount of code in the ContentView:
struct ContentView: View {

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("Number 1")) {
                    Text("Number 1")
                }
                NavigationLink(destination: Text("Number 2")) {
                    Text("Number 2")
                }
                NavigationLink(destination: Text("Number 3")) {
                    Text("Number 3")
                }
            }
        }
    }
}

Running the above code produced the issues on rotation. Another issue that I came across was when you press the < back button after these issues start, the navigation stops working completely and the "detail" view never gets updated.
It is clear that the direction is SwiftUI so I am trying to really go this direction (maybe next week will have some amazing improvements) but this seems to be a pretty significant issue on a very simple set of code. I am hoping that I am just doing something wrong that someone can point out quickly.
EDITED:
After more exploration I found that the second error happens on the 11, 11 Pro Max, and 12 Pro Max where the navigation stack changes to the sidebar by default. Changing the style to StackNavigationViewStyle does eliminate the second error (but doesn't help if I do want to use the sidebar style) but the first error remains. To Schottky's point, changing VStack to List will also eliminate the first error. However a newer convention (based on WWDC videos at least) to solve for collection views I believe is to use a LazyV/HGrid with a ForEach within it which is actually what I am attempting to accomplish. I didn't put that as my code here since I wanted the be able to reproduce the error in the simplest form of course to ensure it wasn't something buried in my view hierarchy.

A: The way I was able to accomplish this was via a post I found at HackingWithSwift here. I still had to use .navigationViewStyle(StackNavigationViewStyle()) to eliminate a different error as it seems that the initial iterations of SwiftUI focuses on the 80% of cases where multiple NavigationLinks only really exist in the List View type. I have not tested this with the latest beta but if you try to use the other navigation style (Column) it will throw another error: unbalanced calls to begin/end appearance transactions. I am okay with this for now as this at least allows me to create a screen that does not have line separators and navigation arrows....I just don't have the Master-Detail setup by default.


text:
Q: doPostBack from C# with JavaScript hi I have one parent page which opens a pop up window, and user makes some changes on child pop up page then clicks a save button.
When the user clicks the save button, I want to doPostBack to the parent page so that the changes made in the pop up window can be seen in parent window.
Question : How can I achive the above scenario?
I want to write the script code in aspx.cs file, I tried
string script = "";
script = "";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);

but this did not do anything, no errors just nothing.
I am new to JavaScript, need help with all steps.

A: The parent page:
<asp:UpdatePanel runat="server">
    <ContentTemplate>

            <asp:Literal runat="server" ID="ChildWindowResult" />

        <input type="button" value="Open Dialog" onclick="window.open('MyDialog.aspx', 'Dialog');" />
        <asp:Button ID="HiddenButtonForChildPostback"  runat="server"
            OnClick="OnChildPostbackOccured" style="display: none;" />
        <asp:HiddenField runat="server" ID="PopupWindowResult"/>
    </ContentTemplate>
</asp:UpdatePanel>

The MyDialog page:

<asp:TextBox runat="server" ID="SomeValueHiddenField" />
<asp:Button runat="server" OnClick="PostData" Text="Click Me" />

protected void PostData(object sender, EventArgs e)
{
   SomeValueHiddenField.Value = DateTime.Now.ToString();
   ClientScript.RegisterStartupScript(this.GetType(), "PostData", "postData();", true);
}

But I believe that it would be much better to utilize here some pop-up controls like PopUpExtender from the AjaxControlToolkit library or dialog from the jQuery-UI.

A: You probably need to use ClientID:
string script = "";
script = "";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);

A: The last parameter is to whether include script tag or not
So, if you do
RegisterClientScriptBlock(page,type, "", true);

You will end up with:
"</script>"

So, change your last parameter to false, or better yet, remove the tags in the string

A: Review the following suggested solution:
http://livshitz.wordpress.com/2011/06/12/use-popup-to-postbackupdate-its-parentopener-without-losing-viewstate-values-and-close/#more-16


text:
Q: Why is PC-Mac emulation a one way street? I know it's possible to run a PC emulator and virtual machine on a Mac, but why is it you can't emulate a Mac on the PC?  Both run on Intel chips these days.
I ask because I'd like to try my hand at iPhone development but don't want to shell out for a dedicated Mac laptop, even a used one, if I can help it.

A: Because they only want it running on hardware you buy from them. It's more of a legal issue with regards to licensing than a limitation issue. There are projects out there (iDeneb) that help you run a Mac OS on other hardware.

A: There's more to a computer than its microprocessor. In the case of Mac OS X, Apple controls the entire in-box hardware ecosystem, and therefore only warrants that OS X will run on its own machines.
Apple employs some additional hardware, and Mac OS X checks for that hardware.
There are "hackintoshes" available -- that is, there are ways to hack OS X into running on some PCs. I was sort-of successfully running one as an alternative boot on my last PC for a while (no networking nor audio). This is, however, a violation of Apple's end user licensing agreement, and software updates often break these deployments.
In any event, I'm not aware any virtualized hackintosh solution at this point. My experience with the hackintosh I had led me to buy a new MacBook last year (replacing my prior PowerBook, which was on its last legs), a decision I have not regretted one bit since.
My official recommendation is buy an inexpensive, used MacBook or Mac Mini running on Intel chips, then Snow Leopard if needed. Easier than trying to get a hackintosh running -- and if you factor in your time at a certain hourly rate, it may ultimately be cheaper. (It was for me -- and I bought a $1300 laptop!)

A: It isn't as though you can't, It is just that they do not want you to.
Apple have their EULA that states you can't install it on non Apple hardware.
At the end of the day, if you turn off some of the ACPI features and add a couple of lines to a VMX file (which I probably shouldn't be going in to detail on here) you can run OSX fine within a virtual machine.
OSX 86 Project is a very good source of news for OSX on pc.
When it comes down to it, the reason it is not more common knowledge is because Apple doesn't want it to be!

A: What John T said, and that Apple licensing prohibits you running their OS on anything other than Apple hardware.

A: You can, but it breaks the eula, and there's no VM that officially supports it (except on OS X itself, and then only the server edition). Requires a fair bit of setup (moreso than a standard hackintosh)
I never got it working, but I've been assured it's possible.
And the whole licensing thing.


text:
Q: How to get email id, name and number from contact list I am trying to fetch name, contact no and email id from contact list and store in array list and forward to server. I am storing name, phone and email id to contactNameArrayList, contactNumberArrayList and contactEmailIdArrayList.
Below code I got name, email and contact no but how to store specific email id to specific contact no?
private void getAllContacts() {
    ContentResolver contactResolver = context.getContentResolver();

    Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

    if(cursor.getCount()>0)
        while ( cursor.moveToNext()) {
            String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Log.e("TAG",  " Name: " + displayName+"==>phone Number==>"+number);
            contactNameArrayList.add(displayName);
            contactNumberArrayList.add(number);
            final String[] projection = new String[]{ContactsContract.CommonDataKinds.Email.DATA,
            ContactsContract.CommonDataKinds.Email.TYPE};
            Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,null, null, null);

            while (emailCursor.moveToNext())   {
                String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
                Log.e(TAG,"EMAIL==>"+email);
            }

            emailCursor.close();
        }

        cursor.close();

        Log.e(TAG,"contactNameArrayList sIZE==>"+contactNameArrayList.size()+"contactNumberArrayList size==>"+contactNumberArrayList.size()+"contactEmailAddressArrayList size==>"+contactEmailAddressArrayList.size());
    }

Above code I call getAllcontact method. I got number and name and email id and store in contactNameArrayList and contactNumberArrayList and contactEmailAddressList. But when I get email id response is like this:

Name: efg==>phone Number==>(256) 655-555
       EMAIL==>abc@gmail.com
       EMAIL==>pqr@gmail.com
       EMAIL==>xyz@gmail.com
       Name: abc==>phone Number==>(256) 655-555
       EMAIL==>abc@gmail.com
       EMAIL==>pqr@gmail.com
       EMAIL==>xyz@gmail.com
        Name: pqr==>phone Number==>(987) 456-1238
       EMAIL==>abc@gmail.com
       EMAIL==>pqr@gmail.com
       EMAIL==>xyz@gmail.com
         Name: xyz==>phone Number==>(987) 456-1238
       EMAIL==>abc@gmail.com
       EMAIL==>pqr@gmail.com
       EMAIL==>xyz@gmail.com

So how to get email id for specific phone and store in contactEmailArrayList. As per above response conatactNameArrayList and contactNumberArrayList size same but ContactEmailAddressArrayList size is different. So please give me suggestion.

A: make one class for getting email,name,no etc.
public class UserContact {
private String userName,userEmail;
private boolean isSelect;

public boolean isSelect() {
    return isSelect;
}

public void setSelect(boolean select) {
    isSelect = select;
}

public UserContact(){}
public UserContact(String userName, String userEmail) {
    this.userName = userName;
    this.userEmail = userEmail;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserEmail() {
    return userEmail;
}

public void setUserEmail(String userEmail) {
    this.userEmail = userEmail;
}

}
then in main activity make one list as global level of class .
    private List<UserContact> mContactList = new ArrayList<>();

then call getContact details.
 /**
 * this method read device in contact name and email.
 */
public void getContact() {
    if (PermissionManager.checkPermission(getActivity(), READ_CONTACT)) {
        mContactList.clear();
        List<UserContact> contactList = new ArrayList<>();
        Cursor cur = getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor cur1 = getActivity().getContentResolver().query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (cur1.moveToNext()) {
                    //to get the contact names
                    String name = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    Log.e("Name :", name);
                    String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    Log.e("Email", email);
                    if (!TextUtils.isEmpty(email)) {
                        contactList.add(new UserContact(name, email));
                    }
                }
                cur1.close();
            }
        }
        mContactList = contactList;
        setAdapter();
    } else {
        PermissionManager.askForPermission(READ_CONTACT, getActivity());
    }
}

above method get only name and email you can modify your needs and add phone number code.


text:
Q: Understanding type inference I believe I am having a problem with both the data type and ownership of iter. It is first declared inside the for loop expression. I believe Rust infers that iter is of type u16 because it is being used inside of my computation on line 4.
  1     let mut numbers: [Option<u16>; 5];
  2     for iter in 0..5 {
  3         let number_to_add: u16 = {  // `iter` moves to inner scope
  4             ((iter * 5) + 2) / (4 * 16)  // Infers `iter: u16`
  5         };
  6
  7         numbers[iter] = Some(number_to_add);  // Expects `iter: usize`
  8     }

I am receiving the following error:
error[E0277]: the type `[std::option::Option<u16>]` cannot be indexed by `u16`
  --> exercises/option/option1.rs:3:9
   |
7  |         numbers[iter] = Some(number_to_add);
   |         ^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`

*

*I tried casting iter as u16 inside the computation in line 4, but still having issues.

Where is my misconception?

A: Your assumption is correct. And your fix was ok too (it led to a different error, see below).
Your first problem was that for slice indexing, iter needs to be of type usize so either
numbers[iter as usize] = Some(number_to_add);

or
((iter as u16 * 5) + 2) / (4 * 16)

will lead to correct type inference through rustc.
Your second problem was that numbers was not initialized, so rustc correctly warns you when you try to modify numbers. Assigning a value, e.g.,
let mut numbers: [Option<u16>; 5] = [None; 5];

will let you compile your program.

A: Aside from the existing answers, a somewhat higher level approach could also be cleaner (depending on taste)
let mut numbers = [None; 5];
for (i, n) in numbers.iter_mut().enumerate() {
    let iter = i as u16;
    let number_to_add: u16 =
        ((iter * 5) + 2) / (4 * 16);

    *n = Some(number_to_add);
}

An other alternative would be a more lazy approach, but there's (afaik) no way to e.g. try_collect into an array, only try_from a slice to an array, so you'd need to collect() to a vec, then try_from to an array, which seems less than useful. Though you could always use an iterator to initialise you array:
let mut it = (0u16..5).map(|i| ((i * 5) + 2) / (4 * 16));
let numbers = [it.next(), it.next(), it.next(), it.next(), it.next()];

Also

 // `iter` moves to inner scope

iter is Copy so it's just... copied. Kinda. And the block is not useful either, it only contains a simple expression.

A: Your reasoning is correct. Just to add, if you only want to initialize your array, you might also consider this way of doing it:
let arr_elem = |i: u16| Some(((i * 5) + 2) / (4 * 16));
let numbers : [Option<u16>; 5] = [
    arr_elem(0),
    arr_elem(1),
    arr_elem(2),
    arr_elem(3),
    arr_elem(4),
];

This way, you do not need to have it mut (at the cost of writing a helper function to initialize a single element and stating the initializer elements, but that could be automated e.g. via a macro or some helper traits).


text:
Q: run query on stackexchange data using python I am attempting to get a list to TOP n tags and its usage so far using python.
I can run this query on stackexchange site as below,
SELECT *
FROM Tags
WHERE ExcerptPostId is not NULL
order by Count
Desc

That gives me result as below,
Id  TagName Count   ExcerptPostId   WikiPostId
3   javascript  1538133 3624960 3607052
17  java    1360163 3624966 3607018
9   c#  1169923 3624962 3607007
5   php 1157178 3624936 3607050
1386    android 1063197 3625001 3607484
820 jquery  890140  3625262 3607053
16  python  877784  3624965 3607014
2   html    717700  3673183 3673182
10  c++ 549953  3624963 3606997
58338   ios 545753  4536664 4536663
 .......
 ....... and so on.

However, is there a way to get exact same data using python? Probably run same query using API,
I looked at stack.py , py-stackexchange , but couldnt find documantion.
Any ideas?

A: Got it.
Looks like there is a tags() method available. Although looking at code , i couldnt understand attributes.
However, I was able to deduce available attributes for tags() method using dir.
>>> dir(tag)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',_sizeof__',
 '__str__', '__subclasshook__', '__weakref__', '_extend', '_up',
  'count', 'fetch', 'id', 'json', 'json_ob', 'name', 'partial', 'site',
 'synonyms', 'top_answerers', 'top_askers', 'transfer', 'wiki']
>>>

After that it was just a matter of selecting proper attributes.
Here is the code.
import stackexchange

so = stackexchange.Site(stackexchange.StackOverflow)

#Print top 10 tags and their count
for  idx, tag in enumerate(so.tags()):
    if idx >= 10:
        break
    print("{},{}".format(tag.name , tag.count))

Result
>>>
javascript,1540896
java,1361964
c#,1171336
php,1158685
android,1064757
jquery,891031
python,880103
html,718747
c++,550622
ios,546498


text:
Q: Render partial later after page loads Using Rails 3.2. Let's say I have the following view:

<%= @shop.name %>

<%= @shop.description %>

    <%= render 'teasers' %>

Is there a way to just load the page first, then load the teasers later? Reason being so is because teasers takes some time to query (I have already optimized the query).

A: I personaly have a pre-defined system for this kind of behavior:
This (coffeescript) Javascript code is executed at each rendering of a page:
$('.ajax_load').each (index, element) ->
  e = $(element)
  $.get e.data('url'), (data) =>
    $(document).replace(e, data)

So each element in my page responding to the class "ajax_load" is actually called by ajax, example:
%div.ajax_load{ data: { url: users_path } }

This will display at first a div with a class ajax_load, and will send a request to users_path and replace the div with the response's content.

This is translated coffeescript:
$('.ajax_load').each(function(index, element) {
  var e,
    _this = this;
  e = $(element);
  return $.get(e.data('url'), function(data) {
    return $(document).replace(e, data);
  });
});

A: How about removing the teasers partial from the view and initially just displaying the page without it.  Then using javascript, make an AJAX call to the server.
You can use wiselinks to simplify your life.


text:
Q: Round the float value using ajax Using json i get the value,from thati try to round the values using the following script:
          function onLoad(){
            var output = $('#product');
            var id = getUrlVars()["cPath"];
            $.ajax({
                url: 'getprice.php?cPath='+id,
                data : {type : 'product'},
                dataType: 'jsonp',
                jsonp: 'jsoncallback',
                timeout: 5000,
                success: function(data){
          $.each(data, function(c,prd){

              var price  =Math.round(prd.products_price,2);

                           var product = '$' + price + '' ;
                           output.append(product);
                            }

                        });
                    output.listview("refresh");
                        //data loaded
                    },
                    });
        }

//OutPut NEEDS
   prd.products_price=450.2500
   price=$450.25

also try this format but not working:
            1.  var num = Math.val(prd.products_price);
                var price = num.toFixed(2);

A: var num = Math.val(prd.products_price);
var num = parseFloat(num);
var price=num.toFixed(2));

A: var price = prd.products_price;
var product = price.formatMoney(0, "")

Number.prototype.formatMoney = function(places, symbol, thousand, decimal) {
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var number = this;
        var negative = number < 0 ? "-" : "";
        var i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "";
        var j = (j = i.length) > 3 ? j % 3 : 0;

        return symbol
                + negative
                + (j ? i.substr(0, j) + thousand : "")
                + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand)
                + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }

A: Try this:
var price = parseFloat(prd.products_price).toFixed(2);


text:
Q: How to divide a line in excel and store in array when they have different spaces between them Hi,
I'm trying to retreive the data from excel sheet using java.
Please tell me how can I divide following lines into array like
0th element is 0171185
1st element is 11200113
2nd element is 404630G 40X46 1.2-MIL GRAY
One of the line is
0171185(MORE THAN A TAB SPACE)11200113 (MORE THAN A TAB SPACE)404630G 40X46 1.2-MIL GRAY

A: Assuming your line is stored in a String called myString:
myString.split("[\\W]{2,}"))

will use "more than one space or tabulator" as your delimitor. So single spaces and/or tabulators will not split your tokens.
Edit: as noted by Litari, \\s is also possible instead of \\W depending on which characters you want to split exactly.

A: Answered here previously: How do I split a string with any whitespace chars as delimiters?
The short answer is, use \\s as delimiter since it's equivalent to [ \\t\\n\\x0B\\f\\r]


text:
Q: tfs 2015 gated check in failed I created a ci build in tfs 2015.3. On the trigger tab I set gated check in.
Is there a way to let the developer now in vs that the build failed. Currently there is no way, I do not want to use alerts, I would like for a message in vs.
In addition, when the build fails, the files are checked out on the build server, how can I cancel this behavior, this requires a tfs admin to release the files.

A: In TFS 2013 there used to be a tool called Team Foundation Build Notification that shipped with Visual Studio 2013. However this is no longer the case.
If you don't want to use e-mail notifications there are third party applications that you can run in your tray to receive build notifications.  I have used catlight myself recently for the exact same problem. If you are using a chat application like Slack you can also integrate build notifications into your team's slack channel to be notified on build failure.
To answer the second part of your question it is important to understand what a gated check-in does exactly.
When you check-in and a gated check-in is triggerd your files are not checked in but TFS creates a shelveset instead. TFS will then perform a private build using the latest version of the sources in combination with the shelveset it just created. Only when the this private build passes the pending changes in your shelveset will be checked in by the build on behalf of the user who triggerd the gated check-in. This will create a new changeset.
Upon check-in all locks will be released so all files that have a check-in or check-out lock will be released when the build server checks in your changes on behalf of you.
When the build fails no the changes in the shelveset (created when the gated check-in build was triggerd) will not be checked-in by the build server thus the locks will not be released. In the source control explorer the files will still have pending changes (and be checked-out) because the changes in your workspace have not yet been checked-in. This is the intended beheaviour and should not cause any issues for you unless you have disabled multiple check-out and you are, by having these files checked-out, blocking other developers from making changes.
I would not advise you to use a gated check-in when also not allowing multiple check-outs. Furthermore I would not advise disallowing multiple check-outs if it can be avoided in any way.
A gated check-in is meant to safeguard the repository from receiving check-ins that would break the application (it no longer compiles or unit tests fail) or diminish the quality below your standards. However this also means you cannot check-in until all the rules and validations you have in your build process pass and thus means other developers will be locked out until you are able to get past the "gate".


text:
Q: Use column type S, from siunitx package with complex table headings I have a table with a complex heading using multirow and multicol packages. I'd like to have the second column of the following table as S type from siunitx package for to align the numbers by its decimal separator, however I failed. Any help, please?
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{multirow,multicol}
\begin{document}

\begin{table}[htb]
\footnotesize
\centering
\caption{Example Table}
\begin{tabular}{ccSS}% <--- HERE
\midrule
\multirow{2}{*}{\textbf{Column 1}} &
\multirow{2}{*}{\textbf{%
\begin{tabular}[c]
{@{}c@{}}Column 2\\
(\si{\g/\mL})
\end{tabular}}} &
\multicolumn{2}{c}{\textbf{Column 3 (\si{\ug/\L})}} \\
\cmidrule{3-4}& &
\textbf{Column 3.1} & \textbf{Column 3.2}\\
\midrule
AE1 &  3.45 & \multicolumn{ 2}{c}{Some text} \\
AE2 & 20.65 & 50 & 4.5 \\
AE3 & 12.67 & 20 & 7.5 \\
AE4 & 0.78 & 75 & 12.09 \\
AE5 & 3.098 & 100 & 14 \\
\midrule
\end{tabular}
\end{table}
\end{document}

A:
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{booktabs, multirow}
\usepackage{siunitx}

\begin{document}

\begin{table}[htb]
\centering
%\footnotesize
\renewcommand\multirowsetup{\centering}% for centering text in multirow cells
\caption{Example Table}
\begin{tabular}{cS[table-format=2.3]
                 S[table-format=3.0]
                 S[table-format=2.2]}% <--- HERE added S column type
    \toprule
\multirow{2}{*}{\textbf{Column 1}}
    &   {\multirow{2}{12ex}{\textbf{Column 2}\\(\si{\g/\mL})}} % enclosed in {...}
                                                               % with defined width is possible write text in more lines
        &   \multicolumn{2}{c}{\textbf{Column 3 (\si{\ug/\L})}}     \\
    \cmidrule{3-4}& &
\textbf{Column 3.1} & \textbf{Column 3.2}   \\
    \midrule
AE1 &  3.45 & \multicolumn{2}{c}{Some text} \\
AE2 & 20.65 & 50 & 4.5                      \\
AE3 & 12.67 & 20 & 7.5                      \\
AE4 &  0.78 & 75 & 12.09                    \\
AE5 & 3.098 & 100 & 14                      \\
    \bottomrule
\end{tabular}
\end{table}
\end{document}

A: I don't think you should lower "Column 1", because it has the same rank as the other headers in columns 2–4.
The \smash[b]{...} trick allows to pretend that the unit below the header doesn't take vertical space.
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{booktabs}
\usepackage{siunitx}

\newcommand{\splitcell}[1]{%
  \smash[b]{\begin{tabular}[t]{@{}c@{}}#1\end{tabular}}%
}

\begin{document}

\begin{table}[htb]
\centering

\caption{Example Table}

\footnotesize % <-- are you sure?
\begin{tabular}{
  @{}
  l
  S[table-format=2.3]
  S[table-format=3.0]
  S[table-format=2.2]
  @{}
}
\toprule
\textbf{Column 1} &
  {\splitcell{\bfseries Column 2 \\ (\si{\g/\mL})}} &
  \multicolumn{2}{c}{\textbf{Column 3 (\si{\ug/\L})}} \\
\cmidrule(l){3-4}
&& \textbf{Column 3.1} & \textbf{Column 3.2}\\
\midrule
AE1 &  3.45 & \multicolumn{2}{c}{Some text} \\
AE2 & 20.65 & 50 & 4.5 \\
AE3 & 12.67 & 20 & 7.5 \\
AE4 & 0.78 & 75 & 12.09 \\
AE5 & 3.098 & 100 & 14 \\
\bottomrule
\end{tabular}
\end{table}
\end{document}

The top and bottom rules shouldn't be \midrule; if you don't like the default thickness of \toprule and \bottomrule, you can change the relevant parameter by adding
\setlength{\heavyrulewidth}{\lightrulewidth}

in the document preamble.


text:
Q: How to cache utils function used in different class instances using lru_cache? When using lru_cache in a utilities module, after decorating a method, and calling from two different class instances, I found that the cache_info() showed only one hit each time the decorated method was called.
awsUtils.py:

@lru_cache(maxsize=32)
def getRdsDetailsCached(name, region):
  return getRdsDetails(name, region):

def getRdsDetails(name, region):
  client = boto3.client('rds', region)
  response = client.describe_db_instances(DBInstanceIdentifier=name,)
  return response['DBInstances']

Replication.py
class Replication(ActionBase):

  def __init__(self, **entries):
    super().__init__(**entries)
    self.rdsDetails = awsUtils.getRdsDetailsCache('my-db', 'us-west-2')

Postgress.py
class Postgress(DependencyBase):

  def __init__(self, **entries):
    super().__init__(**entries)
    self.rdsDetails = awsUtils.getRdsDetailsCache('my-db', 'us-west-2')

When the above two classes are initialized, I would expect the first instance to call awsUtils.getRdsDetailsCache which would create a cache, and any other instance would re-use that cache.  However the actual result is each shows that the hit count is 1.


text:
Q: VBA how to check if download files from Server has success? I'm able to use the below code to download files from server. However, this does tell me whether the files are downloaded successfully.
Sub DownloadFirstRunFilesPart2()
Application.StatusBar = "Downloading files..."
Dim wsh As Object
Dim errorcode4 As Integer
Dim cmd5 As Variant
Dim FirstRunFiles(5) As Variant
Dim var As Variant

FirstRunFiles(0) = ProN & "_KSParameter_UserInput.xlsx"
FirstRunFiles(1) = ProN & "_KSParameter_SysOutput.xlsx"
FirstRunFiles(2) = ProN & "_ModelParameter_UserInput.xlsx"
FirstRunFiles(3) = ProN & "_ModelParameter_SysOutput.xlsx"
FirstRunFiles(4) = ProN & "_VarClusParameter_UserInput.xlsx"
FirstRunFiles(5) = ProN & "_VarClusParameter_SysOutput.xlsx"

For Each var In FirstRunFiles
cmd5 = Chr(34) & "C:\Program Files (x86)" & "\PuTTY\pscp.exe" & Chr(34) & " -sftp -l " & pUser & " -pw " & pPass & _
    " " & " " & pHost & ":" & ServerPath & "/" & var & " " & LocalPath & "\"
Set wsh = CreateObject("wscript.shell")
errorcode4 = wsh.Run(cmd5, vbHide)
'If errorcode4 = 0 Then MsgBox ("Error occurs. Fail to download " & var)
Next var

Application.StatusBar = "Download complete"
MsgBox ("Downloading process complete.")
End Sub

My error code always equals 0 no matter the file exists or not. How should I change this program?
Thanks in advance!

Update:
The new code that I tried:
Sub test()
Dim wsh As Object
Dim WshShellExec As Variant
Dim cmd3 As String
Dim pFirstRunFile1 As String
Const WshFinished = 1
Const WshFailed = 2

pFirstRunFile1 = "this_proj_name.txt"

cmd3 = Chr(34) & "C:\Program Files (x86)" & "\PuTTY\pscp.exe" & Chr(34) & " -sftp -l " & pUser & " -pw " & pPass & _
    " " & " " & pHost & ":" & ServerPath & "/WOE/" & pFirstRunFile1 & " " & LocalPath & "\WOE"

Set wsh = CreateObject("wscript.shell")
WshShellExec = wsh.Exec(cmd3)

Select Case WshShellExec.Status
Case WshFinished
   strOutput = WshShellExec.StdOut.ReadAll
Case WshFailed
   strOutput = WshShellExec.StdErr.ReadAll
End Select

MsgBox strOutput                'write results in a message box

End Sub

However I'm getting error on this line:
    WshShellExec = wsh.Exec(cmd3)
The error message says "Object does not support this property or method". Any ideas?


text:
Q: How to store HTML form data in local? I am making a HTML form where I need my users to be able to get back whatever data that they have filled up, after closing the window/tab and reopening it.
If I do it with JavaScript cookies or HTML 5 local storage, Then I will have to write code for every single input tag there is, even if its like thousands.
So, what would be the most efficient way to accomplish this?
P.S. I am using PHP for back end processing.
I want the function just like we have in the browser like restoring the session in firefox or chrome.

A: you can use like this with localstorage.
localStorage.setItem('formData', JSON.stringify($('form').serialize())); //comfortable java script way.

or with cookies you can like this
$.cookie('formData', JSON.stringify($('form').serialize())); //can support old browsers also.

please read the excellent accepted answer at storage-vs-cookies you will know which one to use.

A: LocalStorage is your best option.

I will have to write code for every single input tag there is, even if it's like thousands.

That is not true. You can use a JS loop, or a jQuery each, to do that:
$("input").each(function(){
              $(this).val(storage.getItem($(this).attr("id")));
          })
          .change(function(){
              storage.setItem($(this).attr("id"), $(this).val());
          });

When the page loads, you loop through each input on the page and put content into it based on the input's ID.Then you attach an event listener to all the inputs, which saves any changes into local storage.
I have not tested this, and it is only for illustrations purposes. This code probably won't work straight away, but I hope you understand the concept.


text:
Q: Playing Videos from Chrome Filesystem Not Working on Android I am trying to create an offline video player that would download video content from my site for later viewing offline via an HTML5 video element.  The code below works fine in Chrome for the desktop, but not on mobile (Nexus S smartphone, Nexus 7 tablet, 4.1 since only that runs chrome, which is required for the filesystem api).  I am using the filesystem API that is supported by chrome on both the desktop and mobile.
I have confirmed it is correctly storing the file on the mobile device and I can retrieve the file correctly, but for some reason after retrieving the video from the localsystem chrome does not want to play the video.  This is true whether I am using the html5 video element or whether I am navigating directly to the filesystem URL.  When I use the html5 video element it returns the error media_err_not_supported.  I have confirmed that the device can play the video if I navigate directly to it on my server (without first storing it using the filesystem api), so the issue is not a codec or video format problem.  I am also using the video/mp4 mime type in both cases.
Again, this works on desktop, but not mobile.  Any ideas?
Here is the code we are using:
<!DOCTYPE html >
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"> </script>
        <script type="text/javascript">
            var _fs;
            var filename = "test3.mp4";
            var diskSpaceRequired = 10 * 1024 * 1024;
            $(document).ready(function () {
                window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
                function onInitFs(fs) {
                    _fs = fs;
                    getVideo(fs);
                }

                if (!!window.requestFileSystem) {

                    window.webkitStorageInfo.requestQuota(
                        window.webkitStorageInfo.PERSISTENT,
                        diskSpaceRequired, // amount of bytes you need
                        function () { },
                        function () {}
                    );
                    window.requestFileSystem(window.PERSISTENT, diskSpaceRequired, onInitFs, function () { alert('error'); });
                } else {
                    alert('not supported');
                }

                $("#play").on('click', playVideo);
                $("#ourVideo").on('error', function(e) { console.log('ERROR!!!', e, arguments);
                  console.log($("#ourVideo")[0].error);
                 });
            });

            function playVideo() {
               _fs.root.getFile(filename, {}, function (fileEntry) {
                    $("#ourVideo").attr('src', fileEntry.toURL());
                    fileEntry.file(function (file) {
                      var reader = new FileReader();
                      reader.onloadend = function (e) {
                        $("#ourVideo").get(0).play();
                      };
                      reader.readAsText(file);
                    }, errorHandler);

                }, errorHandler);
            }

            function getVideo(fs) {
                fs.root.getFile(filename, { create: true }, function (fileEntry) {
                    fileEntry.createWriter(function (fileWriter) {
                        fetchResource(fileWriter);
                    }, errorHandler);

                }, errorHandler);
            }

            function errorHandler(e) {
                console.log('error', e);
            }

            function fetchResource(fileWriter) {
                console.log('fetchresource');
                var xhr = new XMLHttpRequest();
                xhr.responseType = "arraybuffer";
                xhr.open("GET", "http://mydomain.com/trailer.mp4", true);

                xhr.onload = function(e) {
                    if (this.status == 200) {
                        var bb = new WebKitBlobBuilder();
                        bb.append(this.response);

                        var blob = bb.getBlob("video\/mp4");
                        fileWriter.write(blob);
                    } else  {
                      console.log(this.status);
                    }
                };
                xhr.send();
            }

        </script>
        <title>foo</title>
    </head>
    <body>

        <input type="button" value="Play Video" id="play"/>
            <video id="ourVideo" controls="">
                <source id="vidSource"  type="video/mp4"/>
            </video>

    </body>
</html>

A: The problem looks like  your android chrome coudn't access the android file system correctly, For that you can use nanoHttpd server for access android local files in device or sdcard.
for NanoHttpd server use this one class in your application and pass the media file location as http://localhost:8081/sdcard/(your_media_location).mp4
or get nanoHttpd from https://gist.github.com/1893396
I think this is more accurate to access sdcard files than directly calling for them

try change html part to
</head>
<body>

    <input type="button" value="Play Video" id="play"/>
        <video id="ourVideo" controls="">
             <source src="video1.mp4" type= "video/mp4">
             <source src="video1.ogv" type= "video/ogg">
        </video>

</body>

you can convert your mp4 to ogv using
http://video.online-convert.com/convert-to-ogg
and put ogv file in the same location in mp4
**for more information check out these
http://www.broken-links.com/2010/07/08/making-html5-video-work-on-android-phones/
HTML5 <video> element on Android does not play


text:
Q: Combinatorial interpretation of double factorial. Using some basic algebra (and proved afterwards using induction), I found that:
$$ 1 \cdot 3 \cdot ... (2n-1) = \frac{(2n)!}{2^n \cdot n!}$$
After a bit of research, I found out that this is known as the 'double factorial', is there a combinatorial interpretation/proof for this result?

A: André Nicolas gives the clue, "It counts in two different ways the number of ways to divide 2n people into n teams of 2 people."
The left-hand side
Consider the following procedure:

*

*Select the youngest person who has not yet been put in a two-person team.

*Match them with another so far unselected person.

This produces $1\cdot(2n-1)\cdot1\cdot(2n-3)\cdot\ldots\cdot(3)\cdot1\cdot(1)$, which is the left-hand side. The procedure can give any matching, and from any matching we can reconstruct the choices we made.
The right-hand side
Suppose we ask the two-person teams to form a line. There are $2n$ persons, and thus $(2n)!$ possible lines. But for any given ordering, the pairs can be reordered (with the left person remaining on the left) in $n!$ ways, and the relative order (inside the pairs) independently in $2^n$ ways. This produces the right-hand side.


text:
Q: Setting foreground of TextBlock to a LinearGradientBrush causes unwanted behavior I'm getting unwanted behavior from a TextBlock I'm using in my DataTemplate. It seems that the LinearGradientBrush that I'm using for the Foreground property is not drawing the gradient consistantly across the font for words that contain "descenders" like the lower-case 'p' in the word Vampire in the example picture.
I tried setting the LineHeight to the same as the FontSize; no change.
I tried setting the Height of the TextBlock; no change to the color, but added height to the bottom of the TextBlock.
Has anyone else dealt with this and found a solution before? I tried searching Google and StackOverflow for answers but I've come up with nothing so far.
Edit: The problem is the gradient is not applied the same to each textbox, because the descenders increase the height of the font. Look at the difference between the lower-case 'a' in the words Vampire and Brave, and you will see what I mean.

TextBlock XAML
<TextBlock Text="{Binding Title}" FontWeight="Bold" FontStyle="Italic"
           FontSize="20" Padding="3" LineHeight="20">
  <TextBlock.Foreground>
    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
      <GradientStopCollection>
        <GradientStop Color="White" Offset="0.2"/>
        <GradientStop Color="AliceBlue" Offset="0.4"/>
        <GradientStop Color="#6AB0EE" Offset="0.6"/>
        <GradientStop Color="DarkOrange" Offset="0.8"/>
      </GradientStopCollection>
    </LinearGradientBrush>
  </TextBlock.Foreground>
</TextBlock>

A: Try to set MappingMode property like this:
<LinearGradientBrush MappingMode="Absolute" StartPoint="0,0" EndPoint="0,1" >


text:
Q: How does Joomla route to the controller method on submitting the form? In a case where the form action is set to something like:
action="<?php echo JRoute::_('index.php?option=com_test&layout=edit&id='.(int) $this->item->id); ?>"

and the form contains and hidden input:
<input type="hidden" name="task" value="testctrl.save" />

How does joomla route to the controller method?
I would understand if it had the task in the form action, but I can't see how it picks up the task from the hidden input in order to route to the appropriate method in the testctrl controller method

A: It's not that complicated. In your com_mycom directory there is a file called mycom.php. In it you have some lines that look like this:
$controller = JControllerLegacy::getInstance('Contact');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();

See an example here:
https://github.com/joomla/joomla-cms/blob/staging/components/com_contact/contact.php#L15
So that's what takes the task and instantiates an instance of that controller object, and pulls the task from the hidden form input value that you pointed out. It passes the task to the controller from there.
The controller receives the request here:
https://github.com/joomla/joomla-cms/blob/staging/components/com_contact/controller.php#L19
You might be asking "why don't I see it receiving the task that the component file sends it?". Well that's because the controller for this component is a child-class of the JControllerLegacy class:
https://github.com/joomla/joomla-cms/blob/staging/libraries/legacy/controller/legacy.php#L701
public function execute($task)
{ ... }

This function is the execute function which receives the task from the component. This is the parent class of your controller task. Hopefully this all makes sense!

A: When you set the controller name explicitly with hidden fields
<input type="hidden" name="task" value="testctrl.save" />

or
<input type="hidden" name="controller" value="testctrl" />
<input type="hidden" name="task" value="save" />

or even not specifying the controller with task , just used it with view name.
All the cases your component file like com_test have a file with test.php
it includes Joomla library files.
jimport('joomla.application.component.controller');

when you check the library file it have two function for getting related controller and models.
createFileName() and getInstance() in libraries/joomla/application/component/controller.php
These two function do the task.
The above files are applicable only for Joomla 1.5 to Joomla 2.x
Edit
For Joomla3.x
In Joomla 3. x The file structure little bit changed.
Instead of  jimport('joomla.application.component.controller'); Joomla 3.x uses
$controller = JControllerLegacy::getInstance('Content');

This will call the JControllerLegacy class in libraries\legacy\controller\legacy.php
you can find the same functions createFileName() ,getInstance() on the above path.
Hope its helps..


text:
Q: How angular renders templates when there is a recursive call? I am trying to implement a simple directory menu where directories can have children and be part of a parent directory.
However, a very strange thing happens when I implement a recursive template, whenever I click one of the
 elements the function doSomething is called, why is this happening? does that mean angular renders the elements over and over again every time I click any
 element? Isn't this a memory leak?
Template:

    {{d.name}}

      <hello
        *ngIf="d.dirs && d.dirs.length>0"
        [dirs]="d.dirs"
        [some]="doSomething()"
      ></hello>

Component:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  templateUrl: "hello.component.html",
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
   times: number = 0 ;

  @Input() dirs: Directory[];
  @Input() some;
  constructor() {
    this.dirs = [
      new Directory(
        [new Directory([new Directory([], "sub-sub-dir1")], "sub-dir1")],
        "dir1"
      ),
      new Directory([new Directory([], "sub-dir2")], "dir2"),
      new Directory([], "dir3")
    ];
  }

  doSomething() {
    console.log("Something's been done ! ");
    console.log(this.times++);
  }

  clicked(){
    window.alert("Ops I was clicked!")
  }
}

export class Directory {
  dirs: Directory[];
  name: string;

  constructor(dirs: Directory[], name: string) {
    this.dirs = dirs;
    this.name = name;
  }
}

Full code is here
https://stackblitz.com/edit/angular-ivy-yvu84v?file=src/app/hello.component.ts
https://angular-ivy-yvu84v.stackblitz.io

A: This is not related to propagation, it's happening because you're binding a function expression instead of declaration, change it to this and it will work:

 <hello
        *ngIf="d.dirs && d.dirs.length>0"
        [dirs]="d.dirs"
        [some]="doSomething">
 </hello>

Explanation of why this is happening:
This is happening because of how angular Change Detection mechanism works, Angular executes expressions on each change detection run, which is why your function got executed many times.
Because of that my rule of thumb is to try to avoid using function expressions in templates, because they will get executed a lot and it can affect performance.

Brief explanation about change detection:
To help understand why this is the case better, let's explain Change Detection. Your entire component HTML is being represented as a View, the view is a data structure that contains all your elements and their property bindings.
If you have <input [value]="certainVariable"/>, the input element is being represented with the element and the corresponding binding, so in our case input: certainVariable.
Every time a component fires an event, or an Observable emits an event, a Change Detection happens. This is why when you click on an element you're invoking Change Detection, because you are firing an event which triggers change detection automatically.
What Angular does, is that it goes through your entire View and checks each element with its corresponding binding to see if a value has updated. If so, it updates it in the DOM as well.
This is how Angular keeps your component logic and your HTML view in sync.
Specifically what Angular does is that it checks each element and its expression, so for example our input element, it checks the certainVariable value and see if it has changed.
When you have a function as property binding like this [some]="doSomething()", it will do the same thing as in Change Detection Angular checks an expression.
If you have a function declaration instead, it will not call that function because it's not an expression.

A: You are calling your component recursively:
selector: 'hello',

and in the HTML template/view of the 'hello' component you are calling it again inside itself:
...

     <hello ...

This means, with every click you get a whole new instance of the component 'hello' inside the parent component: 'hello'.
So, it is behaving the way you see and it is a correct behavior. You must rethink your design if you need a different behavior.


text:
Q: Change song number font color with songs.sty I'm using songs.sty to create a songbook.
I figured out how to change the background color of the song number boxes by redefining \snumbgcolor like \renewcommand{\snumbgcolor}{green}.

I can also change the background color in the index with \renewcommand{\idxbgcolor}{green}.
Is there an easy way to change the font color for these to white?
MWE:
\documentclass{book}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage[usenames]{xcolor}

\usepackage[lyric]{songs}
\renewcommand{\snumbgcolor}{green}

\begin{document}

\begin{songs}{}

\beginsong{Bella Notte}[sr={\footnotesize Mel: Bella Notte}, cr={}]

\beginchorus
Nu er det nat, en vidunderlig nat,
åh så stille Bella Notte
\endchorus
\beginverse
Stjernernes skær, bringer himlen så nær,
jeg vil drømme Bella Notte
\endverse

\endsong

\end{songs}
\end{document}

A: Maybe it's not exactly the standard solution, but by listing all commands from the songs package and keeping only stuff with "num" in it using latexdef -ll -p songs | grep num, I found the command \printsongnum. Here is a redefinition of it, only adding the white color:
\renewcommand{\printsongnum}[1]{%
    \sffamily \bfseries \LARGE \color{white}#1%
}

It seems to work if I put it in the preamble of your example. Since there aren't a hundred @ signs in the command, let's assume it's not a dirty trick xD

A: I confirm it works, and give an illustration. B.t.W;, needless to use  the usenames option, as it's the default now.
% -----------------------------------------------------------------------------
% !Mode:: "TeX:Hard:UTF-8"
% PDFLaTeX this document and view or print it from Acrobat Reader!
% -----------------------------------------------------------------------------
% Preamble Starts here:
% -----------------------------------------------------------------------------
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[lyric]{songs}
\usepackage[svgnames]{xcolor}

\renewcommand{\snumbgcolor}{SeaGreen!60}
\renewcommand{\printsongnum}[1]{\color{white}\bfseries\Huge#1}

\begin{document}

\begin{songs}{}

\beginsong{How doth the little crocodile}[by={Lewis Carroll}]

\beginverse
How doth the little crocodile\\
   Improve his shining tail,\\
 And pour the waters of the Nile\\
   On every golden scale! \bigskip

 How cheerfully he seems to grin,\\
   How neatly spreads his claws,\\
 And welcomes little fishes in\\
   With gently smiling jaws!
   \endverse

\endsong

\end{songs}

\end{document}


text:
Q: Block other bots/spiders from accessing my site except Googlebot bing and yandex Is there any way to use .htaccess to block bots/crawlers/spiders accessing my site, excluding googlebot, bing, and yandex.
I dont care to know the names of the other bots/spiders. I want to allow only googlebot, bing, and yandex.
Please I have search the other posts but cant find this specific one.


text:
Q: Something is preventing screensaver from starting This happens very often when I don't restart my Windows 11 for awhile - screen saver doesn't start, something is preventing it from starting!
One clue I have is that something is using sound card:
c:\>powercfg -requests
DISPLAY:
None.

SYSTEM:
[DRIVER] USB Audio Device (USB\VID_08BB&PID_2704&MI_00\8&1e28b207&0&0000)
An audio stream is currently in use.
[DRIVER] USB Audio Device (USB\VID_2752&PID_0007&MI_00\9&1f386f2e&0&0000)
An audio stream is currently in use.
[DRIVER] Legacy Kernel Caller
[DRIVER] Legacy Kernel

AWAYMODE:
None.

EXECUTION:
None.

PERFBOOST:
None.

ACTIVELOCKSCREEN:
None.

As you see, it says audio stream is in use, but nothing is playing, I can't hear anything, but still I think Windows thinks some video is playing and won't start the screensaver (like when you put Youtube video to fullscreen).
Even if I close all browser windows and other apps, there's still audio stream in use!
How to "stop" this audio stream, or whatever process/tab is preventing screensaver to start?


text:
Q: unwanted flick effect on mousemove event I have a frame(parent) and one rectangle inside it(child) and I want to move this rectangle on x-axis based on mouse position ... whenever I try to move this rectangle I see flick effect ... can someone guide me how to fix this?

 let frame = document.querySelector('.frame') ;
        let slider = document.querySelector('.frame .slider') ;
        let mouseX = undefined ;
        frame.addEventListener('mousemove',function(e){
            mouseX = e.offsetX ;
            slider.style.left = mouseX + 'px' ;
        }) ;
 html,body{
            height: 100%;
        }
        body{
            padding: 0 ;
            margin: 0 ;
        }
        .frame{
            width: 75vw ;
            height: 75vh;
            border: 4px solid rgb(220,220,220) ;
            position: relative ;
            top: 50% ;
            left: 50%;
            transform: translate(-50%,-50%) ;
        }
        .frame .slider {
            position: absolute ;
            width: 1% ;
            height: 100%;
            left: 100% ;
            background-color: rgb(30,30,30) ;
            cursor: pointer;
        }

A: You need to use mouseX = e.clientX ; instead of mouseX = e.offsetX ; because offsetX will reset when your mouse move over slider and flick will be there for a second hope this will help :)

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>


text:
Q: Simulate two clicks using httpclient C# and pass PKI Certificate Using a client, I want to login to a webpage using PKI certificate. On the website, I would need to agree to an acknowledgement by clicking on a checkbox, then the login button will be enabled to see and then I can click on that. From there, a window will popup for me to select a certificate and input a password and then I can log in.
On a different website, I was able to press the agree button by doing this:
using (var client = new HttpClient())
{
     var content = new FormUrlEncodedContent(new Dictionary<string, string> { { "value", "agree" } });
     var agreementPost = await client.PostAsync(url, content);
}

where 'value' is the element of "input" in html and 'agree' is in between the quotes for the value tag.
For the website I'm working on, the input tag is under several div's, but the tag looks like this:
<input id="agree_cb" type="checkbox" click="handleOnClick(this);">

and for the button I press after that, it looks like this:
<button value="X509"></button>

So my code is this:
X509Certificate2 cert = GetCertificate();
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(cert);

HttpClient client = new HttpClient(handler);
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
    { "id", "agree" },
    { "value" , "X509"}
});
var agreementPost = await client.PostAsync(entry_url, content);

var connectionEntry = await client.GetAsync(main_URL);
var output = await connectionEntry?.Content.ReadAsStringAsync();

But when I output it, it outputs the html page as if it never logged in. I'm not sure if I am clicking the buttons or not. I know the PKI certificate is being passed into the client, but I don't know if the timing of it, is correct or not?
Any help is appreciated


text:
Q: call a base class method using a derived class object outside the derived class i have seen many posts that describe how to call base class function is called inside a derived class function using the super keyword.I want to call a base class overloaded function globally using a derived class object.
class a:
    def __init__(self):
        self.x=45
    def fun(self):
        print "fun in base class"
class b(a):
    def __init__(self):
        self.y=98
    def fun(self):
        print "fun in derived class"
objb=b()
objb.fun()#here i want to call the base class fun()

A: Input:
objb = b()
super(b, objb).fun()

Output:
fun in base class

Edit:
As mentionned in comment below, in Python 2.7+ you need to declare class a(object) for this to work. This comes from a historical evolution of classes in Python, with this solution being functional for "new-style" classes only, i.e. for classes inheriting from object. In Python 3.x however, all classes are "new-style" by default, meaning you don't have to perform this small addition.

A: If you really want to call the 'base' function that works on old-style classes (classes that don't extend object) you can do it like:
objb = b()
a.fun(objb)  # fun in base class

Or if you don't know the base/parent class, you can 'extract' it from the instance itself:
objb = b()
objb.__class__.__bases__[0].fun(objb)  # fun in base class

But save yourself some trouble and just extend your base classes from object so you can use the super() notation instead of doing bases acrobatics.


text:
Q: Not sure how to do Non-Homogeneous Recurrence Relations I have a sample exam paper, and the answer is given, but I can't work out the answer from the question:

Find the solution of:
$a_n = \frac{1}{3}a_{n-1} + 2$
using $a_0 = 4$
Given Answer: $a_n = 3 + (1/3)^n$
I would like someone to show me how to generally approach these sorts of questions, I can solve Homogeneous Recurrence relations, no problem, but these seem a lot more difficult :/

A: Here is one approach. Let $a_n=b_n+c$, where $c$ is a constant we will choose later.  Then the recurrence becomes
$$b_n+c=\frac{1}{3}(b_{n-1}+c)+2.$$
Rewrite as
$$b_n=\frac{1}{3}b_{n-1}-\frac{2}{3}c+2.\tag{1}$$
Choose $c$ so that the constant term in (1) is $0$, and solve the homogeneous recurrence $b_n=\frac{1}{3}b_{n-1}$.

A: $a_n = \frac{1}{3}a_{n-1} + 2$
$a_{n-1} = \frac{1}{3}a_{n-2} + 2$
Subtracting and rearranging gives:
$a_n = \frac{4}{3}a_{n-1}-\frac{1}{3}a_{n-2}$
Putting you back in the homogeneous case.
This method works in some cases when the "let $a_n = b_n +c$" method fails.  As a silly example, if we had $a_n = a_{n-1}+1$ then the substitution method would fail but this would still put you back in the homogeneous case.


text: Q: Gmail Sidebar Gadget OAuth Origin Mismatch Error When setting up an OAuth client id for Google APIs at Google APIs Console, you have to specify the Javascript origin if you are using Google's Javascript API for oauth. However, the Javascript origin does not support wild card urls, and I have confirmed that the server that's hosting my Gmail sidebar gadget has a different subdomain on subsequent requests. Is there a there a known solution for identifying a Gmail server as the Javascript origin, or should I proxy the OAuth requests via a service that I host?


text:
Q: Wordpress every page is 404 not found including admin resources Haven't changed anything on my wordpress in about a year. Suddenly every page is 404 not found, including the admin dashboard.
Any help much appreciated.