loadrunner internal server error

Question: I am running a load test with HP Loadrunner 11.52 for a web site which has Asp.Net MVC 5, C#, Razor,WCF (Windows Communication Foundation),WIF (Windows Identity Foundation),Federated Authentication,.Net Framework 4.5,JavaScript, JQuery, JSON, HTML 5,Bootstrap,Telerik Kendo UI,Telerik Reporting,Oracle 11g R2 technologies.
In a simple search senario, when I click search button, it calls an ajax function "Ara" as following.
<code>web_custom_request("Ara",
        "URL=http://egitim.gocnet.gov.tr/Kisi/Ara/**Ara**",
        "Method=POST",
        "Resource=0",
        "RecContentType=application/json",
        "Referer=http://egitim.gocnet.gov.tr/Kisi/Ara",
        "Snapshot=t8.inf",
        "Mode=HTML",
        "EncType=application/json; charset=UTF-8",
        "Body={\"success\":true,\"message\":\"\",\"result\":{\"mod\":\"kimlikBilgileri\",\"kimlikNo\":null,\"ad\":{\"aranacakString\":\"joe\",\"aramaKriterTipi\":1},\"soyad\":{\"aranacakString\":\"halley\",\"aramaKriterTipi\":1},\"babaAd\":{\"aranacakString\":\"robert\",\"aramaKriterTipi\":1},\"anneAd\":{\"aranacakString\":null,\"aramaKriterTipi\":1},\"dogumTarih\":{\"gun\":null,\"ay\":null,\"yil\":null},\"uyruk\":null,\"ikametIzinNo\":null,\"pasaportNo\":null,\"uyrukKimlikNo\":null,\"pageSize\":10,\"page\":1,\"total\":0,\"sortFields\":null}}",
        LAST);
</code>
When I replay this scenario it gives the following error:

Action.c(113): Error -26612: HTTP Status-Code=500 (Internal Server Error) for "http://egitim.gocnet.gov.tr/Kisi/Ara/Ara" [MsgId: MERR-26612]

What can be its reason?
Comment: It's a server error, so check your server's log.
Comment: I learned that Web 2.0 licence does not support Asp.net MVC 5 so it can be reason.
Comment: @SinemKırtaç you have a server issue not related to LoadRunner. As far as I know, MVC 5 uses regular HTTP calls, perhaps you need special DFE for it but from your code I don't even think this is needed. Please make sure you are authorized to make that REST call, maybe you need some sort of authentication or other type of authorization.
Answer: HTTP 500 in a loadrunner result generally means that you have provided the server with incorrect information or an incorrect request based upon the state of the server.   If you are not explicitly checking for valid expected results from each and every one of your prior requests and simply relying upon an HTTP 200 status to ensure "success!" then then odds are high that you have received a valid HTTP 200 response but with invalid data for continuing the business process.
Check your request responses and branch your code when you have an unexpected response.

loadrunner internal server error


Using RNN (LSTM) for predicting one feature value of a time series

Question: I have been reading several papers, articles and blog posts about RNNs (LSTM specifically) and how we can use them to do time series prediction. In almost all examples and codes I have found, the problem is defined as finding the next x values of a time series based on previous data. What I am trying to solve is the following:

Assuming We have t values of a time series, what would be its value at time t+1?

So using different LSTM packages (deeplearning4j, keras, ...) that are out there, here is what I am doing right now:

Create a LSTM network and fit it to t samples. My network has one input and one output. So as for input I will have the following patterns and I call them train data:

t_1,t_2
t_2,t_3
t_3,t_4

The next step is to use for example t_4 as input and expect t_5 as output then use t_5 as input and expect t_6 as output and so on.
When done with prediction, I use t_5,t_6 to update my model.

My question: Is this the correct way of doing it? If yes, then I have no idea what does batch_size mean and why it is useful.
Note: An alternative that comes to my mind is something similar to examples which generate a sequence of characters, one character at a time. In that case, batch_size would be a series of numbers and I am expecting the next series with the same size and the one value that I'm looking for would be the last number in that series. I am not sure which of the above mentioned approaches are correct and would really appreciate any help in this regard.
Answer: An RNN should also has a time dimension or sequence length for its input. In your example, the sequence length is only 1 for each training sequence so the total time step for each training is only one. That means there is basically no long-term memory that can be built on this network, and you are not using the feature of RNN (especially LSTM).
To do it correctly, you need to increase the sequence length in each training sequence (like t_1, t_2, t_3, t_4) so that the pattern can be seen in one input. You will need to decide how to cut the entire time series into several pieces with fixed length.
If you want the network to learn an indefinite length of sequence like the example you gave, you will need additional setting to make it work. In keras, you should use the stateful mode with batch_size = 1 so that the neural network can still remember the state of previous example. The shuffle needed to turn off so that the order is preserved during the training. Finally, you need to manually reset the state of the neural network model.reset_states() after each epoch of training (since in this case 1 epoch is 1 visit through the time series). See Jason Brownlee's blog for a detail example.
Comment: Louis, could you please give an (concrete!) example, how input data has to look like/be structured.
Answer: You need to distinguish samples and features. A sample is one input sequence you pass to the LSTM model, e.g., your t_1. t_1 is a sequence with any length, so it may be a sequence of 1,2,3,4 and your LSTM model will give an ouput 5. Each individual element '1','2','3','4' of the input sequence is called features.
Batch_size is used when training the model. You may want to train the model (i.e., updating the weights and biases) one sample by one sample. It is very slow and has some disadvantages. So you want to train multiple samples at one time. For example, if the batch_size equals to 3, then you will train t_1, t_2, t_3 as one batch before updating the model weights, t_4,t_5,t_6 at the same time, and so on.
Comment: and what happens to y? should it also be a vector of same length as x or can it be just 1 value?


Find monotonic functions going from $0$ to $+\infty$ for $x \in (-\infty,+\infty)$ (similar to $e^x$)

Question: How can we find functions on $\mathbb{R}$ with exponential-like properties, namely:

$f(x)$ is infinitely differentiable;
$f(x)$ and all its derivatives are monotonic;
$f(x)$ and all its derivatives obey the following limits:

$$\lim_{x \to -\infty}f(x)=0$$
$$\lim_{x \to +\infty}f(x)=+\infty$$

One such function is obviously the exponent itself ($a,b$ - real positive constants):
$$f(x)=ae^{bx}$$
Another function which seems to have these properties (I don't know how to prove it) is the 'Sophomore's function':
$$s(x)=\int_0^1 u^{-u~x} du=\sum_{k=1}^{\infty} \frac{x^{k-1}}{k^k}$$
For the proof of the integral formula see this answer by Sangchul Lee.
The derivatives are easy to find (both for the series and the integral formula) and they all seem to obey the above properties:

How can we find other such functions?
And (related) how to prove that $s(x)$ has these properties?
Comment: The classic example is the function $f$ defined by $f(x) = exp(-1/x^2)$ for $x > 0$ and $f(x) = 0$ elsewhere.
Comment: I think a nice restriction to the problem would be to only look for analytic functions.  Then you could try to characterize these functions by their power series coefficients.
Comment: @mathematician, could you provide an example of an infinitely differentiable function which is not analytic?
Answer: If $g(x) \ge 0$,
$\lim_{x \to -\infty} g(x) = 0$,
and
$\int_{-\infty}^{\infty} g(t) dt
= \infty
$,
then
$f(x)
=\int_{-\infty}^x g(t) dt
$
is such a function.
(added a bit later)
If you want
all the derivatives
to be monotonic,
impose that restriction
on $g$.
Comment: I really think the condition $g(x) \geq 0$ should be clarified. Otherwise, $g(x)=C$ fits the first two conditions for any $C \geq 0$, but $f(x)$ doesn't work the way it should
Comment: Otherwise, a good suggestion, but you could at least offer some explicit $g(x)$
Comment: I added the condition $\lim_{x \to -\infty} g(x) = 0$.
Comment: Any example of g(x)? Or what about my second question?


Deactivate user assignment to a group with PIM

Question: I activated PIM for an eligible group using the command
New-MgIdentityGovernancePrivilegedAccessGroupAssignmentScheduleRequest -BodyParameter

Now, After completing my task I want to exit the role by deactivating this assignment. From the documentation, I figured I could use the below command. But this is not working and is giving me a bad request error.

Stop-MgIdentityGovernancePrivilegedAccessGroupAssignmentScheduleRequest -PrivilegedAccessGroupAssignmentScheduleRequestId

Answer: The error occurred as you are using wrong command to deactivate the user assignment from PIM group.
I have one active assignment to group in PIM under Groups tab as below:

When I ran your command to deactivate the above assignment, I too got same error as below:
Stop-MgIdentityGovernancePrivilegedAccessGroupAssignmentScheduleRequest -PrivilegedAccessGroupAssignmentScheduleRequestId xxxxxx

Response:

To deactivate the active assignment of user from PIM group, you need to use below PowerShell commands with action as selfDeactivate like this:
Connect-MgGraph -Scope "PrivilegedAssignmentSchedule.ReadWrite.AzureADGroup"

$params = @{
    accessId = "member"
    principalId = "userId"
    groupId = "groupId"
    action = "selfDeactivate"
}

New-MgIdentityGovernancePrivilegedAccessGroupAssignmentScheduleRequest -BodyParameter $params

Response:

When I checked the same in Portal, active user assignment deactivated successfully from PIM group as below:

Reference: Create assignmentScheduleRequest - Microsoft Graph


How many different basis' exist for an n-dimensional vector space in mod 2?

Question: Imagine a 2-dimensional vector space in $\mathbb{Z} /2 \mathbb{Z}$. The only possible basis' are
$$
\left(\begin{array}{c}
1\\
0 \end{array}\right),
\left(\begin{array}{c}
0\\
1 \end{array}\right); \left(\begin{array}{c}
1\\
1 \end{array}\right),
\left(\begin{array}{c}
0\\
1 \end{array}\right);\left(\begin{array}{c}
1\\
0 \end{array}\right),
\left(\begin{array}{c}
1\\
1 \end{array}\right)$$
This means for n = 2 would 3 be the correct answer. For n = 1 the answer is 1.
What is the correct answer for a variable n?
Comment: I think this is related to http://en.wikipedia.org/wiki/Gaussian_binomial_coefficient
Answer: We can do the more general case for $F = \mathbb{F}_q$ for $q$ a power of a prime. The first vector can be chosen from $q^n - 1$ possible choices. The subspace generated by it has $q$ points, since each vector is determined by $q$ possible coefficients. Continuing we get the formula $(q^n - 1)(q^n - q)\cdots (q^n - q^{n-1})$. This is the number of ordered bases though, but we can just divide by $n!$ to get the number of unordered bases.
For instance in your case $q = 2^1 = 2$ and $n = 2$, so we get $(2^2-1)(2^2-2) = 3\times 2 = 6$ possibilities. To get your $3$ we just divide by $2!$. You could write the general formula to be
$(q^n - 1)(q^n - q)\cdots (q^n - q^{n-1})/n!$
Comment: So your answer is $f(n,q) = \frac{1}{n!} \cdot \prod_{i=0}^{n-1} (q^n - q^i)$. Thanks.
Comment: Is this equal to $g(n,q) = \frac{1}{2} \cdot \binom {n^q}{n}$?
Comment: No. It just happens to work for $n=2,q=2$. Try $n=3,q=8$, and then $g(n,q)$ is much larger. You can see that these expressions don't have much hope of being equal because the second expression has a $n^q$ in it.
Comment: guess there is no simpler way to write f(n,q) ... Wolfram|Alpha gave me some alternate forms, but they are by far more complex: http://wolframalpha.com/input/?i=1%2Fn%21+%28product_%28i%3D0%29^%28n-1%29+%282^n+-+2^i%29%29 e.g.
$$f(n,2) = \frac{2^{n^2} e^{2 i n π \lfloor \frac{1}{2}-\frac{Im(n) log(2)}{2 π} \rfloor} (2^{-n}, 2)_n}{n!}$$
Comment: It seems that the expression as a product of terms of the form (q^n-q^i) is already pretty elegant and simple, especially as it only involves the basic operations of arithmetic.


chi square or t-test for this case?

Question: I have collected data on the performance of two different website versions. Both pages have been shown on randomly (but not maybe equally) to different people.
So my contingency table is as shown below, and I want to perform a statistical test to make sure the conclusions about the conversions are right.
   A       B
 8 000   1 000  conversions
90 000  30 000  no conversions

The conversion rate for A appears to be 8,8% and the conversion rate for B appears to be 3,3%
I myself did this with a chisq.test, with a hypothesis as follows: "are the differences between A and B significant". What I was trying to test was if I can trust the conversion rates that I am getting and they are not just a product of coincidence
In order to make sure that the conclusions are reliable I used the Chi-square test. However, I was told that I was supposed to use the t.test and now I am confused why.
Which test (t.test or chisq.test) would you choose and why?
Comment: Why not tell us what you think and why so someone can help you with your confusion?
Answer: Strictly, the t test is not appropriate since there is no need to independently estimate the standard deviation.  A z test or a chisquare test are more appropriate, and both are asymptotically equivalent.
The difference would be significant by either test.  The R code to perform a textbook z test is
> prop.test(x = c(8000, 1000), n = c(90000, 30000), correct = F)

    2-sample test for equality of proportions without continuity correction

data:  c(8000, 1000) out of c(90000, 30000)
X-squared = 1001, df = 1, p-value < 2.2e-16
alternative hypothesis: two.sided
95 percent confidence interval:
 0.05280187 0.05830924
sample estimates:
    prop 1     prop 2
0.08888889 0.03333333

Looks like you achieved a lift in conversion of 5.5% (95% CI 5.3% - 5.8%) (assuming A is the new variant)

chi square or t-test for this case?


Option to export path alias not showing in view (pathauto is installed)

Question: On my new D 9.5.x site, I have pathauto installed, and it is working well. That is, neat alias URLs get generated for my articles as expected. I am now trying to export articles from the site. I have the views data export module installed, but when I create the export, I don't see the alias path available as a field to choose (as 'Content: Path' or anything else. The other article fields are available for selection and everything works with the export. Its just that the path is simply not available. Am I missing a setting somewhere? I have looked around, but unable to find any pointers.
I use the same modules on another old D8 site. Everything works perfectly there. I am able to export URL alias paths along with other article information. Makes me wonder if there is some setting from the other D8 site missing in my D9.5 site (note: the 2 sites are unrelated to each other).
Answer: Answering my own query after spending some time looking around:
"Content: Path" was deprecated in 8.5 and removed in 9.
The alternative is to use "Content: Link to Content" and massage it. Described in this drupal.org link here.
NOTE: As the link suggests, this alternative may have issues with multilingual sites, which my site is not.
Comment: The links are missing.
Comment: berliner, fixed link now, sorry.


converting a whole table/dataframe in pyarrow a dictionnay_encoded columns

Question: am loading a parquet file from apache arrow (pyarrow), and so far, i necessarily needs to transfer to pandas, doing a conversion as categorical, and send it back as arrow table (to save it later as feather file type)
the code looks like it :
    df = pq.read_table(inputFile)
    # convert to pandas
    df2 = df.to_pandas()
    # get all cols that needs to be transformed and cast
    list_str_obj_cols = df2.columns[df2.dtypes == "object"].tolist()
    for str_obj_col in list_str_obj_cols:
        df2[str_obj_col] = df2[str_obj_col].astype("category")

    print(df2.dtypes)
    #get back from pandas to arrow
    table = pa.Table.from_pandas(df2)
    # write the file in fs
    ft.write_feather(table, outputFile, compression='lz4')

is there anyway to make this directly with pyarrow ? would it be faster ?
thanks in advance
Answer: In pyarrow "categorical" is referred to as "dictionary encoded".  So I think your question is if it is possible to dictionary encode columns from an existing table.  You can use the pyarrow.compute.dictionary_encode function to do this.  Putting it all together:
import pyarrow as pa
import pyarrow.compute as pc

def dict_encode_all_str_columns(table):
    new_arrays = []
    for index, field in enumerate(table.schema):
        if field.type == pa.string():
            new_arr = pc.dictionary_encode(table.column(index))
            new_arrays.append(new_arr)
        else:
            new_arrays.append(table.column(index))
    return pa.Table.from_arrays(new_arrays, names=table.column_names)

table = pa.Table.from_pydict({'int': [1, 2, 3, 4], 'str': ['x', 'y', 'x', 'y']})
print(table)
print(dict_encode_all_str_columns(table))


problema ao mostrar categoria wordpress

Question: Estou desenvolvendo um tema para Wordpress meu menu é gerado da seguinte forma em header.php

<a href="<?php echo get_option('home');?>">Início

     <?php wp_list_categories('title_li=&orderby=id'); ?>
     <?php wp_list_pages('title_li=&order=id'); ?>

O problema é que quando acesso uma categoria ao tentar mostrar os posts ele retorna todos os posts e não os referentes a categoria.
category.php
<?php if ( have_posts() ) : ?>
  <?php while ( have_posts() ) : the_post(); ?>
    <?php the_title(); ?>
  <?php endwhile; ?>
<?php endif; ?>

Answer: Faz assim:
<?php
   query_posts("category_name=SUA_CATEGORIA");
   while(have_posts()) : the_post();
?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php
  endwhile;
  wp_reset_query();
?>

Comment: Tente dar mais explicações sobre sua solução, para que também seja útil a futuros visitantes
Comment: o problema é que não é apenas uma categoria!
Comment: Já tentou usar o is_category()? Ai você passa sua categoria, faz um if, não sei como quer fazer.
Answer: resolvi o problema faltava o wp_reset_query(); ao final do header.php

problema ao mostrar categoria wordpress


Why is an "await Task.Yield()" required for Thread.CurrentPrincipal to flow correctly?

Question: The code below was added to a freshly created Visual Studio 2012 .NET 4.5 WebAPI project.
I'm trying to assign both HttpContext.Current.User and Thread.CurrentPrincipal in an asynchronous method. The assignment of Thread.CurrentPrincipal flows incorrectly unless an await Task.Yield(); (or anything else asynchronous) is executed (passing true to AuthenticateAsync() will result in success).
Why is that?
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web.Http;

namespace ExampleWebApi.Controllers
{
    public class ValuesController : ApiController
    {
        public async Task GetAsync()
        {
            await AuthenticateAsync(false);

            if (!(User is MyPrincipal))
            {
                throw new System.Exception("User is incorrect type.");
            }
        }

        private static async Task AuthenticateAsync(bool yield)
        {
            if (yield)
            {
                // Why is this required?
                await Task.Yield();
            }

            var principal = new MyPrincipal();
            System.Web.HttpContext.Current.User = principal;
            System.Threading.Thread.CurrentPrincipal = principal;
        }

        class MyPrincipal : GenericPrincipal
        {
            public MyPrincipal()
                : base(new GenericIdentity("<name>"), new string[] {})
            {
            }
        }
    }
}

Notes:

The await Task.Yield(); can appear anywhere in AuthenticateAsync() or it can be moved into GetAsync() after the call to AuthenticateAsync() and it will still succeed.
ApiController.User returns Thread.CurrentPrincipal.
HttpContext.Current.User always flows correctly, even without await Task.Yield().
Web.config includes <httpRuntime targetFramework="4.5"/> which implies UseTaskFriendlySynchronizationContext.
I asked a similar question a couple days ago, but did not realize that example was only succeeding because Task.Delay(1000) was present.
Comment: In my Owin middleware, I had to chain in a last piece of middleware that simply does await Task.Yield();
this seems to cause Thread.CurrentPrincipal to be as expected later throughout the execution.
Comment: What exactly happens if you leave that out?
Comment: @SLaks, If `await Task.Yield()` is skipped, `Thread.CurrentPrincipal` reverts back to what it was before calling `await AuthenticateAsync()`. Since `Thread.CurrentPrincipal` is no longer a `MyPrincipal`, the exception is thrown.
Answer: How interesting! It appears that Thread.CurrentPrincipal is based on the logical call context, not the per-thread call context. IMO this is quite unintuitive and I'd be curious to hear why it was implemented this way.

In .NET 4.5., async methods interact with the logical call context so that it will more properly flow with async methods. I have a blog post on the topic; AFAIK that's the only place where it's documented. In .NET 4.5, at the beginning of every async method, it activates a "copy-on-write" behavior for its logical call context. When (if) the logical call context is modified, it will create a local copy of itself first.
You can see the "localness" of the logical call context (i.e., whether it has been copied) by observing System.Threading.Thread.CurrentThread.ExecutionContextBelongsToCurrentScope in a watch window.
If you don't Yield, then when you set Thread.CurrentPrincipal, you're creating a copy of the logical call context, which is treated as "local" to that async method. When the async method returns, that local context is discarded and the original context takes its place (you can see ExecutionContextBelongsToCurrentScope returning to false).
On the other hand, if you do Yield, then the SynchronizationContext behavior takes over. What actually happens is that the HttpContext is captured and used to resume both methods. In this case, you're not seeing Thread.CurrentPrincipal preserved from AuthenticateAsync to GetAsync; what is actually happening is HttpContext is preserved, and then HttpContext.User is overwriting Thread.CurrentPrincipal before the methods resume.
If you move the Yield into GetAsync, you see similar behavior: Thread.CurrentPrincipal is treated as a local modification scoped to AuthenticateAsync; it reverts its value when that method returns. However, HttpContext.User is still set correctly, and that value will be captured by Yield and when the method resumes, it will overwrite Thread.CurrentPrincipal.
Comment: Hi! Did you ever heard why this was implemented this way? I have read this post 3 times already and it is still blowing my mind.
Comment: @vtortola: I don't know for sure. I assume it was so that the user permissions would flow to background threads automatically. That was probably done a good decade ago, and the copy-context-on-update behavior is much more recent. So they conflicted in this odd way.


How to use in-scope variables in functions passed as parameter

Question: This is probably a basic question, and I am aware that there have been some similar questions around here, but still I did not find an answer. Please consider the following code:
function Outer(inner2) {
  var x = 5;
  this.inner1 = function() {return (x);}
  this.inner2 = inner2.bind(this);
}
var outer = new Outer(function() {return (x);});
alert(outer.inner1()); // works
alert(outer.inner2()); // does not work

If I would replace the second line by this.x = 5;, the second alert would work. So I guess the problem is that x when declared with var is not part of this, so that bind will have no effect.
Is there any way to make this work without using this.x?
Comment: You can't. There's no way JavaScript can know you're referring to a local variable inside the constructor while outside it unless you attach it to `this` or lift it out somehow.
Comment: If you do not want to expose your local variable with `this.x`, you might want to pass it as an argument to your inner2 method : `var outer = new Outer(function (x) { return (x); });` and `this.inner2 = inner2.bind(this, x)`
Comment: `x when declared with var is not part of this` - correct.
Comment: @Li357 True at declaration time, but note that I never call the anonymous function given as parameter directly but only `outer.inner2()`. So, the compiler could infer the context.
Comment: @Flo-Schield-Bobby But then I had to change the signature of the anonymous function (add a parameter). Further, in reality, there are a lot of variables such as `x`, and I do not want to pass each of them...
Comment: x is essentially a private field, you are trying to return a private field from outside the object without using a getter, that can't be done.
Comment: @Remirror but that's because the *JavaScript engine* (not compiler) maintains a record of `this`, and the fact you're calling it with `outer` gives the interpreter the context. The engine can't see that you defined an essentially private (local) variable and access it in the constructor after you've constructed an object—hence the name, *local* variable. There is no way to do it you'd like because that's not how the language, or any language I know of, works.
Comment: @nickzoum I would agree if I called the anonymous function outside of `Outer`, but I don't.
Comment: If you want to know why `inner1` works but not `inner2`, I suggest some [reading on closures](https://stackoverflow.com/q/111102/5647260). Essentially `inner2` can access `x` after the constructor is executed because x is "kept alive" for `inner1` to access. But since the engine has no way of knowing that `inner2` contains a reference to a local variable in the constructor, it can't access it.
Comment: Thanks, but maybe we talk past each other. Please check my answer below.
Comment: `this.inner2 = inner2.bind(this);` is redundant. You may simply do like `this.inner2 = inner2;` Yet don't forget that `inner2` might have already been bound to some other object previously but that's  another problem.
Answer: I think you need clarification on what the word "this" is referring to.
"this" is not pointing to the function "Outer."
When you invoke a constructor function with the "new" keyword, a few things happen.

The constructor function returns an object.
The "this" variable is changed, so that it is set to point to that object that is returned.
(Also, the .proto of the object returned is set to the .prototype of the constructor function, but that step is not relevant here).

So, you are binding the callback function to the object that you are returning from the constructor function, not the constructor function itself.
Thus, the callback function is bound to outer (with a lower-case), not outer (with an  upper-case).
Also, when you bind, you are not binding to the scope of a function. X is not assigned to any property.  I think you only can bind to an object and access its properties with this.a etc.
The x in the first function worked because its value was assigned in the scope of the function.
Comment: Thanks, this was helpful in understanding `this`
Answer:
Is there any way to make this work without using this.x?

No.
Btw, you probably don't even need to use bind, just calling inner2 as a method on the object would suffice when both the constructor and the method use this.x.
If you don't want to make x a property of the object, but keep it as a local variable, the usual strategy would be to pass it to the callback as an argument, not trying to somehow make it available in its scope implicitly:
function Outer(callback) {
  var x = 5;
  this.inner1 = function() { return x; };
  this.inner2 = function() { return callback(x); };
//                                          ^^^
}
var outer = new Outer(function(y) { return y; });
//                             ^           ^
alert(outer.inner1()); // works
alert(outer.inner2()); // works

Answer: I found an, albeit ugly, solution:
function Outer(inner2) {
  var x = 5;
  this.inner1 = function() {return (x);}
  eval('this.inner2 = ' + inner2.toString());
}

This works and shows my point: the parameter inner2 is just a prescription of how this.inner2 should look like; it is never invoked itself.
Let me know, if you have a neater solution than this.


Imagick convert vs imagick PHP

Question: So I built a site that creates thumbnails using a php script that uses imagick for thumbnail creation.  On my personal web host (Hostmonster), this works fine.  When I made a copy of my site and uploaded it to my client's site (hosted on domain.com) it failed.  Asking Domain.com what was up, they said:

"We have ImageMagick binaries. But it is not complied to PHP so
  IMAGICK won't work. So, you will not be able to use IMAGICK as PHP
  built-in class. You have to use the alternative 'convert' utility"

I've never used the "convert utility" before, so I'm not sure what they're talking about.  Should I look into this more?  Or fire them and just stick with my original host (Hostmonster) where imagick works in PHP?  I feel like I should know about this alternative to be more well-rounded in my knowledge, but wondering if its worth my time to learn it, or just forget it and move on.
Suggestions about how to go forward, or resources on this alternative would be appreciated.  Thanks.
Answer: What they are talking about is using PHP's exec() function to execute ImageMagick the same way as you would do it from the command line. There are hundreds of examples on SO of using ImageMagick from the command line, just search for ImageMagick and convert which is the name of the main binary you would use at the command line.
The syntax is pretty simple:
convert input.png ...<processing> ... output.png

So, you might do
convert input.jpg -thumbnail x320 -quality 80 result.png

If you want to do that in PHP, your ISP is suggesting you use:
$cmd = "/usr/local/bin/convert '/path/to/input.jpg' -thumbnail x320 -quality 80 '/path/to/result.png'";
exec($cmd, $output, $retval);

I can't really comment on the relative efficiency, merits or otherwise (though it smacks of laziness or incompetence on their part), but it should work fine.
Comment: A good answer. However, I want to advice that `exec()` is for carefully use because it can be dangerous.
Comment: @MarcosPérezGude Thank you for sharing your advice.
Comment: Thanks @MarkSetchell for the insight.  I'll try to get this to work, but I agree, it felt like it was domain.com dropping the ball on this.  If I can't get it to work to some degree of ease, I'll probably remove them and fall back to another host.
Answer: As I tell people start with some thing simple first. A simple resize code on an image in the same folder; if that works go onto the next step.
You need to have safe mode off and with phpsusex or whatever it is called you will need a CHMOD of 755 otherwise 777 on the folder the image is saved to.
try:
$cmd = "input.jpg -thumbnail x200 -quality 100 output.jpg";
exec("convert $cmd");

You may have to use the path to convert but if Imagemagick is installed correctly it should work with just convert.
In some cases Imagick is quicker that Imagemagick and as said if you are accepting user input make sure you do a good job of validating the data.
On anther subject I try and keep the code in the command simple so I would save all this $thumbsPath.basename($file, ".jpg") as a variable and use that in the IM code. Especialy in this case as you are using it twice in your code.
You can also echo out $cmd to confirm what it actualy contains; sometimes it is not what you expect!
Answer: Ok, I'm attempting to implement this alternative way, but I'm not sure I'm executing it right.  At the moment this is my code, and I'm getting an internal 500 error.  I unfortunately can't figure out how to get error messages generated with domain.com, so I'm flying a bit blind here.
Using the above $cmd = "/usr/local/bin/convert '/path/to/input.jpg' -thumbnail x320 -quality 80 '/path/to/result.png'";
exec($cmd, $output, $retval);
I'm trying to insert a couple variables in for the input path, and the result path:
$thumbsPath = "./RecentAdditions_thumbnails/";
if (!file_exists($thumbsPath)) {
    mkdir($thumbsPath, 0777, true);
}

foreach($files as $file)
    if(!file_exists($thumbsPath.basename($file, ".jpg")."_thumb.jpg")){
        $cmd = "/usr/local/bin/convert ''./'"$file"' -thumbnail x200 -quality 100 '"$thumbsPath.basename($file, ".jpg")."_thumb.jpg'";
        exec($cmd, $output, $retval);

Comment: Did you try the simple test I suggested above?
Comment: I didn't unfortunately.  I'm very strapped for time.  It was easier to fire domain.com and move back to Hostmonster where I don't have to rewrite anything.  If I had more time,  I would try to get this working, but I appreciate your efforts to help!
Comment: It is nice to know what happened; perhaps you can have another go on your current host when you get some time. I prefer Imagemagick and the command line as it has more options and to me is easier to use.

Imagick convert vs imagick PHP


Why is it called a 9-8 suspension instead of 2-1 suspension?

Question: I know that usually suspensions are referred to by simple intervals, and this is the case with almost all suspensions (4-3, 7-6, 2-3, etc). However, we call it 9-8 suspension instead of 2-1 suspension. Is there a reason for this, either practically or historically?
Answer: This is rooted firmly in the practice of basso continuo, where the figures 2 and 9 had different harmonic implications. The basic idea is that, when a ninth is indicated, the bass is one of the chord tones, and the ninth is a dissonant suspension. But when a second is indicated, it is the bass note that is the dissonant suspension which must resolve downward by step (e.g., what we might call a third inversion seventh chord).
As a typical example, consider Francesco Gasparini's early 18th century continuo manual L'Armonico Pratico al Cimbalo ("The Practical Harmonist At the Harpsichord").
In chapter VII on dissonances and resolutions, he says (square brackets are my clarification):

The second may be considered the same as the ninth, since the ninth is
  the compound of the second, and because ordinarily one indicates a
  second [in the bass] and the interval [played] will be a ninth. There
  is, however, a notable difference between the two, since the second
  does not derive from, but proceeds to a tie, that is to say, when the
  bass is tied or syncopated. In this case, the second does not resolve,
  as do the other dissonances, but instead the bass itself resolves
  stepwise downward.

Here's a link to the page in question (p. 49), which contains a musical example that better illustrates his meaning:
https://archive.org/details/practicalharmoni002034mbp/page/n65
A few pages later (p. 51), he even points out that, if, for some reason, there were an actual 2-1 suspension and resolution, it is recommended to play it an octave higher (as a 9-8), because the resolution to an already-held note doesn't work on keyboard:

If a second is found tied like a ninth, which resolves to the octave,
  the second should be resolved to a unison. But since the keyboard is
  not adapted to it, such a resolution would not be heard. For this
  reason, when such ties are needed (which is rare in harmonic
  composition) once can use a ninth instead, which is more distinctly
  resolved to an octave -- as will be seen in the proper place.

Finally, we can compare against his treatment of ninths, where he makes the same distinction, but, I think, explains it more clearly. (p. 60)
https://archive.org/details/practicalharmoni002034mbp/page/n77

Even though the ninth is the equivalent of the second, being a
  compound second, still it is treated differently. It is never used
  without a tie: in contrast to the second, which occurs over a tie in
  the lower part (the bass), the ninth itself is tied in the upper part
  in order to be resolved to the octave.

Once again, there is an example to demonstrate his meaning.

Since this answer received some additional attention recently, and has an incoming bounty, I decided to create a little example of my own to compare the difference between 2nds and 9ths. At each of the first three barlines, there is a C in the bass voice against a D in the soprano voice.
At the first and third barlines, the bass is suspended while the soprano moves to the D, so the interval is considered a 2nd and the bass must resolve downward by step while soprano voice holds the D. However, at the second barline, the soprano's D is suspended while the bass moves, which means the interval is a 9th, and the soprano must resolve down stepwise.

(Also, notice the difference in the chords that accompany the 2nd's, and the resulting harmonic implications: the 5/4/2 implies the bass is a suspended fourth, while the 6/#4/2 implies a 3rd inversion dominant 7th chord, and creates a modulation to the dominant, which I reinforce with a cadence)


read object of object data laravel blade

Question: data looks like this
[
    {
      "id": 22528,
      "user_id": 25273,
      "non_sql": "{\"data\": {\"data_1\": \"4\", \"data_2\": \"5\", \"data_3\": \"4\", \"data_4\": \"5\"}}",
      "created_at": "2022-06-12T04:38:36.000000Z",
      "updated_at": "2022-06-12T04:40:10.000000Z",
    },
]

when tried
 {{ $item["non_sql"] ??  'NA' }}

it gives me
{"data": {"data_1": "4", "data_2": "5", "data_3": "4", "data_4": "5"}}

I just need to return
data_1: 4
data_2: 5
data_3: 4
data_4: 5

I tried
{{ json_decode($item["non_sql"]) ??  'NA' }}

and have error htmlspecialchars(): Argument #1 ($string) must be of type string, stdClass given
Comment: @Refilon give me this error Cannot access offset of type string on string
Comment: Your `non_sql` contains a JSON string, so you will need to decode that first.
Comment: Why are you having the same isset check there twice? That makes little sense to begin with - it will never reach the "branch" after the `:`, if it _was_ set; and if it wasn't ... well then the second isset won't get a different result all of a sudden either.
Comment: @CBroe i tried {{ jsone_decode($item["non_sql"]) ??  'NA' }} and have this error Call to undefined function jsone_decode()
Comment: Well then spell it correctly, and leave out the extra `e`...
Comment: @CBroe oh sorry, but now have this htmlspecialchars(): Argument #1 ($string) must be of type string, stdClass given
Comment: The content of `non_sql`, when decoded, is an object - so it makes little sense to try and output that directly in a context, where a string value is expected. You need to access individual properties of the object.
Comment: @CBroe so I need two json_decode?
Comment: No, you only have one level of JSON encoding at this point.
Comment: @CBroe so you mean access by foreach?
Comment: Give us the code where you send that item to view
Comment: @angel.bonev I read it from json file  return view(
            'gameResult.game-result-table',
            [
                'result' => $result,
                'game'   => $game,
                'sort_by' => $sort_by,
            ]
        );   then use foreach result as item
Comment: @RaneemAyman where ? Give us that code
Comment: @angel.bonev result is my json file in controller
Comment: add `foreach ($result as $k => $v) { $result[$k]["non_sql"] = json_decode($v["non_sql"], true);}` before the return and try `{{$item["non_sql"]["data"]["data_1"]}}`
Comment: @RaneemAyman is it showing something ?
Comment: @angel.bonev do this in blade?
Comment: No in the controller in laravel before the view
Comment: @angel.bonev "Undefined array key "data" and when try {{$item["non_sql"]["data"]}} it give me same error tmlspecialchars(): Argument #1 ($string) must be of type string, array given
Comment: `{{$item["non_sql"]["data"]}}` it is an array try `{{$item["non_sql"]["data"]["data_1"]}}`
Comment: Does this answer your question? [Laravel: How do I parse this json data in view blade?](https://stackoverflow.com/questions/30073065/laravel-how-do-i-parse-this-json-data-in-view-blade)
Comment: @angel.bonev I don't know if this will help but non_sql in resul file looks like this "non_sql": "{\"data\": {\"data_1\": \"4\", \"data_2\": \"5\", \"data_3\": \"4\"} it is object
Answer: You can try this way
{{ implode(",",json_decode($item["non_sql"])) ??  'NA' }}
Comment: give me this error implode(): Argument #2 ($array) must be of type ?array, stdClass given
Comment: when i update the code like this it works but this only prints the value values.;
implode(',',json_decode($data['non_sql'],true)['data'])  \n you can print regularly with loop management


How to convert while loop with arrays in C to ARM

Question: I'm currently learning ARM and I have to convert a particular C snippet into ARM code to test on the machine. However, I don't know how to declare array in ARM specifically and I didn't find very relevant resources that explained it..
i = 0
while (i < 0xB) {
    x[i] = i*2;
}

Many thanks in advance
Comment: There is C for ARM.
Comment: "I don't know how to declare array **due to lack of information on the internet.**" - You are kidding, are you? Your teacher should have given you all information, too. If not, ask him to improve the course material.
Comment: I did not find any way to represent arrays in ARM language on the internet..
Comment: If you want to see what ARM code your C code translates into, use a compiler.  If you are trying to do the translation yourself, then you'll need a lot more help than just how to declare an array.
Comment: @EugeneSh.: See? Helping people to cheat their exams is a really bad idea. Do you want to have a co-worker permanently asking to do his job?Let's hope the tutor know stack overflow. Would not be the first exam failed due to cheating.
Comment: @EugeneSh.: I strongly assume the assignment was to manually translate, which is a vital task learning Assembly language, every programmer should have learned in the first place.
Comment: @Solly: 1) Change course then or complain at the school/university. 2) You talk to an autodidact who learned all this **without** the web even existing and no access to the internet that time and no experts to ask. **You** have the resources available at your fingertips. So yes, my comment is well justified! As a friendly advice: Spoon-feeding is nothing which will get you anywhere in your life, less in programming, etc. Learn to search for yourself first.
Comment: Not sure what you mean?
Comment: The C code can be very well compiled for arm as is. Not speaking of a fact there is no `**` operator in C (or at least it is not doing what you think it is).
Comment: What did you find when you compiled it.  EVERYTHING you need to know about this is very easy to find on the internet BTW...
Comment: there is no such thing as an array in assembly language
Comment: @EugeneSh. where I can I compile this code from C into ARM? Is there an online compiler?
Comment: You are lucky today. https://godbolt.org/
Comment: @EugeneSh. thank you and god bless you sir. You just got me a B from a C in a subject I detest
Comment: @Olaf Not that I solved something for him (her?) . Just pointed to an openly available tool which I've discovered on SO myself.
Comment: @Olaf When the teacher doesn't give you any notes/reference material, doesn't take any classes and gives you assignments for the sake of updating marks, it isn't the students fault. Kinly don't be presumptuous. I used the tool pointed out by Eugene and learnt from it
Comment: @Olaf You probably had a lot more time back then and this course meant something to you. In my country, you can't just *drop* a course because you don't like it. It's a program core course. As for spoonfeeding etc etc, I'm ranked yellow on Topcode and landed an internship at Facebook this summer as a ukrainian. You're probably really good at embedded systems whereas I detest. I don't have/want to allocate my energy to this. That's just the way it is. Thanks for the advice, even though I live by it mostly
Answer: Just write the code in C and let the compiler translate it to ARM assembly. Then inspect the generated code.
Answer: Since, there is not answer to this question, I'm just going to use GodBolt and input the OP's code there.
I'm taking the liberty of formatting the given code as so:
void assign(int num) {
    int x[10];
    int i = 0;
    while(i < 0xB) {
        x[i] = i*2;
    }
}

The compiler used to translate this is ARM gcc 5.4.1
Translated Code:
assign(int):
        str     fp, [sp, #-4]!
        add     fp, sp, #0
        sub     sp, sp, #60
        str     r0, [fp, #-56]
        mov     r3, #0
        str     r3, [fp, #-8]
.L3:
        ldr     r3, [fp, #-8]
        cmp     r3, #10
        bgt     .L4
        ldr     r3, [fp, #-8]
        mov     r2, r3, asl #1
        ldr     r3, [fp, #-8]
        mov     r3, r3, asl #2
        sub     r1, fp, #4
        add     r3, r1, r3
        str     r2, [r3, #-44]
        b       .L3
.L4:
        mov     r0, r0    @ nop
        sub     sp, fp, #0
        ldr     fp, [sp], #4
        bx      lr

Source: https://godbolt.org/g/5Tv3gk
Comment: Thanks, I guess this question is formally closed as it since I got the answer from the comments from Olaf


Como somar valores no sql na coluna

Question: Tenho o seguinte codigo sql:
 select PS.PatSldBemValResidAnt
       ,PS.PatSldBemValDepAcum
       ,Sum(PS.PatSldBemValDep)   PatSldBemValDep
       ,Sum(PS.PatSldBemValResid) PatSldBemValResid
  from  Pat_Saldo_Bem as PS With(Nolock)
  where PS.EmpCod          LIKE '%01.14%'
    and PS.PatBemCodRed       = '0000351'
    and ((PS.PatSldBemAnoMes >= '201807')
    and (PS.PatSldBemAnoMes  <= '201810'))
 group by PS.PatSldBemValResidAnt, PS.PatSldBemValDepAcum, PS.PatSldBemValDep

Como que eu faço para ele me dar o resultado da soma da coluna Patsaldobem, junto com o valor mais alto da PatSaldoDepAcum?
Segue a imagem:

Gostaria de mostrar o total da coluna PatSaldoBemValDep que é a soma dos valores 187.37+187.37+187.37
Comment: Sugiro que, considerando-se os dados que constam na figura, você nos informe como deve ser o resultado. Por exemplo: (1) o que fazer com as colunas `PatSldBemValResidAnt` e `PatSldBemValResid`? (2) os valores devem ser agrupados pela coluna `PatBemCodRed`?
Answer: Tente assim
 Select Max(PS.PatSldBemValDepAcum)
       ,Sum(PS.PatSldBemValDep) PatSldBemValDep
  From  Pat_Saldo_Bem  as PS With(Nolock)
  Where PS.EmpCod LIKE '%01.14%'
    And PS.PatBemCodRed = '0000351'
    And ((PS.PatSldBemAnoMes >= '201807')
    And (PS.PatSldBemAnoMes <= '201810'))

O MAX(campo) vai resultar o maior valor existente na coluna, se quiser o menor valor você pode usar o MIN(campo).
Comment: sim mas eu preciso somar tbm a coluna PatSaldoBemValDep tem que dar 544,11 o total
Comment: Certo, mas na minha resposta eu informei ali o campo `,Sum(PS.PatSidBemValDep) PatSldBemValDep`... Você esta dizendo que minha resposta está errada ou apenas faltando o campo?
Comment: Ajustei o sql, eu tinha coloca o nome dos fields errado.
Comment: Ele tinha que somar os valores 181.37 os 3
Comment: Então me diga... Está somando errado? Não está somando? O que está errado no meu exemplo?
Comment: Não está errado. Ele tem que só somar os 3 valores 181.37
Comment: 181.37+181.37+181.37
Comment: Carinha, edite sua pergunta então e explique corretamente o que deseja. O exemplo que lhe dei é para resultar algo +/- assim `PatSldBemValDepAcum: 21492,55` e `PatSldBemValDep = 544,11`, isso de acordo com a imagem que você nos deu. Explique também qual é o resultado que você quer e quais os campos que deverão ser resultados.
Comment: o PatSldBemValDep = 544,11 não deu este resultado
Comment: já editei a pergunta
Comment: deu certo só foi tirar o group by. vlw pela ajuda
Comment: Opa, que bom carinha, só preste mais atenção ao analisar os scripts!

Como somar valores no sql na coluna


Atualizar Activity anterior ao finalizar Activity atual

Question: Bom dia, estou desenvolvendo um projeto Android e estou com um problema vou tentar explicar de forma clara:
Possuo duas Activitys A e B, minha Activity A chama a B e permanece na pilha, após encerrar as ações na B essa finaliza e retorna para a A (retorna pois a A estava na pilha). Esta Activity B altera dados no servidor que mudam a exibição na A, por isso preciso que ao finalizar a B, a A atualize para exibir tais mudanças.
Existe alguma forma de fazer esta atualização ou recarregar a Activity A assim que a B for finalizada?
Detalhe: Antes da Activity A existem outras na pilha.
Answer: Paul, acho que o modo mais simples e elegante para o seu caso é usar o próprio ciclo de vida da Activity para isso. Quando a Activity B for finalizada, a Activity A, que estava em 'stop' terá seu ciclo de vida percorrido afim de fazê-la sofrer 'restart'. Os métodos principais  chamados serão onRestart() -> onStart() -> onResume(). Perceba que o método onResume() é chamado na criação da Activity e no 'restart' dela!
Você pode colocar toda a comunicação com o web service no método onResume(), para que assim quando a Activity for criada o carregamento de dados aconteça e quando a activity for 'restartada' também aconteça. Sempre você terá os dados atualizados. É nesse sentido que recomendo sempre deixar o carregamento de dados no onResume() para que a tela sempre esteja atualizada.
Comment: Tássio, utilizei o método onRestart na Activity A e funcionou perfeitamente, ao retornar ele chama o método que interage com o web service e dessa forma carrega os dados atualizados. Obrigado pela ajuda!
Comment: Ótimo,  Paul! onRestart também soluciona o seu problema! Foi um prazer ajudá-lo!
Answer: Olá, você pode chamar a Activity B, usando o StartActivityForResult
Activity A
private static final IDENTIFICADOR_B = 1;

Intent i = new Intent(this, ActivityB.class);
startActivityForResult(IDENTIFICADOR_B  1);

Sobreescreva na activity A o método onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == IDENTIFICADOR_B ) {
        if(resultCode == Activity.RESULT_OK){
            String resposta = data.getStringExtra("tag"); //resposta = "atualizar"
           //Atualizar mais coisas aqui
        }
    }
}

Em sua Activity B, finalize assim:
Intent returnIntent = new Intent();
returnIntent.putExtra("tag","atualizar");
setResult(Activity.RESULT_OK,returnIntent);
finish();

Espero ter ajudado...
Comment: Uma alternativa é utilizar o método `onStart()` ou `onResume()` que será chamado ao retornar à *Activity* **A**, depois de **B** finalizar.


Get all current tabs (node view)

Question: How to get all node tabs (MENU_LOCAL_TASK type) which available for current node?
I mean node/%/edit, node/%/translate, node/%/devel etc.
I've tried to use menu_local_tasks() but it shows only empty array.
Answer: Got it!
<code>if ($node = menu_get_object()) {
    $tabs = menu_local_tabs();
}
</code>

Get all current tabs (node view)


Evento change só é disparado ao mudar aba ou mudar de janela

Question: Boa tarde pessoal.
Estou tentando implementar um autocomplete utilizando o typeahead.js. Atribui um evento de change ao meu input para fazer uma requisição ajax que me traz os dados que serão exibidos na lista.
Porém, quando a tela é carregada e eu digito alguma coisa o meu evento não é disparado. Se eu tirar o foco do componente e digitar novamente o evento também não é disparado. Ele é disparado somente quando eu clico na barra de endereços, ou mudo de aba no navegador ou de janela. Após o evento ser disparado pela primeira vez, toda vez que digito alguma coisa o evento é disparado normalmente. Alguma ideia do porque isso pode estar acontecendo?
<!DOCTYPE html>

         <g:form name="formBusca" class="form-inline">

                  Nome:
                  <g:textField id="nome" name="nome" class="form-control" autocomplete="off"/>

                  Usuário:
                  <g:textField  id="username" name="username" class="form-control" autocomplete="off"/>

                  <button type="button" class="btn btn-default btn-sm" id="search-button">Pesquisar</button>
                  <g:link action="form" class="btn btn-default btn-sm">Novo</g:link>

         </g:form>

O Backend da aplicação está sendo fendo com Grails, mas não acredito que isso tenha alguma relação.
Obrigado.
Answer: O evento change em uma input, pode, por vezes, causar esse tipo de problema. Olhe esse exemplo:

$('input').change(function(){
 $('span').text(this.value)
})

<input type="text">

Veja que o texto no span não aparece ao ser digitado e sim em um blur, por isso o fato de ser disparado ao mudar a aba ou janela. Caso queira mudar isso pode usar vários outros eventos, como o input:

$('input').on('input', function(){
 $('span').text(this.value)
})

<input type="text">

Outros eventos: keyup, keydown e keypress.
No seu caso ficaria assism:
$(function() {
  $("#nome").on('input', function() {
    var input = $(this).val()
    $.ajax({
      url: "loadNameChoices",
      type: "get",
      data: {
        input: input
      },
      contentType: 'application/json',
      success: function(response) {
        $("#nome").typeahead({
          source: response
        });
      },
    });
  });
});

Comment: Ótima resposta. Obrigado!!


Github project import to Android Studio : Migrate Project to Gradle? This project does not use the Gradle build system

Question: First of all This is not a duplicate of any of below questions
Migrate project to gradle error
Can't migrate project to Gradle in Android Studio
This project does not use the Gradle build system. We recommend that you migrate to using the Gradle build system
Android Studio Import Project Error
Now let me talk about the problem. I've downloaded a zip file of GitHub project file to build on my laptop. The name of GitHub project is  "VNCpp"   As I'm not allowed to insert more than 2 links, I have given the project name so someone can search.
When I import this project into my android studio, it gives me this error : "Migrate Project to Gradle? This project does not use the Gradle build system. We recommend that you migrate to using the Gradle build system"
Edit: Android Studio has built in facility to import eclipse project and convert it into gradle build format. But in this case, it is not happening.
I'm getting 2 options while importing the project 1)Import from available sources and  2) Import from external model i.e gradle
When I select Import using external model  it shows error like in this image:
gradle path error
And when I select Import from existing sources  it creates some file system that doesn't have gradle structure. So I cannot edit and build the app on studio :
File system without gradle structure
What should I do now to properly import the project ?
Comment: The message is self explanatory. What do you want us to tell you? The migrate process describes that you have to import the `.project` of the Eclipse layout
Comment: And that second post cleanly explains the issue.  *The project thinks it's still a non-Gradle based project; it's not the presence of the build.gradle file that makes it Gradle-based, but it's how the project was set up in the first place.*
Comment: @cricket_007  Checkout the updated question with detailed information
Comment: For the first image, I think you have to actually download / install Gradle.
Comment: @cricket_007  It is already installed. It is working if i create a new project or work on my on going project etc. So there is no issue for installation of gradle.
Any other idea ?
Comment: Right, but the image shows you have not set the path to your Gradle installation
Answer: I solved this problem after reading carefully [the documentation(https://developer.android.com/studio/intro/migrate.html).

Clone the project from GitHub
Close all Android Studio projects.
From the Android Studio welcome screen, click Import Project (Eclipse ADT, Gradle etc).
Select the project folder with the AndroidManifest.xml file
Click ok.


Why is the group of rotations in $\mathbb{R}^n$ not $n$-dimensional?

Question: I have a rather basic mis-understanding about Lie groups and Lie algebras. Consider the Lie group $SO(N)$ for $N>3$ of rotations on $\mathbb{R}^N$. On the one hand this Lie group has dimension $N(N-1)/2$, since every $SO(N)$ element can be parametrized as $e^{X}$, where $X$ is an anti-symmetric matrix with $N(N-1)/2$ free parameters.
On the other hand, $\mathbb{R}^N$ has $N$ cardinal axes. Can I not express every rotation in $\mathbb{R}^N$ as products of rotations about the axes, implying that $SO(N)$ has dimension $N$? Where do the additional degrees of freedom come from? A follow up related question is: each Lie algebra generator $X(i,j)$, for $1 \leq i < j \leq N$ generates a one-parameter group of rotations $O(\theta) = e^{\theta X_{ij}}$. Is there a simple geometric explanation for which axis this rotation is about?
Comment: Well, what would it even *mean* to rotate about an axis in (say) $\mathbb{R}^4$? What would be the matrix for that? You should think about rotations in two-dimensional subspaces instead.
Comment: Bit they aren't necessarily rotations about an axis in dimension $>3$, so your comment seems misleading and wrong.
Comment: Maybe look at https://math.stackexchange.com/a/1402376/27978 It is worthwhile noting that $\binom{n}{2} = {n (n-1) \over 2}$.
Comment: (That is, you need to consider rotating in 2d planes rather than about axes.)
Comment: @CyclotomicField Define rotation?
Comment: To be concrete, write down an element of $SO(4)$ that is not rotation about any axis. In particular, $1$ will not be an eigenvalue of this linear map.
Comment: Rotations can be characterized by points on a sphere which is one dimension lower already and some of those will be redundant. You should expect some loss of dimensionality.
Comment: @TedShifrin I define a rotation as an element of the special orthogonal group. They're rotations so you're allowed to define them circularly.
Answer: Firstly note that already in just 2 dimensions this doesn't make sense. $SO(2)$ represents rotations in the plane and is 1 dimensional. So the naive assumption should be that we have $\frac{N}{2}$ ($\frac{N-1}{2}$  if $N$ is odd) dimensions for $SO(N)$ by splitting into orthogonal 2-dimensional subspaces . The problem being that products of these simple rotations don't generate all possible elements of $SO(N)$. Indeed they generate exactly a Cartan subgroup.
The next naive guess is that we shouldn't have made the 2-dimensional subspaces orthogonal and worked with all subspaces or at least all subspaces we get from a fixed orthonormal basis. But the number of those is exactly $N$ choose $2$ or $\frac{N(N-1)}{2}$ which is the correct answer. Obviously I haven't shown that there is no redundancy there but this is the right idea.
Answer: Nobody seems to have mentioned $\mathbb R=\mathbb R^1$ yet, and yet it would seem to be a good answer to the question: the group of rotations of $\mathbb R^1$ is $0$-dimensional.  Namely, it consists of only two "rotations": the identity map and the antipodal map $x\mapsto -x$.
Comment: I'd argue the second of those is a reflection and that $O(1)$ comprises two elements while $SO(1)$ is just the identity.
Comment: @Callum, very true.
Comment: @Callum, this does not change the dimension of the group :-)


Formatting deep lists in markdown

Question: I want to compose a list with the following format:
.1 - Lorem

    .1.1 - Inside Lorem

        .1.1.1 - Inside Inside lorem

.2 - Lorem

And so on, but 8 whitespaces / 2 tabs are rendered as comments/code blocks, which makes .1.1.1 messy. Is there any way of doing it?
Answer: You need to use the standard ordered list syntax at every level, or Markdown processors do not recognize that the indented content represents a list item
So, you markup needs to look like:
1.  Lorem

    1.  Inside Lorem

        1.  Inside Inside lorem

2. Lorem

Then, to get the 1.1 and 1.1.1 numbering, you need to apply CSS to achieve that. See the answer for Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?
If you really need the hyphen between the number and the list item's text, you would also include that in the CSS:
LI:before { content: counters(item, ".") " - "; counter-increment: item }

Formatting deep lists in markdown


What's the name of this rhythm technique at piano?

Question: I remember my first piano teacher had an interesting technique to help at difficult parts of a piece.
Instead of playing the actual rhythm, I would pretend it was (kind of) dotted 8th notes alternating with 16th notes. Then, I would do the same thing, but starting with a 16th note, alternating with dotted 8th notes.
I would do this only with separated hands and always ff. It was very useful because it helped muscle-memorize every note transition.
Is this a known technique??
Answer: It is indeed a known technique.  Very, even.
Cortot was a famous proponent of it.  You can find copious examples in his pedagogical editions.  You can also find examples of famous pedagogues who disagreed with it.  If memory serves, Neuhaus was lukewarm toward the method in his book.
I know of no universally accepted name for it. My teachers simply called it practising in rhythms.
Examples
In response to a comment asking for examples of this method of practice, I have added some excerpts from Cortot's edition of Chopin.
From the étude op. 25 no. 2,

the suggested variants:

Comments from the end of the fourth Scherzo including suggested rhythmic variations:

He writes that the rhythmic variations throw the accent away from the beat, developing the independence of the fingers.
Comment: Could we have the name of this technique? Maybe some sheet music showing it?
Comment: Concerning the name of this technique, please read my third paragraph again.  The suggestion to add examples is well made.  I have added some images.
Comment: Thank you for the answer! Adding examples was a great bonus.
Comment: Sorry, I was asking the whole community whether anyone knew and didn't mean to put you on the spot. Thanks for the images!


How does having a repeated root in $trigonometric$ $equations$ (non-polynomial) imply touching, but not crossing the $x$-axis?

Question: Consider
$$f(x)=cos\left(2x+\frac{\pi}{3}\right)-cos\left(\frac{3x}{2}+\frac{\pi}{4}\right)=0 \tag{1}$$
giving
$$2x+\frac{\pi}{3}=\pm\left(\frac{3x}{2}+\frac{\pi}{4}\right)+2r\pi \tag{2}$$
$\pm \to +, r \to n$
$$x_n^+=\pi\left(\frac{24n-1}{6}\right) \tag{3}$$
$\pm \to -, r \to k$
$$x^-_k=\frac{\pi}{42}\left(24k-7\right) \tag{4}$$
where $r,n,k \subset Z$.
Then $x=...,-31\pi/42,-\pi/6,17\pi/42, 41\pi/42...,$
According to the textbook that I am reading, as $$x^+_{n=0}=x^-_{k=0}=-\frac{\pi}{6} \tag{5}$$ is a repeated root, $x=-\frac{\pi}{6}$ is a value at which the curve touches the $x-axis$ without crossing it.
But I do not understand how having a repeated root in trigonometric equations implies touching the $x$-axis (the notion of change of sign does not seem applicable here)?
Comment: https://math.stackexchange.com/questions/10408/polynomials-derivatives-and-repeated-roots
Comment: @ lab bhattacharjee But this is for polynomials, not trig. equations isn't it?
Answer: Any real function $y=f(x) $ whether algebraic or trigonometric, has a double root at $x=a$  if
$$ f(a)=0,\; f'(a)=0\;$$
For example there is a double root at
$x=-1$ for the curve (circle)
$$ (x+1)^2+(y+1)^2=1$$
where it touches x-axis.  A trig function
also has the same situation:
Quite the same happens for the following implicit trig function
$$ \sin x \sin (y-\frac14) = \frac14 $$

Any smooth function can be chosen  from trigonometric, hyperbolic algebraic polynomials functions to be eligible.They should have series expansion with continuous derivatives. You were perhaps first introduced to algebraic polynomials for ease of differentiation.
Comment: Did you seek a proof for algebraic/polynomial cases? Accept this also in that function  list.
Comment: Thanks. I can see why this happens for algebraic/polynomial expressions. Is there a proof of this for the trigonometric case?


How to add corresponding Integer values in 2 different DataFrames

Question: I have two DataFrames in my code with exact same dimensions, let's say 1,000,000 X 50. I need to add corresponding values in both dataframes. How to achieve that.
One option would be to add another column with ids, union both DataFrames and then use reduceByKey. But is there any other more elegent way?
Thanks.
Answer: Your approach is good. Another option can be two take the RDD and zip those together and then iterate over those to sum the columns and create a new dataframe using any of the original dataframe schemas.
Assuming the data types for all the columns are integer, this code snippets should work. Please note that, this has been done in spark 2.1.0.
    import spark.implicits._

    val a: DataFrame = spark.sparkContext.parallelize(Seq(
      (1, 2),
      (3, 6)
    )).toDF("column_1", "column_2")

    val b: DataFrame = spark.sparkContext.parallelize(Seq(
      (3, 4),
      (1, 5)
    )).toDF("column_1", "column_2")

    // Merge rows
    val rows = a.rdd.zip(b.rdd).map{
      case (rowLeft, rowRight) => {
        val totalColumns = rowLeft.schema.fields.size
        val summedRow = for(i <- (0 until totalColumns)) yield rowLeft.getInt(i) + rowRight.getInt(i)
        Row.fromSeq(summedRow)
      }
    }

    // Create new data frame
    val ab: DataFrame = spark.createDataFrame(rows, a.schema) // use any of the schemas
    ab.show()

Update:
So, I tried to experiment with the performance of my solution vs yours. I tested with 100000 rows and each row has 50 columns. In case of your approach it has 51 columns, the extra one is for the ID column. In a single machine(no cluster), my solution seems to work a bit faster.

The union and group by approach takes about 5598 milliseconds.
Where as my solution takes about 5378 milliseconds.
My assumption is the first solution takes a bit more time because of the union operation of the two dataframes.

Here are the methods which I created for testing the approaches.
  def option_1()(implicit spark: SparkSession): Unit = {
    import spark.implicits._
    val a: DataFrame = getDummyData(withId = true)
    val b: DataFrame = getDummyData(withId = true)
    val allData = a.union(b)

    val result = allData.groupBy($"id").agg(allData.columns.collect({ case col if col != "id" => (col, "sum") }).toMap)
    println(result.count())
    //    result.show()
  }

  def option_2()(implicit spark: SparkSession): Unit = {
    val a: DataFrame = getDummyData()
    val b: DataFrame = getDummyData()

    // Merge rows
    val rows = a.rdd.zip(b.rdd).map {
      case (rowLeft, rowRight) => {
        val totalColumns = rowLeft.schema.fields.size
        val summedRow = for (i <- (0 until totalColumns)) yield rowLeft.getInt(i) + rowRight.getInt(i)
        Row.fromSeq(summedRow)
      }
    }

    // Create new data frame
    val result: DataFrame = spark.createDataFrame(rows, a.schema) // use any of the schemas
    println(result.count())
    //    result.show()
  }

Comment: Thanks for your reply. It seems like a plausible solution. Can you please comment on the performance difference with my proposition? I am sorry, I am a beginner in Scala and Spark.
Comment: Updated the answer, it seems the performance of union + group is a little bit slow. I can not say definitively though, hope it helps.
Comment: Hey, sorry for bothering again. The solution was working fine until a very small change. Now I have all the date as Double, and when I try to rowLeft.getDouble, it produces error "org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema cannot be cast to java.lang.Double". I can't see why it should not work, it is working absolutely fine when I get an Int, but not with Double.
Comment: It should work. Can you please share your code? Also the sample data you are using.
Comment: `val eventsRDD = machineDF.rdd.zip(diffMachineDF.rdd)
      .map {case (rowLeft, rowRight) =>
        val totalColumns = rowLeft.schema.fields.size
        val summedRow = for(i <- (0 until totalColumns)) yield rowLeft.getDouble(i) + rowRight.getDouble(i)
        Row.fromSeq(summedRow)
      }`
Comment: The data is something like (just one row): `[1.0,1.0,[-7.0E-4,-4.0E-4,100.0],[518.67,641.82,1589.7,1400.6,14.62,21.61,554.36,2388.06,9046.19,1.3,47.47,521.66,2388.02,8138.62,8.4195,0.03,392.0,2388.0,100.0,39.06,23.419]]`. This is the ourput of saveAsTextFile on the RDD.
Comment: Please ignore the square brackets. They were just formatted that way.
Comment: hmm, might be a data issue. I presume you are loading data from a csv file , right? Can you please give the output of these two command: `machineDF.printSchema(); diffMachineDF.printSchema();` I want to see the schema of the data loaded in the dataframes.
Comment: I must be doing something very very stupid. I did that again and it is working. And now Don't even know what was I doing wrong. Thank you very much.


Finding the value of an biased coin flip game with stop loss

Question: Question:
I have a biased coin, with 70% H and 30% T. I receive \$1 each time I flip a H and lose \$1 for T.
I am going to flip the coin 100 times, without any constraints, the expectation of money I will received will be \$40.
Now, what is the expectation if I stop once lose \$10?
My thoughts:
I model this as a random walk, $S_t = \sum_{i=1}^t Z_i$. And $\tau$ be the stopping time when $S_t$ reaches -10 for the first time. Our game stops at $\tau \wedge N$, where $N = 100$.
Now the expectation will be:
$\mathbb{E}[S_{\tau \wedge N}] = -10p + 40(1 - p)$, where $p = P(\tau\leq N)$
If the coin is unbiased, then $p$ can be found using reflection principle. Not sure how to find the distribution of $\tau$ for the biased coin. Any suggestions are welcome!
Edited: I just realized, if the coin is unbiased, then $S_{t\wedge N}$ will be a martingale and we can use optimal stoping theorem to get $\mathbb{E}[S_{\tau \wedge N}] = \mathbb{E}[S_0] \mathbb{E}[\tau \wedge N] = 0$. We can apply this theorem because $\tau \wedge N$ is also a stopping time and bounded.
Comment: The simple answer is that your expectation is still very close to $\$40$ as the chance of losing $\$10$ is very small.  It will be lower because the game is favorable so (from an expected value point of view) you want to play as much as possible and the stop loss will reduce the number of plays.
Answer: This is not a complete answer (since I did not find a closed form for this probability and even suspect it may not exist at all), but here are my thoughts that may give you a better insight to the problem.
First, for a fixed $k$ and a fixed sum $S$ let us count the following probability
$$f(k, S) = P(z_1 + z_2 + \dots + z_k = S)$$
For all $S > k$ and $S < -k$ this probability is equal to 0. Note that $z_k$ is either $1$ or $-1$ with probabilities 0.7 and 0.3 respectively. Thus,
$$f(k, S) = 0.7f(k - 1, S - 1) + 0.3f(k - 1, S + 1)$$
This formula allows computing $f(k, S)$ recursively.
Then, for some $m > 0$:
$$p_m := P(\tau < N, \tau \geqslant m) = P(\tau < N, \tau \geqslant m | \tau = m)P(\tau = m) + P(\tau < N, \tau \geqslant m | \tau \geqslant m + 1)P(\tau \geqslant m + 1) = P(\tau < N | \tau = m)P(\tau = m) + P(\tau < N | \tau \geqslant m + 1)P(\tau \geqslant m + 1) = f(m, -10) + P(\tau < N, \tau \geqslant m + 1)(1-f(m, -10)) = \\ = f(m, -10) + (1-f(m, -10))p_{m+1}$$
As you can see, $p_m$ also can be counted recursively (but the closed form for $p_m$ can hardly be computed). The answer to your question is $p_1$.
Comment: This equality is not true too. R.h.s. is equal to $$P(\tau < N \mid \tau \geqslant m, \tau = m) P(\tau = m) +P(\tau < N \mid \tau \geqslant m, \tau \geqslant m + 1) P(\tau \geqslant m + 1)=\frac{P(\tau < N , \tau \geqslant m, \tau = m)}{P(\tau \geqslant m, \tau = m)} P(\tau = m) +\frac{P(\tau < N, \tau \geqslant m, \tau \geqslant m + 1)}{P(\tau \geqslant m, \tau \geqslant m + 1)} P(\tau \geqslant m + 1)=P(\tau < N , \tau \geqslant m, \tau = m)+P(\tau < N, \tau \geqslant m, \tau \geqslant m + 1)=P(\tau < N, \tau \geqslant m)\neq P(\tau < N\mid \tau \geqslant m).$$
Comment: @NCh Yes, good spot. Thank you, I replaced $P(\tau < N | \tau \geqslant m)$ with $P(\tau < N, \tau \geqslant m)$.
Comment: The equality $$P(\tau<N\mid\tau\geq m)=P(\tau<N\mid\tau =m)P(\tau=m)+P(\tau<N\mid\tau\geq m+1)P(\tau\geq m+1)$$ is not true. You lost $P(\tau\geq m)$ in denominator of r.h.s.
Comment: @NCh According to law of total probability $P(\tau < N | \tau \geqslant m) = P(\tau < N | \tau \geqslant m, \tau = m) P(\tau = m) +P(\tau < N | \tau \geqslant m, \tau \geqslant m + 1) P(\tau \geqslant m + 1) $


Magento 2.0.2 404 not found

Question: I host a site in Magento 2.0.2. I give proper permission and mod_rewrite enable in Apache. but my site is loading home page only. All the pages and admin I got 404 not found.
The Frontend page loads while using with index.php. Admin page is not working.
Comment: check http://magento.stackexchange.com/questions/89125/how-to-fix-magento-2-2-0-0-rc-admin-page-not-found-after-installation/96441#96441
Comment: i tried but its not working for me. Frontend page load while using with index.php. admin is not working
Comment: this is issue with .htacess kindly add in main folder and give the permission
Comment: I already added the .htaccess file and also give 777 permission
Answer: It is probably because mod_rewrite is not installed or working on your Apache server.
mod_rewrite is usually installed as part of MAMP but perhaps your magento .htaccess file is not being loaded for some reason.
The first possibility is that if you extracted the archive file on your mac and moved the files using the finder or uploaded them to a mac web server using something like dreamweaver then by default the Mac does not show files starting with a . such as .htaccess and therfore they would not be copied into the web server directory. The solution to this is probably to enable showing hidden files in the finder on the Mac so you can see and copy the files easily. This link shows you how to enable viewing hidden files. http://ianlunn.co.uk/articles/quickly-showhide-hidden-files-mac-os-x-mavericks/
The second possibility is how you have configured your http server. You must tell it to allow .htaccess to override settings in a directory. To do this you must have this in your httpd.conf file.
<Directory "/your/magento/directory/">
   Options Indexes MultiViews FollowSymlinks
   AllowOverride All
   Order allow,deny
   Allow from all
</Directory>

Obviously replace "/your/magento/directory/" with the actual path to your Magento installation.
Also Put below code:
For Ubuntu edit the file /etc/apache2/apache2.conf (here we have an example of /var/www)
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

and change it to;
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

then
sudo service apache2 restart

Finally during the installation of Magento 2 when you use the web installation setup in your browser, when you get to the Web Configuration section there is an Advanced Options section where you can turn off Apache Rewrites if you can't get mod rewrite to work. That is fine for experimenting but for an actual web store you would really want to get the re-writes working.
solution 2
Install Composer. Now I would like you to download Magento 2 zip from magentocommerce.com/download, create new db in phpmyadmin, extract zip in htdocs folder. Install Magento 2 but do not use localhost use 127.0.0.1 in store URL and admin URL. After successful installation DO NOT run magento.
Now we are going to verify Composer installation, Deploy static content, clear / flush Magento cache and reindex the Magento 2 blocks. To perform all above actions, press WINDOWS KEY + R to open RUN dialog and type "cmd" to open Command Prompt.
Type "cd PATH_TO_YOUR_MAGENTO2_FILES" to enter in Magento 2 ROOT directory.
Now to verify Composer installation in above directory, type "composer install".
If you get any error in this step, please check your Composer installation
In this step, we are setting up static content to deploy on our Magento store. To perform this, type "php bin/magento setup:static-content:deploy".
If you get any error, check your PHP.EXE and PHP.INI Environment Variable
Clear / Flush Magento cache by typing "php bin/magento cache:flush" in CMD.
And finally, to Reindex Magento Static Blocks type "php bin/magento indexer:reindex".
You are done with successful installation of Magento 2.
Comment: I tried your idea. not working.Frontend page is loaded while using with index.php. admin is not working
Comment: For admin, you have to use solution 2 added in above answer.

Magento 2.0.2 404 not found


How can I unShow() after Spreadsheet.show(HtmlOutput)?

Question: I have this working very nicely :
var theForm = HtmlService.createTemplateFromFile('aForm').evaluate();
var theSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();

theSpreadsheet.show(theForm);

When the user has submitted data I want to close "theForm".  Is there something like an unShow() or hide() method on a spreadsheet? a harikiri() method on an HtmlOutput?
Ideally, I'd like to have a reShow() command that saves the submitted data, refreshes the spreadsheet and calls show() again.
I have found no way to do these things, so I just disable the submit button. Ugh!
Any suggestions greatly appreciated.
UPDATE (2012/08/28) :  I should have mentioned that I am calling back into the same code as originally opened "theForm", from the HTML form, using this call ...
google.script.run.recordTheForm(jsonTheForm);

Do I assume correctly that google.script.run.*() calls have no knowledge of any variable values set earlier?
Answer: HtmlService doesn't have an equivalent of app.close()... this is an oversight, not something by design, and we will fix it.
Edit: From within client-side JavaScript code (not from the server like app.close(), but within the HtmlService code itself) you can now call google.script.host.closeDialog()
Comment: Can't argue with that!  Thank you for letting me know.
Answer: Call this:
theForm.close();
SpreadsheetApp.flush();
theSpreadsheet.show(theForm);

Good luck,
Thomas van Latum
Comment: Thomas.  Thank you, with the insufficient info I initially provided, you pointed my in the right direction.
Comment: I found no such method HtmlOutput.close(), although there is HtmlOutput.clear().  Nevertheless, after poking around a bit, I came to the conclusion I mention in my update above; calling back into the calling memory space with google.script.run doesn't seem to be possible.  In the end, by flushing the sheet and showing a new form I have given the end users what they wanted.  They may use more memory each time, but I see no  need, or even a way, to examine what happens down that deep.
Comment: Well happy to help :)
I was just typing this presuming the HtmlOutput had a close function just like an UiApp. But clear works just fine then.
I dont know how you can reduce the memory.
Comment: I couldn't use clear() either!  Calling back to the *.gs code from js code in the browser did not get me the same memory space as launched the the HtmlOutput in the first place.
Comment: Could you post (send me) your complete code so i can see what you exactly want to do and where it goes wrong?
Comment: I do have it working.  As I said, ".. by flushing the sheet and showing a new form I have given the end users what they wanted."  I've asked a new question about the remaining issue. http://stackoverflow.com/q/12655469/1544075
Comment: Thomas, it seems that by accepting CoreyG's answer I unaccepted yours and cost you points.  Sorry, didn't know.


How can I save form data on a node in Drupal?

Question: I want submit form data and save on specific node but I don't know that how to do?
<code>function test1_menu() {
  $items['mytest'] = array(
    'title' => 'My Tes',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test1_form'),
    'access callback' => TRUE,
    'weight'=> 1,
    'type'=> MENU_NORMAL_ITEM,
  );
  return items;
}

function test1_form($form, &$form_submit) {
  $form['firstname'] = array(
    '#title' => t('First Name'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Client Name'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => 'Test',
    '#type' => 'submit',
  );
  return $form;
}

function test1_form_form_submit($form_id, &$form_state) {

}
</code>
Answer: In your submit function, you just need to create a node, e.g.
<code>$values = array(
  'type' => $node_type, // Drop in your desired node type.
  'uid' => $user->uid, // Want to set an author?
  'status' => 0,
  'comment' => 0,
  'promote' => 0,
);
$entity = entity_create('node', $values);
</code>
To make your life easier, I recommend to use entity_metadata_wrapper:
<code>$ewrapper = entity_metadata_wrapper('node', $entity);
</code>
Now, you can just cycle through your form data and add the values to the correct fields of your node:
<code>$key = '<MACHINE_NAME OF YOUR FIELD>'; // e.g. "field_firstname"
$val = '<VALUE TO BE SET FOR THAT FIELD>'; // e.g. $form_state['values']['firstname']
$ewrapper->$key->set($val);
</code>
This of course depends on the field type, the above works for example for simple textfields. Finally, if all is set, just save the freshly created node:
<code>$ewrapper->save();
</code>
Comment: Right, I added an example to my answer.
Comment: And the form values are accessible inside the _form_submit function by using $form_state['values']['firstname']


Domain of composite of three functions

Question: My question is if we want to find the domain of
$[(f\circ g\circ h)](x) $
Will the domain be the Dom of the constructed(new) function intersection with the Dom of $(g(h(x))$ intersection with the Dom of $h(x)$.
Comment: I don't understand why you think it would be anything different than the domain of $f$.  If $f$ is a function from $A$ to $B$ and $g$ is a function from $B$ to $C$ then you have $f\circ g$ is a function from $A$ to $C$.  Composing this again with $h$ a function from $C$ to $D$ makes $f\circ g\circ h$ a function from $A$ to $D$...  Are you perhaps thinking of a scenario where $g$ is *not* a function from $B$ and there are elements in the range of $f$ for which $g$ is not defined?
Comment: Also, since I see you wrote $g(h(x))$... it is worth confirming... are you following the notation that $(f\circ g)(x) = g(f(x))$?  Or are you using here this is instead $(f\circ g)(x) = f(g(x))$?  I may have gotten it backwards then, in which case just take what I wrote above and rearrange the function names... but it would still wind up being the domain of the composition is the domain of the "first" function in the chain.
Comment: Yes Assume that f is from A to B and g from C to D where D contains elements not in A and A also contains elements not in D
Comment: (fog)(x)=f(g(x))
Comment: Then why should you be allowed to compose the functions in the first place if the codomain of the first doesn't match the domain of the second?  What you are doing isn't composing functions... its like a "restricted composition" of functions...
Comment: It is a composition of functions but the question in the textbook asking to state to restrict the domain if it is needed
Comment: So when I explained to my students I gave them what I mentioned in my question
Comment: @Well defined $h$ , $g \circ h $ , $ f \circ g \circ h $ all have same domain,,,so, why do you want to insect them???
Comment: They don't have the same Domain as what I mentioned in my comment , the questuons in the textbook asking to composite the function with restriction of the domain if it is needed
Answer: When defining composite functions, it is reasonable to expect the image of the first function to atleast have some intersection with the domain of the second. We can then define the composition, $g \circ h$ on the smaller $h^{-1}(Dom(g))$.
One might think that there should be some $Dom (g) \cap Im(h)$ involved. But this set is just $h^{-1}(Dom(g))$, because on the points of $Dom(g)$ that don't lie in $Im(h)$, the inverse image doesn't exist.
Extending this to three functions, we can only define the composition on $h^{-1}(g^{-1}(Dom(f))$.
The following inclusion holds:  $$h^{-1}(g^{-1}(Dom(f)) \subset h^{-1}(Dom(g)) \subset Dom(h)$$.
So, the set mentioned by the OP is actually the set $h^{-1}(g^{-1}(Dom(f))$, which is the domain of $f\circ g \circ h$.
Comment: Range of (h) is a subset of domain g and range of (goh) is a subset of domain f  isn't this same as what I mentioned in my question the case of intersection
Answer: The domain of $(f \circ g \circ h ) $ will be the domain of $h$,as $(g \circ h) $ is possible iff $Range(h) ⊂ Dom(g) $ and again , $(f \circ g \circ h ) $  is possible iff $Range(g \circ h) ⊂ Dom(f) $
Comment: Range of (h) is a subset of domain g and range of (goh) is a subset of domain f isn't this same as what I mentioned in my question the case of intersection
Comment: Domain of the new function intersect with the domain of g(h(x)) intersect with the domain of h(x) I think it is still the same as what you mentioned in your answer
Comment: But in the composition of three functions it doesn't depend only on the x values in h as  the h(x) Range values will move you to g(h(x)) so the x values in the domain of h(x) maybe will be undefined in the g(x)
Comment: As JMoravitz says, if $h: A \to B $ and $g: B \to C $ , then $g \circ h : A \to C $ , iff $Range(h)⊂ Domain(g) $....But , $Range(h)⊂ Domain(g) $ doesn't effect to the domain of the composite function..
Comment: But if h : A-> B   and g:C->D then goh: we need to find the x values in the function h whose range values are a subset of the domain of g
Comment: Hmmm,,, right,,,but it doesn't matter with the domain of compsite function,,,,this rule only for whether composite possible or not,,,but if the composite is possible,,,the domain will be the domain of starter function..
Comment: Okk, take a example,,,take $h=x^2 $ on $\mathbb{R} $ , and $g=\sqrt{x} $ on $[0,\infty) $,,, clearly $g\circ h = x $ have domain $\mathbb{R} $ , where $Range(h)=Domain (g) = [0,\infty) $,,, clearly you see domain of $g \circ h$ only depend on the domain of $h$...
Comment: So in your example if I asked you to find h(g(-1))  will the answer be undefined or -1?
Comment: It's for $g \circ h = g(h(x)) $,,,and if you go for $h \circ g $ ,,, then it is undefined!!! As the rule range (g) not in domain of (h).....so, there is no meaning of finding $h(g(-1))$
Comment: So this is what I meant  that for the new constructed function from composition must be restricted as what I memtioned in my Question

Domain of composite of three functions


Herança X Composição - MySQL C# Entity

Question: Estava com uma dúvida de modelagem de herança no C# envolvendo as entidades Pessoa, PessoaFísica e PessoaJurídica, mas Cigano Morrison Mendez ajudou bastante! Agora estou com outra dúvida em outro tipo de relacionamento. Como comentei, uma pessoa pode ser física ou jurídica. Uma pessoa ainda pode ser cliente e/ou fornecedor. E o cliente pode ter serviços relacionados. Segue a modelagem:

Os modelos no código ficaram:
[Table("pessoa")]
public class pessoa
{

    [Key]
    public int idPessoa { get; set; }

    [Required]
    [StringLength(90)]
    public string nomeRazaoSocial { get; set; }

    public virtual fornecedor fornecedor { get; set; }

    public virtual cliente cliente { get; set; }

}

[Table("pessoafisica")]
public class pessoafisica : pessoa
{

    [StringLength(15)]
    public string cpf { get; set; }

}

[Table("pessoajuridica")]
public class pessoajuridica : pessoa
{
    [StringLength(45)]
    public string cnpj { get; set; }

}

[Table("cliente")]
public class cliente
{
    [Key, ForeignKey("pessoa")]
    public int idPessoa { get; set; }

    public virtual pessoa pessoa { get; set; }

}

[Table("fornecedor")]
public class fornecedor
{

    [Key, ForeignKey("pessoa")]
    public int idPessoa { get; set; }

    public virtual pessoa pessoa { get; set; }
}

Até aí tudo funcionou bem... a interação com o banco para cadastro, edição e consulta está ótimo. Porém, na hora de cadastrar os serviços estou com uma pulga atrás da orelha. Conceitualmente falando. Eu relacionei o serviço ao cliente e minha classe ficou:
[Table("servico")]
public class servico
{
    [Key]
    public int idServico { get; set; }

    [ForeignKey("cliente")]
    public int idCliente { get; set; }

    public string descricao { get; set; }

    public virtual cliente cliente { get; set; }
}

Claramente uma PessoaFisica é uma classe herdada de Pessoa, assim como PessoaJuridica é uma classe herdada de Pessoa. Logo, seu eu tivesse uma tabela para os endereços das pessoas, na tabela de endereços eu usaria a chave da tabela Pessoa para manter o relacionamento. Uma pessoa sempre será OU pessoafisica OU pessoajuridica.
Agora tem outra questão... do Fornecedor e Cliente. Uma pessoa PODE OU NÃO ser um fornecedor... também PODE OU NÃO ser um cliente. E pode ser as duas coisas ou não ser nenhuma delas.
Embora um cliente ou fornecedor SEMPRE sejam uma pessoa, a entidade Serviço só poderá estar associada a um Cliente e nunca a um fornecedor (pelo menos nesta aplicação).
Aí vem a primeira dúvida... para esse conceito desejado, essa modelagem está correta? As chaves nas tabelas, cardinalidade... isso está certo?
Segunda dúvida...
Entendo que na tabela Serviço a chave de relacionamento idCliente deva conter a chave primária da tabela Cliente, e não a chave primária da tabela Pessoa. ESSE CONCEITO ESTÁ CORRETO?
Seguindo a valiosa ajuda do Cigano, montei estas classes e na controller de cadastro de serviço o preenchimento da lista de cliente ficou assim:
ViewBag.idCliente = new SelectList(db.cliente
                                            .Include(c => c.pessoa)
                                            .Select (c => new
                                            {
                                                idCliente = c.idPessoa,
                                                nomeRazaoSocial = c.pessoa.nomeRazaoSocial
                                            }).ToList(), "idCliente", "nomeRazaoSocial");

A aplicação funciona, porém ao se cadastrar no banco de dados, o campo idCliente da tabela serviço recebe o campo idPessoa da tabela pessoa. E isso está me deixando incomodado...
O campo idCliente da tabela serviço não deveria ter o campo idCliente, que é chave primária da tabela Cliente? Se sim, como devo ajustar minhas classes para que isso funcione?
Obrigado a todos pela ajuda!
Comment: Tá esquisito isso aí. Como está a *View*?
Comment: Coloquei a view, Cigano!  Acho que a classe servico que tem alguma coisa. Quando segui sua sugestão, na classe cliente não tinha o atributo idCliente. Apenas o idPessoa com a notação [Key, ForeignKey("pessoa")]. Mas para fazer o o relacionamento de cliente 1 : n servico preciso ter o idCliente no servico, correto? Mas se não tem o idCliente na classe cliente, não funciona... estes mapeamentos estão corretos? Obrigado pela força!
Answer: Sua composição está incorreta. Cliente tem relação 0 pra 1 ou 1 pra 1 com Pessoa. Como eu disse na resposta anterior, o correto seria você fazer:
[Table("cliente")]
public class cliente
{
    // Cliente não deve ter Id própria. Apenas idPessoa.
    // [Key]
    // public int idCliente {get; set;}

    [Key, ForeignKey("pessoa")]
    public int idPessoa { get; set; }

    public int idCliente_Grupo { get; set; }

    public virtual cliente_grupo cliente_grupo { get; set; }

    public virtual pessoa pessoa { get; set; }

    public virtual ICollection<servico> servico { get; set; }
}

O mesmo vale para Fornecedor.
Apenas como adendo, eu não usaria Linq pra montar a consulta porque o suporte a carga preguiçosa/antecipada do Linq é limitado. Eu faria assim:
ViewBag.idCliente = new SelectList(db.Clientes
                                     .Include(c => c.Pessoa)
                                     .Select(c => new
                                      {
                                          idCliente = c.idPessoa,
                                          nomeRazaoSocial = c.Pessoa.nomeRazaoSocial
                                      }).ToList(), "idCliente", "nomeRazaoSocial");

Essa modelagem está correta? As chaves nas tabelas, cardinalidade... isso está certo?

Com as suas modificações, sim. Perfeita, eu diria.

Entendo que na tabela Servico a chave de relacionamento idCliente deva conter a chave primária da tabela Cliente, e não a chave primária da tabela Pessoa. ESSE CONCEITO ESTÁ CORRETO?

Sim, mas como a chave de Cliente é a chave de Pessoa (porque Cliente é, por composição, uma especialização de Pessoa), dá no mesmo.
Se você quiser manter o nome idCliente na modelagem, sem problemas. Até é melhor porque você explica por nomenclatura como Servico se relaciona com Cliente.

O campo idCliente da tabela Servico não deveria ter o campo idCliente, que é chave primária da tabela Cliente?

Não. idCliente conceitualmente é equivalente a idPessoa, justamente porque Cliente é a especialização de Pessoa, por composição. Portanto, está correto montar a SelectList com o idPessoa porque a seleção dos dados parte de Cliente, e não de Pessoa, já verificando, assim, se Pessoa é um Cliente ou não.
Comment: Oi Cigano! Obrigado pela ajuda! A cardinalidade é de Pessoa 0 : 1 Cliente. Ou seja, um cliente é sempre uma pessoa. Mas nem sempre a pessoa é um cliente. Eu só coloquei o id no cliente porque a entidade servico tem que ser relacionada ao cliente. Um cliente pode ter 0 ou n serviços. Então minha dúvida era como modelar a classe serviço. Essa sua sugestão para ViewBag.idCliente que você deu não está funcionando porque a entidade cliente não tem o atributo idCliente... por isso eu havia tentado colocar...
Comment: É mesmo. Tem um erro na resposta. No mais, sobre isto: *"Ou seja, um cliente é sempre uma pessoa. Mas nem sempre a pessoa é um cliente. "*, a resposta atende perfeitamente. Veja agora, depois da edição.
Comment: Assim funciona, cigano... mas pelo que entendo a tabela serviço deveria guardar como chave estrangeira o id do cliente e não o id da pessoa. O modelo relacional funciona assim, não? Eu melhorei a pergunta... o que eu perguntei faz sentido? Como eu resolvo minha classe? Mais uma vez, obrigado!
Comment: Não, porque a única maneira de garantir que `Pessoa` tenha apenas um registro relacionado com `Cliente` é fazendo a chave primária de `Cliente` ser também chave estrangeira com `Pessoa`. Vou melhorar a resposta respondendo suas perguntas.
Comment: Mas aí dá problema no banco de dados. No modelo do BD, a tabela servico tem o campo idCliente como chave estrangeira para a tabela cliente. Quando se tenta colocar neste campo um valor do id da pessoa gera o erro de chave estrangeira inexistente. Ex: uma pessoa tem idPessoa 2. Na tabela cliente, ela tem o respectivo campo idPessoa = 2 mas tem o campo idCliente = 1 (chave prim). Quando o sistema tenta cadastrar na tabela servico o valor 2 no campo idCliente, não existe o valor 2 na tabela Cliente, gerando um erro de violação de chave estrangeira. Por isso tem algo errado no BD ou na classe.
Comment: Vou falar mais uma vez: `idCliente` e `idPessoa` **precisam ser a mesma coisa, senão não funciona**. Se uma `Pessoa` é `Cliente` e os respectivos Ids são diferentes, **está errada sua modelagem**. Entendido?
Comment: Valeu pela paciência, cigano... a modelagem não estava perfeita, agora consegui encontrar a inconsistência.
Answer: Valeu pela força, Cigano!
A modelagem tinha um problema. Essencialmente, a tabela cliente deveria ter como chave primária E chave estrangeira o campo idpessoa:

Antes ela tinha idcliente como chave primária e idpessoa como chave estrangeira. Com isso, o banco sofria uma violação ao colocar o idpessoa na tabela servico.
As classes ficaram como o cigano falou:
[Table("final.pessoa")]
public class pessoa
{
    [Key]
    public int idpessoa { get; set; }

    [Required]
    [StringLength(45)]
    public string nome { get; set; }

    public virtual cliente cliente { get; set; }

}

[Table("final.pessoafisica")]
public class pessoafisica : pessoa
{

    [StringLength(45)]
    public string cpf { get; set; }

}

[Table("final.pessoajuridica")]
public class pessoajuridica : pessoa
{

    [StringLength(45)]
    public string cnpj { get; set; }

}

[Table("final.cliente")]
public class cliente
{
    [Key, ForeignKey("pessoa")]
    public int idpessoa { get; set; }

    [StringLength(45)]
    public string codigo { get; set; }

    public virtual ICollection<servico> servico { get; set; }

    public virtual pessoa pessoa { get; set; }
}

[Table("final.servico")]
public class servico
{
    [Key]
    public int idservico { get; set; }

    public int idpessoa { get; set; }

    [StringLength(45)]
    public string descricao { get; set; }

    public virtual cliente cliente { get; set; }
}

Em resumo: em um relacionamento de cardinalidade 0...1, como no caso do cliente com pessoa, use como chave primária E chave estrangeira da tabela dependente o id da entidade principal.
Comment: Agora sim. Perfeito

Herança X Composição - MySQL C# Entity