CouchDB include document in index if count of array field is greater than 0

Question: I am using Cloudant which is just CouchDB with some more features and I'm looking for the syntax to count the number of elements in an array. Specifically, I'm creating a design document where I only index the document if its field 'color' has more than 0 elements. How do I check to see if there are more than 0 elements in 'color'?
{"_id": "_design/geodd",
 "_rev": "5-2729b1453b11f81261ddb3cf3f3de72f",
 "st_indexes": {
  "geoidx": {
   "index": "function(doc) {if (doc.geometry && doc.geometry.coordinates && doc.color != []) {st_index(doc.geometry);}}"
  }
 }
}

Answer: When writing your view, you can execute any Javascript code, so this is more a javascript question than a CouchDB question.
The mistake in your view is that you cannot compare arrays in javascript with the equality operator: doc.color != [] will always return false (because they are not the same objects).
Try replacing this by doc.color.length == 0 if you know in advance that doc.color is always an array.
If your not sure doc.color is an array, write isArray(doc.color) && doc.color.length == 0.
Your view code would become:
{"_id": "_design/geodd",
 "_rev": "5-2729b1453b11f81261ddb3cf3f3de72f",
 "st_indexes": {
  "geoidx": {
   "index": "function(doc) {if (doc.geometry && doc.geometry.coordinates && isArray(doc.color) && doc.color.length == 0) {st_index(doc.geometry);}}"
  }
 }
}


Finding records between date range

Question: I'm trying to find records whose start and end date range over a particular date. Date is random and :start_date and :end_date are attributes of the prices entity.
date = Time.now
record_i_want = Price.where(date => :start_date .. :end_date)

Thank you.
Answer: You can simply do
Price.where(:date => start_date..end_date)

This will result in the following SQL( for start and end dates - '2014-03-27', '2014-03-28')
SELECT `prices`.* FROM `prices` WHERE (`prices`.`date` BETWEEN '2014-03-27' AND '2014-03-28')

EDIT:
Realized that this is the query you are looking for. Thanks, Coenwulf for pointing it out
Price.where(['start_date < ? AND end_date > ?', date, date])

Comment: This is a great tip. Didn't know that. Awesome.
Comment: This looks like it's the opposite of what the OP requests. It would be perfect if date were the field in the table, but it appears based on the text in the post that there are start_date and end_date fields in the table. So this code doesn't solve the posted problem.
Answer: You want to select rows where your date is greater than the start_date and less than the end_date. You can specify the appropriate SQL where clause parameterized in your call to where like so:
Price.where([":date >= start_date AND :date <= end_date", {date: Date.today})

That will give you all the prices that match. If you know you'll get only one you can get it by calling first.
Price.where([":date >= start_date AND :date <= end_date", {date: Date.today}).first

Make any appropriate adjustment to the >= and <= if you want to exclude the start_date and/or the end_date from the results. If for example the Price is valid starting on the start_date but isn't valid through the end_date you can change the clause to:
":date >= start_date AND :date < end_date"

Answer: This should work:
def get_record_by_date(date)
  Price.where([start_date.to_i < date.to_i] && [end_date.to_i > date.to_i])
end

Finding records between date range


Number of ways to choose five lottery numbers so no two are adjacent

Question: Someone stated that in a lottery draw, you have an equal chance of being 1 off of every correct number as you do of actually winning, but this is not true if you have adjacent numbers (such as 7/8). I wrote a program which iterates over all possible numbers and counts the number of outcomes where two numbers are adjacent given a top number. It would be too time-consuming to check all 50 numbers for each 5 possible selections, so I instead used lower numbers and tried to find an equation which I can use.
I've got a dataset of x and y values (where x = top number and y = number of outcomes with atleast one adjacent pair). I believe this dataset turns into a quintic function (x^5) when plotted, but I'm not sure. I have two main questions:

How could I find the equation of the graph? I have tried to find the difference of differences (similar to quadratic, ie 1, 4, 9, 16 = 3, 5, 7 = 2) and it turned out that the difference after 5 differences was a constant 120. I have also tried to find the ratio of one number to the next. This leads to my next question...

This ratio turned out to be strangely nice. When x=8, y=0. x=9,y=120. x=10,y=720. x=11,y=2520. If you divide one number by the previous, you get *6 (6/1), *3.5 (7/2) and so on, (8/3, 9/4). The fraction's denominator and numerator increase by 1 every time. Where does this come from?

Code I used (python) - https://pastebin.com/d2bAQVmV
Answer: You are choosing five numbers between $1$ and $x$, and asking the number of ways where no two of the chosen numbers are either equal or adjacent. The answer is
$$
\binom{x-4}{5}\cdot 5!=x(x-1)(x-2)(x-3)(x-4)
$$
It is well known that, for positive integers $k$ and $x$, the number of unordered selections of $k$ distinct numbers from $\{1,\dots,x\}$ where no two selected numbers are adjacent is $\binom{x-k+1}{k}$. See the sources belwo for a proof. To get the number of ordered selections, you just multiply by $5!$, the number of ways to arrange five numbers, resulting the formula above. This is a degree five polynomial in $x$, as you noticed.
Questions on MSE on counting non-consecutive subsets:
Combinatorial restriction on choosing adjacent objects
How many $5$ element sets can be made?
Analysis of formula for selecting $k$ elements from $n$ elements arranged in a row so that no two selected elements are consecutive

Edit: Everything in this section is only correct for lotteries where the order of the chosen numbers matters.
By the way, the statement "you have an equal chance of being 1 off of every correct number as you do of actually winning" is indeed true, if you interpret it a specific way. Suppose ticket has the numbers $(a,b,c,d,e,f)$. The probability of drawing $(a,b,c,d,e,f)$ is the same as the probability of drawing $(a+1,b+1,c+1,d+1,e+1,f+1)$.
There is a small caveat here; the "+1" must be interpreted modulo $x$. For example, if there were fifty possible lottery numbers, then you would have to say that $50+1$ wraps around back to one.
Comment: Thanks, glad to know about the binomial coefficient as it seems quite fundamental. Also, order is not relevant for the Euromillions, which is the lottery I'm basing it on.
Comment: Thanks for the response! I'm not too familiar with probability beyond a basic understanding, could you explain what the bracket with (x-4, 5) represents? The rest seems quite logical though, thanks.

Also, technically it could be interpreted that the statement is correct if you assume that the numbers are all "independent" in a way. For example, if you choose 2,3 16, 21, 42, then being 1 off would mean the numbers are (3, 4, 17, 22, 43). You could interpret this as being correct for 1 number, 2 off on another, and then 1 off for the rest, but you are indeed *technically* correct!
Comment: @AuraZz It is the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient). Also, you seem to be ignoring order for the lottery tickets. If buy a ticket labeled (1,2,3,4,5), and the numbers drawn are (4,5,1,2,3), then you would win nothing in a typical lottery.
Comment: @AuraZz Wow, the powerball in the US also does not care about order (except for the sixth ball), so I was mistaken. In that case, whoever commented that being off by one has the same probability is just plain wrong!
Comment: "Whoever commented" - Haha! Thank you for your answers, really helpful.


Recommended modules for managing Content access?

Question: I am looking for an access module.
Probably, the most popular is the Content Access module. But what modules are exist for that as well?
Also, when it says I have to rebuild the links (or permission, I don't remember) right after installation, what exactly does it do?
Answer: Recommended modules
Here is what I consider as the "shortlist" for such modules (quotes are from their project pages):

Content Access.

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Taxonomy Access Control:

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

Simple Access (RC4 version only for D7):

This module allows administrators to make some nodes private and/or editable by certain user roles. It can manage viewability, editability, and/or deletability and provides an easy way to make nodes accessible by only a group (or groups) of users. It is perfectly suited for making private nodes that are only viewable to certain 'access groups'.
Access groups are based on roles. So for example, my site has roles entitled "Coach Level 1", "Coach Level 2", and "Coach Level 3". I can create an access group called "Coaches" and assign all of these roles to it. Then when I assign a node to be viewable only by "Coaches", only users who are a member of these roles will be able to view.
Nodes that are not assigned to any access groups will remain viewable by all users, so all nodes will remain viewable when activating this module. And nodes only become private when they are assigned to an access group. The end result is that this module can be enabled for a site with existing nodes without making them all invisible.

Special case: Organic Groups, which provides 'Groups' for Drupal users, and management of Access Control based on these groups. A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.
My "recommended" module is Content Access ... Also because of al sorts of integrations with the Rules module.
For more details, refer to Access Control modules.
Rebuilding permissions
About "Rebuild permissions": any time the "Access" rules are changed (via admin settings), Drupal needs to ensure that these rules are applied to all impacted content (nodes). That's why Drupal then re-applies the updated access rules. A special case is the "installation" (actually "enable") of a module, when rebuilding permissions is also required. Makes sense? Clear enough?


How To Change The $tid to $term_name

Question: I've tried to change this code to show the term name instead of the term ID
but now no term name or term id show at all
Orginal code for term ID
function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }   } }

What I changed it too
function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $term_name = $info['term_name'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
        }
      }   } }

Many thanks for your help
Comment: possible duplicate of [Get/modify taxonomy term info in node edit form field?](http://drupal.stackexchange.com/questions/28177/get-modify-taxonomy-term-info-in-node-edit-form-field)
Answer: To convert from $tid to term name, use  taxonomy_term_load() to load the object, and then access $term->name:
$term = taxonomy_term_load($tid);
$term_name = $term->name;

Your function should look like:
function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
      foreach ($content['field_photo_topic']['#items'] as $index => $info) {
        $tid = $info['tid'];
        $term = taxonomy_term_load($tid);
        $term_name = $term->name;
        $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
      }
    }
  }
}

Please note that this will only work the way you intend if you use PathAlias or similar to alias the path to be accessible by  term name instead of numeric $tid.
Comment: Also, if your term names have capitals, spaces, or other characters that will make `photos/foo bar baz` "ugly", you may want to sanitize or otherwise clean it up.  If this is the case, I like to just use `pathauto_cleanstring()` from the pathauto module to do it.

How To Change The $tid to $term_name


Recurrence relations with factors in recurrence

Question: How would I go about approaching solving a recurrence relation such as:
$$a_{n}=2a_{\frac{n}{3}}+1$$
I'm just not sure how to get a general form for a non-recursive solution, can someone walk through the first couple steps?
Comment: is $n\in\mathbb{Z^+}$?
Comment: Oh yeah $n \in \mathbb{Z}$ and is a power of 3.
Comment: Let $b(n) = a(3^n)$, and close $b$.
Answer: Method 1: Exploit the relationship between recurrences and summations
$$ a(3^0)=\phi $$
$$ a(3^k)=2a\left(3^{k-1}\right)+1 $$
$$\mbox{for}\ k\geq 1 $$
Let's multiply both sides by the summation factor of $\frac{1}{2^k}$
$$ \frac{a(3^0)}{2^0}=\frac{\phi}{2^0}=\phi $$
$$ \frac{a(3^k)}{2^k}=\frac{2a\left(3^{k-1}\right)}{2^k}+\frac{1}{2^k} = \frac{a\left(3^{k-1}\right)}{2^{k-1}}+\frac{1}{2^k} $$
Let $s(k)=\frac{a(3^k)}{2^k}$, then
$$ s(0) = \phi $$
$$ s(k) = s(k-1) + \frac{1}{2^k} $$
Therefore
$$ s(k)= \phi+\sum_{j=1}^{k}\frac{1}{2^j} = \phi + 1 - \frac{1}{2^k}$$
And
$$ a(3^k) = 2^ks(k)=2^k\left(\phi + 1 - \frac{1}{2^k}\right) = 2^k\left(\phi+1\right)-1$$
Method 2: Generalize the recurrence and use the repertoire method
$$ a(3^0)=\phi $$
$$ a(3^k)=2a\left(3^{k-1}\right)+1 $$
$$\mbox{for}\ k\geq 1 $$
This is just a special case of the generalized recurrence
$$ a(1)=a(3^0)=\phi $$
$$ a(n)=a(3^k)=2a\left(3^{k-1}\right)+\beta$$ $$\mbox{for}\ k\geq 1 $$
Also note that we can redefine $a(n)$ as a linear combination of unknown functions and their corresponding coefficients
$$ a(n)=A(n)\phi+B(n)\beta $$
Let's begin by studying the output of $a(n)$
$$ a(3^0)=\phi $$
$$ a(3^1)=2\phi+\beta $$
$$ a(3^2)=4\phi+3\beta $$
$$ a(3^3)=8\phi+7\beta $$
$$ a(3^4)=16\phi +15\beta$$
$$ a(3^5)=32\phi+31\beta $$
The obvious guess for $A(n)$ is $2^k$. So now let's find $A(n)$ via the repertoire method
$$\mbox{Let}\ a(n)=a(3^k)=2^k, \mbox{then} $$
$$ a(1)=a(3^0)=2^0=1=\phi  $$
$$ a(n)=a(3^k)= 2a\left(3^{k-1}\right) +\beta$$
$$2^k=2\cdot 2^{k-1}+\beta$$
$$2^k=2^k+\beta$$
Which implies that
$$\phi=1, \beta=0$$
Now let's apply these facts to the general equation
$$ a(n)=A(n)\phi+B(n)\beta $$
$$ 2^k=A(n)\cdot 1+B(n)\cdot 0 $$
$$ 2^k=A(n)+0 $$
$$A(n)=2^k$$
Now let's find $B(n)$ also via the repertoire method
$$\mbox{Let}\ a(n)=a(3^k)=2^k-1, \mbox{then} $$
$$ a(1)=a(3^0)=2^0-1=0=\phi  $$
$$ a(n)=a(3^k)= 2a\left(3^{k-1}\right) +\beta$$
$$2^k-1=2\left(2^{k-1}-1\right)+\beta$$
$$2^k-1=2^k-2+\beta$$
$$2-1=\beta$$
Which implies that
$$\phi=0, \beta=1$$
Now let's apply these facts to the general equation
$$ a(n)=A(n)\phi+B(n)\beta $$
$$ 2^k-1=A(n)\cdot 0+B(n)\cdot 1 $$
$$ 2^k-1=0+B(n) $$
$$B(n)=2^k-1$$
So now we have
$$ a(n)=A(n)\phi+B(n)\beta $$
$$ a(n)=2^k\phi+\left(2^k-1\right)\beta $$
$$ a(n)=2^k\phi+2^k\beta-\beta $$
Therefore, the closed form solution to the general recurrence is
$$ a(n)=a(3^k)=2^k\left(\phi+\beta\right)-\beta $$
Note that for your specific recurrence, $\beta=1$. So the closed form solution to your specific recurrence is
$$ a(n)=a(3^k)=2^k\left(\phi+1\right)-1 $$
Answer: If I've understood this correctly, $n=3^k,k\in\mathbb{Z^+}$. A good method that I found in Concrete Mathematics - A Foundation for Computer Science is called the repertoire method (please correct me, but this is the way I understood it.) So, the idea is simply to try to break the recurrence into smaller ones, and hopefully, the smaller ones will have a recognizable pattern.
In your case, let's assume that $a_1=\alpha$. So, the idea is simply to evaluate this several times, as shown below:
$$\begin{array}{l}
{a_1} = \alpha \\
{a_3} = 2{a_1} + 1 = 2\alpha  + 1\\
{a_9} = 2(2\alpha  + 1) + 1 = 4\alpha  + 3\\
{a_{27}} = 2(4\alpha  + 3) + 1 = 8\alpha  + 7\\
{a_{81}} = 2(8\alpha  + 7) + 1 = 16\alpha  + 15
\end{array}$$
As you can see, there is a pattern. The initial parameter $\alpha$ has the coefficient that is equal to the power of $3$ squared, i.e. for $a_{81}$, it's $81=3^4$, so $4^2=16$. The constant term is simply one less than the coefficient.
Edit
Here's how it would be expressed:
$$\begin{array}{l}
{a_1} = \alpha \\
{a_{{3^k}}} = {k^2}\alpha  + ({k^2} - 1)
\end{array}$$
Answer: Just use the change of variables $n = 3^k$ and $b_k = a_{3^k}$ to get:
$$
b_k = 2 b_{k - 1} + 1
$$
Solve this one, and express in terms of the original variables.


behaviours.js syntax (Leaflet Map)

Question: An answer is given here to a problem concerning Leaflet Maps
My question: How would I adapt this code (yellow border here) to the syntax of my-theme/my-theme.behaviours.js ?
I think it would begin:
<code>(function($) {
Drupal.behaviors.any_name_here = {
</code>
or maybe
<code>Drupal.behaviors.some_name_here = {
attach: function() {
</code>
Answer: This should do the trick:
<code>(function($) {
    Drupal.behaviors.leafletMap = {
        attach: function(context, settings) {

            $('body').once(function(){
                $(this).on('shown','#link3', function() {
                    L.Util.requestAnimFrame(map.invalidateSize,map,!1,map._container);
                });

            });

        }
    };

})(jQuery);
</code>
I've used .once() as you only want to bind this behavior once and the attach function will run on page load and every subsequent ajax request.
I found this blog post very useful on Drupal behaviors.
Comment: cool answer :). It cleared my concept much better Thanks.
Comment: @Felix Eve ok thanks - maybe this is a different issue but your behaviors.js seems to interfere with my jQuery UI tabs - Garland theme, no behaviors.js = http://tinyurl.com/k9n9y5p - omega theme with behaviors.js = http://tinyurl.com/k8egc3j

behaviours.js syntax (Leaflet Map)


Variável global não muda o valor

Question: Eu sou um iniciante e não sei porque esse código não funciona.
Alguém pode me dizer porquê?
def teste():
    global res1
    res1 = input().strip()

if res1 == '1':
    print('funciona')

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: O maior motivo é que você declarou a função mas não a chamou, então ela não é executada e nada acontece. Assim funciona:
def teste():
    global res1
    res1 = input().strip()

teste()
if res1 == '1':
    print('funciona')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Não garanto que a entrada de dados possa estar causando algum outro problema também.
Mas vou te dar algumas dicas para produzir códigos melhores.
A primeira dica é não usar global até dominar todo o resto da programação e estruturas de Python. Isso é problemático e útil em raros casos. Precisa de bastante experiência para fazer certo. Funciona nesse caso simples, mas vai te ensinar errado. Aprenda usar funções do jeito correto, passando argumentos e recebendo dados como retorno.
Dê nomes significativos para funções e variáveis, assim o código fica mais explicativo.
Só use uma função se ela for realmente necessária. Em um código assim não é. Se quer aprender usar função procure um problema que precise de uma função. Não que não possa usar, mas de qualquer forma se é para usar então use do jeito certo.
Para um primeiro exemplo pode até fazer simples, mas qualquer dados digitado deveria ser validado. E não sei para que esse strip(), ele só complica o que está fazendo e não parece ter muito motivo. Se tiver algum motivo, tente fazer de outra forma, isso tem mais chance de dar errado. Não estou falando para validar agora, até porque não causará um problema tão grande, mas em casos reais precisará fazer isso. E justamente por ser simples demais não faz sentido esse strip().
Assim fica melhor, embora não perfeito:
def pede_dados():
    return input()

if pede_dados() == '1':
    print('funciona')

Melhor ainda:
if input() == '1':
    print('funciona')

Variável global não muda o valor


Variables into array - $array[$var_name] = $var;

Question: I was wondering whether something like this is possible:
$var1 = 1; $var2 = 2;
function varsToArray($param1, $param2...);

and it returns array like this
array([var1] => 1, [var2] => 2).

Simply saying, I'd like arrays keys to be same as variable names. The problem is I don't know how to get variable name as string to put it as key(if possible of course...).
Comment: possible duplicate of [Create array names based on variable value](http://stackoverflow.com/questions/6000147/create-array-names-based-on-variable-value) ... please use the search before you ask a question.
Comment: Well, since that's not valid PHP syntax it's obviously not possible to ascertain what you mean by it. Describe your goal.
Comment: @Felix Kling, nah, no exactly the same problem it seems
Comment: Then you did not describe your problem properly... the accepted answer puts the **parameter** names in the array, not the **variable** names, and I wonder why one would use reflection in this case.
Comment: Nope, I meant varaibles. Noticed after a while that Yoshi's solutions puts parameters names as keys, not varaibles names. Sry, my fault. The example i gave is bad, I'll change it
Answer: You want to use the compact function methinks.
Comment: compact works when you pass variables names as strings so compact("var1", "var2"); I wish to pass just as compact($var1, $var2). In this case @Yoshi's solution works fine:D
Comment: @f1ames: It works because the function's parameters are called `$var1` and `$var2`. If you call `foo($bar, $baz)`, the output will still contain `var1`, `var2`. I think passing the variable names as string is the only useful solution.
Answer: The built-in PHP function compact() does this.
BTW: I'm going to go ahead and assume that instead of:
function $varsToArray($var1, $var2...);

you actually meant:
function varsToArray($var1, $var2...);

Notice the dollar sign has been removed.


Pointers about the concept of 'division extensionality'?

Question: When working a bit on another question (If $a \equiv b\pmod m$, then $\gcd(a, m) = \gcd(b, m)$), I discovered the following, which seems to be valid:
$$
a = b \;\;\equiv\;\; \langle \forall d :: d \mid a \;\equiv\; d \mid b \rangle
$$
(Note that all variables denote natural numbers.)
I have not seen this concept before, and tentatively call it division extensionality: two natural numbers are the same iff they have the same divisors.  I did not succeed in proving this.  How should I go about that proof (or is the above just not true)?  And what is the usual name for this concept?
Also, very likely there is some more general concept of extensionality, which also covers set extensionality.  Any pointers?
Finally, I found that (if the above is true) also the following holds:
$$
a = b \pmod m \;\;\Rightarrow\;\; \langle \forall d : d \mid m : d \mid a \;\equiv\; d \mid b \rangle
$$
The structure of this looks a lot like the first one.  How does this fit in?  Is there a concept of division extensionality modulo $m$?
Thanks!
Answer: To prove this analogue of the Axiom of Extensionality for divisibility, just note that if $a$ and $b$ have the same divisors then because every number divides itself we have $a \mid b$ and $b \mid a$, which can only happen if $a=b$.
I don't know if this fact has a name.
I'm not sure that there is going to be a common generalization of this notion and the Axiom of Extensionality (besides the notion of an extensional relation, which it seems like you have already discovered.)  After all, set membership is only extensional because we say it is—there are alternative set theories where Extensionality is false.


Subclassing a subclass of UIImageView - Forward declaration errors

Question: I have read question after question about people getting the same error as me, but I simply do not understand them, so before you go searching for duplicate questions, maybe someone can explain to me what I am doing wrong with this subclassing deal.
I have a subclass of UIImageView called swapView that I want to subclass to override the method -(void)count for special cases. I went to subclass this as I have any pre-existing UIKit class, but when I tried to build and run the project, I get this error:
Attempting to use the forward class 'swapView' as superclass of 'coinView'

I have tried putting both the #import statement of swapView and @class swapView in coinView.h and I've tried putting the import statement in coinView.m, but it refuses to build because of this continued error. If I move the import statement into the .m file, all references to the superclass's methods and properties, such as @property (nonatomic) int max; cause errors as well.
What am I doing wrong?
swapView.h
#import <UIKit/UIKit.h>

#import "ViewController.h"

@class ViewController;

@interface swapView : UIImageView
{
    NSTimer* tmr;
}

@property (nonatomic) int current;
@property (nonatomic) int max;
@property (nonatomic, retain) UIImage* firstImage;
@property (nonatomic, retain) UIImage* secondImage;
@property (nonatomic) BOOL smallMax;

@property (nonatomic, retain) ViewController* pvc;

- (BOOL)testCollision:(CGPoint)point;
- (float)randomFloatBetween:(float)smallNumber bigNumber:(float)bigNumber;

@end

coinView.h
#import "swapView.h"

@class swapView;

@interface coinView : swapView

- (void)count;
- (void)move;

@end

Comment: How about remove @class swapView; in coinView.h?
Comment: Causes `Cannot find interface declaration for 'swapView', superclass of 'coinView'`
Comment: Are you sure you spelled everything correctly? I get no errors with your code if I import swapView.h (rather than using @class) into the coinView.h file. BTW, you should capitalize the names of your classes.
Comment: I don't know what you're doing wrong, but you should never have both `#import xxx.h` and `@class Xxx`! The whole purpose of `@class Xxx` is to say, "Trust me, Xxx is a class, but you don't need to know the details." If you `#import xxx.h`, where Xxx is declared as a class, then we know it's a class and we know the details.
Comment: @rdelmar Yes I've spelled everything correctly. I've been able to get it to compile using tw_airball's method; I don't know why...and as for my capitalization, I learned to make classes the user interacts with capitalized and supporting classes lowercase on the first letter like method names, but IDK maybe my teacher was wrong.
Comment: the caps thing is just convention. makes it easier to read. The error was likely caused by `swapView.h` and not `coinView.h` -- the superclass was also both forward declaring and importing `ViewController.h`
Answer: For inheritance, the superclass MUST be inherited.
coinView.h
#import "swapView.h"
@interface coinView : swapView
  - (void)count;
  - (void)move;
@end

You're both forward declaring and importing ViewController.h in your swapView, which may cause compiler to complain.
swapView.h
#import <UIKit/UIKit.h>

@class ViewController

@interface swapView : UIImageView
.
.
.
@end


Calcular troco entre textbox?

Question: Boa noite , tenho 3 textbox, e gostaria que alguem disponibilizasse um codigo para me ajudar, quando seleciono o produto no grid o valor total é adicionado no textbox1, e assim por diante , quanto mais eu adicionar produtos , mais ele soma, pois bem ... gostaria de um codigo que ao digitar o valor recebido no textbox2 , ja aparecesse o troco no textbox3, nao sei se eu teria que usar um keypress ou algo do tipo, por isso preciso de ajuda.
Comment: Não é so pegar o valor do textbox `Valor total` e diminuir do textbox do `valor recebido` e jogar no textbox `Troco`? Pode usar o evento `TextChanged` para realizar o calculo toda vez que o usuário alterar o valor, ou o evento `KeyDown`, tipo o usuário pressiona `enter` e realiza o calculo. ou pode fazer quando ele perde o foco do `textbox` realizar o calculo.
Comment: Sim, mas vc poderia me passar o codigo ? Sou novato em c# teria que ser mais claro para que eu entenda, se puder postar um codigo eu agraceria .
Comment: Gostei do evento keydown, como posso faze-lo ?
Comment: De uma lida neste [link](https://msdn.microsoft.com/pt-br/library/windows/apps/xaml/hh465336.aspx) na parte onde diz criando um manipulador de eventos.
Answer: Um exemplo amigo, seria assim:
<code>using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                MessageBox.Show("Enter key pressed");
            }
        }
    }
}
</code>
Lembre-se, existe sempre a documentação oficial para ser consultada:
https://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.onkeydown(v=vs.95).aspx
Comment: Ok, este evento eu faço no textbox valor pago, mas eu nao preciso do codigo da subtração dos valores ? infelismente tbm nao sei , poderia me ajudar ?
Comment: Obrigado Danilo , consegui com seu código! abraço
Comment: Obrigado Meu Chapeu , me ajudou muito também! abraço

Calcular troco entre textbox?


Como calcular a distancia entre X e Y com pontos de Interseção

Question:
Na imagem a cima eu tenho mapeada as posições de separação dentro do armazém onde eu trabalho.
Eu preciso calcular a distancia que a pessoa que esta separando percorre dentro do armazém.
Por exemplo se a pessoa esta separando na posição 1AF-001-10  e se desloca ate a posição 1AD-013-10 se eu calcular apenas X e Y ele vai calcular em linha reta porem vai estar errado eu preciso que ele passe pelos pontos de interseção ai esta o problema.
não sei como vou fazer para ele entender quais pontos ele precisa pegar para calcular a rota certa quando ele sai das ruas que ele estava searando.
eu coloquei os pontos de interseção que seriam essas ligações... e da certinho
só não consegui raciocinar como eu faço para ele entender quais pontos ele precisa pegar.
Por exemplo nesse caso a cima ele deveria calcular da seguinte maneira:
<code>    De           Para
1AF-001-10 || 1AD-013-10 = soma(valor1,valor2,valor3)
</code>
Ou seja :
<code>   De            Para
1AF-001-10  || interseçãoE = valor1

    De            Para
interseçãoE || interseçãoD = valor2

    De            Para
interseçãoD || 1AD-013-10 = valor3
</code>
Answer: Uma resposta breve que vai exigir certa pesquisa por parte do AP.
Modele seu problema como um grafo e aplique o algoritmo A*. Os nós dos seu grafo são suas posições (1AF...). Cada aresta do seu grafo é a ligação existente entre duas localizações. Se não existir ligação, significa que a posição X não é conectada com a posição Y. A aresta carregará também a informação da distância entre cada nó.
No momento que você tiver esse grafo montado, basta implementar um algoritmo de menor caminho (indiquei o A*, mas pode ser o Dijkstra puro) e passar o nó inicial e final como parâmetros. O algoritmo devolverá o menor caminho entre duas localizações, passando por todas as posições intermediárias.
Como eu disse, vai exigir um esforço de pesquisa inicial, mas tem tanto exemplo de grafo na Internet e tanto tutorial que valerá a pena, pois resolverá o problem em definitivo.
Comment: O colega cantoni tem toda a razão. Se você tem os De-Para individuais e a distância entre cada um, você consegue pegar os dados e construir tal programa. Infelizmente, vai precisar estudar um pouco as referências que ele passou. Mas um problema que você certamente vai ter é que fazer esse cálculo a cada consulta pode se tornar computacionalmente inviável (principalmente se ocorrem muitas consultas). Supondo que as localidades não mudem (porque são fixas no armazém), o ideal seria você pré-calcular as rotas possíveis e armazená-las em uma outra tabela. Aí a sua consulta fica trivial. :)
Comment: Olá, bom dia... primeiramente obrigado pela resposta, o problema é que não tenho acesso a todas ferramentas em nosso banco e tem coisas como esse que vc sugerio queeu nao tenho acesso a fazer, só conseigo fazer select e algumas funções isso dificulta bastante
Comment: Se você tem acesso ao banco para dar select, nada impede você de criar um pequeno programa que consulta esse banco, cria o grafo e aplica o algoritmo.
Comment: Poxa agora me senti um burro com vocês falando que é fácil kkkkk. Vou começar a pesquisar por que sou iniciante em sql. mas muito obrigado pelas dicas, vou ver o que eu consigo fazer
Comment: @ArielGonçalves, seu desafio não vai ser no SQL, mas em programar isso em alguma linguagem. Existe muito suporte na Internet. Quando eu disse que não é complicado, é do meu ponto de vista. Entendo completamente a sua dificuldade, mas posso afirmar que se você persistir, você conseguirá exatamente o que quer e com várias coisas a mais que você vai pensando no meio do caminho. Se você gosta de algoritmos, é um ótimo caminho a trilhar. Uma dica: Já existem frameworks e bibliotecas prontas de grafo. Monte o grafo com informacoes do banco de dados e escolha o algoritmo.


How do I write a C header file that can be used in C++ programs?

Question:
Possible Duplicate:
How to check (via the preprocessor) if a C source file is being compiled as C++ code

I'm trying to find a standard macro which will test whether a header file is being compiled as C or as C++. The purpose of this is that the header may be included by either C or C++ code, and must behave slightly differently depending on which. Specifically:
In C, I need this to be the code:
extern size_t insert (const char*);

In C++, I need this to be the code:
extern "C" size_t insert (const char*);

Additionally, is there a way to avoid putting #ifdef's around every declaration in the header?
Comment: I may be biased, but I would argue that this question additionally has to do with extern. Since I had not known about the "extern { ... }" syntax previously, my selected answer is much more helpful than the one given in your proposed duplicate. I will edit the question to show this difference.
Comment: I've left an x-ref to this question on the proposed duplicate.  You could improve the distinction between the two by a revised title such as 'How to conditionally define `extern "C"` or just `extern` auto-detecting the C or C++ compiler?" or something along those general lines.
Comment: @JonathanLeffler I've edited the title to reflect what (I think) is really being asked, as illustrated by the example in the text. ... searching for this did, however, reveal a duplicate title: http://stackoverflow.com/questions/8742534/including-c-header-in-c-file ... but not duplicate content.
Comment: @JonathanLeffler I also found http://stackoverflow.com/questions/11712707/extern-functions-in-c-vs-c in which you gave a lengthy answer that covers the question here, under "Issue 2: Inter-working between C and C++".
Answer: It is normal to bracket C header files as follows so they can be used in C++ programs. Check your system header files such as stdio.h and you will probably see this:
#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

Answer: The answer is to use the macro __cplusplus. In this instance, the most straightforward approach is:
extern
#ifdef __cplusplus
"C"
#endif
size_t insert (const char*);

This macro is part of the C++ standard.
Comment: And if you want to do this for multiple functions, the norm is `#ifdef __cplusplus extern "C" { #endif` ... `#ifdef __cplusplus } #endif`.
Comment: Another possibility: `#ifdef __cplusplus` ... `#define EXTERN extern "C"` ... `#else` ... `#define EXTERN extern` ... `#endif` (where ... denotes a newline)
Comment: g++ does not like

#define EXTERN extern "C"

it wines so:

error: expected unqualified-id before string constant
Answer: You might find it reasonable to define three macros to help with this:
#ifdef __cplusplus
#define EXTERN_C_BEGIN extern "C" {
#define EXTERN_C_END   }
#define EXTERN_C       extern "C"
#else
#define EXTERN_C_BEGIN /* Nothing */
#define EXTERN_C_END   /* Nothing */
#define EXTERN_C       extern /* Or Nothing */
#endif /* __cplusplus */

This would be most useful in a standard header that's included in most places in your project.  For a single function, you might write:
EXTERN_C size_t insert(const char *name);

For a group of functions, you might write:
EXTERN_C_BEGIN

size_t other_insert(const char *name);
size_t other_delete(const char *name);
size_t other_update(const char *old_name, const char *new_name);

EXTERN_C_END

It is permissible to include extern in front of the individual functions inside the EXTERN_C_BEGIN to EXTERN_C_END block.


Problem that involves partial derivative of temperature function

Question: A circular piece of metal with radius $a$ has the temperature given by the following relation: for a point $(x,y)$, the temperature $T(x,y)$ is proportional to the square of the distance of this point $(x,y)$ to the center of the piece of metal, with constant of proportionality $k>0$.
So the exercise asks the following:
a) If a particle at $(\frac{a}{2},0)$ moves to the rigth about the $x$ axis, it'll suffer temperature increase or decrease?
b) What's the rate of change in respect to $y$ at the same point? What does that mean?
Here's what I did:
a)
$$T(x,y) = k\sqrt{x^2+y^2}\implies \frac{\partial T(x,y)}{\partial x} = \frac{kx}{\sqrt{x^2+y^2}} \implies \\  \frac{\partial T(\frac{a}{2},0)}{\partial x} = \frac{k\frac{a}{2}}{\sqrt{\frac{a}{2}}^2} = k > 0$$
therefore, there is a temperature increase
b) if I do the same for $y$, we have:
$$\frac{\partial T(\frac{a}{2},0)}{\partial x} = \frac{2y}{\sqrt{x^2+y^2}} = 0$$
therefore, there is no increase or decrease in temperature in the $y$ axis for that contains this point
Am I rigth?
Answer: I think it is easier since the square of the distance is just $x^2+y^2$.
Indeed $$\frac{\partial T}{\partial y }=2k y~~,$$ therefore in $(a/2,0)$ the rate of change of $T$ along $y$ is zero. This is because this point locally minimizes $T$ respect to displacements in the $y$ direction.
Comment: So the derivative with respect to $x$ at $(a/2,0)$ is $ak>0$?
Comment: but the question is what is the rate of change in respect to y. for me that is the partial derivative respect to y. that was what you calculated, despite you wrote $\partial/\partial x$ though...
Comment: but there are two questions, a) and b)
Comment: a) is correct,  despite you used a more complicated function than necessary I think.


How to precompile a ColdFusion application under Websphere/Solaris 10

Question: I am in the process of installing a ColdFusion application on Solaris 10 64-bit (Sparc) running with WebSphere 6.1. The cfcompile script that comes with CF makes a reference to jrun.jar however this library is not available when CF is installed as an ear file. An abstract of cfcompile.sh is the following:
<code>su $cfuser -c "${_JAVACMD} -cp $CLASSES -Dcoldfusion.classPath=$CFUSION_HOME/lib/updates,$CFUSION_HOME/lib -Dcoldfusion.libPath=$CFUSION_HOME/lib coldfusion.tools.CommandLineInvoker Compiler -cfroot $CFUSION_HOME -webinf $WEBINF -webroot $webroot $dir"
</code>
Do you see ways to solve this problem (that is to precompile an application), besides installing CF as a standalone running on JRUN server?
Answer: Have you checked the contents of the EAR file?  There should be a WAR file, in which you'll find WEB-INF/lib.  It may be in there.  If so, extract it and place it on the classpath.
EAR/WAR file are just zip compressed archives.
This is just a "best guess" on my part.
HTH
Comment: Hi! That is exactly what I did but in the exploded version there is no jrun.jar. This file is available only when you install CF as a standalone version. I simply want to have a sourceless and precompiled deployment option but till now I do not see it possible without JRUN.
Answer: Can you install in stand-alone mode on some other temporary location (preferably the same OS & version), and copy jrun.jar to where you want it to be, on the permanent home of the application?
Answer: I created my own version of cfcompile.sh on-site to work on the client's infrastructure. The most important part is to have a correct reference to j2ee.jar (found in WAS distribution).


How to change the url the core search form submits to?

Question: The action value for the core search form is /search/node.
How could I get it to go instead to a different url for a custom View?
Answer: You can use hook_form_alter or hook_form_FORM_ID_alter to alter a form.
Core's search block form has a form id of search_block_form, so you could implement with hook_form_FORM_ID_alter() like:
<code>use Drupal\Core\Form\FormStateInterface;

function mymodule_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['#action'] = '/my-custom-path';
}
</code>
Comment: Alternatively, you may want to create a custom block with a simple form to submit to your other url.
Comment: Thanks so much @sonfd. That's a great help.
Comment: Further question: do you happen to know how I can pass a search word in the url to an exposed filter in a view? I looked for an answer but could not find one. I am trying to use a Search API view with exposed filter for search term, as the search results page.
Comment: @EdwardPeters - This is a totally different question. You should ask a new one.
Answer: if you don't want to do it with code you can use Custom Searchit gives you the possibility to configure it from configuration page:
For node search you can change it from admin/config/search/pages/manage/node_search


PhoneGap + Childbrowser + Error

Question: I am trying to use the Childbrowser plugin in my application. My code is as follows:
ChildBrowser.prototype.showWebPage = function(url, options) {
    options = options || {
        showLocationBar: true,
        locationBarAlign: "top"
    };
    //Code Runs up to this point
    cordova.exec(this._onEvent, this._onError, "ChildBrowser", "showWebPage", [url, options]);
};

The last line of the code does nothing. It's not giving any errors, but the webpage is not shown. I am using Android 2.3.
Comment: Same here. It does work just fine under 4.x though.
Answer: You seem to be defining this wrongly, I think it should look like this:
var url = "http://www.google.com";

window.plugins.childBrowser.showWebPage( url, {showLocationBar: true});// This opens the webpage.

I do not quite get why you have used the ChildBrowser.prototype.showWebPage

PhoneGap + Childbrowser + Error


COM: calling from other thread causes crashes, how to make it run on the same thread?

Question: I am doing a BHO (extension for IE) that receives events on other thread. When I access the DOM from that other thread, IE crashes. Is it possible to make the DOM accessed from the same thread as the main BHO thread so that it does not crash?
It seems like a general COM multithreading problem, which I don't understand much.
Answer: Look into using CoMarshalInterface or CoMarshalInterThreadInterfaceInStream
These will give you a wrapped interface to an STA COM object that is thread safe.
Comment: That does it! Thank you so much!

So in the main thread, call CoMarshalInterThreadInterfaceInStream, pass the stream pointer to the secondary thread, and on the secondary thread call CoGetInterfaceAndReleaseStream to get a *proxy* to the object to be called.
Answer: I don't know much about IE extensions, but it sounds like some COM object needs to be marked a Single Threaded Apartment, so that the COM runtime system ensures that it is run on the same thread which called it initially. If you can't alter the other object, you could probably route your calls to the DOM through a separate COM object marked as STA to achieve the same effect. Hope this helps... I know a bit about COM multithreading, but not much about IE extensions.
Answer: ah, fun fun fun multithreading with COM.
Gerald's answer looks right if you want to transfer an interface pointer from one thread to another exactly once. I've found that the GIT (global interface table) is a big help for this kind of thing if you're in a multithreaded system... basically you don't keep around interface pointers but rather DWORD cookies used by the GIT to get an appropriately-marshaled interface pointer for whatever thread you are using it. (you have to register the object in question with the GIT first, and unregister it later when you are done or your object is finished)
Answer: Be careful though.  Performance can become a serious issue.
If you're just playing around to learn about BHOs, you can use the STA to make your ::SetSite() implementing object operate as if it were single threaded (this allows you to let other threads pull your BHO's pointer out of the GlobalInterfaceTable as @JasonS mentions.
If you're doing something that is expected to be part of a product I highly recommend you very carefully reconsider going MTA everywhere you can and handling the concurrency and thread safety issues yourself.  In this case you would only need to ensure that the threads inter-operating with your BHO COM object, were themselves, initialized for COM.
For example, if you want to monitor incoming/outgoing data of website looking for things (either dangerous or sensitive) - then you do NOT want to force all of those threads down the throat of an STA object because, using Yahoo as an example, more than 30 requests will launch and your BHO will start locking up IE.


Does $\sum \frac{n^2 + 1}{n^{3.5} -2}$ converge?

Question: Does $\sum \frac{n^2 + 1}{n^{3.5} -2}$ converge? I think it does. But I cannot find a series to compare. I tried to compare it with $\sum \frac{1}{n^{1.5}}$, but I do not know how.
$$\sum \frac{n^2 + 1}{n^{3.5} -2}?\sum\frac{n^2}{n^{3.5}-2}?\sum\frac{n^2}{n^{3.5}}$$
Comment: Can you prove the general term is less than $\frac{7892}{n\sqrt{n}}$, for any $n\geq 10^{4875}$?
Comment: You could also use the Limit Comparison Test.
Comment: The general term behaves like $\frac{1}{n\sqrt{n}}$ and $\sum_{n\geq 1}\frac{1}{n\sqrt{n}}$ is converging.
Comment: Compare with $\frac{1}{n^{1.5}}$
Comment: @JackD'Aurizio I understand. But I cannot derive that my series is less than $\frac{1}{n^{1.5}}$.
Comment: It's less than $\sum \frac{n^2+1}{n^{3.5}}$ which is the same thing as $\sum \frac{1}{n^{1.5}}+\sum \frac{1}{n^{3.5}}$ which converges
Answer: Compare it to $\frac{2}{n^{1.5}}$. We know that for sufficiently large $n$:
$$n^{1.5} \le n^{3.5}-4$$
$$n^{3.5}+n^{1.5}\le2(n^{3.5}-2)$$
$$\frac{n^2+1}{n^{3.5}-2}\le\frac{2}{n^{1.5}}$$
Answer: We can use the limit comparison test with $b_n = 1/n^{1.5}$ The limit of $a_n/b_n = 1 < \infty,$ and $\sum b_n$ is a p series that converges, so $\sum a_n$ converges.
Answer: You can separate this out into two series, $\sum\frac{n^2}{n^{3.5}-2}+\sum\frac1{n^{3.5}-2}$. Then, you should be able to compare the two series with $\sum\frac1{n^{1.5}}$.
Answer: Beside the good and simple solutions you already received, setting $x=\frac 1 n$ and using Taylor series around $x=0$, you could show that $$\frac{n^2+1}{n^{7/2}-2}=x^{3/2}+x^{7/2}+2 x^5+2 x^7+4 x^{17/2}+O\left(x^{21/2}\right)$$ Back to $n$ $$\frac{n^2+1}{n^{7/2}-2}=\frac{1}{n^{3/2}}+\frac{1}{n^{7/2}}+\frac{2}{n^5}+\frac{2
   }{n^7}+
   \frac{4}{n^{17/2}}+O\left(\frac{1}{n^{21/2}}\right)$$ and then $$\sum_{n=2}^\infty\frac{n^2+1}{n^{7/2}-2}=-10+\zeta \left(\frac{3}{2}\right)+\zeta \left(\frac{7}{2}\right)+2 \zeta (5)+2 \zeta
   (7)+4 \zeta \left(\frac{17}{2}\right)+\cdots$$ which is $\approx 1.8411$ while the exact summation would lead to $\approx 1.8469$.
Using the ratio test and Taylor again, $$u_n=\frac{n^2+1}{n^{7/2}-2}\implies \frac{u_{n+1}}{u_n}=1-\frac{3}{2 n}+O\left(\frac{1}{n^2}\right)$$ which is inconclusive. But, using Raabe's test and Taylor again, $$n\left(\frac{u_n}{u_{n+1}}-1 \right)=\frac{3}{2}+\frac{3}{8 n}+O\left(\frac{1}{n^{3/2}}\right)$$ the limit is $>1$ then convergence.


Can no persist entity with lazy loading elements

Question: I have entities
<code>@Entity public class A implements Serializable {
    @OneToMany(mappedBy = "a", fetch = FetchType.LAZY)
    private List<B> bList;
}

@Entity public class B implements Serializable{
    @JoinColumn(name = "A_ID", referencedColumnName = "ID")
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private A a;

    @JoinColumn(name = "C_ID", referencedColumnName = "ID", nullable = false)
    @OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
    private C c;
}

@Entity public class C implements Serializable {
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "c", fetch = FetchType.EAGER)
    private B b;
}
</code>
if I  pass B entity to ejb method from remote client, then entity
passed to app server is NULL; If I change LAZY loading to EAGER, then every thing goes well.
I do not want to use EAGER loading, how to avoid EAGER loading?
Answer: The only way you can persist instance of B type, received from remote client is restore state of its children from old copy and then persist.
<code>public B updateFromRemote(B b) {
   B oldCopy = bDao.findBById(b.getId());
   b.setA(oldCopy.getA());
   b.setC(oldCopy.getC());
   return bDao.save(b);
}
</code>
Comment: from remote client I pass new instance of B. B newb=new B();  newb.set(new C(...)); newb.set(oldA);  and after pass newB to server.
Comment: To make it clear, when you initialize instance of B remotely and then pass it to server, the b.getC() equals null?
Comment: yes.  after initializing of B on client side and passing it to server side, B  instance passed to server is NULL. JPA provaider is eclipselink and app server gf 3.
Comment: Sounds like you have to check object serialization graph and find place where your remotely initialized instance of class B gets turned to NULL. I'd like to help further but I'm not familiar with neither EcliplseLink nor GF3.
Comment: thanks !  how to check object serialization?  I create test case and check entity data before passing to remote ejb method and after that check Entity instance on server, but passed Entity is null. how to monitor object serialization process?


finding the prior predictive distribution

Question: I have that Y ~ Bernouill(Pi) and Pi~Beta(a,b), find the prior predictive distribution.
I know the pmf of Y is Pi^Y(1-Pi)^1-Y
And the pdf of Pi is Pi^(Y+a-1)(1-Pi)^(b-Y)
I then multiplied these together and put the product in an intgral over 0,1 but now I am stuck...
Thanks
Answer: Basic fact: For every positive $u$ and $v$, $\displaystyle\int\limits_0^1x^{u-1}(1-x)^{v-1}\,\mathrm dx=\frac{\Gamma(u)\Gamma(v)}{\Gamma(u+v)}$.
Thus the PDF of $\Pi$ is not what you wrote but a multiple of this, and, for every $y$ in $\{0,1\}$,
$$
L_{a,b}^y=\int_0^1f_{Y\mid\Pi}(y\mid x)\cdot f_\Pi(x)\,\mathrm dx=\int_0^1x^y(1-x)^{1-y}\cdot\frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}x^{a-1}(1-x)^{b-1}\,\mathrm dx,
$$
that is,
$$
L_{a,b}^y=\frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}\cdot\frac{\Gamma(a+y)\Gamma(b+1-y)}{\Gamma(a+b+1)}.
$$
In other words, $L_{a,b}^0=\dfrac{b}{a+b}$ and $L_{a,b}^1=\dfrac{a}{a+b}$.


How should my final regression model be if I have a categorical variable (2 categories) and 3 continuous variable?

Question: The final model needs to include all variables. I need to analyze the significance of their effects on the dependent variable and then see if there's any difference in effects of continuous variables between the two categories. Is my final model y~x1+x2+x3+x4?
Comment: Is this a question from a course or textbook? If so, please add the `[self-study]`
tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info). Also, please add some context regarding your situation, your data, and your goals.
Answer: Short answer: It depends on what notation are you using.
Longer answer:
Let's say you have a dummy variable Z1 for your categories, and 3 continuous variables X1, X3, X3.
If you build your model as Y ~ a0 +a1*Z1 + a2*X1 + a3*X2 + a4*X3 you will be able to estimate following thing: holding x1,2,3 fixed, group two will have, on average, values of Y higher by a1 compared to group one.
But you will not be able to judge the different impacts of X1, X2 and X3.
So what should you do?
You should include also multiplicative terms between Z1 and Xs!
Using Y ~ a0 + a1*Z1+a2*X1 + a3*X2 + a4*X3 + a5 * Z1* X1 + a6 * Z1 * X2 + a7 * Z1 *X3, you will be able to say, what happens to individual groups when variables X1,2,3 change. Note that a5, a6 and a7 will contribute to the Y only when the observation falls into category 2 (so that Z1 = 1).
Comment: The first paragraph of the Note in the documentation of aov tells you what I suspect is happening but really this is off-topic here as it is about programming rather than statistics.
Comment: I get the final model, but how do I use the lm() call for it?
Comment: Something like `fit <- lm(y~as.factor(z)*(x1+x2+x3))` will do the trick. You should also go through the documentation of lm function to learn more about it
Comment: It works well, but I find that when I move the order of the continuous variables, the values from summary(aov()) changes quite alot. Is this a sign of collinearity?


PHP - Short hand if statement with a date format with weird output

Question: I am using a short hand notation of an if statement to format a field. If the field is an empty string I leave it as an empty string, if not then I am trying to format it to a proper datetime format so it can be inserted into a mysql db. here is my php code
$date = ($date == '') ? date("Y-m-d", strtotime($date)) : $date;

for some reason when the $date string is not empty it is returning it int he format 'm/d/Y' example: 04/01/2010
When I pull the code out of the shorthand if
$date = date("Y-m-d", strtotime($date));
print($date);

it is formatted correctly like this 'Y-m-d' or 2010-04-01. Does anyone know why this happens? Thanks
Answer: I'm taking a bit of a stab in the dark here at what you were trying to accomplish, but you might have more luck with this:
$date = ($ts = strtotime($date)) ? date("Y-m-d", $ts) : '';

This will attempt to parse any incoming date string, and fail to an empty string if the date was unparsable.
Note that it's important to do a check on strtotime's ability to parse a date, because date("Y-m-d", strtotime($date)) will return a date somewhere around 1970 if $date doesn't contain a parsable date.
e.g.:
$ php -r 'var_dump(date("Y-m-d", strtotime("thisisnotadate")));'
string(10) "1970-01-01"
$ php -r 'var_dump(date("Y-m-d", strtotime("01/01/1901")));'
string(10) "1970-01-01"
$ php -r 'var_dump(date("Y-m-d", strtotime("01/01/2048")));'
string(10) "1970-01-01"
$

strtotime can only handle dates that fit in a 32 bit timestamp, which limits it to 1970 - 2038.  Additionally, some date formats may be ambiguous.
Answer: you confused the arguments of your ternary operator, just switch them, or change the equality operator to check for inequality:
$date = ($date !== '') ? date("Y-m-d", strtotime($date)) : $date;

Answer: In the case you describe, $date must have already been set elsewhere in the script using the m/d/Y notation. In that case, the ternary operator leves $date untouched.
When you get rid of the shorthand, that m/d/Y string is being forced into a timestamp by strtotime, and then into a proper Y-m-d string by date().
Comment: @McNabb the logic of your code is flawed. You are formatting the date *only if it is empty*. If `$date` is set, it will go unformatted.
Comment: nope it has not, I have check and it is defiantly happening in the shorthand if statement.
Comment: @McN can you show an example value of `$date` before this code is executed?
Comment: $date = '4/01/2010';

is what it prints out to be so I guess you are right, the input box is setting it to that, I guess the function is just not working for some reason when its inside the shorthand if.
Answer: Right now, your statement is:
If $date is an empty string, pass that empty string as a timestamp to the string to time function.  Pass that to the date function.  Otherwise return the contents of $date.
Perhaps you intend:
$date = ($date == '') ? date("Y-m-d") : $date;

Comment: @McNabb your code is doing the reverse right now. You need to turn them around.
Comment: My intention is that if it is an empty string then keep it an empty string, if not then formate it using strtotime then the date function. I would need the strtotime in there to properly format it for mysql
Answer: Seems to me you're doing something you don't need to (using ternary syntax).  From one of your comments My intention is that if it is an empty string then keep it an empty string, if not then formate it using strtotime then the date function. I would need the strtotime in there to properly format it for mysql
if($date != '')  // leave it alone if it is an empty string
{
    $date = date("Y-m-d", strtotime($date));
}

(Important note - I haven't touched PHP for years, so syntax may be off, but the principle is the same)


Reducing a string from a file, into a new file

Question: I want to make python make a new file from the file I already have, then reduce the letters from the first file and in the new file.
This is what i got so far, without any luck:
my_file = open("my_full.txt", "r")
my_file2 = open("my_partial.txt", "w")

for each_line in my_file:
    my_file2.write(len[0:2]+"\n")

my_file.close()
my_file2.close()

Example:
"This must be reduced"
"This is one as well"
"And the last one"
I now want python to open up the first one, and reduce the letters in the first file and make a new one, with the result.
so the new file python makes should contain for example:
"Thi"
"Thi"
"And"
Comment: When you say reduce, you mean just take the first 3 letters from each line?
Comment: Yes @PaulRooney , and putting the 3 letters in another file.
Answer: You almost have it!
Inside of your for loop, you need to change the write call to:
my_file2.write(each_line[:3] + '\n')

There are two problems with the line you currently have:

You're using len instead of the variable holding the current line of the file which is a function in python to determine the length of a given item (e.g. string, list, etc.)
You want the first 3 characters but are using the range of [0:2] which is ending exclusive so you will only get the first 2. That must be changed to [0:3].
Comment: Thank you so much! this helped! Oh, i totally forgot the 0:3 part , wops!
Comment: only very pedantic corner case would be if the line was less than 3 characters and the newline was included in the slice, then you append a second newline. Not a major consideration and I'm sure the OP doesn't care about that.


Finding a jordan basis for a jordan form

Question: Let $$A = \left(\begin{array}{cccc} 1&0&0&0\\3&-2&0&0\\14&0&-2&0\\8&-1&1&-2 \end{array}\right)$$
Easy to verify that $f_(x) = (x-1)(x+2)^3$. So the eigen-values are: $\lambda = 1,-2$. Some more calculations gives the result that the Jordan form is:
$$J = \left(\begin{array}{cccc} 1&0&0&0\\0&-2&0&0\\0&0&-2&0\\0&0&1&-2 \end{array}\right)$$
Now, I want to find $P$ such that $P^{-1}AP = J$. Meaning, we wish to find $AP = PJ$. More detailed. Let's denote $P=(v_1,v_2,v_3,v_4)$. Then,
$$Av_1 = v_1 \implies (A-I)v_1 = 0 \\ Av_2 = -2v_2 \implies (A+2I)v_2 = 0 \\ Av_3 = -2v_3 + v_4 \implies (A+2I)v_3 = v_4 \\ Av_4 = -2v_4 \implies (A+2I)v_4 = 0$$
Now, that means that $v_3 \in \ker (A+2I)^2$ since $$(A+2I)^3v_3 = (A+2I)(A+2I)v_3 = (A+2I)v_4 = 0$$
I evaluated that:
$$ \ker(A+2I) = \text{span}\{(0,0,0,1), (0,1,1,0)\} $$
$$ \ker(A+2I)^2 = \text{span}\{(0,0,0,1), (0,1,0,0), (0,0,1,0)\} $$
First we choose $v_4\in\ker(A+2I)$. We may select $v_4 = (0,0,0,1)$.
Now, we want $v_3$ such that $$(A+2I)v_3 = v_4$$
So I picked $v_3 = (0,1,1,0)$ which answers the criteria.
But now, I need to pick $v_2,v_1$ which linearly independent of $v_3,v_4$ but that's impossible I'm afraid.
What am I doing wrong/ understand wrong?
Comment: @jmiller You cannot pick $v_3=(0,1,1,0)$ since it belongs to $\text{Ker}\,(A+2I)$ and gives $v_4=0$. $v_3$ should be in $\text{Ker}\,(A+2I)^2\setminus\text{Ker}\,(A+2I)$.
Comment: "some more calculations gives the result that the Jordan form is..." usually we determine jordan form and basis together
Comment: @MichaelGaluza dim(Ker($A+2I$))=$2$ gives $2$ Jordan blocks with eigenvalue $-2$ without calculation of the basis.
Answer: You cannot pick (0, 1, 1, 0) as v₃ because as you have already shown, (0, 1, 1, 0) is an eigenvector whereas v₃ is a second-order generalized eigenvector.
From your equations, the eigenvectors are  v₁ = (9, 9, 42, 35), v₂ = (0, 1, 1, 0), and v₄ = (0, 0, 0, 1).  Now, use your equation to solve for v₃ to get v₃ = (0, –1, 0, 0).
(FYI, the eigenvalues of a triangular matrix are the diagonal entries, so you do not need the characteristic polynomial.)


Tem como calcular a diagonal no Canvas?

Question: Preciso desenhar um quadrado com o Canvas em uma imagem. Essa imagem vem do banco de dados, onde tem diferenciadas dimensões. Estou conseguindo desenhar o quadrado no centro da imagem, mas se a imagem for com uma largura maior, o Canvas sai da sua proporção. Tem como ao invés de pegar a altura e a largura da imagem, pegar sua diagonal ou polegadas para que o quadrado não saia da proporção?
Aqui está o código utilizado para fazer o Canvas:

Comment: Tem sim.

Fórmula da Hipotenusa.

`Hˆ2 = Cˆ2 + Cˆ2`
Answer: Se você tem a altura e a largura, pode calcular a diagonal a partir disto.
Pode ser resolvido utilizando o Teorema de Pitágoras, da seguinte forma:
Diagonal² = altura² + largura²;
Em js:
var diagonal = Math.sqrt(Math.pow(height, 2) + Math.pow(width,2), 2);

Espero ter ajudado.

Tem como calcular a diagonal no Canvas?


Aspose.Tasks. Microsoft Project. Get the resource usage by day

Question: Im trying to get a resource usage of specific resource in specific day.
I tryed to use Resource.TimeScaleData but it always returns 0 items.
While in debug mode, the Resource.TimephasedData ArrayList has 6118 items.
Maybe, there is a sample code for getting resource usage?
Can someone direct me, how to approach these?
Answer: Try this:
Set tsv = ActiveProject.Resources("your resource").TimeScaleData(#6/6/2013#, #6/6/2013#)
amt = tsv(1)

This will give you the amount of forecast work for the resource for the given day, expressed in minutes. If you want baseline work, you'll need to add the third argument (e.g. pjResourceTimescaledBaselineWork).


Inserir dados no Active Directory via SQL SERVER

Question: Estou trabalhando com integração entre Sql Server e o Active Directory. Já consigo importar informações do AD através de scripts. Gostaria de saber se é possível o contrário, através de comandos insert, inserir informações nos usuários do AD. Por exemplo, todos os usuários do AD estão sem o cargo cadastrado. Por um comando de insert no Sql Server consigo inserir as informações direto no campo correspondente no AD?
Comment: A resposta necessariamente tem que abranger apenas o SQL Server ou você aceitaria alguma alternativa em outra plataforma como o C#, por exemplo?
Comment: A princípio em SQL Server que é o que estamos usando no momento. A menos que não seja possível ou não muito adequado usar o SQL Server.
Comment: @CiganoMorrisonMendez pode me mostrar por gentileza a alternativa de inserção pelo c# então? Sabe me dizer como inserir por prompt de comando também, de repente criando um arquivo .bat?
Answer:
Aviso: Conforme combinado com o autor da pergunta, esta resposta não se destina a responder exatamente o que foi pedido, e sim em fornecer alternativas para a manipulação de dados do Active Directory utilizando outras linguagens e plataformas.

Inserir informações pelo SQL Server no Active Directory poderia constituir prática insegura, com resultados imprevisíveis. Portanto, o recurso não foi habilitado. O que é possível fazer pelo SQL Server é obter informações a nível de consulta.
Sendo assim, existe ainda a possibilidade de inserção de informações usando métodos alternativos, em aplicativos escritos em linguagens como C# e VBScript.
Há um artigo bem grande no CodeProject em que são explicadas várias funcionalidades que podem ser implementadas para realizar várias tarefas de inserção.
Para VBScript e BAT, Existe este site com centenas de exemplos para as mais variadas tarefas.
Comment: Muito bom! Obrigado @Cigano
Comment: o Link já não se encontra mais ativo: https://www.activexperts.com/network-monitor/windowsmanagement/adminscripts/


Overriding Pathologic when it comes to img src

Question: I have Pathologic installed and it is working great from normal links in a document, but for anything that points to the file system ( img src for example) I can't get it to not use ?q= in the url.
Answer: You could alternatively use the scanner module or export the DB and use a text editor to replace the domains. Therefore getting rid of pathologic.
Answer: If you know how to write a custom module, you can implement hook_pathologic_alter() and tell Pathologic to not modify certain paths. See pathologic.api.php for examples.


Erro na classificação de textos com arvore

Question: Estou tentando classificar, mas está dando o erro. Segue o código, depois o erro.
#coding=UTF-8

import io
import os
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import tree

pasta="c:/users/usuario/dados"
os.chdir(pasta)

def main():
    df=pd.read_csv('twits_classificados.csv', encoding='ISO-8859-1', sep=";")
    exemploArvore(df)

def exemploArvore(df):
    textos=df['texto'].values
    sentimento=df['sentimento'].values

    #a linha abaixo traz a frequencia de palavras
    vectorizer = CountVectorizer(analyzer="word")

    freqWords = vectorizer.fit_transform(textos)

    modelo = tree.DecisionTreeClassifier()

    modelo.fit(freqWords, sentimento)

    texto=["estou com medo da violência"]
    fwTexto=vectorizer.fit_transform(texto)

    print(modelo.predict(fwTexto))

main()

O erro:

Traceback (most recent call last):
  File "C:\Users\USUARIO\workspacePython\testes\arvore.py", line 39, in <module>
    main()
  File "C:\Users\USUARIO\workspacePython\testes\arvore.py", line 14, in main
    exemploArvore(df)
  File "C:\Users\USUARIO\workspacePython\testes\arvore.py", line 36, in exemploArvore
    print(modelo.predict(fwTexto))
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py",
line 404, in predict
    X = self._validate_X_predict(X, check_input)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py",
line 376, in _validate_X_predict
    % (self.n_features_, n_features))
ValueError: Number of features of the model must match the input. Model n_features is 2765 and input n_features is 5

Answer: Você só deve chamar o método fit_transform durante o treino, no teste você deve chamar apenas o método transform do seu vectorizer.
No seu teste, troque a linha:
fwTexto = vectorizer.fit_transform(texto)

Por
fwTexto = vectorizer.transform(texto)


Subtrair elementos de um array bidimensional

Question: Tenho um array
x = [[2,5,16,26],[5,28,35,46],[1,9,28,54,60,102],[...]...]

Os arrays dentro do array não tem tamanhos fixos, podem conter de 1 a N elementos. Como faço para ter um novo array y com a subtração de cada elemento pelo seu antecessor, se houver. Ex:
[[3,11,10],[23,7,11],[8,19,26,6,42]

O 3 é a subtração de 5-2, o 11, 16-5 etc. E nesse array y o índice começando por 1.
Comment: essa pergunta é um dever de casa ou se aplica a algum problema específico? Seria interessante contextualizar. Além disso, você poderia dizer qual solução você está pensando e quais as suas dificuldades.
Answer: Pode utilizar o método each_cons. Observe:
a = [1, 8, 17, 20]
a.each_cons(2) {|pair| p pair }

#=> [1, 8]
#=> [8, 17]
#=> [17, 20]

Com base nisso pode fazer o seguinte:
x = [[2, 5, 16, 26], [5, 28, 35, 46], [1, 9, 28, 54, 60, 102]]
r = x.map{|e| e.each_cons(2).map{|pair| pair[1] - pair[0] } }

#=> [[3, 11, 10], [23, 7, 11], [8, 19, 26, 6, 42]]

Comment: Preciso ler mais sobre os métodos de array.


Pular de coluna a cada N linhas contadas

Question: Preciso de ajuda com vba. Ao inserir valores usando contador de linas, Quero mudar de coluna, a cada N numero de linhas.
Ex.: a cada 100 linhas contadas e valores inseridos automaticamente, a coluna é alteradora e a contagem de linhas recomeça numa nova coluna. Eu consigo mudar de linha usando contador de linhas mas não consigo fazer o mesmo p colunas.
Eis a situação do codigo:
Sub numberlist()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
<code>Dim a1 As Single
Dim b1 As Single
Dim c1 As Single
Dim count As Integer
Dim lrow As Long
Dim lcolumn As Integer

a1 = 0
b1 = 0
c1 = 0

    For a1 = 0 To 9 Step 1
    For b1 = 0 To 9 Step 1
    For c1 = 0 To 9 Step 1
    lrow = Cells(Rows.count, "A").End(xlUp).Row + 1
    Cells(lrow, "A") = a1 & b1 & c1

    If lrow Mod 100 = 0 Then
        Application.EnableEvents = False
        lcolumn = Range(1, Columns.count).Next(xlToRight).Column + 1
        lrow = 0
        lrow = Cells(Rows.count, Columns.count).End(xlUp).Row + 1
        Cells(lrow, "A") = a1 & b1 & c1
        Else
        End If

    Next
    Next
    Next

Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
</code>
Answer: Consegui! Mudei a logica na condicional com funçao mod.
Ex.: A cada 100 linhas o contador de colunas muda pra mais 1.
Fica desta forma:
<code> Sub numberlist()

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim a1 As Single
    Dim b1 As Single
    Dim c1 As Single
    Dim count As Integer
    Dim lrow As Long
    Dim lcolumn As Long

    a1 = 0

    b1 = 0

    c1 = 0

    lcolumn = 1

        For a1 = 0 To 9 Step 1
        For b1 = 0 To 9 Step 1
        For c1 = 0 To 9 Step 1
        lrow = Cells(Rows.count, lcolumn).End(xlUp).Row + 1
        Cells(lrow, lcolumn) = a1 & b1 & c1

        If lrow Mod 100 = 0 Then

            lcolumn = lcolumn + 1
            lrow = 1

            Else
            End if
Next
Next
Next

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

    End Sub
</code>


The Hölder condition with the negative exponent $|f(x) - f(y)| \leq \frac{1}{|x-y|}$

Question:
Suppose $f: \mathbb{R} \to \mathbb{R}$ is such that $\forall \ x, y: x \neq y \to$ $|f(x) - f(y)| \leq \frac{1}{|x-y|}$

I need to prove that $f$ is

A) bounded
B) continuous
C) differentiable
D) non decreasing

on $\mathbb{R}$
Could you please give me any hints?
Thanks a lot in advance!
Comment: If $|x-y|<\delta$, then $\frac1{|x-y|}>\frac1{\delta}$. So you can't do B) this way...
Comment: @MundronSchmidt yes, It's true. Thank you
Comment: For A), notice that the expression on the right is bounded above by 1, so what can you do with that?
Comment: @Quantaliinuxite why? if for example $x = \frac{1}{2}$ and $y = 0$ then $\frac{1}{|x-y|} = 2 > 1$
Comment: @DF yes sorry i don't know what went through my head
Comment: @DF did you try experimenting with various functions to try to make an educated guess?
Comment: @DF you can still use it by splitting R in say everything except (-1,1) and (-1,1)
Answer: Fix a point $a \in \mathbb R$. The stated hypothesis tells you that
$$ \lim_{x \to \infty} f(x) = f(a).$$
Can you take it from there?
Comment: Yes. Thank you a lot!


Send Email upon Registration to Author of node

Question: I have searched and can not find anything similar.
I have a Rule, Event = send email after someone registers for an event.
I have the rule sending to the user just fine. However, I am trying to also email the Author of the page and I can find the correct replacement pattern.
I have an action Fetch Entity by ID Value=registration - DATA-Selector=registration:author:uid
I have tried many patterns:

[node:author:mail] mail - Nothing happens
[registration:author:uid] uid - give me the logged in user id
[registration:author:uid] reg-a-uid  (this give mne the id of the logged in user- not the author on the page.)
[node:author:uid] node-a-uid
[site:author:uid] site-a-uid
[registration:author] reg-author - show logged in user
[registration:author:mail] reg-author-mail - show logged in user

I am at a loss when trying to figure out how to pull the author of the node/page to email them.
Any ideas???
Thanks
[EDIT]
I was able to get the Author to print out.
author: [registration:entity:author]

Any ideas to pull the author first name, email and phone number???
Please any little thought would help.
Thanks
Comment: how you are handling registration process? looks like registration is an entity itself,are you using any contrib module for registration?
Comment: We are using the Registration module. We have a live events page with the registration block on the page to register for that event. I can choose from a few different options, entity is not one. Node, registration, user, profile, and a few others.
Answer: So after getting the base set I needed to connect to the table for the users profile information.
So for first name it would be:
[registration:entity:author:profile-main:field_first_name]

So for phone number it would be:(field_office is what they called the Office Phone field.)
[registration:entity:author:profile-main:field_office]

Hope it helps someone else.
Comment: I'm a "rules" fan (can you tell from my rep specific to its tag?). Therefor i'm curious what you mean by "connect to the table". Can you explain that AbitMORE please?


Como conectar uma Storage Account do Azure em um projeto ASP.NET Core?

Question: Estou utilizando VS2017 com ASP.NET Core 2.0 (template Angular) e preciso fazer as operações básicas de CRUD baseada em tables no Azure Storage.
Existe alguma maneira de fazer scaffold no meu ambiente?
Comment: Existe uma ferramenta no Visual Studio Marketplace que pode te ajudar a fazer Scaffold do Azure Storage Tables.

https://marketplace.visualstudio.com/items?itemName=StephanJohnsonBlueMarble.AzureTableStorageScaffolder
Comment: Infelizmente não tem pro VS2017... só pro 2013, então acredito que não tenha como fazer com essa extensão usando .NET Core
Comment: Acho que não! :(
Answer: Azure Storage Emulator
Primeiro você deve configurar o emulador de Azure Storage localmente, assim poderá desenvolver sem a necessidade de ir remoto.
O emulador de armazenamento está disponível como parte do Microsoft Azure SDK. Voce também pode instalar o emulador de armazenamento individualmente (download aqui).
Após instalar, basta executar o aplicativo Azure Storage Emulator, selecionar o tipo que deseja emular e pronto.
Azure Storage Explorer
Para ajudar, vc também poder usar o Azure Storage Explorer para tornar mais amigável seu consumo dos armazenamento - seja no Azure, ou seja localmente.

Baixe o Azure Storage Explorer aqui.
Fontes:
https://docs.microsoft.com/pt-br/azure/vs-azure-tools-storage-emulator-using
https://docs.microsoft.com/pt-br/azure/storage/common/storage-use-emulator
Answer: Infelizmente não tem nenhuma forma conectar uma Storage Account do Azure via Connected Services usando qualquer versão e layout do ASP.NET Core (pelo menos no Visual Studio 2017), entretanto, existe uma maneira manual de fazer essa ponte, seguem os passos que utilizei para resolver o problema:
Primeiramente, precisei instalar o pacote NuGet WindowsAzure.Storage.
Na minha pasta Models, criei uma classe Foo que representava o modelo da minha table do Azure. Todos as classes de modelo herdam de TableEntity, que tem aquelas propriedades básicas para todas as tables do Azure: PartitionKey, RowKey, ETag, etc.
public class Foo : TableEntity {
  public string FooField { get; set; }
  public string FooField2 { get; set; }
}

Criei uma pasta Repositories na raiz do projeto e adicionei uma classe FooRepository, para manipulação das tables (CRUD)
public class FooRepository {

  private readonly CloudStorageAccount storageAccount { get; }

  public FooRepository(string connectionString) {
    storageAccount = CloudStorageAccount.Parse(connectionString);
  }

  public Task<IEnumerable<Foo>> GetAsync() {
    // ...
  }

  public Task<Foo> GetAsync(string partitionKey, string rowKey) {
    // ...
  }

  public Task UpdateAsync(string partitionKey, string rowKey, Foo updatedEntity) {
    // ...
  }

  public Task DeleteAsync(string partitionKey, string rowKey) {
    // ...
  }

  public Task CreateAsync(Foo newEntity) {
    // ...
  }
}

O FooRepository foi referenciado no meu FooController, que ficou mais ou menos dessa forma:
[Produces("application/json")]
[Route("api/Foo")]
public class FooController : Controller {
    readonly FooRepository repo = new FooRepository("connectionString");

    [HttpGet]
    public async Task<List<Foo>> Get() {
        return (await repo.GetEntitiesAsync()).Item1;
    }
}

A string de conexão pode ser encontrada no portal do Azure. Pode passá-la como eu fiz, a cada vez que referenciar um Repository, ou colocá-la em um arquivo estruturado como *.xml ou *.json e ler de forma fixa, tirando o connectionString do construtor dos repositories, que é uma prática que eu recomendo, já que essas strings de conexão podem mudar eventualmente (DRY!).

Um Repository pode ser mais abstrato, como fiz no exemplo abaixo:
public class BaseRepository<T> : IRepository where T : class, ITableEntity, new() {

    CloudStorageAccount IRepository.StorageAccount { get; set; }
    CloudTableClient IRepository.TableClient { get; set; }
    CloudTable IRepository.Table => ((IRepository)this).TableClient.GetTableReference(nameof(T));

    public BaseRepository(string connString) {
        ((IRepository) this).StorageAccount = CloudStorageAccount.Parse(connString);
        ((IRepository) this).TableClient = ((IRepository) this).StorageAccount.CreateCloudTableClient();
    }

    public Task CreateAsync(T entity) {
        TableOperation insertOperation = TableOperation.Insert(entity);
        return ((IRepository) this).Table.ExecuteAsync(insertOperation);
    }

    public async Task<T> GetEntityAsync(string partitionKey, string rowKey) {
        TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey);

        T entity = (await ((IRepository)this).Table.ExecuteAsync(retrieveOperation)).Result as T;
        return entity;
    }

    public async Task<Tuple<List<T>, TableContinuationToken>> GetEntitiesAsync(TableContinuationToken token = null) {
        List<T> list = new List<T>();
        TableQuery<T> query = new TableQuery<T>().Take(15);

        TableQuerySegment<T> tableQueryResult = await ((IRepository)this).Table.ExecuteQuerySegmentedAsync(query, token);
        list.AddRange(tableQueryResult.Results);

        return Tuple.Create(list, tableQueryResult.ContinuationToken);
    }

    public async Task<T> DeleteEntityAsync(string partitionKey, string rowKey) {
        T entityToDelete = await GetEntityAsync(partitionKey, rowKey);

        TableOperation deleteOperation = TableOperation.Delete(entityToDelete);
        await ((IRepository)this).Table.ExecuteAsync(deleteOperation);

        return entityToDelete;
    }
}

Sendo IRepository uma interface simples:
interface IRepository {
    CloudStorageAccount StorageAccount { get; set; }
    CloudTableClient TableClient { get; set;  }
    CloudTable Table { get; }
}

Veja que o GetEntitiesAsync(TableContinuationToken) só está pegando 15 resultados, quando o usuário passar a página, você chama o método passando o token retornado. Mais detalhes sobre a manipulação podem ser lidos aqui.


How to install hdf5 on Docker image with Linux alpine 3.13

Question: I am building a Docker image with python 3.7.10 (Linux Alpine v3.13) but when building the image with docker build . the package hdf5 will fail during the installation. This is my Dockerfile:
FROM python:3.7.10-alpine3.13

RUN mkdir /app
WORKDIR /app
COPY requirements.txt /requirements.txt
ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1
RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers
RUN apk add --no-cache jpeg-dev zlib-dev mariadb-dev libffi-dev openblas-dev libgfortran lapack-dev build-base openssl-dev
RUN apk add --no-cache hdf5 hdf5-dev
RUN pip install -r /requirements.txt
RUN apk --no-cache del build-base

ENV PYTHONUNBUFFERED 1
COPY . /app/

CMD ["uwsgi", "my_app"]

requirements.txt file:
h5py==2.10.0
numpy==1.19.2

I have tried with and without the --no-binary flag but still no luck. Was somebody able to install that library on this Alpine version?
Error logs:
    17858 |   __pyx_t_1 = H5Ovisit_by_name(__pyx_v_loc_id, __pyx_v_obj_name, __pyx_v_idx_type, __pyx_v_order, __pyx_v_op, __pyx_v_op_data, __pyx_v_lapl_id); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1641, __pyx_L1_error)
          |               ^~~~~~~~~~~~~~~~
    In file included from /usr/include/H5Apublic.h:22,
                     from /usr/include/hdf5.h:23,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/api_compat.h:27,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c:654:
    /usr/include/H5Opublic.h:213:15: note: declared here
      213 | H5_DLL herr_t H5Ovisit_by_name3(hid_t loc_id, const char *obj_name,
          |               ^~~~~~~~~~~~~~~~~
    /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c: In function '__pyx_f_4h5py_4defs_H5Pget_driver_info':
    /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c:21768:13: warning: assignment discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
    21768 |   __pyx_t_1 = H5Pget_driver_info(__pyx_v_plist_id); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2016, __pyx_L1_error)
          |             ^
    In file included from /usr/include/H5public.h:32,
                     from /usr/include/hdf5.h:22,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/api_compat.h:27,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c:654:
    /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c: In function '__pyx_f_4h5py_4defs_H5Sencode':
    /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c:34528:15: error: too few arguments to function 'H5Sencode2'
    34528 |   __pyx_t_1 = H5Sencode(__pyx_v_obj_id, __pyx_v_buf, __pyx_v_nalloc); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 3303, __pyx_L1_error)
          |               ^~~~~~~~~
    In file included from /usr/include/hdf5.h:38,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/api_compat.h:27,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c:654:
    /usr/include/H5Spublic.h:129:15: note: declared here
      129 | H5_DLL herr_t H5Sencode2(hid_t obj_id, void *buf, size_t *nalloc, hid_t fapl);
          |               ^~~~~~~~~~
    In file included from /usr/local/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:21,
                     from /usr/local/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/api_compat.h:26,
                     from /tmp/pip-install-fkianwj6/h5py_dfa9366c1fdb47e98e9e2e8de85ac21e/h5py/defs.c:654:
    At top level:
    /usr/local/lib/python3.7/site-packages/numpy/core/include/numpy/__multiarray_api.h:1464:1: warning: '_import_array' defined but not used [-Wunused-function]
     1464 | _import_array(void)
          | ^~~~~~~~~~~~~
    error: command 'gcc' failed with exit status 1
    ----------------------------------------

Comment: @jordanvrtanoski I have updated the question, adding the `requirements.txt`
Comment: Works fine up to the stage to install `requirements.txt` both on `X86` and `ARM64` platforms. It looks like the problem of versions compatibility, but without your `requirements.txt` is not reproducible.
Comment: For me it works without issues, using the provided requirements.txt as well. Image build log: https://pastebin.com/CXXFaqN5
Comment: apologies to both jordanvrtanoski & @valiano. I have copied the wrong setup, it failed for me when using **h5py==2.10.0** but now with **h5py==3.2.1** works  perfectly.
Comment: No worries @Ander. Glad you figured it out
Answer: Seems like I have used a wrong and old h5py version (h5py==2.10.0). The following setup worked just fine when updating to h5py==3.2.1 within the requirements.txt.
FROM python:3.7.10-alpine3.13

RUN mkdir /app
WORKDIR /app
COPY requirements.txt /requirements.txt
ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1
RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers
RUN apk add --no-cache jpeg-dev zlib-dev mariadb-dev libffi-dev openblas-dev libgfortran lapack-dev build-base openssl-dev
RUN apk add --no-cache hdf5-dev
RUN pip install -r /requirements.txt
RUN apk --no-cache del build-base

ENV PYTHONUNBUFFERED 1
COPY . /app/

CMD ["uwsgi", "my_app"]

requirements.txt file:
h5py==3.2.1
numpy==1.20.1

Thanks to @jordanvrtanoski and @valiano for the feedback.


How to use CvPhotoCamera with iOS openCV?

Question: I have followed the tutorial on how to use the CvVideoCamera object to play a video and apply some processing.
I am now interested to use the CvPhotoCamera object to capture a high definition picture by using the takePicture method. However, the tutorial uses CvVideoCamera and does not make any references to CvPhotoCamera.
Both CvPhotoCamera and CvVideoCamera are inheriting from CvAbstractCamera. They are sister classes so I have no idea on how can I use the takePicture function.
Answer: My solution was to create a new class named CvVideoPhotoCamera which inherits from CvAbstractCamera. The content of CvVideoPhotoCamera was made from a merge between CvVideoCamera and CvPhotoCamera.
Answer: Do the same as @poiuytrez: add modification to cvPhotoCamera
CvPhotoCameraMod.h:
<code>#import <UIKit/UIKit.h>
#import <opencv2/highgui/cap_ios.h>
#import <opencv2/highgui/ios.h>

#define DEGREES_RADIANS(angle) ((angle) / 180.0 * M_PI)

@class CvPhotoCameraMod;

@protocol CvPhotoCameraDelegateMod <CvPhotoCameraDelegate>
- (void)processImage:(cv::Mat&)image;
@end

@interface CvPhotoCameraMod : CvPhotoCamera <AVCaptureVideoDataOutputSampleBufferDelegate>

@property (nonatomic, retain) CALayer *customPreviewLayer;
@property (nonatomic, retain) AVCaptureVideoDataOutput *videoDataOutput;
@property (nonatomic, weak) id <CvPhotoCameraDelegateMod> delegate;

- (void)createCustomVideoPreview;

@end
</code>
CvPhotoCameraMod.mm:
<code>#import "CvPhotoCameraMod.h"
#import <CoreGraphics/CoreGraphics.h>
#define DEGREES_RADIANS(angle) ((angle) / 180.0 * M_PI)

@implementation CvPhotoCameraMod

-(void)createCaptureOutput;
{
    [super createCaptureOutput];
    [self createVideoDataOutput];
}
- (void)createCustomVideoPreview;
{
    [self.parentView.layer addSublayer:self.customPreviewLayer];
}

//Method mostly taken from this source: https://github.com/Itseez/opencv/blob/b46719b0931b256ab68d5f833b8fadd83737ddd1/modules/videoio/src/cap_ios_video_camera.mm

-(void)createVideoDataOutput{
    // Make a video data output
    self.videoDataOutput = [AVCaptureVideoDataOutput new];

    //Drop grayscale support here
    self.videoDataOutput.videoSettings  = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];

    // discard if the data output queue is blocked (as we process the still image)
    [self.videoDataOutput setAlwaysDiscardsLateVideoFrames:YES];
    if ( [self.captureSession canAddOutput:self.videoDataOutput] ) {
        [self.captureSession addOutput:self.videoDataOutput];
    }
    [[self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:YES];

    // set video mirroring for front camera (more intuitive)
    if ([self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo].supportsVideoMirroring) {
        if (self.defaultAVCaptureDevicePosition == AVCaptureDevicePositionFront) {
            [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo].videoMirrored = YES;
        } else {
            [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo].videoMirrored = NO;
        }
    }

    // set default video orientation
    if ([self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo].supportsVideoOrientation) {
        [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation = self.defaultAVCaptureVideoOrientation;
    }

    // create a custom preview layer
    self.customPreviewLayer = [CALayer layer];

    self.customPreviewLayer.bounds = CGRectMake(0, 0, self.parentView.frame.size.width, self.parentView.frame.size.height);

    self.customPreviewLayer.position = CGPointMake(self.parentView.frame.size.width/2., self.parentView.frame.size.height/2.);

    // create a serial dispatch queue used for the sample buffer delegate as well as when a still image is captured
    // a serial dispatch queue must be used to guarantee that video frames will be delivered in order
    // see the header doc for setSampleBufferDelegate:queue: for more information
    dispatch_queue_t videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL);
    [self.videoDataOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    (void)captureOutput;
    (void)connection;
    if (self.delegate) {

        // convert from Core Media to Core Video
        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        CVPixelBufferLockBaseAddress(imageBuffer, 0);

        void* bufferAddress;
        size_t width;
        size_t height;
        size_t bytesPerRow;

        CGColorSpaceRef colorSpace;
        CGContextRef context;

        int format_opencv;

        OSType format = CVPixelBufferGetPixelFormatType(imageBuffer);
        if (format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) {

            format_opencv = CV_8UC1;

            bufferAddress = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);
            width = CVPixelBufferGetWidthOfPlane(imageBuffer, 0);
            height = CVPixelBufferGetHeightOfPlane(imageBuffer, 0);
            bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0);

        } else { // expect kCVPixelFormatType_32BGRA

            format_opencv = CV_8UC4;

            bufferAddress = CVPixelBufferGetBaseAddress(imageBuffer);
            width = CVPixelBufferGetWidth(imageBuffer);
            height = CVPixelBufferGetHeight(imageBuffer);
            bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);

        }

        // delegate image processing to the delegate
        cv::Mat image((int)height, (int)width, format_opencv, bufferAddress, bytesPerRow);

        CGImage* dstImage;

        if ([self.delegate respondsToSelector:@selector(processImage:)]) {
            [self.delegate processImage:image];
        }

        // check if matrix data pointer or dimensions were changed by the delegate
        bool iOSimage = false;
        if (height == (size_t)image.rows && width == (size_t)image.cols && format_opencv == image.type() && bufferAddress == image.data && bytesPerRow == image.step) {
            iOSimage = true;
        }

        // (create color space, create graphics context, render buffer)
        CGBitmapInfo bitmapInfo;

        // basically we decide if it's a grayscale, rgb or rgba image
        if (image.channels() == 1) {
            colorSpace = CGColorSpaceCreateDeviceGray();
            bitmapInfo = kCGImageAlphaNone;
        } else if (image.channels() == 3) {
            colorSpace = CGColorSpaceCreateDeviceRGB();
            bitmapInfo = kCGImageAlphaNone;
            if (iOSimage) {
                bitmapInfo |= kCGBitmapByteOrder32Little;
            } else {
                bitmapInfo |= kCGBitmapByteOrder32Big;
            }
        } else {
            colorSpace = CGColorSpaceCreateDeviceRGB();
            bitmapInfo = kCGImageAlphaPremultipliedFirst;
            if (iOSimage) {
                bitmapInfo |= kCGBitmapByteOrder32Little;
            } else {
                bitmapInfo |= kCGBitmapByteOrder32Big;
            }
        }

        if (iOSimage) {
            context = CGBitmapContextCreate(bufferAddress, width, height, 8, bytesPerRow, colorSpace, bitmapInfo);
            dstImage = CGBitmapContextCreateImage(context);
            CGContextRelease(context);
        } else {

            NSData *data = [NSData dataWithBytes:image.data length:image.elemSize()*image.total()];
            CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);

            // Creating CGImage from cv::Mat
            dstImage = CGImageCreate(image.cols,                                 // width
                                     image.rows,                                 // height
                                     8,                                          // bits per component
                                     8 * image.elemSize(),                       // bits per pixel
                                     image.step,                                 // bytesPerRow
                                     colorSpace,                                 // colorspace
                                     bitmapInfo,                                 // bitmap info
                                     provider,                                   // CGDataProviderRef
                                     NULL,                                       // decode
                                     false,                                      // should interpolate
                                     kCGRenderingIntentDefault                   // intent
                                     );

            CGDataProviderRelease(provider);
        }

        // render buffer
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.customPreviewLayer.contents = (__bridge id)dstImage;
        });

        // cleanup
        CGImageRelease(dstImage);

        CGColorSpaceRelease(colorSpace);

        CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
    }
}

@end
</code>
Comment: XCode is giving me errors in the CvPhotoCameraMod.h file. It doesn't seem to recognize the `cv` namespace. Any idea why?
Comment: If `using namespace cv;` in `CvPhotoCameraMod.h` doesn't help you - maybe problem not in namespace.


php session always created on refresh

Question: I am new to PHP so have a very basic question
I creating a page I am creating a page initially with user id and password, once user id and password are entered and submit is clicked, AJAX is called to validate that against database.
once validation done I want to refresh the page which show more option to user
I was thinking to use session
but every time I refresh the page a new session is created
I put this at the top of the page as a test and always when F5 is press I see "new session" on top of the page
<?php
if (!isset($_SESSION)){
    session_start();
    echo("new session");
}
else
{
    echo("old session");
}
?>

Comment: I think you are misunderstanding what `session_start` does. From the documentation: "session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie."
Comment: `$_SESSION` will never be set before `session_start()` is called. You should call `session_start()` at the top of each of your session-enabled pages. It will not overwrite an existing session. Instead, it will  give you access to the user's current session or create one if none exists yet. If you want to explicitly start a new session, use `session_destroy()` first, then `session_start()`.
Answer: session_start must be called always before anything related to a session. After calling it, you can get or set values of the $_SESSION variable.
Reference.
Your code should be:
<?php
session_start(); // always call this at top
if (!isset($_SESSION['has_been_here'])){
    $_SESSION['has_been_here'] = true;
    echo("new session");
}
else
{
    echo("already been here");
}
?>

Comment: Thanks so much, that answered my question. Now I got a new problem. I have a AJAX that is called after submit is preseed.
Comment: Start another question
Answer: From php.net:
session_start — Start new or resume existing session

That means you have to start your session with
session_start();

on every page, in the first line, which will start or resume it. Check the php.net manual, it will help you understand how to handle and check sessions correctly.

php session always created on refresh


Order of autocomplete suggestions in PHP Intelephense

Question: How can I specify the order of autocomplete suggestions provided by Intelephense extension for VS Code?
In particular, I would like to push all the classes located in vendor directory down the list. In other words, I would like classes specific to my app to appear first in the list.
I looked into the settings options of this package, but didn't find anything that would allow me to modify the order of autocomplete options.
Answer: You can't. Though, for this particular case it would be possible using the sortText property. In general, VSCode extensions have limited ability to influence suggestion sorting via sortText and preselect properties of the CompletionItem. VSCode has it's own ranking algorithm that dominates suggestion order.
Comment: I'm planning on adding it to act as a tiebreaker when suggestions are ranked the same by the matched text
Comment: Do I understand correctly, that it would work because `vendor` would be at the bottom of the list sorted alphabetically?
Comment: Correct, sortText could be modified to be sorted last alphabetically
Comment: Just realized that you're the extension author - I think you should mention it in the answer, so it's easier for people to know it comes from the 'source' ;) By the way: are you planning to add such feature (maybe as a config option)? Or would you rather have someone PR it?