Drag & Drop - Check item was dropped in the correct place

Question: I'm teaching myself javascript/jquery and decided as a side project to create a drag and drop game. I've based it on other tutorials I've found and just adapted it really, so go easy on the code - hopefully its not too scary.
I'm using the jquery ui dropable library to implement the game and currently I check once the item is dropped if it is in the correct place, if it is I increment the score by one.
However the problem I have is I can't get the score to go down by one when the item is dropped in the wrong place.
If a square is placed on the correct placeholder it adds 1 to the score but if that same square gets removed from the correct place holder then it needs to take 1 off the score.
Heres a demo here of what I've done so far
http://creativelabel.co.uk/drag-and-drop/
Any ideas?
Answer: One way to approach this is to store in the dropped element whether it was placed in a valid square. This means when it is moved to an invalid square you can check if it was previously in a valid one and if this is the case reduce the score by one.
Hope this is clear!
See http://jsfiddle.net/pET3y/ for a live demo
Relevant code:
  if ( slotNumber == imgNumber ) {
    ui.draggable.addClass( 'img-match' );
    ui.draggable.data("valid", true);

    imgMatch++;
  }  else {
      if(ui.draggable.data("valid")) {
         imgMatch--;
         ui.draggable.data("valid", false);
      }
  }

Note: the the fiddle has an alert alert(ui.draggable.data("valid")); for debug
--
Changing for on drag the score goes down
What you do now is listen for the drag event (called activate), and when this is called run a function. The function checks if the element being dragged was previously in the correct position and if it was, marks it as not in the correct position and decreases the score.
See: http://jsfiddle.net/3NkwJ/1/
      drop: handleDropEvent,
      activate: handleDragEvent //add new event
} );

And add the below:
  function handleDragEvent( event, ui ) {
    if(ui.draggable.data("valid")) {
             imgMatch--;
             $('input[name=Score]').val(imgMatch);
             $('#score h1').text(imgMatch);
             ui.draggable.data("valid", false);
    }
  }

Comment: Now to add the timer, that shouldn't be too hard. Thanks again.
Comment: That works if I drag the item on to another square, is there a way to make it remove the score straight away on drag?

So if drop is correct add to score but as soon as its picked up again it removes score.
Comment: Nice one, worked a treat. I hadn't come across activate event until now. I was looking into the out event for a solution but no luck. Thanks for your help.
Comment: Good luck, would be interested to see it when it's finished
Comment: I'm using this as a reference and in turn hopefully helping someone else with a similar problem. Currently the game allows you to drag more than one square on top of another. I'm working on disabling the drop when a square has already been dropped. I'll post my answer when I get somewhere. If anyone has any ideas in the mean time...?
Answer: i only skimmed the code but after this block
if ( slotNumber == imgNumber ) {
    ui.draggable.addClass( 'img-match' );
    imgMatch++;
}

can you just add an else statement
else
    imgMatch--;

Comment: An else statement won't work, if you drop it in an invalid place 5 times the score is -5, but it should be 0.
Comment: ah i see, your answer covers everything much better anyway


Show that $T$ is or isn't a strict contraction but have fixed points

Question: Define $T: C[0,1] \to C[0,1]$ by
$$(Tf)(x) = \int^x_0 f(t)dt.$$
Show that $T$ is not a strict contraction while $T^2$ is. What is the fixed point of $T$?
Comment: If there were a fixed point for $T$ (other than $0$), would that not also be a fixed point for $T^2$? If so, $T^2$ cannot be a strict contraction.
Comment: The null function is a fixpoint of $T$.
Answer: We need to first specify a metric on $C[0,1]$, but I think that we want the metric  $d(f,g)=max_{x \in [0,1]} \{ |f(x)-g(x)| \}$.
Then to show that $T$ is a weak contraction but not a strict contraction:
$d(Tf,Tg)=max_{x \in [0,1]}\{ |\int_{0}^{x}f(t)dt-\int_{0}^{x}g(t)dt|\} = max_{x \in [0,1]} \{ | \int_{0}^{x}f(t)-g(t)dt | \} $
Using the inequality for Riemann integrable functions $|\int_{a}^{b}f(x)dx| \le \int_{a}^{b}|f(x)|dx$ we get:
$max_{x \in [0,1]} \{ | \int_{0}^{x}f(t)-g(t)dt | \} \le max_{x\in[0,1]} \{ \int_{0}^{x}|f(t)-g(t)|dt\} = \int_{0}^{1}|f(t)-g(t)|dt$
where the final equality is since we're now integrating a non-negative function.  Since $d(f,g)$ is the maximal size of the difference between $f$ and $g$ we have:
$\int_{0}^{1}|f(t)-g(t)|dt \le \int_{0}^{1}d(f,g)dt =d(f,g)$
So that $d(T(f),T(g) \le d(f,g)$ and we have at least a weak contraction.  Now to show that there is no constant $ c \in [0,1)$ such that $d(T(f),T(g)) \le c \cdot d(f,g)$ for all functions $f,g \in C[0,1]$ we need to come up with a pair of functions $f,g$ in our space where $c=1$.  For this take $f(x)=1$ and $g(x)=0$ so that $d(T(f),T(g))=d(f,g)=1$.
To show that $T \circ T=T^2$ is a strict contraction use the following:
$|(T^2f)(x)-(T^2g)(x)|= |\int_0^x \int_0^u f(t)dtdu-\int_0^x \int_0^ug(t)dtdu| \le \int_0^x \int_0^u|f(t)-g(t)|dtdu $
and then from here:
$\int_0^x \int_0^u|f(t)-g(t)|dtdu \le \int_0^xd(f,g) \cdot udu=d(f,g) \frac{x^2}{2} \le \frac{1}{2}d(f,g)$
so we have a strict contraction with constant $c=\frac{1}{2}$.


Dúvida com soma de valores no sql server 2008

Question: Tenho a consulta a baixo que me retornar os valores de DESCONTO_PRECO e DESCONTO_PRECO_ESTADO, gostaria de saber se eu consigo somar estes resultados para que venha no mesmo campo.
Agradeço
select
 --calculo do desconto individual
((P.DESCONTO01 / 100 ) * P.PRECO )+
((P.DESCONTO02 / 100 ) * P.PRECO )+
((P.DESCONTO03 / 100 ) * P.PRECO )+
((P.DESCONTO04 / 100 ) * P.PRECO ) AS DESCONTO_PRECO,

case (P.ADICIONAL_ESTADO )
  when 'S' then   (0 / 100 ) * P.PRECO   --0 é o valor do desconto para o estado caso tenha vai receber um valor
  when 'N' then   (P.DESCONTO05 / 100 ) * PRECO
END AS  DESCONTO_PRECO_ESTADO,

 --calculo do desconto individual promoção
((P.DESCONTO01 / 100 ) * P.PROMOCAO ) +
((P.DESCONTO02 / 100 ) * P.PROMOCAO ) +
((P.DESCONTO03 / 100 ) * P.PROMOCAO ) +
((P.DESCONTO04 / 100 ) * P.PROMOCAO ) AS DESCONTO_PROMOCAO,

case (P.ADICIONAL_ESTADO )
  when 'S' then   (0 / 100 ) * P.PROMOCAO   --0 é o valor do desconto para o estado caso tenha vai receber um valor
  when 'N' then   (P.DESCONTO05 / 100 ) * P.PROMOCAO
END AS DESCONTO_PRECO_PROMOCAO_ESTADO,

P.PRECO,P.DESCONTO01,P.DESCONTO02,P.DESCONTO03,P.DESCONTO04,P.DESCONTO05,P.IDPRODUTO,P.CODIGO
from TB_PRODUTO P
WHERE CODIGO = '016055IR'

Comment: [Duplicou a pergunta ????](http://pt.stackoverflow.com/questions/114772/d%C3%BAvida-com-cast-sql-server-2008/114776#114776)
Answer: você pode:
WITH CTE_VALORES AS (
    SELECT
        (P.DESCONTO01 / 100 ) * P.PRECO AS DESCONTO_PRECO_1,
        (P.DESCONTO02 / 100 ) * P.PRECO AS DESCONTO_PRECO_2,
        (P.DESCONTO03 / 100 ) * P.PRECO AS DESCONTO_PRECO_3,
        (P.DESCONTO04 / 100 ) * P.PRECO AS DESCONTO_PRECO_4,
        CASE WHEN P.ADICIONAL_ESTADO = 'S'
            THEN 0
            ELSE (P.DESCONTO05 / 100 ) * PRECO
        END AS DESCONTO_PRECO_5,
        (P.DESCONTO01 / 100 ) * P.PROMOCAO AS DESCONTO_PROMO_1,
        (P.DESCONTO02 / 100 ) * P.PROMOCAO AS DESCONTO_PROMO_2,
        (P.DESCONTO03 / 100 ) * P.PROMOCAO AS DESCONTO_PROMO_3,
        (P.DESCONTO04 / 100 ) * P.PROMOCAO AS DESCONTO_PROMO_4,
        CASE WHEN P.ADICIONAL_ESTADO = 'S'
            THEN 0
            ELSE (P.DESCONTO05 / 100 ) * PROMOCAO
        END AS DESCONTO_PROMO_5,
        P.PRECO,
        P.DESCONTO01,
        P.DESCONTO02,
        P.DESCONTO03,
        P.DESCONTO04,
        P.DESCONTO05,
        P.IDPRODUTO,
        P.CODIGO
    FROM TB_PRODUTO P
    WHERE CODIGO = '016055IR'
)

select
    DESCONTO_PRECO_1 + DESCONTO_PRECO_2 + DESCONTO_PRECO_3 + DESCONTO_PRECO_4 + DESCONTO_PRECO_5 AS DESCONTO_PRECO,
    DESCONTO_PROMO_1 + DESCONTO_PROMO_2 + DESCONTO_PROMO_3 + DESCONTO_PROMO_4 + DESCONTO_PROMO_5 AS DESCONTO_PROMOCAO,
    PRECO,
    DESCONTO01,
    DESCONTO02,
    DESCONTO03,
    DESCONTO04,
    DESCONTO05,
    IDPRODUTO,
    CODIGO
from CTE_VALORES


Finding a $V$ open s.t. $V^{-1}V \subset U$

Question: I'm trying to understand a sentence in a theorem about Polish groups.  I'll write the proof all the way up to the sentence that I'm having trouble with.
Theorem: Let $G,H$ be Polish groups and $\phi: G \rightarrow H$ be a group homomorphism. If $\phi$ is Baire measurable, then $\phi$ is continuous.
Proof: Let $U \subset H$ be open and let $g \in \phi^{-1}(U)$.  Let $V \subset H$ be open s.t. $1_H \in V$ and $V^{-1}V \subset \phi(g)^{-1}U$.
I'm having trouble with how to find such a $V$.  I know that since $\phi(g) \in U$ we have that $1_H \in \phi(g)^{-1}U$.
Answer: We have $\phi(g) \in U$. Therefore $\phi(g)^{-1}U$ is an open neighbourhood of $1_H$. In every topological group $T$, the map $\psi \colon (x,y) \mapsto x^{-1}y$ is continuous, in particular it is continuous at $(1_T,1_T)$. That means for every neighbourhood $N$ of $1_T$, there are neighbourhoods $A,\, B$ of $1_T$ such that
$$\psi (A\times B) = A^{-1}B \subset N.$$
Then $C = A \cap B$ is a neighbourhood of $1_T$ with $C^{-1}C \subset N$.
Take $N = \phi(g)^{-1}U$.


Drupal multiple node url aliases

Question: Is it possible to take a field from my node and create a url alias from the content of that field?
Say I have a node type article. This gets its normal url via pathauto, but I also wish to be able to create a short url so I can go to example.com/LS and I will be redirected to the node.
How can this custom short url be created automatically?
Answer: When you create a node they will always use the url node/[nid].
You can use the path auto module to create an url alias for the standard node. Path auto uses the token module to create the url alias for the nodes.
What you can do, is to create a token for the value of the field, and then setup path auto to use the contents of the field when creating the url alias.
Another thing you could do is to use the ShURLy module, to actual create short urls. You could make a custom module where you created or update the short url for the node when saved, and let ShURLy handle the redirects.
Comment: My node type has already been set up to use the title of the node as the alias like `/articles/node-title-here` and I'd like it to stay this way. But in addition to this it'd be cool if I could also have `/[my_cck_field]` to point to the article. Is this possible with the path auto module?
Comment: Okay so I created a triggered rule that creates an additional alias based on a token when a node is created or updated. It works alright. It works alright except I'd like it to be case sensitive - and well...the alias doesn't redirect (of course) so maybe I should take a look at the ShURLy module.
Comment: I decided it wasn't necessary to create the urls based on my cck field so the [ShURLy](http://drupal.org/project/shurly) module combined with [Shorten URLs](http://drupal.org/project/shorten) did the trick.
Comment: @theory I am having the same issue. And I have installed these two module, and I wanted to auto generate short url. Can you suggest how can I do this?
Answer: You can use hook_node_insert and path_save like so:
function mymodule_node_insert {
  $nid = $node->nid;
  $path = array(
    'source' => 'node/' . $nid,
    'alias'  => 'my/other/path',
  );
  path_save($path);
}

This will add an additional alias after the node is created. This won't interrupt Pathauto, so you'll have both aliases active.

Drupal multiple node url aliases


Why does the core search module not index node titles?

Question: The search results only show terms in the body if that. Take the example of a product site. There is a product called Funkywidget with a description that has Funckywidget written twice in it. However, the core search module does not show any results for Funkywidget. It has a record in the search_index table but doesn't show when typed into the search form.
What is the best way to enable people to find a Funkywidget?
Answer:
There is a product called Funkywidget

If the title of the node is "Funkywidget" it's searchable by that term. If you want to incorporate search terms that aren't in the node's fields, you should look at more complex search solutions like Apache Solr.
See here: http://api.drupal.org/api/drupal/modules--node--node.module/function/_node_index_node/6
The title is added to the search string that's going in the db.
$text = '
' . check_plain($node->title) . '
' . $node->body;
Comment: The core search module absolutely does not make the terms in the title field searchable.
Comment: See code above, it should be in there.
Comment: This is a bug in the Workbench Moderation module.
Comment: I have had that problem with title too. Is there a workaround or patch for the Workbench Moderation bug?


Is there a module to include translatable variables in content?

Question: I'm building a bilingual site with a lot of content. We need to be able to edit and translate certain titles that affect many pages at once, like "Today's News" or "Sign up here." But I don't want to make them all fields on content types because there's too many of them.
Is there a module or plugin that allows you to places these variables inside the content? And allows you to edit/translate and show what pages they're on?
Answer: Can't you wrap them in t() when fetching them?
Note: The author wants to be able to translate values from the variables table. I suggest a way to translate values from the variables table. No point in using contrib modules if core can do it just fine. That is, unless there are restrictions not mentioned in the original post that would make using the t() function impossible.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/90809)
Comment: How does it not provide an answer to the question? The author wants to be able to translate values from the variables table. I suggest a way to translate values from the variables table. No point in using contrib modules if core can do it just fine. That is, unless there are restrictions not mentioned in the original post that would make using the t() function impossible.


Access Resources from Externally-Created .resx File

Question: My main Windows Forms (managed C++) project has a class that presents an image with tiles that can be shown or hidden to create a responsive diagram.
I created a separate utility app that helps me get all the images positioned correctly, etc.  This app is written in C# and writes a .resx file containing the image data and positioning, using the following code snippet:

using(ResXResourceWriter resx = new ResXResourceWriter(sfd.FileName)) {
    resx.AddResource("Size", canvas.Size);
    List<int> IDs = canvas.IDs;
    resx.AddResource("IDList", IDs);
    resx.AddResource("BackgroundIndex", canvas.BackgroundIndex);
    foreach(int id in IDs) {
        String positionKey = String.Format("Position.id{0}", id);
        String visibilityKey = String.Format("Visibility.id{0}", id);
        String imageKey = String.Format("Image.id{0}", id);
        resx.AddResource(imageKey, canvas.TileImage(id));
        resx.AddResource(positionKey, canvas.TilePosition(id));
        resx.AddResource(visibilityKey, canvas.TileVisible(id));
    }
}

I can open the .resx file in a text editor and see that it is well-formed and contains the expected data.
Then I take that .resx file and add it to my main application's project.  Now I can't figure out how to get at the resources inside it.  The code I've tried is:

ResourceManager ^ image_rm = gcnew ResourceManager(
    "resx_file_name_without_extension", GetType()->Assembly);
ResourceSet ^ image_rs = image_rm->GetResourceSet(
    System::Globalization::CultureInfo::CurrentCulture, true, true);

At runtime, the second line (the GetResourceSet call) throws a System.Resources.MissingManifestResourceException with the following message text:

Resource load failure:
  Could not find any resources appropriate for the specified culture or the
  neutral culture. Make sure "resx_file_name_without_extension.resources" was
  correctly embedded or linked into assembly "my_assembly" at compile time, or
  that all the satellite assemblies required are loadable and fully signed.

I suspect my problem is...well I don't really know.  Maybe I'm not using the right identifier in the ResourceManager constructor.  I tried explicitly setting "Excluded From Build: No" and "Content: Yes" in the file's properties, but that had no effect.
Is it even possible to drop an externally-created .resx file into a project and get at the resources within?  I definitely need it compiled in; I can't ship a product with dangling .resx files.  I can always create a set of static data objects in .cpp files, but the .resx approach seemed more elegant...
Answer: Turns out a comment on this unanswered question was the secret sauce.  Prepending the root namespace to the identifier made the ResourceManager happy:
ResourceManager ^ image_rm = gcnew ResourceManager(
    "my_root_namespace.resx_file_name_without_extension", GetType()->Assembly);
ResourceSet ^ image_rs = image_rm->GetResourceSet(
    System::Globalization::CultureInfo::CurrentCulture, true, true);

Just how or why the compiler decided to place the resources within that namespace is still a bit of a mystery to me, but that's trivia for another day.
The question to which I link involves a .resx created with VS within the project, and mine involves adding one created externally, so I think it's a different-enough situation to warrant a separate Q/A.


Limit of segments ratio in partition of an arc of circle

Question: Consider an arc $(AB)$ of a circle $C$ and the partition $(A_i^n)$, where $A_0^n=A$,$A_n^n=B$. The measure of $A_{i-1}^n A_{i}^n$ will be denoted $h_n$.
Now consider the following: Trace the bissector of each angle $A_{i-1}OA_{i}$ and mark the medium point $B_{i}^n$ of the arc $(A_{i-1}^n A_{i}^n)$, then the tangente line $r_i$ to $C$ through $B_i^n$. Consider then the points
$V_{i}^{n}$ where the line $r_i$ intersects the ray $OA_i^n$, and denote $v_n$ the measure of $V_{i-1}^n V_{i}^n$.
Show that $\displaystyle\lim_{n \to \infty}  \frac{v_n}{h_n} = 1$ .
I believe that if $n \to \infty$, then $V_i^n = A_i^n$ and the limit will be trivial, but I don't quite see how to formalize this argument.
Thanks.
Comment: I'm needing an explanation on why $n \to \infty \Rightarrow V_{i}^{n} = A_{i}^{n}$
Answer: By similar triangles you have (see diagram below):
$$
{v_n\over h_n}={R\over\sqrt{R^2-h_n^2/4}},
$$
where $R$ is the radius of $C$.
But $h_n\to 0$ when $n\to+\infty$, so that:
$$
\lim_{n\to+\infty}{v_n\over h_n}=
\lim_{n\to+\infty}{R\over\sqrt{R^2-h_n^2/4}}=1.
$$


Finite Element Method Weak Formulation

Question: I have a question about the weak formulation of a PDE in finite element analysis.
Suppose we have the following two-dimensional PDE:
$$ \Delta \cdot u(x,y) = q(x,y)
$$
where $q$ is given, $u$ is unknown, and $\Delta$ is the Laplacian operator $\Delta = \left(\dfrac{\partial ^2}{\partial x^2}, \dfrac{\partial ^2}{\partial y^2}\right)$. The domain is an open set $\Omega \subset \mathbb{R}^2$. The boundary condition is that $u = 0$ on $\partial \Omega$.
The weak formulation is something like
\begin{equation}
\int_\Omega \Delta u(x,y) \cdot v(x,y)  d\mathbf{x} = \int_\Omega q(x,y) \cdot v(x,y) d\mathbf{x}\end{equation}
 for every $v$ in $H^1_0(0,1)$ (or perhaps a difference space?) However, we're going to  reduce $H^1_0(0,1)$ to considering only a finite-dimensional subspace (in this case, suppose all the basis functions are affine.)
Here comes my question. It seems we always turn the left-hand side into
$$-\int_\Omega \nabla u(x,y) \cdot \nabla v(x,y)  d\mathbf{x}$$
using Green's Identity, basically integration by parts. But why do we have to change it? Why can't we solve the system as originally stated?
I can see there's something fishy going on, since in the original system $\Delta u \equiv 0$ if we assume $u$ is piecewise-linear. But shouldn't both forms be the same? ... What's going on here?
Answer: You almost certainly can formally believe the equivalence of the two formulations if you have seen the proof of the Green's identity, right? However, when you "balance the derivatives" of the solution $u$ and the test function $v$ as you have done (in the beginning $u$ has two derivatives and $v$ zero, and in the weak formulation both have one derivatives and are, thus, balanced out), you actually end up requiring less smoothness from the solution $u$.
This implies that solutions to the weak problem are not, in general, equivalent to the solutions of the strong problem. The weak solution is equivalent to the strong solution only if  $q \in L^2(\Omega)$ and the boundary of the domain satisfies some smoothness criteria. See, e.g., the wonderful book of Lawrence Evans, Partial Differential Equations, for more information on this matter.
But why do we have to change it? Why can't we solve the system as originally stated?
This is something which you will realize when implementing the finite element solver. It is much more convenient to have only single derivative in the weak formulation than two derivatives since then the finite element is only required to be $H^1$-conforming. (Intuitively, second derivative of piecewise-linear function is zero just as you mentioned and therefore the stiffness matrix would be zero.) You could solve the problem directly with $H^2$-conforming elements but those are much more harder to construct.
Furthermore, if the weak formulation is symmetric then you end up having a symmetric stiffness matrix which is faster to solve.
Comment: Everything you said is absolutaly right. Furthermore, when we use the Green's identity, we put the problem in a variational (weak) formulation, which is related to a problem of minimization of a functional energy. Then, we can use a powerful mathematical theory assernal to solve the problem or make proofs of convergence of finite element methods.
Comment: @knl l I have a very similar question to what is posted here and I would appreciate it if you could comment on my post https://math.stackexchange.com/q/3186878/374907 I am a bit confused how how symmetry of the weak form impacts the solution found.

Finite Element Method Weak Formulation


Test iOS app on device without apple developer program

Question: I want to run the app on an iPhone. I developed the app in xcode 5.0.
Is it any way to install the app on the phone, which is not physically connected to my computer (i.e. via email)?
Please suggest.
Comment: No you can't you need to have a developer licence then create some provisioning profiles and some certificates so you can develop on a real device. Also why are you telling us your girlfriends birthday is next month? If you like sharing personal information so much please can you give me your bank details?
Comment: Please visit : http://stackoverflow.com/help/how-to-ask.
Answer: Download XCode 7. Apple has changed its policy regarding permissions required to build and run apps on devices. Until now, Apple required users to pay $99/year to become a member of Apple's Developer Program in order to run code on physical iPhone and iPads. As part of the new Developer Program, this is no longer required. Apps can be tested on devices, no purchase necessary.
Comment: Download XCode 7 and export the build for AdHoc distribution, as @slxl stated before
Answer: This is very true from Xcode 7 onwards. The membership fee is not required for testing but for submitting your app to the App Store, you'll have to pay $99/year to Apple.


How to login-redirect users to their profile page on specific days only?

Question: By using Rules Once per Day module, logged in user would be redirected to profile page on specific day. My issue is, every time when user logged in to the site, the user is redirected to profile page.
But I want this rule to work on specific days, like Monday and Thursday. How I can handle this without Rules Once per Day module?
I want to this functionality works at only once. How can I do this?
Any suggestions?
Comment: I fixed this scenario by setting the flag on User and update the Rule for logged in user using Rules Once per Day module. So, when every time user logged in, Rule will check the user is flagged or not if flagged then redirect once and in action set user unflagged again so every time user will be check.
Answer: You could do it simply by rules module (no extra module required):

Create a new rule.
Select event - user has logged in
Could add in a condition, check for a role for eg. This step is optional, and can be ignored if not required.
Select an action - Page redirect, and add the url /user to the destination.
Make sure you enable the rule.
Test, test, and test ;-)

If you want to schedule this view to run on a particular day you could check on Scheduling rules. There is also a very good video from nodeone about the same.
Comment: I want to work this rule on specific day itself like Monday and Thursday. How i can handle this without Rules Once per Day module? Please suggest.
Comment: @latikas edited the question on how a rule could be scheduled. Check it out
Answer: Even though the Rules module is one of those amazing Drupal modules, it does have some challenges with processing dates ... (= open issues in its issue queue).
Therefor consider using an approach as detailed in the (great) answer to the question about Rule to check if a date value is a specific day of the week ...
Another option is to write your own module for this. Refer to Drupal custom Rules how to write your own events conditions, actions and custom object (+custom tokens) for a great tutorial about how to do so. The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).
Part 1: Defining the Event, Condition and Action
Define the Rules Event
/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

Define the Rules Condition
/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

Define the Rules Action
/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

Part 2: Coding the custom Event, Condition and Action
Event:
Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the your_module_package_bought in it):
  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

Condition:
To evaluate the Rules condition (to check if it is TRUE or FALSE), the function your_module_condition_package_type is executed using the arguments provided. Here is an example of how such function could look like:
function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

Action:
Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named your_module_action_change_order_status.


Notice: Trying to get property of non-object

Question: I have created a module, and I am trying to use the following code:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state['view']->name == 'album1') {
    // ...
  }
  // ...
}

The line that causes the error is the following one:
if ($form_state['view']->name == 'album1') {

The error I get is the following one:

Notice: Trying to get property of non-object in mymodule_form_alter() (line 15 of C:\xampp\htdocs\drupal\sites\all\modules\mymodule\mymodule.module).
Comment: See http://drupal.stackexchange.com/questions/5185/notice-trying-to-get-property-of-non-object
Answer: $form_state['view'] is not defined for all the forms, and it is not a value set by Drupal core modules. Before to access $form_state['view']->name you should verify $form_state['view'] is defined, and it is an object (and not an array, for example).
Comment: but desired value i am getting from the variable..


Understanding Rayleigh distribution

Question: I am an aerospace enthusiast. I have obtained wind speed data that's been gathered and published by NCEP/NCAR. It provides wind speed data for every $2.5^\circ$ increment in latitude and longitude for 17 altitude levels. I want to predict the upper bound of the wind speed that a given location and altitude will face with a confidence percentage of 99. Wind speed data is usually modelled as a Rayleigh distribution. How can I find this upper bound?
I have tried something along these lines, please let me know if I'm going about it the right way.
The probability of a wind exceeding $v_i$ for each day ($d$), altitude ($h$), latitude ($\Phi$)
and longitude ($\lambda$) as
$P(d, h, \phi, \lambda)_i = e^{-\frac{\pi}{4}\left(\frac{v^2}{\mu^2}\right)}$
The percent availability (i.e., the percent of the time that the wind is less than $v_i$) is,
$\bar{P}(d,h,\phi,\lambda)_i = 1 - P(d,h,\phi,\lambda)_i \times 100%$
So the desired station keeping probability if set at 99%, we need to find $v_i$ that satisfies,
$0.99 = \frac{\sum_{d=1}^{365} P(d,h,\phi,\lambda)_i}{365}$
i.e., taking the mean of the probability over 365 days.
Is that right?
Comment: Where does the $365$ come from? Are you looking for a $99%$ probability daily speeds throughout a year are never above a given value? Assuming independence, what happens with probability $P$ per day happens with probability $1-(1-P)^{365}$ per non-leap calendar year. (Note that $1-0.99^{1/365}=2.75\times10^{-5}$, which approximates $0.01/365=2.74\times10^{-5}$.)
Comment: Oh, so should I solve for $v_i$ that satisfies $e^\left(-\frac{\pi}{4} \frac{v_i^2}{\mu^2}\right)=2.74 \times 10^{-5}$
Comment: The $2.75\times10^{-5}$ would be more accurate, but that's the basic idea. You should find $v_i\approx3.657\mu$.
Answer: Wind speed (or the magnitude of any vector with orthogonal components sampled from normal distributions) follow a Rayleigh distribution (or $\chi_2$-distribution). The density and cummulative distribution functions are (from wiki),
\begin{equation}
f(x;\sigma) = \frac{x}{\sigma^2} e^{\frac{-x^2}{(2\sigma^2)}}
\end{equation}
\begin{equation}
F(x;\sigma) = 1 - e^{\frac{-x^2}{(2\sigma^2)}}
\end{equation}
Distribution mean:
\begin{equation}
\mu(X) = \sigma \sqrt{\frac{\pi}{2}}
\end{equation}
We are interested in finding the velocity threshold where the probability of sampled velocity will be less than the threshold is 0.99. That is, we need $v_T$, such that,
\begin{equation*}
Pr(V \leq v_T) = F(v_T;\mu) = 1 - e^{\frac{-\pi}{4}\left(\frac{v_T}{\mu}\right)^2} = 0.99
\end{equation*}
using sampled mean over a year ($\hat{\mu}$),
\begin{equation*}
\hat{\mu} = \frac{\sum_{d=1}^{365}v_{d}}{365}
\end{equation*}
Inversing (with $0.99$ as $p_T$),
\begin{equation*}
v_T = \frac{-2\hat{\mu}}{\sqrt{\pi}} ln(1 - p_T) \approx 5.2 \hat{\mu}
\end{equation*}
Edit:
\begin{equation*}
v_T = \frac{2\hat{\mu}}{\sqrt{\pi}} \sqrt{-\ln(1 - p_T)} \approx 2.4 \hat{\mu}
\end{equation*}
I made an error in coming up with inverse.
Would also suggest you post it on stat stack exchange too. Please link the answer if they provide a more convincing one in your question.

Understanding Rayleigh distribution


ObjC code in Android using ndk under Linux

Question: I am trying to implement this under Linux,
Adding Objective C Support to the Android NDK
I took some references from here
http://blog.vucica.net/2011/06/developing-objective-c-apps-for-android-using-mac-os-x.html
but it doesn't compile, since the binaries are for OS-X
So after that I decided to compile the ndk-tools for Linux, following this link
http://michael.f1337.us/2011/11/19/rebuilding-the-android-ndk-for-objective-c-support/
first error I got , was missing --mpc-version info, which could be added manually in the build-gcc.sh file,
Now I am stuck at the next step, where I am getting this error
Error:
"Fixing Google Bug Copying from /home/SDKs/Android/toolchain-src/binutils/binutils-2.22.51/binutils/sysinfo.h to /tmp/ndk-root/build/toolchain/binutils-2.22.51/binutils/sysinfo.h"
Building : arm-linux-androideabi-4.6.1 toolchain [this can take a long time].
Error while building toolchain. See /tmp/ndk-root/build/toolchain/config.log
which further says :
configure: error: in `/tmp/ndk-root/build/toolchain/libbfd-binutils-2.22.51':
configure: error: C compiler cannot create executables
If anyone ever came across this or has any information regarding this, please share..
thanks a lot !!
Comment: A search for ["C compiler cannot create executables"](https://www.google.com/search?q=C+compiler+cannot+create+executables) reveals many results, some of them may be relevant for you.
Answer: I rebuild latest NDK for supporting ObjC, just from vanilla. So, you need just perform 2 scripts and change 2 files in NDK.
for download toolchain
./download-toolchain-sources.sh
and rebuild gcc, but don't forget to modify it.
./build-gcc.s
What the files you need to modify, you can find on page http://michael.f1337.us/2011/11/19/rebuilding-the-android-ndk-for-objective-c-support/


asp mvc session variables

Question: Need to store some auth information of client on server, to share between 2 pages.
Dont matter how, session, cookie, tempdata, i tried everything, and nothing works, for exampe:
public ActionResult CheckIn(string pass)
    {
        if (System.Configuration.ConfigurationManager.AppSettings["pass"] == pass)
        {
            HttpContext.Session.Add("admin", "yes");
        }
        return View();
    }
public ActionResult Helper() {
        if (HttpContext.Session["admin"] != null)
        {
            if (HttpContext.Session["admin"].ToString() == "yes")
                return PartialView("InitConfig");
            else
                return PartialView("StationLogics");
        }
        else
            return PartialView("StationLogics");
    }

and i get always null in session in helper method. what i'm doing wrong?
Answer: Have you tried HttpContext.Current.Session instead ?
ps. doing that you do is actually not good desing you should reconsider it in your application.
Comment: and i dont have HttpContext.Current
Comment: this might be good for start : http://www.asp.net/mvc/tutorials/authenticating-users-with-forms-authentication-cs
Comment: it depends what you want to do :), using session for such trivial task is bad. whole mvc framework created to make it more correct. you have to have action that would authicate user and redirect him base on his role. each action could include attbite which role it handles. you should be more familar with asp.net membership
Comment: thx. so, i want to call controller, with diffrent roles, have u any links about it?
Answer: Are you sure that all those if conditions are met? Try with a simple example:
public ActionResult CheckIn()
{
    Session["foo"] = "bar";
    return View();
}

public ActionResult Helper()
{
    var foo = Session["foo"];
    if (foo == null)
    {
        // this won't be null if you called the CheckIn method first
    }
    return View();
}

Call the CheckIn action first to store a value in the session and then call the Helper action. Unless you have disabled session for this ASP.NET application or cookies in your browser you should get correct value.
Comment: i;m sure, looking by debugger. how can i check enbled or disabled session in my app?
Comment: And what about cookies? Are they enabled in your browser?

asp mvc session variables


Error when trying to view revisions

Question: Using Drupal 8/9. When trying to view previous revisions I am getting the following error:
Error: Call to a member function getType() on string in clc_d8_theme_theme_suggestions_page_alter() (line 13 of /var/www/html/wrc/web/themes/clc_d8_theme/clc_d8_theme.theme)

It refers to this code:
function clc_d8_theme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType()); <-- error at this line
  }
}

I need the type suggestions for my theme. How do I fix this? I thought the check on the node would be enough to avoid issues.
Answer: "$node" can vary a bit by context, but here are some ways to set $node:
$routeName = \Drupal::routeMatch()->getRouteName();

$node = NULL;

// $variables['node'].
if (isset($variables['node'])) {
  $node = $variables['node'];
  if (is_numeric($variables['node'])) {
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($variables['node']);
  }
}

// $variables['row'].
if (isset($variables['row']) && !empty($variables['row']->nid)) {
  $node = \Drupal::entityTypeManager()->getStorage('node')->load($variables['row']->nid);
}

// $routeName === 'entity.node.canonical'.
if ($routeName === 'entity.node.canonical') {
  $node = \Drupal::routeMatch()->getParameter('node');
}

// $routeName === 'entity.node.revision'.
if ($routeName === 'entity.node.revision') {
  $revisionId = \Drupal::routeMatch()->getParameter('node_revision')->getRevisionId();
  $node = node_revision_load($revisionId);
}

// $routeName === 'entity.node.preview'.
if ($routeName === 'entity.node.preview') {
  $node = \Drupal::routeMatch()->getParameter('node_preview');
}

if ($node) {
  // run your code...
}

Specifically, it looks like you're after:
// Get route name.
$routeName = \Drupal::routeMatch()->getRouteName();

// Check if route is node revision.
if ($routeName === 'entity.node.revision') {
  $revisionId = \Drupal::routeMatch()->getParameter('node_revision')->getRevisionId();
  $node = node_revision_load($revisionId);
}

This will fully load your node object and ->getType() should work without error.

Error when trying to view revisions


Inverse elements in the absence of identities/associativity.

Question: Lets view groups as consisting of a binary operation, a distinguished element $e$, and unary operation $x \mapsto x^{-1}$. Then the group axioms can be stated as follows.

$(xy)z=x(yz).$
$xe=ex=x.$
$xx^{-1}=x^{-1}x=e.$

Supposing we dropped axiom 2 and forgot about $e$, we would need to rephrase 3. One possibility would be
3'. $xx^{-1}y=x^{-1}xy=yxx^{-1}=yx^{-1}x=y.$
So my first question is, can 3' be shortened and simplified?
Now suppose we dropped associativity, as well. Then 3' needs to be further rephrased. One possibility would be
3''. $(xx^{-1})y=(x^{-1}x)y=y(xx^{-1})=y(x^{-1}x)=y,$ and $x(x^{-1}y)=x^{-1}(xy)=(yx)x^{-1}=(yx^{-1})x=y.$
Again, my question is, can 3'' be shortened and simplified?
Answer: This isn't exactly an answer to your question, but I thought you might like to know how inverse elements are defined in semigroups (i.e. structures with only your first axiom).
If $S$ is a semigroup, and $a\in S$, then an inverse of $a$ is any element $b\in S$ such that $aba=a$ and $bab=b$.  This is equivalent to the usual definition in the case of groups, and doesn't necessitate the existence of an identity (as your 2' ends up doing).
An element can have more than one inverse.  If every element of $S$ has a unique inverse, then $S$ is called an inverse semigroup.  Inverse semigroups are very nice objects which capture the idea of partial symmetry.
I know very little about non-associative structures, so I'm not sure whether there is a standard definition of inverse there.  You might find the section on inverse properties in quasigroups here of interest.
Comment: There is a very neat connection to ring theory hidden here. When for $a$ there exists a $b$ such that $aba=a$, we call $a$ regular. Rings for which every element is regular are exactly the von Neumann regular rings. I thought that when, in addition, $bab=b$ that $a$ would be called "biregular" but I am not certain that's been done. If memory serves, I think it is true that every element of a von Neumann regular ring without nilpotent elements is "biregular" (or semigroup-invertible). So, they are kind of like analogues of division rings since all elements are semigroup-invertible.
Comment: I think the reason that 'biregular' is not a standard concept is that regularity already implies the existence of an inverse: If $aba=a$, then $bab$ is an inverse for $a$, since $a(bab)a = (aba)ba = aba = a$ and $(bab)a(bab) = b(aba)bab = babab = b(aba)b = bab$.
Comment: So, in summary, your second-to-last sentence is true even without the 'without nilpotent elements' assumption.
Comment: Ah ok, then the concept of biregular rings (in [Jacobson's *Structure of rings*](http://books.google.com/books?id=KlMDjaJxZAkC&printsec=frontcover&dq=jacobson+structure+of+rings+biregular&hl=en&sa=X&ei=zCRTUfK0EaTD4APq24Fg&ved=0CD0Q6AEwAA#v=onepage&q=biregular&f=false) ) deals with something stronger then. Thanks for showing me the trick! I guess that means von Neumann regular rings are the 'semigroup-invertible rings' then.
Answer: You are assuming (indeed, using) the very axioms you are trying not to introduce or rely upon, even though you clearly are relying on them, which is not at all desirable in mathematics.
We need to state such assumptions explicitly, if we are going to use them, as they also serve as "definitions:" definitions required if 3' and 3'' are to express what you want them to express.
What does $x^{-1}$ mean with respect to $x$ if we do not define it in terms of some element $e$ for which $ex = xe = x$, such that there exists an element $x^{-1}$ with $x^{-1}x = xx^{-1} = e$?
Similarly, with associativity.

I'm not entirely clear about your motivation. If you want to maintain the integrity of a group structure, we need axioms $1, 2, 3$, though the axioms are equivalent to requiring only left-identity and left-inverse in the second and third properties/axioms:
$(2')$ $\exists e^L, \forall x: \;e^Lx = x$
$(3')$ $\forall x, \exists x^{-1^L}:\; x^{-1^L}x = e^L$
With associativity, one can prove that $e^L = e \;$ as in $(2)$, and $\;x^{-1^L} = x^{-1}\;$ as in $(3)$.
Comment: Well $x \mapsto x^{-1}$ is just a unary operation. Such an operation needn't behave as we expect inverses to behave.
Answer: a. You already capture 2. in once with 3'.:
Let $e:=xx^{-1}$ for an arbitrary but fixed $x$, then we have
$ey=y=ye$ according to 3'. for all $y$, so $e$ is a unit, so must be unique, alternatively, we can get $yy^{-1}=yy^{-1}xx^{-1}=xx^{-1}$.
b. Again, the first part of 3''. states that $xx^{-1}$ is a unit (and also $x^{-1}x$), so we didn't really get rid of 2., and the associativity is not needed for showing uniqueness of a unit ($e=ef=f$ if $e,f$ are both units).
However, the original group axioms can also be simplified, one only needs to require the existence of a left unit $e$ and a left inverse for all $x$.
Answer: Unless I'm missing something obvious, any nonempty set $S$ with axioms 1, 2, and 3' is in fact a group.  First, take any $y \in S$.  Certainly $yy^{-1} \in S$ because the operations of multiplication and inverse are defined in $S$.  Let $z=yy^{-1}$.  Then for all $x \in S$, we have $zx=xz=x$.  Thus $z$ is an identity.  Furthermore, an elementary argument shows $z$ is unique.  Voila, $S$ is a group.
But with non-associativity, I am out of my element (no pun intended).....
Hope this helps!
Answer: Foreword: I am surprised because I may (I must...) have read this question several times before tonite but only now I thought about adding one definition, not yet mentioned in this thread, that may hopefully be pertinent and interesting as well among the others.

In associative structures, the inverse element is defined after the identity element. In a generic (non associative) groupoid, an inverse property can be defined without identity element instead.
A groupoid or quasigroup $G$ has the left inverse property if
$$
\forall x\in G, \exists\ z\in G : z(xy)=y\ \forall y\in G\tag{1}
$$
and has the right inverse property if
$$
\forall x\in G, \exists\ t\in G : (yx)t=y\ \forall y\in G.\tag{2}
$$
$G$ is also said to have the inverse property if it satisfies both the above equations.
If $z$ as in $(1)$ exists and the groupoid $G$ is a quasigroup, such $z$ is also unique because in a quasigroup the equation $z(xy)=y$ has a unique solution $z$ given $x,y$: therefore we can denote $z$ with $x_l^{-1}$.
If $t$ as in $(2)$ exists and the groupoid $G$ is a quasigroup, such $t$ is also unique because in a quasigroup the equation $(yx)t=y$ has a unique solution $t$ given $x,y$: therefore we can denote $t$ with $x_r^{-1}$.
Let now $G$ be a loop with identity element $e$. Then:
$$
\forall x\in G, \exists\,!\,x_l\in G : x_l\,x = e
$$
and
$$
\forall x\in G, \exists\,!\,x_r\in G : x\,x_r = e.
$$
The (existence and) uniqueness of $x_l$ and $x_r$ is again due to the fact that the loop is a quasigroup and hence all linear equations have a unique solution in here. We can call $x_l$ and $x_r$ left inverse of $x$ and right inverse of $x$ respectively.
But beware: in the absence of associativity, the only existence of $x_l$ and $x_r$ does not imply $(1)$ and $(2)$ to be verified, indeed not all the loops have the inverse property.
(Source)


Accessing a REST API from behind a firewall: whitelist the API's outbound IP addresses?

Question: We have two applications. One application exists behind an on-premise site's firewall. It communicates with our second application, a service app that operates a REST API in the Azure cloud.
My question relates to the on-premise firewall. The service app in the Azure cloud has a single static inbound IP address. It also has a slew of outbound IP addresses. I plan to whitelist the Azure service app's inbound IP address. Do I also need to whitelist the outbound IP addresses?
(Does the REST API's response go through the outbound IP, or does the response travel back through another mechanism.)
Answer: Ordinarily you would not need to whitelist anything outbound as most firewalls allow outbound connections from any host by default. In the case of a REST API you should not need to whitelist the outbound, even if your firewall is set to block all outbound, because most times the response will be made along the same connection that made the query. If a separate connection is needed for the response, the firewall generally will have retained enough state to know that the query connection inbound between these hosts was allowed, so the outbound response between the same two hosts will also be allowed.


React custom onClick event with parameter

Question: I'd like to have a custom onClick event fired any time one of my  is selected, however I can't get the step.id to be passed properly. stepId is undefined when I try to dispatch requestStep. Any thoughts?
var requestStepOnEnter = ({ stepId }) => {
  store.dispatch(requestStep(stepId));
};

const ExperimentDetail = ({ steps }) => (

    {
      steps.map(step =>
        <NavItem
         eventKey={step.order}
         key={step.id}
         onClick= {() => requestStepOnEnter(stepId)}>
         {step.order}
        </NavItem>
      )
    }

);

export default ExperimentDetail;

Answer: Change
var requestStepOnEnter = ({ stepId }) => {
  store.dispatch(requestStep(stepId));
};

to
var requestStepOnEnter = (stepId) => {
  store.dispatch(requestStep(stepId));
};

because you aren't passing an object, so the signature is wrong. Alternatively, pass stepId in an object:
onClick= {() => requestStepOnEnter({ stepId })}>

const test = ({ prop }) => console.log('The value of prop?' , prop);

test({ prop: 'works' });

test('doesnt work');

Another problem would be that you're calling requestStepOnEnter with the argument stepId which is undefined. The correct should be step.id

Here is a working suggestion
var requestStepOnEnter = (stepId) => {
  store.dispatch(requestStep(stepId));
};

const ExperimentDetail = ({ steps }) => (

    {
      steps.map(step =>
        <NavItem
         eventKey={step.order}
         key={step.id}
         onClick= {() => requestStepOnEnter(step.id)}>
         {step.order}
        </NavItem>
      )
    }

);

export default ExperimentDetail;


Condição para o INSERT INTO

Question: Preciso que o SQL Confira se na '@variavel' enviada existe algum valor igual a 1, 2 ou 3; Caso seja verdeiro insira o valor 1, do contrario insira o valor 0.
Obs: a tabela e coluna podem ser dadas de exemplo como fictícias.
Comment: Em qual banco de dados? O SQL em si não aceita isto de forma padrão, mas extensões da linguagem de um banco de dados pode aceitar, provavelmente deveráa ser em uma *stored procedure*.
Comment: Assim como o seu script de `INSERT`
Answer: Basicamente isso:
INSERT INTO tabela SET coluna = IF( @variavel IN (1,2,3), 1, 0 );

O IN retorna verdadeiro se a variável estiver na lista

O IF retorna o segundo valor se a primeira expressão for verdade, senão retorna o terceiro.

Veja funcionando no SQL Fiddle.
Notas:

Em T-SQL a partir do 2012, existe a função IIF, que funciona da mesma forma que o IF do MySQL/MariaDB

Para outros DBs tem o CASE, pode ver mais detalhadamente neste post:

Retornar valores pré-definidos dependendo de condição lógica
Answer: Usando SQL Ansi, que funciona em todos os bancos de dados, você pode fazer algo como:
insert into dados (coluna1) values (
case @parametro
   when 1 then 1
   when 2 then 1
   when 3 then 1
   else 0
end)

Condição para o INSERT INTO


Can't split tensor due to () shape

Question: If i print tensor.shape I get this:
tf.Tensor(b["Can we make this quick?  Roxanne Korrine and Andrew Barrett are having an incredibly horrendous public break- up on the quad.  Again.",
"Well, I thought we'd start with pronunciation, if that's okay with you.",
'Not the hacking and gagging and spitting part.  Please.',
"Okay... then how 'bout we try out some French cuisine.  Saturday?  Night?"],
shape=(), dtype=string)

Why my shape is () ? I want to split each phrase to 2 tensors:

Tensor A will have phrases 1 and 3
Tensor B will have phrases 2 and 4

But I cannot use split because my tensor shape is (). I've tried to change its shape with set_shape(1, ) but I get this:
ValueError: Tensor's shape () is not compatible with supplied shape [1, None]

Comment: what is `b` here?
Comment: @NicolasGervais b stands for binary in tensorflow (if i'm not wrong). i've just formatted its output so that it could be more readable
Comment: Please add code to show how you created the tensor of strings
Comment: You can use `tf.strings.split('hello world').numpy()`. Thanks!
Answer: Well this is common tensor are design to handle multi dimension (array within an array) but it looks like you got a single array wrap around a single string.
Just do normal string processing
split_str = my_str.split('\n')

Can't split tensor due to () shape


How to resolve the $ conflict between jQuery and mooTools?

Question: Okay, I have been working for quite some time on a website for a friend.. My coding skills are .. questionable, and I've been having quite a few problems.
Currently the jQuery on my site simply stopped working, I could not find the reason, and I have done everything I could to try to get it to work. ( I have followed countless guides all over the internet, for troubleshooting etc. and I still cannot get it to work)
Then after looking closely at the errors, using the browser console I've found out that mootools and jQuery are conflicting between $.
I've been trying to use jQuery.noConflict() but I can't seem to figure out how to use it.
Could anyone help me?
Sincerely yours, Malmoc
Answer: After making the call to jQuery.noConflict() you just need to refer to the jQuery object as jQuery instead of $. Your code would need to be updated to reflect this:
$(document).ready();

Would become
$.noConflict();
jQuery(document).ready();

Answer: Once you've called $.noConflict(), you would proceed to use jQuery instead. If you want to continue using $, you can do so by using a closure:
// Free-up $
$.noConflict();
// Use jQuery as '$' safely
(function($){
    // Fire on ready
    $(function(){
        alert( "Page loaded" );
    });
})(jQuery);

This prevents any outside code from tampering with the $ within the closure.
Answer: jQuery.noConflict() restores the value of $ to whatever it was before.
This means you're going to have to use jQuery to refer to jQuery from then on.
A neat way to keep using jQuery as $ is to do something like this:
(function ($) {
    // $ is actually jQuery here
    $(document).ready(function () {

    })
}(jQuery))

Answer: A simple solution would be to wrap your jQuery code like so:
(function($)
    $(document).ready(function() {
        $('#myelementID').fadeIn(399);

        //do other jQuery stuff ....
    });
})(jQuery);

Answer: $ = jQuery
jQuery = $
Your experiencing collision of your $,
A. Drop Mootools or Jquery
B. Use jQuery('selector') instead of $()
C. Reference the $ to something else, buckWildProgramming = $

Hope that helps.


Parameter obj to Document() must be an object when trying to convert array to mongoose document with redis

Question: I have using redis to cache my queries. Its working fine with object but not when i get array. It gives me an error **"Parameter "obj" to Document() must be an object, got kids", **. It also happens with count query. Here is my code :
const mongoose = require("mongoose");
const redis = require("redis");
const util = require("util");

const client = redis.createClient(process.env.REDIS_URL);
client.hget = util.promisify(client.hget);

const exec = mongoose.Query.prototype.exec;

mongoose.Query.prototype.cache = async function (options = {}) {
    this.useCache = true;
    this.hashKey = JSON.stringify(options.key || "");
    this.time = JSON.stringify(options.time || 36000);

    return this;
};

mongoose.Query.prototype.exec = async function () {
    if (!this.useCache) {
        return exec.apply(this, arguments);
    }
    const key = JSON.stringify(
        Object.assign({}, this.getQuery(), {
            collection: this.mongooseCollection.name,
        })
    );
    // client.flushdb(function (err, succeeded) {
    //  console.log(succeeded); // will be true if successfull
    // });

    const cacheValue = await client.hget(this.hashKey, key);

    if (cacheValue) {
        const doc = JSON.parse(cacheValue);
        /*
        this.model refers to the Class of the corresponding Mongoose Model of the query being executed, example: User,Blog
        this function must return a Promise of Mongoose model objects due to the nature of the mongoose model object having other
        functions attached once is created ( validate,set,get etc)
      */

        console.log("Response from Redis");
        console.log(doc);
        console.log(Array.isArray(doc));

        return Array.isArray(doc)
            ? doc.map((d) => new this.model(d))
            : new this.model(doc);
    }

    //await the results of the query once executed,  with any arguments that were passed on.

    const result = await exec.apply(this, arguments);

    client.hset(this.hashKey, key, JSON.stringify(result));
    client.expire(this.hashKey, this.time);
    console.log("Response from MongoDB");

    return result;
};

module.exports = {
    clearHash(hashKey) {
        client.del(JSON.stringify(hashKey));
    },
};

Data in redis - [ 'kids', 'men', 'women' ]
Query -     const collectionType = await Product.find() .distinct("collectionType") .cache({ key: "COLLECTION_TYPE" });
can i anyone please tell me what i am doing wrong?
Answer: I have solved by directly returning the doc and its working fine. Not sure if it is the right way if i directly do return doc then sending data from redis only


Match (and delete) LF character in Notepad++ regex

Question: In Notepadd++ the \r\n regex will find all the CRLF combinations.  But I have some lines which end just with LFs. First of all, what is that that?  Next, how can I match and delete just that?  Neither \r or \n works.
Comment: @BoltClock  it matches CR and CR/LF combinations..
Comment: Are you sure `\n` doesn't work?
Answer: LF stands for 'Line Feed'
You can read some more on this answer on serverfault.se:

CR LF means "Carriage Return, Line Feed" - it's a DOS hangover from
  the olden days from when some devices required a Carriage Return, and
  some devices required a Line Feed to get a new line, so Microsoft
  decided to just make a new-line have both characters, so that they
  would output correctly on all devices.
Windows programs expect their newline format in CRLF (\r\n). *nix
  expect just LF data (\n). If you open a Unix text document in Notepad
  on windows, you'll notice that all of the line breaks dissapear and
  the entire document is on one line. That's because Notepad expects
  CRLF data, and the Unix document doesn't have the \r character.
There are applications that will convert this for you on a standard
  *nix distro (dos2unix and unix2dos)
For those wondering, a carriage return and a line feed differ from
  back in Typewriter days, when a carriage return and a line feed were
  two different things. One would take you to the beginning of the line
  (Carriage Return) and a one would move you one row lower, but in the
  same horizontal location (Line Feed)

Thus, you should be able to replace it with \n.
Comment: `\n` matches both `LF` and `CRLF`
Comment: Is there an answer within Notepad++?
Comment: @thomas Updated my answer with some pictures of how I used `\n` to remove the `LF` characters.
Comment: And disregard the regex in the background, it was something I was trying and it was left there for I don't know how long =P
Comment: Thanks. I don't know why that doesn't work for me. I'm not even sure how you got the LFs on a line by themselves.
Comment: @thomas The `CR` are carriage returns and I just replaced `\r` by nothing. :)
Answer: Using common sense I would suggest following approach:

Replace all the CRLFs with some special string (that you are sure is not present in file), say "fuuuuuu!!!".
Replace LFs with empty string.
Replace all the special strings ("fuuuuuu!!!") back with CRLF.

And you are done.
Comment: how do you replace "LF"s; that is the question
Comment: This seems the right answer. Problem was to replace only \n and let \r\n as is eventually.
Answer: Set the encoding to ANSI.
Then \n will see only "LF"
Comment: Are you sure? Where have you seen that?


Count infinite occurrence

Question: I am working on a game theory assignment where a game $G$ is played on a graph. Let $G = (V,E)$ where $V$ is a set of all vertices and $E$ a set of all edges connecting said vertices.
Two players Adam and Eve take alternating turns moving from vertex to vertex along the existing edges. More information about the game exists but is not relavant for my question.
An infinite play $P$ is won by Eve if some position (a vertex that they moved to) repeats infinitely often, otherwise Adam is the winner.
I want to write this condition down as formally as I can and I came up with the following
$$\forall p\in V, \sum_{i \in P:i=p}^\infty 1 = \infty$$
Is this a valid notation? Is there a better/more efficient/more easily understandable way of writing the winning condition?
Forgive me if I got the formatting wrong, this is my first time posting anything math related on any stack exchange community.
Comment: "Formally" is not the same thing as "without using words". If you say "An infinite play is won by Eve if some position repeats infinitely often, otherwise Adam is the winner", that's formal. "If you say $\exists \sum p \sum i \mathbin{\forall} \infty$" or whatever, that's *shorthand*. You would use it if you're trying to state the condition as concisely as possible.
Comment: It seems like you want to say $\exists p$ instead of $\forall p$.  As it is, it says that every position occurs infinitely often.
Comment: You would need to formalise the notion of *position* and make sense of phrases *infinitely often* and *eventually*. Your proposed condition is incomprehensible as it is.
Comment: @AlvinLepik Thanks for the feedback, a position is a vertex that is part of the play. In other words, they moved to or from that vertex at some point during their play.
Infinitely often in this case means that the number of times that the position occurs in the play is equal to infinity.
Comment: @saulspatz you're right, I suppose I was more looking at as a for each loop logic, but that does make sense.
Answer: The first thing you should do is to give a formal definition of a play. It could be defined as a sequence $(v_n)_{n \geqslant 0}$ of vertices of your graph such that, for each $n$, $(v_n, v_{n+1})$ is an edge of the graph. Thus a play is just an infinite path $p = v_0 \rightarrow v_1 \rightarrow v_2 \rightarrow \dotsm\ $ in the graph. You can now define
$$
  \text{Inf}(p) = \{v \in V \mid v \text{ occurs infinitely often in the sequence $(v_n)_{n \geqslant 0}$} \}
$$
Now your winning condition is usually expressed as a condition on $\text{Inf}(p)$.
Comment: Really nice answer, very clear and seems to cover all bases.
Comment: you're welcome.

Count infinite occurrence


Test for homogeneity in meta-analysis with a large number of studies

Question: So I am conducting some literature searches on behalf of someone. I stumbled across a meta-analysis which used 23 studies. It tested the homogeneity of the studies used, using what I think is a Cochran's Q test. The output is as follows:
Heterogeneity: $\hat{\tau}^2 = 0.11$; $Q = 35.59$, $df = 13$ ($P = 0.0007$); $I^2=63%$
The issue is that I think this output means that these studies fail the test of homogeneity and thus a meta-analysis is not appropriate. Am I incorrect in this?
My second question is: Does increasing the number of studies used increase the heterogeneity anyway and thus might it be the case that this test was going to be significant anyway due to sample size?
Any help in understanding this would be greatly appreciated.
Answer: The null hypothesis that is tested by the Q-test is that the true effects/outcomes are homogeneous. Since the test is significant, we would reject that null hypothesis and conclude that the true effects are heterogeneous.
I would not say that the studies "fail" the test, but phrasing is a matter of taste. More importantly, there is no reason to consider a meta-analysis inappropriate just because the test is significant. I don't know what kind of analyses the authors did, but the common strategy is to account for heterogeneity by fitting a random-effects model, which provides us with an estimate of the average true effect (and an estimate of the amount of variance in the true effects -- that is in fact the $\hat{\tau}^2$ value).
With respect to the second question: Increasing the number of studies does not automatically increase the amount of heterogeneity. However, the power of the Q-test to reject the null hypothesis increases as the number of studies increases. But this assumes that the true effects are really heterogeneous. If they are homogeneous, then the chances that you will reject the null hypothesis is not influenced by the number of studies.


Iframe not resizing anymore since timeline update

Question: Since the update to timeline, my resize scripts stopped working on facebook.
This is my code:
CSS:
html {

margin:0;
padding:0;
height:1500px;
}

body {
width:520px;
padding:0;
margin:0;
height:1500px;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#555859;
}

In the body:

In the footer:

In the app, I've set the Canvas Height to fluid.
Am I missing something important? Is there a better way?
Answer: Try modifying the code like this:
window.fbAsyncInit = function () {
    FB._https = (window.location.protocol == "https:");
    FB.init({
        appId : 'YOUR_APP_ID',
        status : true,
        cookie : true,
        xfbml : true
    });
    FB.Canvas.setAutoGrow();

}


Convergence of average of uncorrelated random variables

Question: Let $(X_n)_{n\ge 1}$ be a sequence of pairwise uncorrelated random variables. If their second moments are uniformly bounded then
$$\frac{S_n-E(S_n)}{n}\overset{a.s.}{\to} 0$$
I know how to for convergence in $L^2$, but no clue for the almost sure case. I would appreciate some hint.
Comment: A first idea to try is to apply Borel-Cantelli. It "almost" works, but do you see how to start?
Comment: Right, that's why it does not "exactly" work (but if we had something slightly lower than $1/n$, it would converge). Now someone has given the full answer below, but you can see that the idea is to look instead at an extracted subsequence of $S_n/n$ (say $S_{n^{1.01}}/n^{1.01}$) to be able to use Chebyshev upper bound, and then bound the increase that you did not take into account between $n^{1.01}$ and $(n+1)^{1.01}$
Comment: I know it is enough to prove that $\sum_{n\ge 1} P[\vert \frac{S_n-E(S_n)}{n}\vert > \varepsilon]<\infty$ for every positive $\varepsilon$, but I did not manage to prove it.
Comment: I thought about using $P[\vert \frac{S_n-E(S_n)}{n}\vert > \varepsilon]\le P[\vert \frac{S_n}{n}\vert > \frac{\varepsilon}{2}]+P[\vert \frac{E(S_n)}{n}\vert > \frac{\varepsilon}{2}]$ but I don´t know if it helps. How can apply the properties I know about the expectations?
Comment: To simplify, we can try to prove it assuming, say, $\mathbb{E} X_i=0$ and $\mathbb{E} X_i^2\le 1$ (second moment uniformly bounded by one). In that setting you want to estimate $P(|S_n/n|>\varepsilon)$. Can you find some upper bound with your uncorrelation/second moment assumptions?
Comment: I tried to apply Chebyshev's inequality, but I could only prove that this probabilty is bounded above by $\frac{1}{n}$, which is not useful.
Comment: I guess the person has deleted the answer, but I'll try to follow your path
Answer: I prove the following theorem:

Theorem
Let $(X_n)_{n\ge 1}$ be a sequence of pairwise uncorrelated random variables which are bounded from below by a constant. If their second moments are uniformly bounded then
$$\frac{S_n-E(S_n)}{n}\overset{a.s.}{\to} 0$$

Without loss of generality,  let $$\mathbb{E}(X_n^2) \le 1 $$ for all $n$. So $$\mathbb{E}(|X_n|) \le 1 \quad \forall n$$
Also,WLOG: $X_n$ are nonnegative random variables,i.e
$$X_n \ge 0$$
for all $n$
For all $\epsilon >0$, we have:
$$\begin{align}
&\sum_{n \ge 1} \mathbb{P} \left( \left| \frac{S_{n^2}-\mathbb{E}(S_{n^2})}{n^2} \right|> \epsilon \right) \stackrel{\text{Markov's}}{\le}& \frac{1}{\epsilon^2} \sum_{n \ge 1} \mathbb{E} \left( \left| \frac{S_{n^2}-\mathbb{E}(S_{n^2})}{n^2} \right|^2 \right)
\stackrel{\text{pairwise uncorr.}}{\le} \frac{1}{\epsilon^2}\sum_{n\ge 1}\frac{1}{n^2} < \infty
\end{align}
$$
Thus,
$$\lim_{n} \frac{S_{n^2}-\mathbb{E}(S_{n^2})}{n^2} = 0 \quad \text{a.s}$$
Now for any $m \in \mathbb{N}$, let $n$ be the positive integer such that $n^2 \le m <(n+1)^2$ (thus $n= \lfloor \sqrt{m}\rfloor$), we see that:
$$S_m - \mathbb{E}(S_m)= S_{n^2}-\mathbb{E}(S_{n^2})+\sum_{k=n^2+1}^m \left( \underbrace{ X_k}_{ \ge 0} -\underbrace{ \mathbb{E}(X_k)}_{ \le 1}\right) \ge S_{n^2}-\mathbb{E}(S_n^2)-(m-n^2) \ge \left(S_{n^2}-\mathbb{E}(S_n^2)\right) -2n$$
So
$$\liminf_{m\rightarrow \infty} \frac{S_m -\mathbb{E}(S_m)}{m} \ge \liminf_{n=[\sqrt{m}]; m\rightarrow +\infty}\frac{n^2}{m}\left( \frac{S_{n^2} -\mathbb{E}(S_{n^2})}{n^2}  -\frac{2}{n}\right) = 0 \quad \text{a.s}$$
Similarly, we can show that:
$$S_m - \mathbb{E}(S_m) \le S_{(n+1)^2}-\mathbb{E}(S_{(n+1)^2})+2n+1$$
and then deduce that:
$$\limsup_{m\rightarrow \infty} \frac{S_m -\mathbb{E}(S_m)}{m} \le 0 \quad \text{a.s}$$
Hence
$$\frac{S_n-\mathbb{E}(S_n)}{n} \xrightarrow[]{n \rightarrow \infty} 0 \quad \text{a.s}$$
$\square$
P.s: I undeleted my answer by because it seems like someone might need it
Comment: Just to make sure I understand: $\sum_{n \ge 1} \mathbb{P} \left( \left| \frac{S_{n^2}-\mathbb{E}(S_{n^2})}{n^2} \right|> \epsilon \right)<\infty$ implies $ \mathbb{P} \left( \left| \frac{S_{n^2}-\mathbb{E}(S_{n^2})}{n^2} \right|> \epsilon \text{ for infinitely many } n \right)=0$ by Borel-Cantelli, and using the argument from https://math.stackexchange.com/a/2079377/522332 we get that $\lim_{n} \frac{S_{n^2}-\mathbb{E}(S_{n^2})}{n^2} = 0$ a.s. ?
Comment: And for the $\limsup$ part we need to use the fact that $\frac{(n+1)^2}{m}\leq (1+\frac{1}{n})^2 \to 1$ as $m\to \infty$ so that $\frac{(n+1)^2}{m}$ is bounded right?
Comment: Yeah, it is Borel-Cantelli and the limit you are talking about.
Comment: Ok and we need the boundedness of $\frac{(n+1)^2}{m}$ right? For the $\limsup$ part I mean.
Comment: I think the existence of limit is what is required.
Comment: I get $ \limsup_{m\rightarrow \infty} \frac{S_m -\mathbb{E}(S_m)}{m}\leq  \limsup_{m\rightarrow \infty} \frac{(n+1)^2}{m} \bigg( \frac{ S_{(n+1)^2}-\mathbb{E}(S_{(n+1)^2})}{(n+1)^2}+\frac{2n+1}{(n+1)^2} \bigg)$ and from there I need to use  that $\frac{(n+1)^2}{m}\leq (1+\frac{1}{n})^2 \to 1$ as $m\to\infty$ no?
Comment: I didn't check your calculation but it looks generally correct.
Comment: Do you know a book reference for this result?
Comment: I don't know. I just came up with it, but I think it's a well-known result


Visual composer elements cannot be edited in wordpress

Question: I have purchased Jupiter theme and i have been using it for a number of website. But recently i am not able to work on the theme because the theme default plugin Visual composer is not working properly. When i go to edit page to edit the elements it shows blank and stays idle. I also tried to reduce the version of WordPress to 4.4 but still no use. Can somebody please support to solve this issue. The theme support has expire so no hope on that. And i am not so techie to sort what the exact problem is. If someone can guide me to solve it, it would be much appreciated. Many many thanks in advance.
The following image show the what i have explained
Comment: if you purchased the theme, you are likely also entitled to get support, so I'd suggest to contact the vendor instead of asking here
Comment: I think you can ask in support forum of the theme. Otherwise it seems like that the issue is with your admin-ajax.php, please check your console for any errors.
Answer: I think it is the compatibility issue of visual composer with the wordpress. If the visual composer installed it not latest there are the chances of conflict with latest versions of wordpress. So you may please confirm that the plugin you are using is compatible with the wordpress version you are using on your site.
Comment: Can you tell me how can i check the version compatibility?


Mean Absolute Error (MAE) derivative

Question: $$MAE=|y_\textrm{pred} - y_\textrm{true}|$$
$$\dfrac{\mathrm dMAE}{\mathrm dy_\textrm{pred}} = ?$$
I'm trying to understand how MAE works as a loss function in neural networks using backpropogation. I know it can be used directly in some APIs - e.g. Keras - however I see tensorflow doesn't allow it (although you can manually declare it tf.abs(tf.minus(y_pred,y_true))).
My question is: How is the derivative of MAE generally calculated (I only found this which uses an apparently complex approximation) and specifically how is it computed in tensorflow (when manually declaring) and keras?
Answer: The mae, as a function of $y_{\text{pred}}$, is not differentiable at $y_{\text{pred}}=y_{\text{true}}$. Elsewhere, the derivative is $\pm 1$ by a straightforward application of the chain rule:
$$\dfrac{d\text{MAE}}{dy_{\text{pred}}} =
\begin{cases}
  +1,\quad y_{\text{pred}}>y_{\text{true}}\\
  -1,\quad y_{\text{pred}}<y_{\text{true}}
\end{cases}$$
The interpretation is straightforward: if you are predicting too high ($y_{\text{pred}}>y_{\text{true}}$), then increasing $y_{\text{pred}}$ yet more by one unit will increase the MAE by an equal amount of one unit, so the gradient encourages you to reduce $y_{\text{pred}}$. And vice versa if $y_{\text{pred}}<y_{\text{true}}$.
Skimming the paper you link, it seems like they approximate the MAE by a differentiable function to avoid the "kink" at $y_{\text{pred}}=y_{\text{true}}$.
As to what specifically is implemented in TensorFlow and keras, that is off-topic here. Best to consult the documentation, the source code or any specific help community.
Comment: @PranitBankar: yes indeed. If you are at any point that is different from the minimum, moving towards the minimum will reduce the MAE value - and the amount of the reduction does not depend on where you started.
Comment: But doesn't this mean that the weighted increase or decrease is independent of the magnitude of the error?
Comment: Thanks, I'm guessing implementations are programmed to default to either +1 or -1 if y_pred=y_true, I'm sure I've read somewhere that's how the Relu is normally handled.
Answer: As for Tensorflow's Keras here is the good answer:
TensorFlow or Theano: how do they know the loss function derivative based on the neural network graph?
And if we will dig into the source code we will see that it uses math_ops.sign wich is return 0 for 0:
https://github.com/tensorflow/tensorflow/blob/c91e944d626b517781af6a63c0aee302ab2457e3/tensorflow/python/ops/math_grad.py#L577
Answer: In this way, we can use Subgradient method
Subgradient descent
$$w^{t+1}=\ w^t-\alpha g$$
$$g=\begin{cases}1& x> 0 \\ [-1,1] & x=0\\-1 & x<0\end{cases}$$
Derivation of MAE with L1 and L2 regularization
$$MAE=\frac{1}{n}\sum_{i=0}^{n}\left|y_{pred}-y_{true}\right| \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,{(\left|u\right|)}^′=\frac{uu^′}{\left|u\right|}$$

L1
L2

$$MAE=\frac{1}{n}\sum_{i=0}^{n}\left|\left(w_1x+w_0\right)-y^i\right|$$
+
$$\frac{\lambda}{n}\sum_{i=1}^{n}\left|w_j\right|$$
$$\frac{\lambda}{n}\sum_{i=1}^{n}w_j^2$$

$$\frac{dMAE}{dw_1}=\frac{1}{n}\sum_{i=0}^{n}{\frac{w_1x+w_0-y^i}{\left|\left(w_1x+w_0\right)-y^i\right|}\left(x\right)}$$
+
$$\lambda\frac{w_j}{\left|w_j\right|}$$
$$2\lambda w_j$$

$$\frac{dMAE}{dw_0}=\frac{1}{n}\sum_{i=0}^{n}{\frac{w_1x+w_0-y^i}{\left|\left(w_1x+w_0\right)-y^i\right|}\left(1\right)}$$
+
-
-
Comment: Very well. Thanks for informing. In fact, this is a MathJax enabled site. You can typeset your equations here. For help, check [Instructions on how to use LaTeX on CrossValidated](https://stats.meta.stackexchange.com/questions/1604/instructions-on-how-to-use-latex-on-crossvalidated).
Comment: Hi. Where is this snapshot of the page taken from? From a book? From a lecture note? If it is so, please cite the reference.
Comment: @User1865345 no I wrote it by myself in MSWord and then took a snapshot of that, cause I couldn't write a formula in the answer.

Mean Absolute Error (MAE) derivative


Webform Submission not Working with .tpl.php file

Question: I have a webform that i needed to style a little differently. So I did this creating a webform-form-3.tpl.php file (the node of my form is 3). Inside that I have this code:
<?php // Contact Us form ?>

    <?php print drupal_render($form['submitted']['event']);?>

        <?php print drupal_render($form['actions']['submit']);?>

Unfortunately, by doing this, it stops the submitting functionality of the form. I am assuming that I messed up on missing some of the submitting options. Does anyone have any ideas where i may have gone wrong? Any help would me much appreciated! Thank you!
Answer: Stick this at the bottom:
<?php echo drupal_render_children($form); ?>


Add multiple nodes at the same time?

Question: I've got a requirement to allow Users the ability to create multiple nodes within a single experience.
All this content the Users are adding share much of the same data, so the idea is to give them a more convenient way to add multiple nodes without all the Save and Add Content clicking.
They don't necessarily need to be able to edit the nodes in the same single experience.
Any modules, and/or case studies you recommend?
Answer: Maybe the Multi Node Add will cover what you require :

This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.

See if it does it for you. But also beware that it's a beta release.

Add multiple nodes at the same time?


Parse hex numbers along with decimal numbers from XML with boost::property_tree

Question: I am parsing an XML file with boost::property_tree. The data I need to parse includes regular decimal numbers such as 42 and hex numbers such as 0xF1. For example:
<hex>0xF1</hex>
<dec>42</dec>

It's easy to parse decimal numbers and convert them to int with ptree::get<int>(). However, the same call on the hex number fails.
I can work around this by parsing the hex number as a std::string and then using std::istringstream and std::hex to convert it to int. Demonstrating with code:
#include <iostream>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

using std::string;
namespace pt = boost::property_tree;

int main() {
    pt::ptree tree;

    try {
        pt::read_xml("debug.xml", tree, pt::xml_parser::no_comments);
    } catch (const pt::xml_parser_error&) {}

    int hexnum;

    // Doesn't work (throws exception)
    try {
        hexnum = tree.get<int>("hex");
    } catch (const pt::ptree_bad_data&) {
        std::cout << "caught bad ptree data exception";
    }

    // Workaround: parse as a string, then convert the string
    string hexstring;

    try {
         hexstring = tree.get<string>("hex");
         std::istringstream iss(hexstring);
         iss >> std::hex >> hexnum;
         if (!iss) throw std::ios_base::failure("invalid hex string");
    } catch (const pt::ptree_error&) {
        // get() failed
    } catch (const std::ios_base::failure& fail) {
        std::cout << fail.what();
    }

    // Parsing a regular decimal number is straightforward
    int decnum;

    try {
        decnum = tree.get<int>("dec");
    } catch (const pt::ptree_error&) {}

    return 0;
}

Is there a more elegant way to do this, similar to how I can convert a std::string into a number using std::istringstream with std::hex, std::oct, or std::dec? The documentation shows that there is a stream_translator.hpp header file which looks promising as a way to do this -- but there's not much documentation for this file either on the Boost website or in the header file itself. The workaround with std::istringstream is acceptable, but stream_translator.hpp makes me wonder if boost::property_tree provides a way to do this.
I need to be able to easily switch between parsing hex and decimal numbers, just as it's easy to do so with iss >> std::hex or iss >> std::dec on std::istringstream iss.
(In case it matters, my compiler is VS2005. Yes, '05 not '15.)
Answer: The code of stream_translator looks pretty simple: it has only two methods. I guess you can write your own translator and setup a hex flag. Something like this:
/// Implementation of Translator that uses the stream overloads.
template <typename Ch, typename Traits, typename Alloc, typename E>
class stream_translator
{
    typedef customize_stream<Ch, Traits, E> customized;
public:
    typedef std::basic_string<Ch, Traits, Alloc> internal_type;
    typedef E external_type;

    explicit stream_translator(std::locale loc = std::locale())
        : m_loc(loc)
    {}

    boost::optional<E> get_value(const internal_type &v) {
        std::basic_istringstream<Ch, Traits, Alloc> iss(v);
        iss.imbue(m_loc);
        iss.setf(std::ios_base::hex, std::ios_base::basefield);
        E e;
        customized::extract(iss, e);
        if(iss.fail() || iss.bad() || iss.get() != Traits::eof()) {
            return boost::optional<E>();
        }
        return e;
    }
    boost::optional<internal_type> put_value(const E &v) {
        std::basic_ostringstream<Ch, Traits, Alloc> oss;
        oss.imbue(m_loc);
        oss.setf(std::ios_base::hex, std::ios_base::basefield);
        customized::insert(oss, v);
        if(oss) {
            return oss.str();
        }
        return boost::optional<internal_type>();
    }

private:
    std::locale m_loc;
};

ptree itself has get method that accepts a translator. So you can pass your own translator there.
    template<class Type, class Translator>
    Type get(const path_type &path,
             const Type &default_value,
             Translator tr) const;

Comment: This works (+1) but isn't any easier than the workaround. I was hoping there'd be a way to do it without defining an entire translator.
Comment: I don't know I just looked at the code of boost::property_tree and I found this solution the most obvious.
Answer: Just use the new stoi/stol/stoll
with its "base" set to 0, which will do the auto detection of the numeric base.


access video file information using standard Unix utilities

Question: I want to access video file information (specifically, the video horizontal and vertical dimensions) in the Bash terminal of Scientific Linux on a system over which I do not have root privileges. The setup is conservative and does not feature the modern utilities, such as exiftool and avprobe, that would be used to do this. What would be a way of accessing this information using standard Unix utilities or some other means likely to work on a conservative Linux setup? To be specific, I am looking for something such as the following:
<utility> video1.mp4
1280x720

Thanks for any ideas!
Comment: That's going to be tough. A single format you might have gotten away with examining the format and reading bytes. However, another option: you don't need root privileges to get an executable there if it doesn't depend on libraries, you just have to upload it once your know on what kind of system you are, or you may even build the tool from source, you normally don't special privileges for that. It seems the sanest way to avoid re-implementing those tools from scratch, by hand.
Comment: What kind of input video formats are you expecting?
Comment: MP4 and OGG files are likely to be the overwhelming majority (though f4v may appear sometimes).
Answer: How to build and run typical open source software from source without root
Even if you don't have root, provided that:

you can at least use the compiler and related tools
you can download source code
you don't need too many strange libraries

then download the source code for your tool of choice and install it into $HOME/opt/somedir.
For example, for avprobe you could probably download the last stable source release, then build it like this:
tar xzf libav.....gz
cd libav.....
./configure --prefix=$HOME/opt/libav
make
make install

then run it as
$HOME/opt/libav/bin/avprobe

You may or may not need to tweak the value of LD_LIBRARY_PATH or various other things.
Comment: Thanks for the suggestion. It appears this is the most balanced way of  making these capabilities available.


IOS - Adjust cell height based on content

Question: im trying to build apps that have tableview cell similiar with twitter, there are text and images.
My problem is i want to insert the image above the text. While it can be text only.
So if there are no image, the text will be in position (0,0). And if there are images it will be (0,306) position.
Do i have to use programatically or using autolayout?
Appreciate for the answer. Thanks..
Answer: If use AutoLayout the use this code
You try to set the UITableView properties estimatedHeight.
-(void)viewWillAppear:(BOOL)animated{
     _messageField.delegate = self;
     _tableView.estimatedRowHeight = 65.0;
     _tableView.rowHeight = UITableViewAutomaticDimension;
}

Other wise use this UITableView Delegate Method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300; // your dynamic height...
}

Comment: do i have to set all the label and imageview using programatically by doing subiview or i can set using IB?thanks
Answer: It is better to do it programmatically use this delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

Answer: Using AutoLayout, just take an NSLayoutConstraint and bind it to the Top Space constraint of the label. Also you need to calculate the size of the label, to adjust cell height based on content.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //If image exists, set the value of the constraint to 306, else set it to 0
    constraintName.constant = 306;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat labelHeight = [self findHeightForText:labelMe.text havingWidth:labelWidth andFont:[UIFont systemFontOfSize:22];
    return labelHeight + paddingHeight;
}

//Method to calculate label height
- (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
    #ifdef __IPHONE_7_0
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height);
    #else
        size = [text sizeWithFont:font constrainedToSize:CGSizeMake(widthValue, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    #endif
    }
    return size.height;
}

Answer: Try this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //calculating the height according to the device height.
    return self.view.frame.size.height * (102.0 / 568.0);
}

Where 102.0 will be the current height according to the current design xib height 568.0. This will resize the cell according to the height.


gravando no firebase usando firebase cloud function

Question: Boa tarde comunidade Developers....
dificuldade na gravação usando firebase...
o console do firebase cloud functions dá essa mensagem de erro:
decode64(userTo) ********@gmail.com
decode64(userFrom) YWRyaWVsQHVuaXBsYWNsYWdlcy5lZHUuYnI=
Uncaught exception
ReferenceError: ut is not defined

meu código está assim:
let ut = decode64(userTo)
let uf = encode64(userFrom)
console.log('decode64(userTo)', ut)
console.log('encode64(userFrom)', uf)

db.collection('users').doc(ut).collection('contacts').doc(uf).set({
lastMessage: messageDoc.content,
lastMessageTime: new Date()
}, {
    merge: true
}).then(() => {
    console.log('[END]');
    resolve(true);
    return true;
}).catch(e => {
    throw new Error("User last message not saved.");
});

agradeço desde já...
Answer: ele passou a funcionar quando eu adicionei as seguites linhas >
            let ut = decode64(userTo)
            let uf = encode64(userFrom)
            console.log('decode64(userTo)', ut)
            console.log('encode64(userFrom)', uf)

            console.log('db.collection -> ', db.collection('users')) //essas 3 linhas
            console.log('db.collection.ut -> ', db.collection('users').doc(ut))
            console.log("db.collection('users').doc(ut).collection('contacts')",db.collection('users').doc(ut).collection('contacts'))

            db.collection('users').doc(ut).collection('contacts').doc(uf).set({
                lastMessage: messageDoc.content,
                lastMessageTime: new Date()
            }, {

Simplesmente passou a funcionar !!!


How can I accurately depreciate a set of elements?

Question: I have the following function to determine the value $v$ of an element:
$$a =\space\text{age in days} \\
    v = a\left(\frac{-1}{730}\right)^\frac{5}{8} + 1$$
My intention is for each element, which starts out with a value of $1$ at the moment of its creation, to depreciate in value daily at a declining rate. But it turns out that it would be too costly in terms of computing power to calculate each element individually. So, instead, I would like to consolidate the calculation into one variable $t$, which will increase by 1 each time an element is added. Then every day, $t$ will be multiplied by a certain value $r$ (probably around $0.99$) to depreciate it. Is there a value I can choose for $r$ to make the depreciation rate match the rate in my original function?
Comment: Do you mean $v=1-a\left(\frac{1}{730}\right)^\frac{5}{8}$?  The way you wrote it (with the negative sign inside the $\frac 18$ power) is imaginary.
Comment: Oh yes, you're right.
Answer: If my reading $v=1-a\left(\frac{1}{730}\right)^\frac{5}{8}$ is correct, the item is linearly depreciated to zero value in about $61.6$ days and the value goes negative after that.  You should throw them away.  Then you can just store the number of items added each day for the last $61$ days.  If $n(i)$ is the number added $i$ days ago, the total value is then $\sum n(i)(1-\frac i{61.6})$
Your suggestion to use a multiplier will result in things always having positive value.  I don't know which suits your reality better.


Date token to use user timezone instead of site timezone

Question: Our site is having users from different timezones and we are sending event notification emails using rules. We need to specify the event date-time in addressee's timezone.
So, is there any way to specify the the timezone within/along with date-time token?
Or, should I introduce a custom token for this purpose?
Answer: You can try date token with custom date formatting
[entity:field-event-date:custom:m/d/y T]

replace entity with appropriate token (node, etc.), and insert the name of your date field.
Refer to PHP:date - Manual for custom date formats.
Comment: It will display it in default timezone, here I want to pass my different timezone to token.


If $\langle Lx,y\rangle = \langle x,Ry \rangle$ then $L$ is bounded

Question: Suppose $L,R$ are not necessarily bounded operators on a hilbert space $H$. Show that, if $L,R$ satisfy $$
\langle Lx,y \rangle = \langle x,Ry\rangle
$$ for all $x,y \in H$, then $L$ is bounded.
I tried looking at the uniform boundedness theorem, but I cannot go much further than noting that $L,R$ resemble the property of an adjoint operator (they will be each others adjoint once you prove they are bounded).
Any thoughts?
Comment: This looks like a generalisation of the Hellinger-Toeplitz theorem, which means the way to go could be to use the closed graph theorem.
Answer: This is a generalisation of the Hellinger-Toeplitz theorem, which can incidentally be proved the same way as said theorem:
Consider $(x_n)_n \subset H$ and $(x,y) \in H^2$ such that $\begin{cases} x_n \to x\\ L(x_n) \to y\end{cases}$ when $n \to \infty$.
Then, for all $\varphi \in H$:
$$\begin{cases} \langle L(x_n), \varphi\rangle \xrightarrow[n \to \infty]{} \langle y, \varphi\rangle\\
\langle L(x_n), \varphi \rangle = \langle x_n, R(\varphi)\rangle \xrightarrow[n \to \infty]{} \langle x, R(\varphi)\rangle = \langle L(x), \varphi \rangle\end{cases}$$
Thus we obtain, by uniqueness of the limit and the fact that this is true for all $\varphi \in H$: $L(x) = y$, thus the graph of $L$ is closed, hence $L$ is bounded by the closed graph theorem.
Comment: This is a very nice solution, thanks!
Answer: Note that for any fixed $y \in H$, $\sup_{||x|| \leq 1} |\langle Lx, y \rangle| = \sup_{||x|| \leq 1} |\langle x, Ry \rangle| = ||Ry||$, so by uniform boundedness principle, $\sup_{||x|| \leq 1, ||y|| \leq 1} |\langle Lx, y \rangle| < +\infty$. But then $||L|| = \sup_{||x|| \leq 1} ||Lx|| = \sup_{||x|| \leq 1, ||y|| \leq 1} |\langle Lx, y \rangle| < +\infty$, so $L$ is bounded.
Comment: Very neat no-sequence argument, and sorry that I didn't see your answer while typing mine (+1)
Answer: The question can be reduced to the Hellinger-Toeplitz theorem.
Namely $\langle Lx,y\rangle =\langle x,Ry\rangle $ implies
$$\langle (L\pm R)x,y\rangle =\langle x,(L\pm R)y\rangle$$
Thus the operators $L+R$ and $L-R$ are bounded, so are $L$ and $R.$
The Hellinger-Toeplitz theorem can be proved by the closed graph theorem (the most popular method) or by the uniform boundedness principle see.