text:
Q: Coding conventions for ASPX filenames I have been looking around in Coding guidelines and in the MS coding convention. I can't find what the proper way of naming .aspx files is. Should they start with a capital or not?
So
News.aspx or news.aspx

A: Personal preference: Pascal naming convention, but use IIS to force urls to the same case for SEO.


text: Q: How to convert Common Alerting Protocol (CAP)  to WKT I've come across some data being sent in the CAP (http://docs.oasis-open.org/emergency/cap/v1.2/CAP-v1.2.html) format, which in turn contains an <area> element with either a polygon or circle definition.  I want to ultimately get this into a SQL Server geometry, but I think parsing it into WKT would facilitate that.  Are there any common algorithms already out there that deals with this CAP format geometries, or am I on my own for parsing it out?

redpajama_set_name: RedPajamaStackExchange


text:
Q: why doesn't getBoundingClientRect serialise with JSON.toStringify? Try this in dev tools console:
JSON.stringify(document.body.getBoundingClientRect())

the output is {}, instead of something sensible.
Any ideas?

A: JSON.stringify internally uses a method called toJSON.
You can specify it for your object or in your case, override it:
ClientRect.prototype.toJSON = function(){ return { top: this.top } }

JSON.stringify(document.body.getBoundingClientRect())

"{"top":-583}"


text:
Q: Reflexivity of the relation between strings over language $L$ defined by $xc \equiv L$ and $yc \equiv L $
Given any two strings, call them $x$ and $y$, over any language $L$ and given property such that  if $xc \equiv L$ and  $yc \equiv L $ (where $c$ is some string), then $x \equiv y$.

I would like to prove that $\equiv$ is reflexive. I tried $x \equiv x \rightarrow x-x \equiv0$ and $y(0) \rightarrow x(0)\equiv0$ Therefore, $\equiv$ is reflexive.
But somehow I don't feel this is right.  Can someone point out what I am doing wrong here?

A: The relation $\equiv_L$ is defined by: $x\equiv_L y$ iff $xz\in L\iff yz\in L$ for all strings $z$.
Clearly, $x\equiv_L x$ since $xz\in L\iff xz\in L$ for all strings $z$.


text:
Q: How to redirect WooCommerce shop URL? Is there any way to redirect WooCommerce default 'http://website.com/shop/' URL to 'http://website.com/shop/all/'?
After a long research found this :
How does Wordpress redirect to WooCommerce shop page? but not works as i expect
So you Have any idea?

A: You can use woocommerce_return_to_shop_redirect filter to overwrite the redirection url.
add_filter( 'woocommerce_return_to_shop_redirect', "custom_woocommerce_return_to_shop_redirect" ,20 );
function custom_woocommerce_return_to_shop_redirect(){
   return site_url()."shop/all/";
}

A: @Swarnendu Paul answer is great, I'd just replace site_url().'shop/all' with home_url('/shop/all') in case the home url and site url are not the same :)
so, it'd be:
add_filter( 'woocommerce_return_to_shop_redirect', "custom_woocommerce_return_to_shop_redirect" ,20 );
function custom_woocommerce_return_to_shop_redirect(){
    return home_url('shop/all/');
}

A: for 2017 try:
function custom_shop_page_redirect() {
    if( is_shop() ){
        wp_redirect( home_url( '/shop/all/' ) );
        exit();
    }
}
add_action( 'template_redirect', 'custom_shop_page_redirect' );


text:
Q: How to write this substitution in Vim? So I have a line of code containing the following:
eq(["JetFuelBird", "JetFuelBet", "JetFuelComputer", "JetFuelDog", "JetFuelElephant"])

I want to swap each phrase starting with JetFuel with the ending word so that I have something like eq["BirdJetFuel", "BetJetFuel"....etc.]
I tried something like:
:24s/.*(JetFuel)(\w)"/.*\1JetFuel/g

where 24 is the line number and got a pattern not found error......How do I write this?  This seems like it should be simple.

A: :24s/JetFuel\(\w\+\)/\1JetFuel/g

Vim normally uses old-style regular expressions, where many of the "special characters" aren't yet special, so when they became special they needed to be escaped. Nowadays we are used to regular expressions where all special characters are special by default, and we escape them when we want them not to be special. You can also use the "very magic" switch (\v), which makes the regular expressions a bit more modern:
:24s/\vJetFuel(\w+)/\1JetFuel/g


text:
Q: Google Maps API V3 infoWindow - All infoWindows displaying same content In my page, latitude, longitude and info window content are present in an array of objects named obj.
So if I need the latitude of property of the 1st object, I can call obj[0].latitude.
The infoWindow content for each object is stored in obj[i].text.
I'm using the below loop to loop through the lat & long values and display the markers and infoWindows.

  for (x=1; x<=obj.length; x++)
  {
      var latlng1 = new google.maps.LatLng(obj[x].latitude, obj[x].longitude);

  var marker2  = new google.maps.Marker({
    position : latlng1,
    map  : map,
    icon     : prevIcon
    });

  infowindow = new google.maps.InfoWindow();

  info = obj[x].text;

   google.maps.event.addListener(marker2, 'mouseover', function() {
       infowindow.setContent(info);
       infowindow.open(map, this);
      });

}

The above code works, but all the infoWindows are showing the content of the last obj[i].text.
How do I associate the infoWindow content of a particular infoWindow (obj[x].text) to that infoWindow instance only?
It would be better if someone can point out a solution without using jQuery or any other external libraries.
Thanks,

A: Should get you a long way.
function attachMarker( data ) {

    var latLng = new google.maps.LatLng( data.latitude, data.longitude );

    var marker = new google.maps.Marker({
        position : latLng,
        map      : map, // global variable?
        icon     : prevIcon // global variable?
    });

    google.maps.event.addListener(marker, 'mouseover', function() {
       infowindow.setContent( data.text );
       infowindow.open(map, this);
    });

    // add marker here.

}

// afaik, you only need 1 instance of InfoWindow if you only change content.
var infowindow = new google.maps.InfoWindow();

var i = obj.length;
while ( i-- ) {
    attachMarker( obj[ i ] );
}

A: BGerrissen's comment above helped a lot.
I managed to achieve function closure on the info variable.
The following Google Groups post explains how to.
https://groups.google.com/group/google-maps-api-for-flash/browse_thread/thread/befeb9bf2d1ebcc9
Thanks everyone :)


text:
Q: How do I find the column used in a HASH DISTRIBUTION within Azure Synapse? This query gives me everything i need except the column used in HASH distribution:
select * from sys.pdw_table_distribution_properties

Do I need a table to join to get it?

A: You have to specify the distribution as HASH in sys.pdw_table_distribution_properties and set the distribution_ordinal to > 0 (presumably paving the way for multi-column HASH tables).  Something like this should work:
SELECT
    OBJECT_SCHEMA_NAME(tdp.object_id) schemaName,
    OBJECT_NAME(tdp.object_id) tableName,
    c.name AS hashDistributionColumnName,
    cdp.distribution_ordinal
FROM sys.pdw_table_distribution_properties tdp
        INNER JOIN sys.pdw_column_distribution_properties cdp ON tdp.object_id = cdp.object_id
            INNER JOIN sys.columns c ON cdp.object_id = c.object_id
                AND cdp.column_id = c.column_id
WHERE tdp.distribution_policy_desc = 'HASH'
  AND cdp.distribution_ordinal > 0;

A: Use this to also see the other distribution types other than hash.
SELECT OBJECT_SCHEMA_NAME(PDW_TABLE_DISTRIBUTION_PROPERTIES.OBJECT_ID) AS [SCHEMA],
       OBJECT_NAME(PDW_TABLE_DISTRIBUTION_PROPERTIES.OBJECT_ID) AS [TABLE],
       DISTRIBUTION_COLUMN.DISTRIBUTION_ORDINAL AS [DISTRIBUTION_ORDINAL],
       PDW_TABLE_DISTRIBUTION_PROPERTIES.DISTRIBUTION_POLICY_DESC AS [DISTRIBUTION_POLICY],
       DISTRIBUTION_COLUMN.[COLUMN]
FROM SYS.PDW_TABLE_DISTRIBUTION_PROPERTIES
  LEFT OUTER JOIN (
            SELECT PDW_COLUMN_DISTRIBUTION_PROPERTIES.OBJECT_ID AS [OBJECT_ID],
                   PDW_COLUMN_DISTRIBUTION_PROPERTIES.DISTRIBUTION_ORDINAL AS [DISTRIBUTION_ORDINAL],
                   COLUMNS.NAME AS [COLUMN]
            FROM SYS.PDW_COLUMN_DISTRIBUTION_PROPERTIES
              INNER JOIN SYS.COLUMNS
                      ON COLUMNS.OBJECT_ID = PDW_COLUMN_DISTRIBUTION_PROPERTIES.OBJECT_ID
                     AND COLUMNS.COLUMN_ID = PDW_COLUMN_DISTRIBUTION_PROPERTIES.COLUMN_ID
            WHERE DISTRIBUTION_ORDINAL > 0 ) AS DISTRIBUTION_COLUMN
               ON DISTRIBUTION_COLUMN.OBJECT_ID = PDW_TABLE_DISTRIBUTION_PROPERTIES.OBJECT_ID
ORDER BY OBJECT_SCHEMA_NAME(PDW_TABLE_DISTRIBUTION_PROPERTIES.OBJECT_ID),
         OBJECT_NAME(PDW_TABLE_DISTRIBUTION_PROPERTIES.OBJECT_ID),
         DISTRIBUTION_COLUMN.DISTRIBUTION_ORDINAL


text:
Q: Limit of a particular sequence I came across a sequence and tried to find out to what it converges. I have a conjecture and a proof for it, but I am not sure whether it is correct. The sequence develops in the following matter:
\begin{align*}
x_1 &= \frac{1}{2} - s \\
x_2 &= \frac{1}{2} - s + \frac{1}{2}x_1^2 \\\vdots \\x_t &= \frac{1}{2} - s + \frac{1}{2}x_{t-1}^2
\end{align*}
where $s \in (0,\frac{1}{2})$.
So my conjecture is that this sequence converges to $1 - \sqrt{2s}$ whenever $t$ tends to infinity, numerically it seems to be right.
So far I have been thinking about the following approach: Suppose that the sequence converges to some $\bar{x}$, then the average of that sequence must also converge to $\bar{x}$. Therefore, it must hold that $\frac{1}{t} \sum\limits_{i=1}^{t}x_i$ tends to $\bar{x}$ whenever $t$ tends to infinity. Now, summing up the equations describing the sequence we have:
\begin{align*}
\sum\limits_{i=1}^{t} x_i = t\cdot(\frac{1}{2} - s) + \frac{1}{2}\sum\limits_{i=1}^{t-1} x_i^2
\end{align*}
Multiplying with $\frac{2}{t}$ and rearranging terms yields:
\begin{align*}
2s = 1 - \frac{2}{t}\sum\limits_{i=1}^{t}x_i + \frac{1}{t}\sum\limits_{i=1}^{t-1}x_i^2
\end{align*}
which we can rewrite to finally get:
\begin{align*}
2s = \frac{\sum\limits_{i=1}^{t} (1-x_i)^2}{t} - \frac{x^2_t}{t}
\end{align*}
From this point on, I am not sure what to do. Assuming that the sequence converges to some $\bar{x}$, I know that the last term on the RHS would tend to 0. If now the first term on the RHS would tend to $(1-\bar{x})^2$, then I would indeed find that $\bar{x} = 1 - \sqrt{2s}$. So my question is whether this proof is correct or whether I am missing something.
Thanks for your help!

A: Your answer seem to be correct but let me give you another approach to this problem, hopefully an easier way.
Note that your sequence is defined by the following recurrence relation:
$$x_1=\frac{1}{2}-s,\,\, x_{t+1}=\frac{1}{2}-s+\frac{1}{2}x^{2}_t=x_{1}+\frac{1}{2}x^{2}_t$$
Since $s\in(0,\frac{1}{2})$ the first term is positive. I'll drop some details but you can show using induction that the sequence is monotonically increasing and bounded by 1, so we know it converges, further more we know it converges to its supremum!
So let $L=\underset{t\to\infty}{\lim}x_t$, $x_{t+1}$ is a subsequence of $x_t$ so it converges to $L$ as well and we get the equation from the recurrence formula as t goes to infinity:
$$L=(\frac{1}{2}-s)+\frac{1}{2}L^2$$
Rearranging the equation and using the quadratic formula we get:
$$L=1\pm\sqrt{2s}$$
but since we know the sequence converges to its supremum and is bounded by $1$ we conclude: $L=1-\sqrt{2s}$

A: The proof seems fine. There are two things missing, but they are fixable.
First off, you already mentioned that you believe $\frac1t\sum_{i=1}^t(1-x_i)^2$ tends to $(1-\overline{x})^2$ if $x_i\to\overline{x}$. This is true in a more general sense. For any continuous $f:\mathbb{R}\to\mathbb{R}$ we have $\frac1t\sum_{i=1}^tf(x_i)\to f(\overline{x})$ if $x_i\to\overline{x}$. This is because $x_i\to\overline{x}$ implies $f(x_i)\to f(\overline{x})$.
Secondly, you start your proof by assuming the sequence converges, but this requires justification. This is not that difficult in this case. You can first show by induction that the sequence will always be in the interval $[0,1-\sqrt{2s}]$. You can then use that to also show that the sequence is increasing. Then because the sequence is increasing but bounded from above, it follows that it converges.
There is also an easier way to show what the limit is when you know that the limit exists. We have $$\overline{x}:=\lim_{i\to\infty}x_i=\lim_{i\to\infty}\frac12-s+\frac12x_{i-1}^2=\lim_{i\to\infty}\frac12-s+\frac12x_i^2=\frac12-s+\frac12\overline{x}^2.$$ Then using your favorite method to solve quadratics you can find $\overline{x}=1-\sqrt{2s}$.


text:
Q: "unary operator expected" in condition in Bash I have the following code:
#!/bin/bash
#even or odd

echo enter the no
read num
i=1
while [ $i -le $num ]
do
   if [ `expr $i % 2` -eq 0 ]
   then
    "$num is even"
  else
echo "$num is odd"
fi
i=`expr $i + 1`
done

When I run this, I get the following error:

[: ==: unary operator expected

How can I fix this?


text:
Q: How do I force Python to append to a csv file that someone currently has open? Is there a way to do this? Here is my current code.
try:
    if len(df) > 0:
        with open(r'\\path\to\dir\IDS_' + str(now)[:-2] + '.csv', 'a') as f:
            df.to_csv(f, sep=',', header=False, index=True, encoding='utf-8')
            f.close()
except Exception, e:
    print e

A: I found out that I can't edit a file that someone already has open. What I can do is handle the Exceptione by using cPickle to dump the new information into a pickle file and load it when it's time to put the file into the csv the next time around.
try:
    if len(df) > 0:
        with open(r'\\path\to\dir\IDS_' + str(now)[:-2] + '.csv', 'a') as f:
            df.to_csv(f, sep=',', header=False, index=True, encoding='utf-8')
            f.close()
except Exception, e:
   cPickle.dump(df, open(r'C:\missed rows.p','wb'))

missed_rows = cPickle.load(open(r'C:\missed rows.p','rb'))

if len(missed_rows) > 0:
    df = missed_rows.append(df, sort=True)
    missed_rows = pd.DataFrame()
    cPickle.dump(missed_rows, open(r'C:\missed rows.p','wb'))
    df = df.drop_duplicates()


text:
Q: How to map dynamic property to element bracket function in react? Im trying to map a state property as value to a generated form input with react, but have been unsuccessful so far. The example below shows what im trying to do, but the wrong way as group.value is imported as a string, and wont be compiled into the value of the state variable. Does anyone know how to accomplish this? I need both the final object and property to be dynamically called  (in this example frame and brand/year/model)
Map function:
return frameData.map((group) => {
            return (

                        <input
                            type="text"
                            className="form-control"
                            id={group.name}
                            name={group.name}
                            placeholder={group.placeHolder}
                            value={group.value}
                            onChange={(event) => this.updateValue(event)}
                        />

            );
        });

dataset
const frameData = [
    {
        name: "frame-brand",
        placeHolder: "Brand",
        value: "{this.state.newSubmission.frame.brand}",
    },
    {
        name: "frame-year",
        placeHolder: "Year",
        value: "{this.state.newSubmission.frame.year}",
    },
    {
        name: "frame-model",
        placeHolder: "Model",
        value: "{this.state.newSubmission.frame.model}",
    },
];

state
    this.state = {
        newSubmission:
          frame: {
            year: "",
            model: "",
            brand: "",
          }
    };

A: what you are trying to achieve is cool, but instead of passing the variable name i,e the entire state object, you can just pass the key and you can assign that to the <input /> component.
const frameData = [
    {
        name: "frame-brand",
        placeHolder: "Brand",
        value: "brand",
    },
    {
        name: "frame-year",
        placeHolder: "Year",
        value: "year",
    },
    {
        name: "frame-model",
        placeHolder: "Model",
        value: "model",
    },
];

and in the map function, you can use
return frameData.map((group) => {
        return (

                    <input
                        type="text"
                        className="form-control"
                        id={group.name}
                        name={group.name}
                        placeholder={group.placeHolder}
                        value={this.state.newSubmission.frame[group.value]}
                        onChange={(event) => this.updateValue(event)}
                    />

        );
    });


text:
Q: Update label properties of table view cell dependant upon data So I have a custom table view cell which I have designed in its own xib, containing a few labels and images.
I'm trying to update the background colour of one of these labels depending upon the text given to the label & give it rounded edges.
I'm trying this for the edges with the following code, however it does not work and i'm not sure where this code needs to be for it to update each cell as it scrolls.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CardCell";
    CardTableViewCell *cell = (CardTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        //cell = [[CardTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CardCell"];
        cell = [[[NSBundle mainBundle]loadNibNamed:@"CardCell" owner:self options:nil]objectAtIndex:0];

    }

    // Configure the cell...
    NSManagedObject *card = [self.cards objectAtIndex:indexPath.row];
    [cell.cardName setText:[card valueForKey:@"name"]];
    [cell.type setText:[card valueForKey:@"attribute"]];
    [cell.attack setText:[card valueForKey:@"attack"]];
    [cell.defense setText:[card valueForKey:@"defense"]];
    [cell.species setText:[card valueForKey:@"species"]];
    [cell.starLevel setText:[card valueForKey:@"stars"]];
    cell.type.layer.cornerRadius = cell.type.bounds.size.height / 8;

    UIImage *cardImage = [UIImage imageWithData:[card valueForKey:@"thumb"]];
    [cell.cardImage setImage:cardImage];

    return (UITableViewCell *)cell;
}

The text and card image display correctly.

A: The cell has no frame in cellForRowAtIndexPath, therefore the corner radius is not set.
In this case, you should set the corner radius in willDisplayCell.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (yourCellShouldHaveRoundedCorners) {
        cell.layer.cornerRadius = cell.bounds.size.height / 8;
    }
}

The background color of the label should work in cellForRowAtIndexPath.
Also, I see that you set a lot of properties on the cell in cellForRowAtIndexPath (i.e. type, attack, defense and so on). Since you already have a custom cell, it would be better to create an NSManagedObject property on the cell, and set all these properties on the setter of this object.
This way, you will only have to call cell.managedObject = card and the setter will furher set the other properties.
This approach is more model-oriented and it can save you some code duplication.

A: Try to use fixed number as cell.type.bounds.size.height won't render to a correct value in cellForRowAt
 cell.type.layer.cornerRadius = 10 ;

 cell.type.clipsToBounds = YES;

OR add this to cell class
 -(void)layoutSubviews
 {
     self.type.layer.cornerRadius = self.type.bounds.size.height / 8;
 }

Regarding color it will work perfectly in cellForRowAt like that
 if(yourLogic)
 {
    cell.type.backgroundColor = [UIColor redColor];

 }
 else
 {
    cell.type.backgroundColor = [UIColor greenColor];
 }


text:
Q: A little quirk on the good old "how many ways are there to place balls into boxes" Given $n$ (unlabeled) balls, and $m$ (labeled) containers of equal size, I want to calculate what is the most probable distribution of balls, from the point of view of have many containers will remain empty. Balls are assigned randomly , with equal probabilites for each container.
So, I believe the number of configurations in which $k$ containers out of the available $m$ contain at least one ball equals
$$ C(k) = { {n -1} \choose {k -1} }{ {m} \choose {k} } $$
where the first term gives the number of combinations to put $n$ balls in $k$ containers with each container containing at least one ball (Put $N$ identical balls into $m$ different buckets, each bucket has at least one ball, how many ways?), and the second reflects the freedom in choosing the $k$ containers to place balls in.
It is a matter now to maximise the function $C(k)$.
I checked that when Stirling's approximation applies, for large arguments of the factorial, the maximum tends to $n$, so filling all the boxes. In other words, with many particles, it is unlikely any box will remain empty.
But plotting $C(k)$ for smaller $n$ and $m$, one notices the maximum occurs for $k<m$, so some containers are indeed empty.
Now, the question.
I am interested in estimating when the transition occurs, i.e. for which values of $m, n$ the maximum of $C(k)$ occurs for $k < m$. I am stuck a bit as I cannot manipulate the binomial coefficients and the factorials for small values of their argument.
My attempt followed this route.  Let us assume that with given $n$ and $m$, one computes the most likely outcome is such that $k$ containers only are filled. But then, one could divide the containers in two sets, filled and empty by the process described above, each considered as a container in itself. One can view the process as a Bernoulli process, in which balls are assigned to a larger Container, union of  the selected $k$ "filled" containers) with probability proportional to $k$ (and this is a Bernoulli "success"), and the union of the $m-k$ empty containers, with probability proportional to $m-k$. The analogue of getting $k$ empty containers in the above described process is, for the Bernoulli process, to get all successes over the $n$ attempts.  For the event "all successes" to be the expected value, the following conditions has to hold
$$ n p \geq n -1/2 $$
where $p$, the chance of success on the single  draw, equals
$$ p = \frac {m-k}{m}$$
I end up then with the condition
$$ n (\frac {m-k}{m} ) \geq n -1/2 $$
At least, I believe this confirms that when $n \to \infty$, $k \to 0$.
Any hint on how to substantiate the condition found with a direct calculation on $C(k)$ would be greatly appreciated, thanks.

A: Using the Generalized Inclusion-Exclusion Principle
The sum of the probabilities of missing $j$ particular bins over all selections of $j$ particular bins is
$$
\overbrace{\ \ \ \binom{m}{j}\ \ \ }^{\substack{\text{the number of}\\\text{ways to choose}\\\text{$j$ particular bins}}}\overbrace{\left(\frac{m-j}m\right)^n}^{\substack{\text{the probability}\\\text{of missing $j$}\\\text{particular bins}}}\tag{1}
$$
Then, according to the Generalized Inclusion-Exclusion Principle, the probability of missing exactly $k$ bins is
$$
\begin{align}
\sum_{j=0}^m(-1)^{j-k}\binom{j}{k}\binom{m}{j}\left(\frac{m-j}m\right)^n
&=\binom{m}{k}\sum_{j=0}^m(-1)^{j-k}\binom{m-k}{m-j}\left(\frac{m-j}m\right)^n\tag{2}
\end{align}
$$
In the question, $k$ is the number of non-empty bins, so we need to substitute $k\mapsto m-k$. Since $j$ is a dummy variable, we can also substitute $j\mapsto m-j$. This gives the probability of getting exactly $k$ non-empty bins to be
$$\newcommand{\stirtwo}[2]{\left\{#1\atop#2\right\}}
\begin{align}
\binom{m}{k}\sum_{j=0}^m(-1)^{k-j}\binom{k}{j}\left(\frac{j}m\right)^n
&=\binom{m}{k}\stirtwo{n}{k}\frac{k!}{m^n}\\
&=\bbox[5px,border:2px solid #C0A000]{\stirtwo{n}{k}\frac{(m)_k}{m^n}}\tag{3}
\end{align}
$$
where $\stirtwo{n}{k}$ is a Stirling Number of the Second Kind and $(m)_k$ is a Pochhammer Symbol or Falling Factorial.
One of the "defining" relations of the Stirling Number of the Second Kind is that
$$
\sum_{k=0}^n\stirtwo{n}{k}(m)_k=m^n\tag{4}
$$
and $(4)$ guarantees that the sum of $(3)$ over all $k$ is $1$, which is comforting.
Formula $(3)$ matches user49640's formula, though I believe this approach is different.

Looking for the Maximum
Now we are looking for when $\stirtwo{n}{k}(m)_k$ is maximum for $k=m$. Since
$$
\frac{\stirtwo{n}{k}(m)_{k}}{\stirtwo{n}{k-1}(m)_{k-1}}=\frac{\stirtwo{n}{k}}{\stirtwo{n}{k-1}}(m-k+1)\tag{5}
$$
we are looking for $n$ and $m$ so that
$$
\stirtwo{n}{m}\ge\stirtwo{n}{m-1}\tag{6}
$$
According to this Wikipedia article section, the maximum $m$ satisfying $(6)$ is asymptotically
$$
m\sim\frac{n}{\log(n)}\tag{7}
$$
If some $m$ satisfies $(6)$, any smaller $m$ will.

A: This isn't a complete answer to the OP's question, but it corrects the expression given for the required probability.
Let $P(n,m,k)$ be the probability that after $n$ balls are randomly assigned to $m$ containers, exactly $k$ of them have at least one ball in them.
Using the inclusion-exclusion formula, we find
$$P(n,m,m) = 1 - m(1-1/m)^n + \binom{m}{2}(1-2/m)^n - \dots = \sum_{i=0}^{m-1} (-1)^i \binom{m}{i}(1 - i/m)^n.$$
Now, summing over all possible $k$-element subsets of the $m$ containers, we have
$$P(n,m,k) = \binom{m}{k}(k/m)^nP(n,k,k) = \binom{m}{k} \sum_{i=0}^{k-1} (-1)^i \binom{k}{i}\left(\frac{k-i}{m}\right)^n =  \frac{m!}{m^n(m-k)!}S(n,k),$$
where $S(n,k)$ denotes a Stirling number of the second kind.

A: Suppose we have fixed value of $m$, the number of bins, and we want to find the value $n$ which maximizes the chance of exactly $k$ nonempty bins, either for a single value of $k=K$ or for all $k\le K$.  We can create a Markov process with $K+1$ states that computes these values.
Note that the labelling of the bins does not enter the computation.  If $k$ out of $m$ bins are nonempty, then drawing a ball will result either in a new bin getting a ball with probability $(m-k)/m$ or preserving the same set of bins that have at least one ball with probability $k/m$.
Assume $1 \lt K \lt m$.  Once more than $K$ bins have a ball, this will always remain true.  So we group together all states with more than $K$ nonempty bins as a single "absorbing" state.
The state after drawing one ball is deterministic: one bin is nonempty and the rest of the $m-1$ bins are empty.  So we have a state vector of length $K+1$ at step $1$:
$$ s_1 = (1,0,0,\ldots,0) $$
and the probability transition matrix looks like:
$$ M = \begin{bmatrix} 1/m & 1 - 1/m & 0 & 0 & \dots & 0 \\
0 & 2/m & 1-2/m & 0 & \dots & 0 \\
0 & 0 & 3/m & 1-3/m & \dots & 0 \\
\vdots & \vdots & \ddots & \ddots & \ddots & \vdots \\
0 & 0 & \dots & (K-1)/m & 1-(K-1)/m & 0 \\
0 & 0 & \dots & 0 & K/m & 1-K/m \\
0 & 0 & \dots & 0 & 0 & 1 \end{bmatrix} $$
Thus the probability distribution of states at step $n$ is simply $s_1 M^{n-1}$.  The next two steps give these results:
$$ s_2 = (m^{-1},1-m^{-1},0,\ldots,0) $$
$$ s_3 = (m^{-2},3m^{-1}-3m^{-2}, 1-3m^{-1}+2m^{-2},0, \ldots,0) $$
Numerical computation to find the step $n$ that maximizes a particular entry (the $k$th entry of $s_n$ is the probability that $k$ bins are nonempty) can be scaled to integer arithmetic by extracting a factor $1/m$ from matrix $M$.  If the column vectors $e_j$, $j=1,..,K+1$ are the "standard basis vectors", then since $s_1 = e_1^T$:
$$ \Pr(k \text{ bins exactly are nonempty after } n \text{ balls}) = m^{1-n} e_1^T A^{n-1} e_k $$
where $A = mM$ is an upper triangular matrix with nonnegative integer entries.
Furthermore $A = P^{-1}D P$ is similar to its matrix $D$ of diagonal entries, so once $u^T = e_1^T P^{-1}$ and $v_k = P e_k$ are computed, the above probability is easy to find:
$$ \Pr(k \text{ bins exactly are nonempty after } n \text{ balls}) = \frac{u^T D^{n-1} v_k}{m^{n-1}} $$


text:
Q: Convergence of $u_{n+1}= 2\left| u_n \right| -1$
Find all $u_0$ such that the recursive sequence defined by $u_{n+1}= 2\left| u_n \right| -1$ converges.

Let $f(x) = 2\left|x\right|-1$. If $(u_n)$ converges, it converges to a fixed point of $f$, that is to say $-\frac 13$ or $1$.
Furthermore, if $(u_n)$ converges to $l\in\{-\frac 13, 1\}$ , the mean value theorem yields, for some large enough $n_0$,  $$\forall n\geq n_0, \displaystyle \left|\frac{u_{n+1}-l}{u_{n}-l} \right|=2$$
Since $\lim_{n\to \infty}(u_{n}-l)= 0$ it must be that $u_{n_1}=l\;\;$ for some $n_1\geq n_0$ which implies $u_n=l$ for all $n\geq n_1$.
Note that $u_0<-1$ or $u_0>1$ both lead to divergence of $(u_n)$
Therefore, finding the $u_0$ for which the sequence converges amounts to studying the following set $$X:= \{x\in[-1,1], \exists p\in \mathbb N, f^{(p)}(x)\in\{-\frac 13, 1\}\}$$

Is it possible to determine what this set contains exactly ? Certainly $X\cap (\mathbb R \setminus \mathbb Q)=\emptyset$.

A: Note that if $x\in I=[-1,1]$, then $f(x)\in I$, and as you have remarked, for $x$ to be in $X$, we need that $x\in I\cap \mathbb{Q}$.
Let $u_0=p/q$ in $X$, with $p$ prime to $q\geq 1$. Suppose that there exists a prime $l$, $l\not = 2,3$, such that $l$ divide $q$. Then if we set $u_1=\frac{p_1}{q_1}=\frac{2|p|-q}{q}$ ($p_1$ prime to $q_1$), we see that we have also that $l$ divide $q_1$. Hence as we want by a finite number of iteration to arrive at $1$ or $-1/3$,  the only prime divisors of $q$ are possibly $2$ and $3$. The same argument works if $9$ divide $q$: we see that $9$ divide $q_1$. It remain to show that if $q=2^l$ or $q=3 2^l$, then $p/q$ is in $X$, If I am not wrong, it is easy.


text:
Q: change time format in SQL select query metabase in .cvs export show time in this format:
2017-08-30T02:15:30.000+04:30
but when I export data directly with mysql returns:
2017-08-30 02:15:30
how can change this format in SELECT?

A: I find it. https://www.w3schools.com/sql/func_sqlserver_convert.asp
thanks.
127 yyyy-mm-ddThh:mi:ss.mmmZ    ISO8601 (with time zone Z)


text:
Q: Qt connecting to slotted secondary interface My question is essentially the inverse of this Declare abstract signal in interface class.  In that problem, you hold a pointer to a slotted QObject and are trying to test another object for an interface containing the signal you want to wire into your slot object.
Suppose the problem is inverted:  you hold a pointer to a QObject that emits a signal and you wish to test a series of other QObjects to see if they implement a receiving slot.  If so, you would like to connect them all to your signaler.
The design I would like to use would be that the receivers each have a primary (QObject-derived) interface and a secondary slot interface that I might test for, i.e. with Q_DECLARE_INTERACE, qobject_cast, etc.
It seems as though that secondary interface must also be QObject-derived else you cannot connect to it, but that opens up the multiple inheritance problem with QObject.
Is there a way around this other than using a single inheritance chain?
// receiver's primary interface
class IPrimary : public QObject
{
    Q_OBJECT
public:
    // etc.
};

// receiver's secondary interface with slot
class ISecondary : public QObject // QObject won't fly
{
    Q_OBJECT  // nope
public slots:
    void OnReceiptOfSomething(...);

public:
    // etc.

};

// signaler
class Signaler : public QObject
{
   Q_OBJECT

signals:
    void SignalOfSomething(...);

public:
   // etc.
};

A: I'm not entirely sure I understand what you're after but it appears that given a QObject *emitter and a signal name signal_one you want to find all slots in a second QObject *receiver that are compatible with signal_one and automatically create the required connections.  If so then I think that's possible using just the Qt metadata infrastructure -- QMetaObject, QMetaMethod etc.
Firstly defined a function are_compatible which compares two QMetaMethod instances for calling compatibility.
bool are_compatible (const QMetaMethod &signal_meta,
                     const QMetaMethod &slot_meta)
{

  /*
   * Work on the assumption that the arity of the signal must be at least that
   * of the slot.
   */
  if (signal_meta.parameterCount() < slot_meta.parameterCount())
    return false;

  /*
   * Now check that all required parameters have the same type.
   */
  for (int i = 0; i < slot_meta.parameterCount(); ++i) {
    if (signal_meta.parameterType(i) != slot_meta.parameterType(i))
      return false;
  }
  return true;
}

Now define the main function we need that should automatically connect a named signal in the specified emitter to all compatible slots in a specified receiver.
void connect_where_possible (const char *signal_name,
                             QObject *emitter,
                             QObject *receiver)
{
  const auto *emitter_meta_object = emitter->metaObject();

  /*
   * Look for signal_name in the emitter's metadata.
   */
  auto index_of_signal = emitter_meta_object->indexOfSignal(signal_name);
  if (index_of_signal == -1)
    return;

  /*
   * Get the signal's associated QMetaMethod.
   */
  const auto signal_meta_method = emitter_meta_object->method(index_of_signal);

  /*
   * Now go through the receiver's methods.  We could naively attempt to
   * connect to each and every slot knowing that the Qt runtime will only
   * succeed when the signal and slot are compatible.  A nicer/cleaner
   * implementation is to use the metadata available to check for
   * compatibility _before_ attempting to connect -- if only to avoid unwanted
   * warning messages on the console.
   */
  const auto *receiver_meta_object = receiver->metaObject();
  for (int method_index = 0; method_index < receiver_meta_object->methodCount(); ++method_index) {
    const auto receiver_slot_method = receiver_meta_object->method(method_index);
    if (receiver_slot_method.methodType() == QMetaMethod::Slot) {

      /*
       * Found a slot so check it's compatibility and, if ok, try to connect.
       */
      if (are_compatible(signal_meta_method, receiver_slot_method)) {
        QObject::connect(emitter, signal_meta_method, receiver, receiver_slot_method);
      }
    }
  }
}

By way of an example try the following code...
class signaler: public QObject {
  Q_OBJECT;
signals:
  void sig1(int i, float f);
};

class receiver: public QObject {
  Q_OBJECT;
public slots:
  void slot1 (int i, float f) const
    {
      std::cerr << "\nreceiver::slot1(i = " << i << ", f = " << f << ")";
    }
  void slot2 (int i) const
    {
      std::cerr << "\nreceiver::slot2(i = " << i << ")";
    }
  void slot3 (float f) const
    {
      std::cerr << "\nreceiver::slot3(f = " << f << ")";
    }
};

...

signaler signaler;
receiver receiver;
connect_where_possible(QMetaObject::normalizedSignature("sig1(int, float)"), &signaler, &receiver);
signaler.sig1(10, 20.0f);

I see the output...
receiver::slot1(i = 10, f = 20)
receiver::slot2(i = 10)

So, as expected, receiver::slot1 and receiver::slot2 are connected but receiver::slot3 isn't as it's deemed incompatible.


text:
Q: Select with Case - amalgamating results into single record I have a query as follows
SELECT
FGB.TEMPLATE_DETAILS_REF, FGB.TEMPLATE_STRUCTURE_REF, FGB.DFEE_ELEMENT,
    CASE
    WHEN Condition = 'A' THEN SUM(FGS.Weighted) END AS CondA,
    CASE
    WHEN Condition = 'B' THEN SUM(FGS.Weighted) END AS CondB,
    CASE
    WHEN Condition = 'C' THEN SUM(FGS.Weighted) END AS CondC,
    CASE
    WHEN Condition = 'D' THEN SUM(FGS.Weighted) END AS CondD
    FROM            FGBlockSummary AS FGB INNER JOIN
                             FGSurveyItem AS FGS ON FGB.TEMPLATE_DETAILS_REF = FGS.TEMPLATE_DETAILS_REF AND FGB.TEMPLATE_STRUCTURE_REF = FGS.TEMPLATE_STRUCTURE_REF AND
                             FGB.DFEE_ELEMENT = FGS.DFEE_ELEMENT
    GROUP BY FGB.TEMPLATE_DETAILS_REF, FGB.TEMPLATE_STRUCTURE_REF, FGB.DFEE_ELEMENT, FGS.Condition

which produces results as follows:

*

*16  109 Ceilings    NULL    14101.47    NULL    NULL

*16  109 Ceilings    NULL    NULL        227.68  NULL

How can I amalgamate the results into a single row eg

*

*16   109 Ceilings    NULL    14101.47    227.68  NULL

Thanks

A: Is this what you're looking for?
I moved the SUM outside of the CASEs and eliminated FGS.Condition from the GROUP BY. It'll have the side-effect of changing your NULL values to '0', but that might be tolerable?
SELECT
  FGB.TEMPLATE_DETAILS_REF
 ,FGB.TEMPLATE_STRUCTURE_REF
 ,FGB.DFEE_ELEMENT
 ,CondA = SUM(
          CASE
            WHEN FGS.Condition = 'A' THEN FGS.Weighted
            ELSE 0
          END)
 ,CondB = SUM(
          CASE
            WHEN FGS.Condition = 'B' THEN FGS.Weighted
            ELSE 0
          END)
 ,CondC = SUM(
          CASE
            WHEN FGS.Condition = 'C' THEN FGS.Weighted
            ELSE 0
          END)
 ,CondD = SUM(
          CASE
            WHEN FGS.Condition = 'D' THEN FGS.Weighted
            ELSE 0
          END)
FROM
  FGBlockSummary AS FGB
INNER JOIN
  FGSurveyItem   AS FGS
    ON
    FGB.TEMPLATE_DETAILS_REF = FGS.TEMPLATE_DETAILS_REF
      AND FGB.TEMPLATE_STRUCTURE_REF = FGS.TEMPLATE_STRUCTURE_REF
      AND FGB.DFEE_ELEMENT = FGS.DFEE_ELEMENT
GROUP BY
  FGB.TEMPLATE_DETAILS_REF
 ,FGB.TEMPLATE_STRUCTURE_REF
 ,FGB.DFEE_ELEMENT;


text:
Q: Creating tables with the SQLite-net library I'm researching SQLite - .net (https://github.com/praeclarum/sqlite-net) in order to add a local storage to my project.
I've come up with a few questions:

*

*The tables are created per model, and then in order to create the tables this code should be used:
var db = new SQLiteConnection("foofoo");
db.CreateTable<Stock>();
db.CreateTable<Valuation>();

The problem is, in a MVVM approach, where would this be written?
I thought about the bootstrapper.cs but I'm not quite sure how effective it is.

*In one of the examples, this is the example code of a certain model:
public class Valuation
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [Indexed]
    public int StockId { get; set; }
    public DateTime Time { get; set; }
    public decimal Price { get; set; }
}

Does the [Indexed] statement apply ONLY to StockId, or to all three StockId, Time and Price?

A: Data Service! Just create a DataService class. Pass it the path to the database or look it up config. Have the constructor create the SQLiteConnection, create tables, add any default data.
If you are using an IOC container you can register DataService for use in your ViewModels. Consider registering with the create immediate flag set to True so the database gets initialized right away.
Sorry I don't have a working example at the moment.


text:
Q: GSON how do I test for an key/value pair without throwing a null pointer exception I have a JsonArray of elements and I want to check each object in the array for a field "video" some items in the array will not have the key, some will have the key and it will be null, I want to only find the elements that have the key and it is not null
public void addItems(ArrayList<JsonObject> j) {

    if (j.size() > 0) {

        ArrayList<String> videos = new ArrayList<String>();

        for (int i = 0; i < j.size(); i++) {

            try {
                JsonElement test = j.get(i).getAsJsonObject().get("video");

                if(!test.isJsonNull()){
                    videos.add(test.getAsString());
                }
            }
            catch (JsonParseException e) {
                e.printStackTrace();
            }

        }

        if (videos.size() > 0) {
            cloudCache.downloadVideos(videos);
        }
    }
}

I keep getting null pointer exception on the line
 if(!test.isJsonNull()){
    videos.add(test.getAsString());
 }

A: Your JsonElement "test" is null for the object you are tring to find.
As you stated some objects have the video and others don't have.
Just change your code to:
if(test!=null && !test.isJsonNull()){
    videos.add(test.getAsString());
}


text:
Q: Closing JDBC connection when calling a database multiple times inside the same function I am trying to execute multiple queries in a single function using single connection object. I would like to know what is the best practice to close the database connection in a scenario like this. Currently , I close the connection once all the db calls are completed. I am wondering whether I need to close the connection and open a new connection for every db call. Which is better?

A: You should keep the Connection open as long as possible. Creating a database connection is a (relatively) expensive operation, so you don't want to do it more often that you need to.
To manage the lifetime, you should use the try-with-resources statement assuming you are on at least Java 7:
try (Connection connection = myDataSource.getConnection()) {
    // Do your queries here
}


text:
Q: Determine Primary Keys of an Entity using the Context in Entity Framework 4.0 I have several entities generated from my Entity Framework data model. In the .edmx file I can see the properties that are flagged as primary keys. My POCO's/custom context are generated from this and the T4 templates.
I am looking for a way to find out the primary keys of my entities using reflection with Entity Framework 4.0. Is there an attribute I need to setup to get set on my POCO's when they are generated? Is there a property in my context I can use to drill down and find this information?

A: Updated my T4 template to add the following:
<#  if(ef.IsKey(edmProperty))
{
#>
[EdmScalarPropertyAttribute(EntityKeyProperty=<#=code.CreateLiteral(true)#>)]
<#
}
#>

Then used reflection to find the EntityKeys.


text:
Q: Issue trying to query for all "names" on MongoDB? I'm trying to find all "names" in my collection, and I can't figure out how.
I've tried a bunch of different queries, for example -

db.collectionname.find( { "customers" : {   "id" : 1, "name" : 1 } }

nothing really seems to work.
Here is a relevant part of the collection:
{
    "id" : 1,
    "customers" : {
            "id" : 1,
            "name" : "ronald"
    }
}

The rest of my collection is essentially identical. I just need to get a list for all the names, for example, ronald in this case. I have no idea how, would appreciate some help! Thanks in advance.

A: You will need to use aggregations in this case.
What you need is to group customers.name and push each name into an array.
Please refer here: https://docs.mongodb.com/manual/reference/operator/aggregation/push/
or if you want unique names only, use addToSet instead of push.
Try this:

db.collectionname.aggregate([{
  $group: {
        _id: null,
        names: {
          $push: "$customers.name"
        }
      }
     }
    ]).pretty()

This will give you an array "names" with all the names stacked together.


text:
Q: Finding the sum of this Gamma series I am trying to compute the sum of the following series
$$\sum _{k=0}^{\infty }\frac{\left(2it (1-H)^{2 (1-H)} \left(\frac{H}{\mu}\right)^{2 H}  \right)^k \Gamma \left(\frac{k}{2 (1-H)}+\frac{1}{2 H}\right)}{k!}$$
where $0 < H < 1$, $\mu > 0$ and $t \in \mathbb{C}$, but I am unsure how to proceed  forward.
Any suggestions/help would be much appreciated.
Edit
I am trying to evaluate a characteristic function for a probability density. Below is the derivation I have so far
The Characteristic function is given by
\begin{eqnarray}\nonumber
\phi_Q\left(t\right) &=& \mathrm {E}\left[\exp \left(itQ\right)\right]\\\nonumber
&=& \int_{-\infty}^{\infty} \exp \left(itx\right)f_Q\left(x\right) \mathrm{dx}\\\nonumber
&=& c \int_{0}^{\infty} \exp \left(itx\right)x^{\frac{1}{H}-2} \exp \left(-\frac{1}{2} (1-H)^{2 (H-1)} H^{-2 H} \mu ^{2 H} x^{2-2 H}\right) \mathrm{dx}\\\nonumber
\end{eqnarray}
where $c = \frac{\mu \left(1-H\right)^{\left(2 - \frac{1}{H}\right)}{2^{\left(1 - \frac{1}{2H}\right)}}}{H\Gamma\left(\frac{1}{2H}\right)}$
Upon substituting $y = x^{2-2 H}$, $\mathrm{dx}=\frac{y^{\frac{2H - 1}{2\left(1-H\right)}}}{2\left(1-H\right)}\mathrm{dy}$, $\zeta = \frac{1}{H}$ and $\eta = \frac{H^{\left(2H-1\right)}}{\mu^{2H}\left(1-H\right)^{2\left(H-1\right)}}$ we get
\begin{eqnarray}\nonumber
\phi_Q\left(t\right) &=& \frac{c}{2\left(1-H\right)}\int_{0}^{\infty}\exp \left(ity^{\frac{1}{2\left(1-H\right)}}\right)y^{\frac{\zeta}{2} - 1}\exp \left(-\frac{\zeta y}{2\eta} \right) \mathrm{dy}\\\nonumber
\end{eqnarray}
Upon substituting Taylor's series expansion of $\exp \left(ity^{\frac{1}{2\left(1-H\right)}}\right)$ we get
\begin{eqnarray}\nonumber
\phi_Q\left(t\right) &=& \frac{c}{2\left(1-H\right)}\int_{0}^{\infty}\sum\limits_{k=0}^{\infty}\frac{\left(ity^{\frac{1}{2\left(1-H\right)}}\right)^k}{k!}  y^{\frac{\zeta}{2} - 1}\exp \left(-\frac{\zeta y}{2\eta} \right) \mathrm{dy}\\\nonumber
&=& \frac{c}{2\left(1-H\right)}\sum\limits_{k=0}^{\infty}\frac{\left(it\right)^k}{k!}\int_{0}^{\infty}  y^{{\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2} - 1}\exp \left(-\frac{\left(\frac{k}{1-H} + \zeta\right) y}{2\eta \left(\frac{\frac{k}{1-H} + \zeta}{\zeta}\right)} \right) \mathrm{dy}\\\nonumber
&=&\frac{c}{2\left(1-H\right)}\sum\limits_{k=0}^{\infty}\frac{\left(it\right)^k}{k!}2^{\left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) }\Gamma \left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) \left(\frac{\zeta}{\eta}\right)^{-\left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right)}\\\nonumber
& &\int_{0}^{\infty} \frac{\left(\frac{\zeta}{\eta}\right)^{\left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right)}}{2^{\left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) }\Gamma \left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right)}  y^{{\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2} - 1}\exp \left(-\frac{\left(\frac{k}{1-H} + \zeta\right) y}{2\eta \left(\frac{\frac{k}{1-H} + \zeta}{\zeta}\right)} \right) \mathrm{dy}\\\nonumber
\end{eqnarray}
As the integrand is the pdf of a Gamma Random variable, the integral resolves to 1 and upon using the definition of $c$ we get
\begin{eqnarray}\nonumber
\phi_Q\left(t\right) &=& \frac{\left(\frac{\zeta}{\eta}\right)^{\frac{\zeta}{2}}}{2^{\frac{\zeta}{2}}\Gamma \left(\frac{\zeta}{2}\right)}\sum\limits_{k=0}^{\infty}\frac{\left(it\right)^k}{k!}2^{\left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) }\Gamma \left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) \left(\frac{\zeta}{\eta}\right)^{-\left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right)}\\\nonumber
&=& \frac{1}{\Gamma \left(\frac{\zeta}{2}\right)}\sum\limits_{k=0}^{\infty}\frac{\left(it\right)^k}{k!}2^{{\frac{k}{2\left(1-H\right)}} }\Gamma \left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) \left(\frac{\zeta}{\eta}\right)^{\frac{-k}{2\left(1-H\right)}}\\\nonumber
&=& \frac{1}{\Gamma \left(\frac{\zeta}{2}\right)}\sum\limits_{k=0}^{\infty}\frac{\left(it\right)^k}{k!}\left(\frac{2\eta}{\zeta}\right)^{{\frac{k}{2\left(1-H\right)}} }\Gamma \left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) \\\nonumber
&=& \frac{1}{\Gamma \left(\frac{\zeta}{2}\right)}\left(\frac{2\eta}{\zeta}\right)^{{\frac{1}{2\left(1-H\right)}}}\sum\limits_{k=0}^{\infty}\frac{1}{k!}\left(\frac{2\eta it}{\zeta}\right)^k\Gamma \left({\frac{k}{2\left(1-H\right)}} + \frac{\zeta}{2}\right) \\\nonumber
\end{eqnarray}
Upon substituting back the values for $\zeta$ and $\eta$ I got the series in my original question. Suggestions to side step this series evaluation are also welcome.

A: In fact, if you know how to express the following series
$$
\sum_{k=0}^{\infty}\frac{\Gamma(ak+b)}{k!}x^k \tag1
$$
in terms of a known special function, then it is OK.
Using Mathematica, we obtain that
$$
\sum_{k=0}^{\infty}\frac{\Gamma(ak+b)}{k!}x^k = 2^{1-b} e^{x^2/8} \Gamma(2b) D_{-2b}(-2 b,-x/\sqrt{2}) \tag2
$$ where $x \mapsto D_\nu(x)$ is the parabolic function which satisfies the differential equation
$$
y''+(\nu+\frac12-\frac{x^2}{4})\:y=0, \quad y(0)=y'(0)=\Gamma(b). \tag3
$$
Finally, using your computation, you may rewrite the charateristic function for your probability density as
$$
 \phi_Q\left(t\right)=\frac{\Gamma(\zeta) }{\Gamma \left(\frac{\zeta}{2}\right)}\left(\frac{2\eta}{\zeta}\right)^{{\frac{1}{2\left(1-H\right)}}}2^{1-\frac{\zeta}{2}} e^{-\left(\eta t\right)^2/(2\zeta)} D_{-\zeta}\left(-\zeta,-\frac{\sqrt{2}\eta it}{\zeta}\right).
$$
Hoping it helps.


text:
Q: Using multipolygon shape layers in profile tool I am working with QGIS for some time. The profile tool is indeed very useful to visualize the 3D problems. My problem now is associated with this tool.
I have a multi polygon shape layer which I assigned z levels by set z option in processing tool hence I believe z levels are assigned to the vertices of the multi polygons I have. I wanted to use this shape layer to plot a cross-section by using the profile tool however got an error as "unprofilable layer" or such. It is understandable since this layer is not a surface or a point data neither a raster. I cannot export this layer as DXF and turn it into a surface since I need the attributes assigned to these multipolygons for my project.
Is there any method so that I can transform this multipolygon shape layer into a kind of surface and/or raster or something else which I can both use it in the profile tool and also keep the attributes assigned?

A: You can create an interpolation with the multipolygon layer to generate a raster. Just need to set to interpolate Z coordinates.
For instance, with TIN interpolation tool:

Also you can clip the raster with the multipolygon features, this is a test result with one feature which have two parts. The vertices were extracted to label their Z coordinate:


text:
Q: How to perform search with angularJS inside column nested ng-repeat in order to fill all rows first I have this table of rows and columns, but I would like to know how to search the data with angularjs, so it moves into rows, instead of staying in same columns. For example if you search for number 3 it shapes into letter L. I want it to put the data in one row and if that row is 100% filled then move to another column and fill that row and so on... Example on fiddle - http://jsfiddle.net/6aqtj/67/
HTML:

   <colgroup span="7"></colgroup>
   <input type="search" ng-model="search" placeholder="search">

             {{ day }}

AngularJS:
window.myApp = this.angular.module('myApp', []);

var monthDays = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];

myApp.controller('MyCtrl', function($scope) {
    var dates = [];
    for (var i = 0; i < monthDays.length; i++ ) {
        if (i % 7 == 0) dates.push([]);
        dates[dates.length-1].push(monthDays[i]);
    }
  return $scope.dates = dates;
});

A: Instead of using tables, just use  and let them wrap to the next line.
View

<input type="search" ng-model="search" placeholder="search" />

    {{ day }}

CSS
.calendar {
    font-size: 12px;
    margin: 10px 0;
    width: 154px;
    border: solid 1px #ccc;
    border-width: 1px 0 0 1px;
}

.day {
    border: solid 1px #ccc;
    border-width: 0 1px 1px 0;
    display: inline-block;
    padding: 3px 0;
    width: 22px;
    text-align:center;
    box-sizing: border-box;
}

Controller
window.myApp = this.angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  return $scope.dates = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
});

http://jsfiddle.net/6aqtj/69/


text:
Q: NestJS + CASL + Mongoose: CASL cannot infer subject type from Mongoose Schema Context
I have defined a Cat schema using Mongoose and NestJS:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type CatDocument = Cat & Document;

@Schema()
export class Cat {
  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  breed: string;

  @Prop({ required: true })
  createdBy: string;

  // Other fields...
}

export const CatSchema = SchemaFactory.createForClass(Cat);

I have also defined an ability factory using CASL to handle authorization for my API:
import {
  Ability,
  AbilityBuilder,
  AbilityClass,
  ExtractSubjectType,
  InferSubjects,
} from '@casl/ability';
import { Injectable } from '@nestjs/common';
import { Cat } from '../cats/schemas/cat.schema';
import { User } from '../users/models/user.model';

type Subjects = InferSubjects<typeof Cat | typeof User> | 'all';

export enum Action {
  Manage = 'manage',
  Create = 'create',
  Read = 'read',
  Update = 'update',
  Delete = 'delete',
}

export type AppAbility = Ability<[Action, Subjects]>;

@Injectable()
export class CaslAbilityFactory {
  createForUser(user: User) {
    const { can, build } = new AbilityBuilder<
      Ability<[Action, Subjects]>
    >(Ability as AbilityClass<AppAbility>);

    can(Action.Read, Cat);
    can(Action.Create, Cat);
    can(Action.Update, Cat, {
      createdBy: user.id,
    });

    if (user.isAdmin()) {
      can(Action.Manage, 'all');
    }

    return build({
      detectSubjectType: (item) =>
        item.constructor as ExtractSubjectType<Subjects>,
    });
  }
}

Problem
When I try to check permissions in my service (note: the user is not an administrator):
import {
  ForbiddenException,
  Injectable,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { EditCatInput } from './dto/edit-cat.input';
import { Cat, CatDocument } from './schemas/cat.schema';
import { Action, CaslAbilityFactory } from '../casl/casl-ability.factory';
import { User } from '../users/models/user.model';

@Injectable()
export class CatsService {
  constructor(
    private readonly configService: ConfigService,
    private readonly caslAbilityFactory: CaslAbilityFactory,
    @InjectModel(Cat.name) private catModel: Model<CatDocument>,
  ) {}

  // Other methods...

  async update(id: string, input: EditCatInput, user: User): Promise<Cat> {
    const updatedCat = await this.catModel
      .findOne({
        _id: { $eq: id },
        deleted: { $eq: false },
      })
      .exec();
    const ability = this.caslAbilityFactory.createForUser(user);
    if (!ability.can(Action.Update, updatedCat)) {
      throw new ForbiddenException(
        'You cannot edit this cat.',
      );
    }
    Object.assign(updatedCat, input);
    await updatedCat.save();

    return updatedCat;
  }
}

ability.can(Action.Update, cat) always return false, while it should be true.
Additional information
ability.can returns false for any action when the user is not administrator.
My guess is that CASL cannot infer the subject type of my Mongoose model using the Cat class in InferSubject interface of the ability builder. But I don't know which class to use to infer subject type correctly.
What did I miss?

A: So the key is to inject the cat model over nest js injection in the casl ability factory.
So a factory like this should work:
import {
    Ability,
    AbilityBuilder,
    AbilityClass,
    ExtractSubjectType,
    InferSubjects,
  } from '@casl/ability';
  import { Injectable } from '@nestjs/common';
  import { InjectModel } from '@nestjs/mongoose';
  import { Model } from 'mongoose';
  import { Cat, CatDocument } from '../cats/schemas/cat.schema';
  import { User } from '../users/models/user.model';

  export enum Action {
    Manage = 'manage',
    Create = 'create',
    Read = 'read',
    Update = 'update',
    Delete = 'delete',
  }

  @Injectable()
  export class CaslAbilityFactory {
    constructor(
        @InjectModel(Cat.name)
        private catModel: Model<CatDocument>,
    ) {}
    createForUser(user: User) {
      const { can, build } = new AbilityBuilder(
        Ability as AbilityClass<
          Ability<[Action, InferSubjects<typeof this.catModel> | 'all']>
        >,
      );

      can(Action.Read, this.catModel);
      can(Action.Create, this.catModel);
      can(Action.Update, this.catModel, {
        createdBy: user.id,
      });

      if (user.isAdmin()) {
        can(Action.Manage, 'all');
      }

      return build({
        detectSubjectType: (item) =>
          item.constructor as ExtractSubjectType<InferSubjects<typeof this.catModel> | 'all'>,
      });
    }
  }

full example project:
https://github.com/Wenish/nestjs-mongoose-casl


text:
Q: How to open image in new tab in Edge In Google Chrome / Mozilla Firefox I can open an image under the mouse pointer in new tab using context menu. The menu contains "Open image in new tab" or "View Image" command for this.
How can I open an image in new tab in Edge browser?

A: When you right-click an image on a website while using Edge, a window appears, giving you a few different options: Ask Cortana, Save Picture As, Share Picture, Select All, and Copy.

Click Copy and open a new tab, then right-click in the address bar and choose Paste and Go in the window that appears.

This will paste the image URL into the address bar or the new tab and open the image directly.  Otherwise, you can choose Paste and then press enter - the result is the same.


text:
Q: Firebase Android: onDataChange() event always executed in Main UI Thread? In an Android application using Firebase, I need to execute long operations in background once Firebase returns a query answer.  E.g.:
query.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot data) {
         dosomething very long. . .
         then call a callback forUI thread
   }

I know that firebase execute the query in asynchronous mode but the onDataChange() method seems to be always executed in the main UI Thread, even if I try to call the query in a custom background Thread.
Does anyone knows how to manage this use case?

A: Might be a little too late to the party, but if you want Firebase to return call backs on the background thread, you can use the BACKGROUND_EXECUTOR from com.google.firebase.firestore.util.Executors.BACKGROUND_EXECUTOR like
.addOnCompleteListener(BACKGROUND_EXECUTOR, OnCompleteListener<Void> {
   ...
}

There are other executers as well like -
DEFAULT_CALLBACK_EXECUTOR
DIRECT_EXECUTOR

A: The callbacks for your Firebase listeners are indeed executed on the main UI thread.
If you need to do heavy operations in a callback, spin up an AsyncTask and do the work there. The AsyncTask.doInBackground() method executes on a different thread, so it won't block the Android UI. But AsyncTask. onPostExecute() executes on the main thread again, so you can update your UI views from there.
If you're using Cloud Firestore, see Abhriya Roy's answer on how to get the callbacks on a background thread.


text:
Q: Deserialization of large numpy arrays using pickle is order of magnitude slower than using numpy I am deserializing large numpy arrays (500MB in this example) and I find the results vary by orders of magnitude between approaches. Below are the 3 approaches I've timed.
I'm receiving the data from the multiprocessing.shared_memory package, so the data comes to me as a memoryview object. But in these simple examples, I just pre-create a byte array to run the test.

I wonder if there are any mistakes in these approaches, or if there are other techniques I didn't try. Deserialization in Python is a real pickle of a problem if you want to move data fast and not lock the GIL just for the IO. A good explanation as to why these approaches vary so much would also be a good answer.

""" Deserialization speed test """
import numpy as np
import pickle
import time
import io

sz = 524288000
sample = np.random.randint(0, 255, size=sz, dtype=np.uint8)  # 500 MB data
serialized_sample = pickle.dumps(sample)
serialized_bytes = sample.tobytes()
serialized_bytesio = io.BytesIO()
np.save(serialized_bytesio, sample, allow_pickle=False)
serialized_bytesio.seek(0)

result = None

print('Deserialize using pickle...')
t0 = time.time()
result = pickle.loads(serialized_sample)
print('Time: {:.10f} sec'.format(time.time() - t0))

print('Deserialize from bytes...')
t0 = time.time()
result = np.ndarray(shape=sz, dtype=np.uint8, buffer=serialized_bytes)
print('Time: {:.10f} sec'.format(time.time() - t0))

print('Deserialize using numpy load from BytesIO...')
t0 = time.time()
result = np.load(serialized_bytesio, allow_pickle=False)
print('Time: {:.10f} sec'.format(time.time() - t0))

Results:
Deserialize using pickle...
Time: 0.2509949207 sec
Deserialize from bytes...
Time: 0.0204288960 sec
Deserialize using numpy load from BytesIO...
Time: 28.9850852489 sec

The second option is the fastest, but notably less elegant because I need to explicitly serialize the shape and dtype information.

A: I found your question useful, I'm looking for best numpy serialization and confirmed that np.load() was best except it was beaten by pyarrow in my add on test below. Arrow is now a super popular data serialization framework for distributed compute (E.g. Spark, ...)
""" Deserialization speed test """
import numpy as np
import pickle
import time
import io
import pyarrow as pa

sz = 524288000
sample = np.random.randint(0, 255, size=sz, dtype=np.uint8)  # 500 MB data
pa_buf = pa.serialize(sample).to_buffer()

serialized_sample = pickle.dumps(sample)
serialized_bytes = sample.tobytes()
serialized_bytesio = io.BytesIO()
np.save(serialized_bytesio, sample, allow_pickle=False)
serialized_bytesio.seek(0)

result = None

print('Deserialize using pickle...')
t0 = time.time()
result = pickle.loads(serialized_sample)
print('Time: {:.10f} sec'.format(time.time() - t0))

print('Deserialize from bytes...')
t0 = time.time()
result = np.ndarray(shape=sz, dtype=np.uint8, buffer=serialized_bytes)
print('Time: {:.10f} sec'.format(time.time() - t0))

print('Deserialize using numpy load from BytesIO...')
t0 = time.time()
result = np.load(serialized_bytesio, allow_pickle=False)
print('Time: {:.10f} sec'.format(time.time() - t0))

print('Deserialize pyarrow')
t0 = time.time()
restored_data = pa.deserialize(pa_buf)
print('Time: {:.10f} sec'.format(time.time() - t0))

Results from i3.2xlarge on Databricks Runtime 8.3ML Python 3.8, Numpy 1.19.2, Pyarrow 1.0.1
Deserialize using pickle...
Time: 0.4069395065 sec
Deserialize from bytes...
Time: 0.0281322002 sec
Deserialize using numpy load from BytesIO...
Time: 0.3059172630 sec
Deserialize pyarrow
Time: 0.0031735897 sec

Your BytesIO results were about 100x more than mine, which I don't know why.


text:
Q: C# DllImport - pointer to a pointer receiving image (uchar**) I am trying to DLLImport the function simxGetVisionSensorImage
from remoteApi.dll of v-rep software. Here is the link to the function description:
http://www.coppeliarobotics.com/helpFiles/en/remoteApiFunctions.htm#simxGetVisionSensorImage
and here is the brief description for this function from the above link:
Description: Retrieves the image of a vision sensor. The returned data doesn't make sense if simHandleVisionSensor wasn't called previously (simHandleVisionSensor is called by default in the main script if the vision sensor is not tagged as explicit handling). Use the simxGetLastCmdTime function to verify the "freshness" of the retrieved data.
C synopsis: simxInt simxGetVisionSensorImage(simxInt clientID,simxInt sensorHandle,simxInt* resolution,simxUChar** image,simxUChar options,simxInt operationMode)
C parameters:
clientID: the client ID. refer to simxStart.
sensorHandle: handle of the vision sensor
resolution: pointer to 2 simxInt values receiving the resolution of the image
image: pointer to a pointer to the image data.
options: image options, bit-coded: bit0 set: each image pixel is a byte (greyscale image), otherwise each image pixel is a rgb byte-triplet
operationMode: a remote API function operation mode.
Here is the way I am importing it (simxGetVisionSensorImage function):
    [DllImport("remoteApi.dll", CallingConvention = CallingConvention.Cdecl)]
    public extern static simx_error simxGetVisionSensorImage(int clientID, int sensorHandle, out int resolution, out IntPtr image, char option, simx_opmode opmode);

and here is how I am calling it:
int intResolution = 0;
char option = '\0';
IntPtr imageIntPtr= IntPtr.Zero;
simxGetVisionSensorImage(intClientID, intCamera1Handle, out intResolution, out imageIntPtr, option, simx_opmode.streaming);

It runs successfully and intResolution is 128 and imageIntPtr is validated as well after running. However, I don't know how to convert the "imageIntPtr" variable to image or bitmap.
I really appreciate if someone can help me on this.

A: The simplest way would be to construct a new Bitmap from it.
var bmp = new Bitmap(bitmapWidth, bitmapHeight, 3 * bitmapWidth,
    PixelFormat.Format24bppRgb, ptrFromApi);


text:
Q: Javascript DOM extend text selection one word in both directions Assuming a user has selected some text on the page, i want to extend the selection within my code to include one word from last and end both. I have tried the following:
selection.modify('move', 'forward', 'word');
selection.modify('move', 'forward', 'word');
selection.extend(endNode, endOffset);
selection.modify('extend', 'backward', 'word');
selection.modify('extend', 'backward', 'word');

But looks like it doesnt pick up the adjacent sibling nodes. It makes no difference. Can someone help me out on this one.


text:
Q: Modify values of a numpy array based on a condition Hello I have a numpy array as follows:
list_of_values = [-0.5, -0.8, -0.6, -0.2, 0.2, 0.5, 0.7, 0.9, -0.3, 0.2, 0.6, 0.4, 0, 0.2, 0, -0.3, -0.2, 0, -0.6, 0, 0.3]
array= np.array(list_of_values)

I need an array of the same size, having a 1 when the value goes from negative to positive, and a -1 when the value goes from positive to negative, and a 0 for the rest. If there is a 0 in list_of_values, and it bounces back, it should not be considered as the 0 line has been crossed.
This is the exact output that I am looking for
output = [0, 0, 0, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]

The real list_of_values is large, with 3000+ numbers, so the solution should use Numpy (some for loop is not valid), and it should be quick.
Thank you

A: You can use numpy.ediff1d:
>>> import numpy as np
>>> arr = np.array([-1, -0.8, -0.6, -0.1, 0.1, 0.5, 0.7, 1, -0.3, 0.2, 0.6])
>>> np.ediff1d(np.sign(arr), to_begin=0) // 2
array([ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0., -1.,  1.,  0.])

If you'd like to consider 0 as positive:
>>> arr = np.array([-1, -0.8, -0.6, -0.1, 0.0, 0.5, 0.7, 1, -0.3, 0.2, 0.6])
>>> np.ediff1d(np.where(arr==0, 1, np.sign(arr)), to_begin=0)//2
array([ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0., -1.,  1.,  0.])

EDIT
Based on your edit, you can do the following:
>>> arr = [-0.5, -0.8, -0.6, -0.2, 0.2, 0.5, 0.7, 0.9, -0.3, 0.2, 0.6, 0.4, 0, 0.2, 0, -0.3, -0.2, 0, -0.6, 0, 0.3]
>>> output = np.array(arr)
>>> nonzero_idx = output != 0
>>> nonzero_arr = output[nonzero_idx]
>>> res = np.ediff1d(np.sign(nonzero_arr), to_begin=0) // 2
>>> output[nonzero_idx] = res
>>> output
array([ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0., -1.,  1.,  0.,  0.,  0.,
        0.,  0., -1.,  0.,  0.,  0.,  0.,  1.])

A: The answer provided by Cyttorak is correct and a lot prettier than mine, however, if you don't mind a little bit uglier code and want speed, this is faster.
a2 = np.array([-1, 1])
array = np.array([-1, -0.8, -0.6, -0.1, 0.1, 0.5, 0.7, 1, -0.3, 0.2, 0.6])
array = np.where(array >= 0, -1, 1)
output = np.convolve(array, a2, mode='same')
output = np.where((output == 2) | (output == -2), output, 0) // 2

Edit: sorry, forgot to copy-paste a2 :D


text:
Q: Why am I getting an empty response with this JSON-formatted request? I am sending JSON data as request and in response I am getting 0 bytes of data with content type "application/JSON;charset=ISO-8859-1". Why I am getting no response? I think it is related to encoding. Please help.
 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", [self getBaseURL], @"FileListIOS"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod:@"POST"];

UserProfile *userProfile = [[AppCacheManager manager] getUserProfile];
NSString *personalPath = userProfile.personalPath;
NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:userProfile.personalPath,userProfile.personalPath,userProfile.userType, nil] forKeys:[NSArray arrayWithObjects:@"currentpath",@"rootpath",@"usertype", nil]];
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

[request setHTTPBody:data];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(data) {

    }
}];


text:
Q: 7 and 4.7 inch tab/phone come under normal screen i have bsnl penta 7" tab. It comes under normal, mdpi, 455x800, screen size is ~5.4"(but tab is 7") when checked via code.
The real problem is, when running my application it loads images, size etc from \res\drawable folder (not a problem with mdpi also not loading from /res/drawable-large). So that the images and font will be small. Similar problem is occurring in some other smart phones too. How can be handled it.
I also configured an emulator similar spec to that tab and it works perfectly.
thanks in advance


text: Q: Display Grouped Product Tier Pricing in Table Columns I am using grouped products with tier pricing and I would like to have each tier in it's own table column. Default display has the columns "Product", "Price", and "Quantity". I would like the columns to be "Product", "Price for 1", "Price for 5", "Price for 100" (etc.), and "Quantity". Is there any way to do this without rewriting pricing from the ground up?


text:
Q: DC Motor only works with programmer I have designed a micro controller circuit to actuate a DC motor using signals from an ATmega234P chip via a L239DNE H-Bridge. The problem I am having is that the motor runs slower than usual while executing the PWM code. As soon as I connect an MKII programmer to the ISP the motor works properly. Attached are my circuit schematics and the code that I am running. Any help would be very much appreciated!
Code (source):
/*
 * DCM_PWM.c
 *
 * Created: 14/09/2018 6:31:42 PM
 * Author : s4354441
 */

#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>

void setup_timer0 (void)
{
  DDRB = (1<<DDB3) | (1<<DDB4); // set the PWM pin to output.
  TCCR0A = (1<<COM0A1) | (1<<COM0A0) | (1<<COM0B1) | (1<<COM0B0) | (0<WGM01) | (1<<WGM00); // toggle OC0A on compare match
  TCCR0B = (0<<WGM02) | (0<<CS02)| (0<<CS01) | (1<<CS00); //select PWM, Phase Correct
  OCR0A = 0; // set output compare value
  OCR0B = 0; // set output compare value
}

void PWM_func (void)
{
  for (int i=0; i<255; i++) {
    OCR0A = i;
    _delay_ms(25);
  }

  for (int i=255; i>0; i--) {
    OCR0A = i;
    _delay_ms(10);
  }

  for (int i=0; i<255; i++) {
    OCR0B = i;
    _delay_ms(5);
  }

  for (int i=255; i>0; i--) {
    OCR0B = i;
    _delay_ms(25);
  }

  for (int i=0; i<255; i++) {
    OCR0A = i;
    _delay_ms(10);
  }
}

int main (void)
{
  setup_timer0();
  PWM_func();
}

PCB Schematic 1:

PCB Schematic 2:

A: It would not run at all with the schematic as shown,. So L1C2 must be reversed on the schematic.
But servo motors demand heavy current only during position command changes, (which in this case may be >> 100mA ) so the low power L05 regulator is possibly suffering from overload while the voltage drops to limit the current.
Make sure you scope the voltage and ensure this is not the problem.  The LC values are not ideal as a low pass filter breakpoint and more filtering and care with analog ground not sharing motor current is essential.
In short, no pun intended, without reviewing your code, you seem to be having power supply issues and no report of servo surge current specs.
Try a PC PSU until you learn how to specify and choose a better supply.


text:
Q: How to solve an equation with variables in a matrix in Python? i'm coding in Pyhon, and I'm working on stereo-correlation. I want to resolve this equation : m = K.T.M
m,K,M are know.
where :
M is the  homogeneous coordinate of a point in the cartesian coordinate system "world"
M=np.array([X,Y,Z,1])

K is my intrinsic matrix for the left camera
K=np.matrix([ [fx,  0, cx, 0],
              [ 0, fy, cy, 0],
              [ 0,  0,  1, 0]])

m its the M point views by the left camera
m=np.array([x,y,1])

and T is the transformation to pass to the "world" coordinate system to the left camera coordinate system.
T= np.matrix([[x00, x01, x02, Tx],
              [x10, x11, x12, Ty],
              [x20, x21, x22, Tz],
              [0  , 0  , 0  , 1 ]])

So I want to solve this equation to find T but it's impossible to create a matrice without give values to variables.
someone have a solution?
Thanks
best regards

A: If you want a generic solution, you can use Sympy, which allows you to work with symbolic expression. In the following code the expression K.T.M = m is reformulated to a standard linear equation HH.xx = mm, where xx is the vector with the unknowns extracted from T:
from IPython.display import display
import sympy as sy

sy.init_printing()  # LaTeX like pretty printing for IPython

# declaring symbolic variables:
x, y, X, Y, Z, fx, fy, cx, cy = sy.symbols("x y X Y Z f_x f_y c_x c_y", real=True)
x00, x01, x02, x10, x11 = sy.symbols("x00, x01, x02, x10, x11", real=True)
x12, x20, x21, x22 = sy.symbols("x12, x20, x21, x22", real=True)
Tx, Ty, Tz = sy.symbols(" T_x T_y T_z", real=True)

# Building matrices and vectors:
M = sy.Matrix([X, Y, Z, 1])
m = sy.Matrix([x, y, 1])
K = sy.Matrix([[fx,  0, cx, 0],
               [0,  fy, cy, 0],
               [0,   0,  0, 1]])
T = sy.Matrix([[x00, x01, x02, Tx],
               [x10, x11, x12, Ty],
               [x20, x21, x22, Tz],
               [0,     0,   0,  1]])

print("KTM = K.T.M = ")
KTM = sy.simplify(K*T*M)
display(KTM)

print("Vector of Unkowns xx.T = ")
xx = sy.Matrix(list(T.atoms(sy.Symbol)))
display(xx.T)
print("For equation HH.xx = mm, HH = ")
HH = KTM[:2, :].jacobian(xx)  # calculate the derivative for each unknown
display(HH)

As @Sven-Marnach already noted, there are not enough equations for a unique solution. Since the last row of the vector KTM and of m is 1, there are only two equations for twelve variables.
If you have multiple pixelsto evaluate, i.e., multiple pairs of (m, M), you can use Numpy's Least Squares Solver to find a solution.


text:
Q: Eclipse View Open location I have a view that can be opened multiple times containing different data. I added a placeholder for the view in a folder that is below the editor area. The first instance of the view opens in the proper location but if I open a second version of the view it opens to the right of the editor. Is there a way to have all views of this type open in the folder below the editor like the first one does? Do I have to add multiple place holders? Even when I close the first instance of the view and open another instance of it, the new view opens to the right of the editor.
The views differ by the secondary id that populates the view based on that id.


text:
Q: SQL - Using an exclusion List from another table with a wild card I have created a table with a number of business exclusion names within it for the purpose of when I receive a weekly data file I want to run the business names against the exclusion list which I will then flag as being excluded. I can achieve this if it was the exact name I was wanting to exclude, but I want to run a wildcard on each business exclusion name against my new data.
For example:
I have in my exclusion table a business exclusion name that is "Marks and Spencers" but I have in my new data file an account called "Marks and Spencers Manchester" which I want to exclude so a like for like wouldn't match so I would want to do something possibly using the Like function and in this example use something like "  Where ExclusionName like "Marks and Spencer%"   "
I can obviously achieve using the above logic but I want to go through all the data in the new file iterating through the exclusion list flagging if the account is to be excluded or not.
Would this have to achieved using a cursor? and how efficient would that be with a larger data file and a reasonably large exclusion list?
Any advice would be appreciated.
Thanks
DC

A: My advice is to expand your exclusions table so that it's a "what to do" table.  Each record should include, at the very least, a business name and a "what to do field".  The values would indicate whether you should include or exclude records from your weekly imports.
When you get your weekly imports, put all records into a staging table.  Then run a report showing all names which are not in the "what to do" table.  Make a decision on each record and add it to the table with the appropriate values.  Then carry on with whatever you have to do with the weekly import.
This might appear to be tedious, but you'll get better results.  Using the Marks and Spencers example, in addition to the city at the end part, you might get some records with apostrophe's, spelling mistakes, city at the start, and so on and so forth.


text:
Q: guessing geometric series from a partial sum?
I had thought the answer would be $b$ since the graph seems to be nearing a specific value and the infinite geometric sum is defined only when $|r| < 1$. However, the answer states it is $c$. Am I wrong (if so how and why), or is the answer wrong?

A: Your answer was almost certainly the intended answer.  Answer (c) definitely can't be correct, since the partial sums of a geometric series with $r>1$ would be growing faster and faster, since the powers of $r$ are increasing.
[As pointed out in the comments, the exact graph shown is not actually correctly to scale to be a geometric series, so all of the answers are wrong if you assume it is drawn accurately and not just a very rough sketch.  This is probably an error of laziness on the part of whoever wrote the problem: they just drew a graph of roughly the shape they wanted, without checking whether it actually numerically worked.]


text:
Q: How do I find the max value for each 5 minute interval? The program below prints the following data:
 Wed,Jun,13,10:37:34,2012,759,41,0,30,10,0,0,1
 Wed,Jun,13,10:38:34,2012,767,33,0,25,6,0,0,2
 Wed,Jun,13,10:39:34,2012,758,42,0,32,10,0,0,0
 Wed,Jun,13,10:40:35,2012,758,42,0,29,11,0,0,2
 Wed,Jun,13,10:41:35,2012,761,39,0,34,5,0,0,0
 Wed,Jun,13,10:42:35,2012,769,31,0,22,6,0,0,3
 Wed,Jun,13,10:43:35,2012,754,46,0,29,17,0,0,0

I need to output the max value (ex. 769) for each 5 minute interval.  Ideally this would be 10:00:00 - 10:05:00, etc.  Time is military time (24 hour).  What is the best way of doing this?  Please note that I am a beginner in Perl.  Below is my code:
#!/usr/bin/perl

# This program displays the max thread count at 5 minute intervals and writes the lines to a CSV file.

use strict;
use warnings;
use diagnostics;

# Initialize functions
my @data;
my $line;
my @L1;
#my $outFivemin = "log_5min.csv";
#open (FiveMin, ">> $outFivemin");

# Open the error_log
open(FH, "error_log");
@data = <FH>;

# Filter the results to MPMStats only
sub findLines {
    my @return = ();
    foreach $line (@data) {
        if ( ($line =~ /notice/) && ($line =~ /rdy/) ) {
                $line =~ s/ /,/g;
                my @L1 = split(/|notice|\[|,mpmstats:,|\t|rdy,|bsy,|rd,|wr,|ka,|log,|dns,|cls,/, $line);
                $line =~ s/|notice|\[|,mpmstats:,|\t|rdy,|bsy,|rd,|wr,|ka,|log,|dns,|cls,//g;
                push @return, join("", @L1);
        }
    }
    return @return;
}

# Initializers for my data
my($dayOfWeek1,$month1,$dayOfMonth1,$time,$year1,$rdy,$bsy,$rd,$wr,$ka,$log,$dns);
my($cls);

# Create a 2D array
my @L2 = &findLines;
foreach my $line (@L2){
    ($dayOfWeek1, $month1, $dayOfMonth1, $time, $year1, $rdy, $bsy, $rd, $wr, $ka, $log, $dns, $cls) = split(/,/, $line);
    print "$dayOfWeek1,$month1,$dayOfMonth1,$time,$year1,$rdy,$bsy,$rd,$wr,$ka,$log,$dns,$cls";
}

A: I suggest you manipulate the date/time in each record to supply a five-minute key, and maintain a maximum for each key.
For example, if a record starts Wed,Jun,13,10:37:34,2012 then an appropriate key is Jun 13 10:35 2012.
Ordinarily this would be a hash, but since it is likely that the output is wanted in chronological order, and extra work and modules are required to provide a sortable date/time string, the program below uses an array of pairs.
The program works by using a regex subtitution s/// on the time (fourth) field that replaces the minutes and seconds with the first two-digit minute preceding the time: the seconds are ignored and the minutes rounded down to a multiple of five.
A new [$range, $value] pair is pushed onto the @maxima array if the array is empty or if we are in a different $range. Otherwise the $value element of the latest pair is updated if we have found a new maximum.
Note that this program expects a log file name on the command line, and will default to error_log of none is provided.
use strict;
use warnings;

@ARGV = ('error_log') unless @ARGV;

my @maxima;

while (<>) {

  my @fields = /([^,\s]+)/g;
  next unless @fields;
  $fields[3] =~ s|(\d+):\d\d$|5*int($1/5)|e;

  my $range = join ' ', @fields[1..4];
  my $value = $fields[5];

  if (@maxima == 0 or $range ne $maxima[-1][0]) {
    push @maxima, [$range, $value];
  }
  else {
    $maxima[-1][1] = $value if $maxima[-1][1] < $value;
  }
}

for (@maxima) {
  printf "Maximum for five minutes starting %s is %d\n", @$_;
}

output
Maximum for five minutes starting Jun 13 10:35 2012 is 767
Maximum for five minutes starting Jun 13 10:40 2012 is 769

Update
Now that I understand you want the entire record containing the maximum value of field 6 for each five-minute period I have written this revised code.
It also works from the contents of your @L2 array instead of reading from a file.
I am certain this would be far better coded to read from the file in a while loop and generate the output directly from there, but unless you show us some log file data I cannot suggest a better alternative than this.
This program continues from the point where you populate @L2 in your own program.
my @L2 = findLines();

my @maxima;

for my $record (@L2) {

  my @fields = $record =~ /([^,\s]+)/g;
  next unless @fields;

  my @range = @fields[1..4];
  $range[2] =~ s|(\d+):\d\d$|5*int($1/5)|e;
  my $range = join ' ', @range;
  my $value = $fields[5];

  if (@maxima == 0 or $range ne $maxima[-1][0]) {
    push @maxima, [$range, $value, $record];
  }
  else {
    @{$maxima[-1]}[1,2] = ($value, $record) if $maxima[-1][1] < $value;
  }
}

print $_->[2] for @maxima;

output
 Wed,Jun,13,10:38:34,2012,767,33,0,25,6,0,0,2
 Wed,Jun,13,10:42:35,2012,769,31,0,22,6,0,0,3

A: Something along these lines should do the trick...
#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

# Somewhere to store the data
my %data;

# Process the input a line at a time
while (<DATA>) {
  # Split the input line on commas and colons.
  # Assign the bits we need to variables.
  my ($mon,$day,$hr,$min,$sec,$yr,$val) = (split /[,:]/)[1 .. 7];

  # Normalise the minute value to five-minute increments
  # i.e 37 becomes 35, 42 becomes 40
  $min = int($min / 5) * 5;

  # Create push the value onto an array that is stored in %data using
  # a key generated from the timestamp.
  # Note that we use the 5-min normalised value of the minute so that
  # all values from the same five minute period end up in the same array.
  push @{$data{"$yr-$mon-$day $hr:$min"}}, $val;
}

# For each key in the array (i.e. each five minute increment...
foreach (sort keys %data) {
  # ... sort the array numerically and grab the last element
  # (which will be the largest)
  my $max = (sort { $a <=> $b } @{$data{$_}})[-1];
  # Say something useful
  say "$_ - $max";
}

__DATA__
Wed,Jun,13,10:37:34,2012,759,41,0,30,10,0,0,1
Wed,Jun,13,10:38:34,2012,767,33,0,25,6,0,0,2
Wed,Jun,13,10:39:34,2012,758,42,0,32,10,0,0,0
Wed,Jun,13,10:40:35,2012,758,42,0,29,11,0,0,2
Wed,Jun,13,10:41:35,2012,761,39,0,34,5,0,0,0
Wed,Jun,13,10:42:35,2012,769,31,0,22,6,0,0,3
Wed,Jun,13,10:43:35,2012,754,46,0,29,17,0,0,0

A: Whoops, I mistakenly thought that your csv output was the data file being parsed.
Ignore the answer below.
Here is a solution that prints out the original comma separated line. The max value and the time are also available for printing. But I created a comma separated file with the results instead.  :-)
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV_XS;

my %interval;
my $csv = Text::CSV_XS->new ({ binary => 1 }) or
     die "Cannot use CSV: ".Text::CSV_XS->error_diag ();

open my $fh, "<", "o33.txt" or die "o33.txt: $!";
while (my $row = $csv->getline ($fh)) {
    my ($time, $amt) = @$row[3,5];
    my ($hr, $min) = split /:/, $time;
    my $key = sprintf "%02d:%02d", $hr, int($min/5) * 5;

    if (exists $interval{$key}) {
        if ($interval{$key}{amt} < $amt) {
            $interval{$key}{amt} = $amt;
            $interval{$key}{data} = $row;
        }
    }
    else { # first time in this 5 minute interval
        $interval{$key}{amt} = $amt;
        $interval{$key}{data} = $row;
    }
}
$csv->eof or $csv->error_diag ();
close $fh or die $!;;

$csv->eol ("\r\n");
open $fh, ">", 'junk.csv' or die $!;

for my $time (sort keys %interval) {
    $csv->print($fh, $interval{$time}{data});
}

close $fh or die $!;

The output to 'junk.csv' is:
Wed,Jun,13,10:38:34,2012,767,33,0,25,6,0,0,2
Wed,Jun,13,10:42:35,2012,769,31,0,22,6,0,0,3

A: This works(?), (didn't test), and it begins with your loop right after my @L2 = &findLines.
my %interval;
my %month;
@month{qw/ jan feb mar apr may jun jul aug sep oct nov dec /} = '01' .. '12';

# Create a 2D array
my @L2 = &findLines;
foreach my $line (@L2){
    #($dayOfWeek1, $month1, $dayOfMonth1, $time, $year1, $rdy, $bsy, $rd, $wr, $ka, $log, $dns, $cls) = split(/,/, $line);
    #print "$dayOfWeek1,$month1,$dayOfMonth1,$time,$year1,$rdy,$bsy,$rd,$wr,$ka,$log,$dns,$cls";
    my ($dow, $mon, $day, $hr, $min, $sec, $yr, $amt) = split /[:,]/, $line, 9;
    my $key = sprintf "%4d-%02d-%02d %02d:%02d",
                $yr, $month{lc $mon}, $day, $hr, int($min / 5) * 5;

    if (exists $interval{$key}) {
        if ($interval{$key}{amt} < $amt) {
            $interval{$key}{amt} = $amt;
            $interval{$key}{data} = [split ",", $line];
        }
    }
    else { # first time in this 5 minute interval
        $interval{$key}{amt} = $amt;
        $interval{$key}{data} = [split ",", $line];
    }
}

my $csv = Text::CSV_XS->new ({ binary => 1 }) or
     die "Cannot use CSV: ".Text::CSV_XS->error_diag ();

$csv->eol ("\r\n");
open my $fh, ">", 'junk.csv' or die $!;

for my $time (sort keys %interval) {
    $csv->print($fh, $interval{$time}{data});
}

close $fh or die $!;

I hope this brings you closer to a good solution to your problem.
Update: added first field to split and changed from 8 to 9 portions.


text:
Q: how to connect 2 UL lists with jQuery traversal. I am trying to implement some next/previous navigation across a list I have had to break into 2 lists due to the page design.  I can easily do this in a single list with jQuery, but cannot figure out how to jump to the first item in the second list from the last item in the first list (and vice versa).  Code is here: http://pastebin.com/5DjtzGBa

A: You can check if this is the last li, and then jump to next list. Similarl logic for jump to prev:
Pseudo code (I'll try to post a working function later)
$("#nav ul li a").bind("click keypress",function(e){
    var dTitle=$(this).text();
    var dContentkey=$(this).attr("id");
                if($(this).parent().is(":last")) {
                     // get next ul item
                }
                else {
         nextItem=$(this).parent().next("li").find("a").attr("id");
                }
    testItem=$(this).parent("#nav").next("div ul li").find("a").attr("id");
    e.preventDefault();
    $("#currTitle").text("Clicked item: "+dTitle);
    $("#nextObjID").text("Next Item: "+nextItem);
    $("#testObjID").text("Test Item: "+testItem);
});

A: You want (as an alternate, if your first search in the current list returns no results):
nextItem = $(this)
    .closest("div") // find the closest div ancestor
    .next("div")    // then its next sibling div
    .find("ul li a")// then the first link in the list
    .attr("id");

Fully functional example here.

A: First, if you're IDs are going to be numbered, like in your example, simply use the ID attributes to find the next or previous items.
Second, here is a more general solution. This will work for your case, but it'll also work if you have LIs, divs or whatever scattered all across the page in random locations, and you want to chain all the individual elements together so you can traverse forward and backward through them.

*

*Step 1: Select all the elements you want. e.g. for you $("#nav li")

*Step 2: Iterate through all elements and store its index number as a data value.

*Step 3: When you click on a chosen element, retrieve it's stored data number, and then retrieve the element from the index position one less or greater than the item clicked on to get the previous or next element (don't forget about looping the ends). You can simply use the selection from Step 1 and .eq(). In your case.

Working example (click on an LI to see which one's next)
$(function() {
    // You can link lists anywhere on the page,
    // not just consecutive ones
    // create an object of all lis and store the index

    // Let's cache our big combine list
    $bigList = $("ul.big-list li");

    // Store the index value in the list item
    $bigList.each(function(index) {
        $(this).data("indexNum", index);
    });

    // Retrieve stored index value and add or subtract one
    $bigList.click(function() {
        // Add one to find next
        // Subtract one to find prev
        var nextIndex = $(this).data("indexNum") + 1;

        // Wrap from last to first
        if (nextIndex === $bigList.length)
            nextIndex = 0;

        // Find next or prev using .eq()
        $bigList.eq(nextIndex).animate(
                    {"font-size":"200%"},500).animate(
                    {"font-size":"100%"},500);
    });
});


text:
Q: Parse a json file generated for jstree in C# I wish to parse a JSON file which is generated dynamically and does not have a definite structure.
[
  {
    "children": [
      {
        "children": [
          {
            "children": [],
            "text": "Child node 2.txt",
            "isFolder": false,
            "id": "1childnode2.txt",
            "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 2.txt",
            "type": "itsfile"
          }
        ],
        "text": "Child node 1.txt",
        "isFolder": false,
        "id": "0childnode1.txt",
        "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 1.txt",
        "type": "itsfile"
      },
      {
        "children": [],
        "text": "Child node 2.txt",
        "isFolder": false,
        "id": "1childnode2.txt",
        "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 2.txt",
        "type": "itsfile"
      },
      {
        "children": [],
        "text": "Child node 3.txt",
        "isFolder": false,
        "id": "2childnode3.txt",
        "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 3.txt",
        "type": "itsfile"
      }
    ],
    "text": "Root node",
    "isFolder": true,
    "id": "3rootnode",
    "itsPath": "C:\\Users\\pandyapa\\Root node",
    "type": "default"
  }
]

This JSON can have any nested children.  I wish to parse each JSON object, compare its "id" key and retrieve the "itspath" value.
I tried but was unsuccessful. Any help is highly appreciated.

A: It looks to me like your JSON does have a very definite structure, which can be represented by this recursive class:
public class Node
{
    public Node[] Children { get; set; }
    public string Text { get; set; }
    public bool IsFolder { get; set; }
    public string Id { get; set; }
    public string ItsPath { get; set; }
    public string Type { get; set; }
}

It may be that the JSON can be deeply nested and you may not know ahead of time how many levels or how many children there will be at each level, but the fact remains that each "node" has a uniform structure.  This is good, because it means that it can be easily deserialized with a parser such as Json.Net.  In fact, you can do it with just one line of code:
List<Node> nodes = JsonConvert.DeserializeObject<List<Node>>(json);

Once you have the nodes deserialized, you need to be able to find the one you want.  By introducing a short "DescendantsAndSelf" method to the class, you can make the structure queryable using LINQ methods.
    public IEnumerable<Node> DescendantsAndSelf()
    {
        yield return this;
        if (Children != null)
        {
            foreach (Node child in Children)
            {
                yield return child;
            }
        }
    }

Now you can do this to find a particular node by ID:
var idToFind = "2childnode3.txt";

var node = nodes.SelectMany(n => n.DescendantsAndSelf())
                .Where(n => n.Id == idToFind)
                .FirstOrDefault();

if (node != null)
{
    Console.WriteLine(node.ItsPath);
}
else
{
    Console.WriteLine("Not found");
}

Fiddle: https://dotnetfiddle.net/u9gDTc


text:
Q: Jquery Windows authentication not working in chrome I am using ajax to call a wcf service in backend. Backend has windows authentication. It works fine in IE but it is not working in Google Chrome. It says the error is "Unauthorized" with status code of 401.
How to send the authentication details along with the ajax call?
Thank you.

A: One way you can do it if you have a secure website is to put the username and password in the URL of your web service.
For example:
https://username:password@mywebsite.com/webservice.svc/


text:
Q: Ubuntu Phone (BQ Aquaris E4.5) with mouse - How to make mouse coursor visible? When I connect a USB mouse to my BQ Aquaris E4.5 Ubuntu Edition, I can do different actions, with a non visible mouse cursor.
Is it possible to make the mouse cursor visible?
I installed a terminal and tried this:
gsettings set org.gnome.settings-daemon.plugins.cursor active false

like I found here:
http://itsfoss.com/invisible-mouse-cursor-ubuntu-1310/
But that doesn't work, because this settings doesn't exist on the phone.
Is there a solution to make the mouse cursor visible?

A: I asked similar question in:
Ubuntu Phone lack of cursor for OTG/USB mouse
mhall119 replied:
'It's not available yet, but is being actively worked on. Mir 0.16 has just been released, and I think the mouse cursor fix is targeted for 0.17.'
Hope that helps out.


text:
Q: Add data to ImageView to retrieve later with onClick I have an layout with an ImageView, like this:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@color/blue" />

</LinearLayout>

This layout is used in my RecyclerView. Here is the adapter for the layout:
public class LayoutAdapter extends RecyclerView.Adapter<LayoutAdapter.ViewHolder> {
    private Context context;

    private List<Data> data;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView image;

        public ViewHolder(View v) {
            super(v);

            image = (ImageView) v.findViewById(R.id.image);
        }
    }

    public LayoutAdapter(Context context, List<Data> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public LayoutAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.main_layout, parent, false);

        ViewHolder vh = new ViewHolder(v);

        return vh;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Data data = data.get(position);

        // TODO: bind data.getUser() to image
        // data.getUser() returns the User model object

        // starts new activity, need to pass image getUser() data to the activity
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, UserActivity.class);
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}

What I need to do (as commented in the code), is add data to the ImageView so that I can pass that data to the UserActivity when the image is clicked.
How can I achieve this?

A: First, you can set image source like what you used to do.
Second, you can pass Data from your activity to UserActivity like this:

*

*Edit your Data class, implement Serializable
public class Data implements Serializable{

*in onClick method
final Data data = data.get(position);
    // TODO: bind data.getUser() to image
    // data.getUser() returns the User model object

    // starts new activity, need to pass image getUser() data to the activity
    holder.image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, UserActivity.class);
            intent .putExtra("data", data);
            context.startActivity(intent);
        }
    });

*in UserActivity you can retreive it
Data receivedData = (Data) getIntent().getSerializableExtra("data");