Can't pass php variable to javascript in Drupal 7

Question: Can somebody help me with this problem.
In the body of a Basic page:
drupal_add_js(array('my_var' => array('orderid' => '123')), 'setting');
drupal_add_js('sites/all/scripts/printout.js');

In printout.js:
alert("Before");
alert(Drupal.settings.my_var.orderid);

Result:
"Before" was alerted then returned to Basic page, no orderid.
What have I done wrong?
Comment: Did you add the jQuery namespace wrappers in printout.js?
Answer: Make sure you call for jquery setting inside Drupal behaviour, you can do like this:
(function ($) {
    Drupal.behaviors.example_name = {
        attach: function(context) {
            alert(Drupal.settings.my_var.orderid);
        }
    }
})(jQuery);

or you can call inside jQuery's .ready() event (less preferable than behaviours approach in Drupal world):
jQuery(document).ready(function($) {
   alert(Drupal.settings.my_var.orderid);
});

These both approaches ensure that jQuery is loaded before calling a variable.
P.S. I recommend using console.log instead of alert for quick debugging, like this:
console.log(Drupal.settings.my_var.orderid);

Then go to your developer console / firebug (depending on browser you use) and you'll see an output in console.
Comment: Thanks Tim, it works. Didn't realize have to use jquery to get Drupal.settings vars.
Comment: you're welcome :) don't forget to mark this answer as "the answer" :)
Answer: You have to say drupal where to put the javascript like this:
$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end     of   the document
);

drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

But like i learned a more sophisticated way would be to use Drupal.behaviors.
Look at my question:
How to pass values from php to javascript properly?


Can db_select cope with mysql "case when" structures?

Question: I have a complex mysql query with "case when" to combine values across multiple rows in columns. I'm currenty using db_query, but I would like to use the TableSort and Pager extenders. But (correct me if I'm wrong) those only work with db_select.
This is the query:
SELECT gsid, created_by_uid, difficulty, gametime, max(submitted_on), score, mission, name,
 ifnull(max(case when mission = 1 then score end),0) as mission_1,
 ifnull(max(case when mission = 2 then score end),0) as mission_2,
 ifnull(max(case when mission = 3 then score end),0) as mission_3,
 ifnull(max(case when mission = 4 then score end),0) as mission_4,
 ifnull(max(case when mission = 5 then score end),0) as mission_5,
 ifnull(max(case when mission = 6 then score end),0) as mission_6
FROM `game_sessions` m
INNER JOIN `users` u ON m.created_by_uid = u.uid
GROUP BY created_by_uid

The game_sessions table contains a row for each game mission that a user played. The game mission can be 1-6. This query gives me an overview with the maximum score for each mission per user (each row is a user).
Is it possible to rewrite this query using db_select? I'm using Drupal 7.
Answer: SelectQuery has the addExpression() method for adding arbitrary expressions. e.g.
$query = db_select('game_sessions', 'm')->fields('m');
$query->addExpression('ifnull(max(case when mission = 1 then score end),0)', 'mission_1');

Yields:
SELECT m.*, ifnull(max(case when mission = 1 then score end),0) AS mission_1
FROM {game_sessions} m

Comment: Awesome, I had completely forgotten about that method. Thanks.
Comment: Yeah - thanks for this - took me a while to find this answer...


Citrus Framework - Attempt to use validator in JSON causes error with header ACCEPT

Question: I have written an integration test using Citrus Framework for a Spring Boot service that communicates via HTTP REST.
I was able to embed some of the Citrus validation "methods" in the JSON to handle situations like @isNumber()@ for timestamps that are always changing. I ran into a problem, however, when I attempted some others.
There is another field (commandID) in the JSON which contains a UUID and is likely to change from one invocation to another. I first decided to use @match("<regex>")@ to match a UUID pattern, and when that produced a problem, switched to trying to use @ignore@, but that also produced the same problem.
Here is the error from the console:
13:29:21.962 [main] ERROR com.consol.citrus.report.LoggingReporter - TEST FAILED MissionPlannerIT.testPlanMission <edu.mit.ll.mission_services.service.mission_planner> Nested exception is:
com.consol.citrus.exceptions.TestCaseFailedException: Validation failed: Values not equal for header element 'Accept', expected 'application/json' but was 'application/json,application/*+json'

I don't know what the issue is here, nor how to fix it.
gen-route-command.json:
{
    "header": {
        "timestamp": "@isNumber()@",
        "typeID": "edu.mit.ll.mission_services.messages.GenerateRouteCommand",
        "transaction": {
            "id": 1,
            "startTime": "@isNumber()@"
        },
        "signature": {
            "algorithm": null,
            "keySize": 0,
            "keyValue": null,
            "sender": null
        }
    },
    "commandID": "@ignore@",
    "commandType": "GENERATE_ROUTE"
}

The @isNumber()@ functions work and allow the matching of those elements to pass validation. @ignore@, however does not. I have tried with both variations: @ignore@ and @ignore()@, neither works. As mentioned earlier, @match(...)@ also does not work.
UPDATE:
I modified things so that I try to do the validation in the test case code. I changed the value in the JSON back to a UUID.
runner.http(builder -> builder
    .server(routeGeneratorServer)
    .receive()
    .post("/v1/missionServices/missionPlanning/generateRoute")
    .accept(ContentType.APPLICATION_JSON.getMimeType())
    .payload(new ClassPathResource("templates/gen-route-command.json"))
    .validate("$.commandID", "@ignore@"));

gen-route-command.json:
{
    "header": {
        "timestamp": "@isNumber()@",
        "typeID": "edu.mit.ll.mission_services.messages.GenerateRouteCommand",
        "transaction": {
            "id": 1,
            "startTime": "@isNumber()@"
        },
        "signature": {
            "algorithm": null,
            "keySize": 0,
            "keyValue": null,
            "sender": null
        }
    },
    "commandID": "0710d523-43da-4f68-90c7-a2b4544a955d",
    "commandType": "GENERATE_ROUTE"
}

Unfortunately, this does not work. I get the error that I originally was trying to mitigate with @ignore@ or @match(...)@.
14:12:57.299 [main] ERROR com.consol.citrus.report.LoggingReporter - TEST FAILED MissionPlannerIT.testPlanMission <edu.mit.ll.mission_services.service.mission_planner> Nested exception is:
com.consol.citrus.exceptions.TestCaseFailedException: Failed to validate JSON text:
{"header":{"timestamp":1581016372132,"typeID":"edu.mit.ll.mission_services.messages.GenerateRouteCommand","transaction":{"id":1,"startTime":1581016372130},"signature":{"algorithm":null,"keySize":0,"keyValue":null,"sender":null}},"commandID":"9302ebde-894b-43a3-b7a3-92a158c7170e","commandType":"GENERATE_ROUTE"} Values not equal for entry: 'commandID', expected '0710d523-43da-4f68-90c7-a2b4544a955d' but was '9302ebde-894b-43a3-b7a3-92a158c7170e'

The commandID values are different because it generates a new UUID each run.
It appears that the validation in the test does not "ignore" the value and instead the JSON validation flags the UUID differences.
Answer: It would seem that the Citrus "functions" embedded in the JSON were not the problem. The problem was that I was not setting the Accept and Content-Type headers in the message the service was POSTing for the Citrus receive call. Since the receive call was set up to look for message type application/json, it was failing because my message had no headers at all (this is my impression).
The Citrus call:
// Set route generator to receive and validate generate route command.
runner.http(builder -> builder
    .server(routeGeneratorServer)
    .receive()
    .post("/v1/missionServices/missionPlanning/generateRoute")
    .accept(ContentType.APPLICATION_JSON.getMimeType())
    .payload(new ClassPathResource("templates/gen-route-command.json")));

The "generate route command" message it received had no headers defined. Once I set the Accept and Content-Type headers to application/json, the test was able to proceed.


Elementary proof that $Gl_n(\mathbb R)$ and $Gl_m(R)$ are homeomorphic iff $n=m$

Question:
Prove that $Gl_n(\mathbb R)$ and $Gl_m(R)$ are homeomorphic iff $n=m$

Since $Gl_n(\mathbb R)$ is homeomorphic to an open subset of $\mathbb R^{n^2}$, this boils down to proving that two open subsets of $\mathbb R^n$ and $\mathbb R^m$ are homeomorphic iff $n=m$.
This can be done via homology, of which I know absolutely nothing.
Do you know a proof that doesn't cover things an undergraduate isn't supposed to know ?
EDIT: I'll close the question, since it's a duplicate of Elementary proof that $\mathbb{R}^n$ is not homeomorphic to $\mathbb{R}^m$
Comment: related (essentially duplicate of?): [Elementary proof that $\mathbb{R}^n$ is not homeomorphic to $\mathbb{R}^m$](http://math.stackexchange.com/q/24873/)
Comment: See http://en.wikipedia.org/wiki/Invariance_of_domain.
Comment: You are basically asking for a proof that the dimension of a manifold is a topological invariant. There are proofs that do not use homology, and they are not short, but they may be accessible to a very energetic undergraduate. See for example the book by Hurewicz and Wallman, "Dimension Theory".
Comment: I'd say it is a duplicate.
Answer: If $\mathrm{GL}_n(\mathbb{R})$ is homeomorphic to $\mathrm{GL}_m(\mathbb{R})$, then (using that these are $n^2$-dimensional resp. $m^2$-dimensional manifolds) it follows that there is a homeomorphism between $\mathbb{R}^{n^2}$ and $\mathbb{R}^{m^2}$. It is well-known that this implies $n=m$ and there a lot of proofs for this, also without homology. See SE/24873 and arXiv:1310.8090.


samba: map specific user to guest

Question: This is how the Samba auth backend works:

Client username
Server username via the username map. This is a system (/etc/passwd) account.
If the server username is empty "" goto "Guest Authentication". Otherwise, goto "passdb/SAM Authentication".

passdb/SAM Authentication:

Check credentials via passdb/SAM database. This is because hashes differ from UNIX accounts, the the SAM database also includes additional information.
Login the client user as the server user

Guest Authentication:

Check credentials via guest authentication, which always succeeds.
Login the client user as the user specified by "guest account", default "nobody"

Unfortunately, while Samba accepts "" to mean guest windows doesn't accept/allow that. Even if the guest account is mapped to "nobody", Samba won't treat a client username of "nobody" as guest. Authentication will proceed through the passdb/SAM backend. The same pitfall applies to the username map.
Now I'm aware of Samba's "map to guest". If configured as "Bad User", non-existent user accounts will be mapped to the guest account. This is unfortunately error prone, with problems similar to that of the discouraged value "Bad Password".
I'm looking for a way to map one user, or several finite users (such as "nobody", "guest") to the guest account. Is this possible?
Edit:
I have tried this crazy map, which as expected doesn't work:
= guest nobody
Answer: Use username map =. But you seem to use an unorthodox approarch, so I seriously doubt you really need it.
P.S. And no, your description of how authrization works is beyound any acceptable error threshold.
Comment: I don't see how that could work. Also I need the username map, I'm currently using it. And I've just described what I see in my logs with `log level = 3 passdb:5 auth:10`, so it can't be wrong.
Comment: Okay, you seem to think that you know the subject better than all the others, and you're doing it right. Why asking then ? PS Get rid of this dangerous delusion. You actually can do this, the way I told you, just reread it until you get it. And no, you aren't using the username map, at least you didn't mention it.

samba: map specific user to guest


Extjs4 Media Types

Question: How to display a PDF document in the Extjs4 window. When click on some link like

OPEN DOCUMENT

  buttons: [{
            text :'OPEN DOCUMENT',
            formBind : true,
            handler:function()
          {}

Im trying to display pdf file. Thank You
Answer: If you don't want to convert it to an image server-side, you can show it in an iframe:
buttons: [{
    text :'OPEN DOCUMENT',
    formBind : true,
    handler:function() {
        new Ext.window.Window({
            title: 'Document',
            height: 800,
            width: 800,
            layout: 'fit',
            items: [{
                html: ''
            }]
        });
    }
}]

Answer: See example here: http://whatisextjs.com/extjs-4-tutorial/extjs-4-download-file-button
There are some undocumented properties that let you do what you want, with a button.  You can't handle a javascript event and download a file that way - most browsers will barf, for security reasons.

Extjs4 Media Types


Python / Pandas - The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Question: I have this two pandas objects (each of them is a a row taken out of a dataframe):
tg:

cnpj                               7350260000136
city_id                                        3
federation_unit_id                             8
primary_activity_id                            2
primary_activity_identifier           61.90-6-01
city_id                                        3
federation_unit_id                             8
CNAE                                  61.90-6-01
Name: tg, dtype: object

pred:

cnpj                       2178302000180
city_id                                3
federation_unit_id                     8
CNAE                          61.90-6-99
Name: pred, dtype: object

I'm trying to run the following if sentence:
x = 5
y = 1

if target.federation_unit_id == pred.federation_unit_id: x += y

The result here should be 6, however I'm getting the following error:
Traceback (most recent call last):
File "/file.py", line 735, in <module>
target=index(pdsim,target,tgcsv='target_1.csv',predcsv='predictor_1.csv',pred_fine=pred_fine)
File "file.py", line 610, in similarity_index if target.federation_unit_id == pred.federation_unit_id: x += y
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/generic.py", line 892, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Does anyone know how could I fix it?
Comment: try `print(type(target.federation_unit_id))`
Answer: I think you have a couple of issues.

It might have been a typo but your first series is 'tg' not 'target' not sure if that is some other series or dataframe
Even if that is a typo your first series has two elements called 'federation_unit_id' so tg.federation_unit_id gives two values which can't be compared to a single value.

If those weren't issues your code should work.


Setting autologon to a local user after joining to a domain

Question: I'm building an application to assist in re-configuring devices on our network. I've got the entire script working except for setting the device to auto logon. Nothing I am trying seems to work. Now, the use is a little different, as the device will be joined to the domain, but logged on with a local user account. I'm trying to use the Sysinternals Autologon utility, but it is not working.
Here is the relevant code for logging on:
function  Set-Autologon {

    param (
        [Parameter()][string]$domain
    )

    $exePath = "$scriptPath\$autologon"
    $user = 'aloha'
    $logonPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
    $defaultdomain = "DefaultDomainName"
    $alohass = '<very long string>' | ConvertTo-SecureString -Key $key
    $alohaptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($alohass)
    $aloharesult = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($alohaptr)

    LogInfo "Setting auto logon for $aloha user."
    Start-Process -FilePath $exePath -ArgumentList "/accepteula", $user, $domain, $aloharesult -Wait -Verbose
}

The domain is being passed in as that is coming from a CSV file. The $key is set somewhere else in the script. I've tried with the /accepteula in both the front and the back.
What am I missing here?
Thanks
Comment: For one thing, we have no idea what is in `$scriptPath`, nor what is inside `$autologon` if anything at all. You should not create a path like `"$scriptPath\$autologon"` anyway, but use the [Join-Path](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/join-path) cmdlet for that.
Comment: `$autologon` is just the name of the executable, Autologon.exe. `$scriptPath` is just that, that path that the script is running from. It is where autologon.exe is being housed as well.
Comment: But.. does the function also know that? Are these vars script scoped? Please elaborate on _but it is not working_
Comment: Even if I take all of the code out of the function and run it by itself, and hardcode all of the values, nothing is happening. Autologon looks like it is running, but the logon does not get set. I have tried to run Autologon from the GUI, and even that is coming back with an error "The username or password is incorrect".
Comment: So, does the autologon app need a plain-text password or a SecureString?
Answer: This should work with "/accepteula" as the last argument but, you can create a DWORD registry key in HKCU\Software\Sysinternals\AutoLogon for EulaAccept=1 before running the exe. You could also try starting the autologon.exe with the /accepteula flag and then immediately killing the process before running with the username/credentials arguments.


Features can export everything?

Question: Built all blocks, menu, taxonomies, view etc in Drupal CMS on localhost machine, but I need to export everything to the live server. Is it possible to use features or just export sql?
Answer: The Features module allows you to export all the configurations in code (instead of DB). It is very usefull when you have 2 separated versions of database, in example one for your localhost or test installation, and one for your live/production website.
However, if you want to deploy the local database to the live server too, it is not necessary to export everything with Features.
Comment: After re-reading your question, I just want to clarify that it is not possible to export "content" with Features. That means that if you have created a page or a block in your local Drupal, it is not possible to export it in code and deploy it on your live server. If you want to move all the content too, you have to export your local database... Am I clear enough? :P
Comment: So if live server has clean database and if i export via features, the pages online will show everything similar to localhost pages?
Comment: oh it means i have to create pages, views and blocks over again on the live one then? Sigh I thought it would help to save time lol
Comment: Yes indeed! But if you have a very clean work on your local DB and if it is the first live deployment of your project, you can import your DB on live server :-)
Comment: Local DB - export all contents right? So what is the point of exporting content when I have to create pages, views and blocks over again :(
Comment: If you export your database in .sql and import it on your live server, you won't have to create all your content over again!

I just wanted to say that Features is not the solution you were looking for. There is no other way (to my knowledge) to export content than by exporting the database in .sql... :-(
Comment: My pleasure ;-)
Answer: I love using features for just what you're describing you need. I admit it's a bit challenging at first, and doesn't always appear to work as expected. Here are some videos that I think may be helpful:
https://www.youtube.com/watch?v=P874hgin5xI
https://www.youtube.com/watch?v=ZHbOh9bf1dg&list=PL-Ve2ZZ1kZNTykHOLO0jzRADq8iZxvzkU (several by Shane Thomas, codekarate)
If you want to export individual content, you have modules such as https://www.drupal.org/project/uuid_features, but that's not for large scale use. I think you'll want this: https://www.drupal.org/project/node_export. It makes import/export of nodes pretty easy.
Hope this helps some.

Features can export everything?


asked to reauthenticate with the same IDP - Spring SAML

Question: @vschafer
I have a scenario where my application acts as one of the service providers. My application interacts with another service provider as well to get access. But both the service providers are communicating with the same IDP for authentication.

user logs into my application by validating against the IDP
User is provided access to the application upon successful authentication
Now, user tries to access a resource in the application
User is redirected to another service provider application which is also tied with the same IDP for authentication
Though the user is authenticated once with the same IDP, the user is asked to authenticate again with the second service provider.

I believe the user should not be allowed to authenticate again forcefully. Please let me know if my understanding on the same is correct or not.
More over, does forceAuthn has a role to play in this scenario??
Answer: All of this should not be in any way related to your application or Spring SAML. Once you redirect user to the second application (step 4), it is its responsibility to interact with the IDP (send its own AuthnRequest and receive a Response) and there's nothing you can affect about it anymore.
It is possible that the second application is setting the forceAuthn flag when sending AuthnRequest to the IDP - forcing the IDP to re-authenticate your user. It could also be related to some setting on the IDP side, or perhaps some cookie problems. You should communicate with the IDP's owners and ask them to troubleshoot why is the user asked for re-authentication (for example by examining their logs) instead of being single signed-on.


Why is SEM/CFA failing to find the correct factors in this simple set up? Possible error in 'predict'?

Question: I've been getting very odd factors in more complex models and simplify to this minimal case that behaves oddly vs my intuition.
Suppose we have the generative model, where everything is IID Normal
$A \sim N(0,1)$
$B \sim N(0,1)$
$Y_1 = A + \epsilon$ ; $Y_2 = A + \epsilon$ ; $Y_3 = A + \epsilon$
$X_1 = A + B + \epsilon$ ; $X_2 = A + B + \epsilon $ ; $X_3 = A + B + \epsilon$
Where each $\epsilon$ is independant, and in practice we divide by $Y$ and $X$ by $\sqrt{2}$ and $\sqrt{3}$ respectively to standardize.
The task is then to find the latent factors $A$ and $B$ from observed $X$s and $Y$s, pretending of course that we don't know the coefficients happen to all be 1.0, but we do know that $Y$ contains no $B$
This should be perfect for SEM/CFA, but when I try it fails to correctly identify factor A by an amount that can be corrected manually (so the solution does exist!).  I'm using lavaan, and can't tell if it is a flaw in the software, the method, or my understanding.
In code:
library(lavaan)
library(data.table)

N = 100000

DT =  data.table(A = rnorm(N), B = rnorm(N))

DT[, Y1 := (A + rnorm(N))/sqrt(2)]
DT[, Y2 := (A + rnorm(N))/sqrt(2)]
DT[, Y3 := (A + rnorm(N))/sqrt(2)]
DT[, X1 := (A + B + rnorm(N))/sqrt(3)]
DT[, X2 := (A + B + rnorm(N))/sqrt(3)]
DT[, X3 := (A + B + rnorm(N))/sqrt(3)]

model = 'FA =~ Y1 + Y2 + Y3 + X1 + X2 + X3
FB =~ X1 + X2 + X3
FA ~~ 0*FB
'

fit = sem(model, data= DT, std.lv = TRUE, std.ov = FALSE)
summary(fit)

and the summary of our fit is
lavaan (0.5-20) converged normally after  20 iterations

  Number of observations                        100000

  Estimator                                         ML
  Minimum Function Test Statistic                9.770
  Degrees of freedom                                 6
  P-value (Chi-square)                           0.135

Parameter Estimates:

  Information                                 Expected
  Standard Errors                             Standard

Latent Variables:
                   Estimate  Std.Err  Z-value  P(>|z|)
  FA =~
    Y1                0.711    0.003  227.070    0.000
    Y2                0.708    0.003  226.475    0.000
    Y3                0.709    0.003  226.770    0.000
    X1                0.580    0.003  176.083    0.000
    X2                0.577    0.003  175.597    0.000
    X3                0.579    0.003  176.073    0.000
  FB =~
    X1                0.579    0.003  183.034    0.000
    X2                0.580    0.003  183.912    0.000
    X3                0.575    0.003  181.946    0.000

Covariances:
                   Estimate  Std.Err  Z-value  P(>|z|)
  FA ~~
    FB                0.000

Variances:
                   Estimate  Std.Err  Z-value  P(>|z|)
    Y1                0.498    0.003  160.623    0.000
    Y2                0.497    0.003  161.192    0.000
    Y3                0.497    0.003  160.910    0.000
    X1                0.333    0.002  141.244    0.000
    X2                0.329    0.002  139.731    0.000
    X3                0.337    0.002  143.257    0.000
    FA                1.000
    FB                1.000

So far so good, but if we take the scores for those factors then they are not uncorrelated!  Furthermore, if we regress Y1 on those factors, then Y1 appears to depend on factor B, which we specified is not the case.
DT = cbind(DT, predict(fit))

DT[, cor(FB, FA)]
#[1] 0.2219724

summary(DT[, lm(Y1 ~ FA + FB)])

Call:
lm(formula = Y1 ~ FA + FB)

Residuals:
     Min       1Q   Median       3Q      Max
-2.67157 -0.39035  0.00245  0.38889  2.32116

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.002491   0.001823  -1.367    0.172
FA           0.945142   0.002102 449.682   <2e-16 ***
FB          -0.231733   0.002351 -98.586   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5764 on 99997 degrees of freedom
Multiple R-squared:  0.6691,    Adjusted R-squared:  0.6691
F-statistic: 1.011e+05 on 2 and 99997 DF,  p-value: < 2.2e-16

There does appear to be a correct solution though, because if we take those regression coefficients and make a new factor A, then orthogonality is achieved and the Ys all only depend on this new factor
DT[, CA := 0.94*FA - 0.235*FB]

DT[, cor(CA,FB)]
#[1] -0.00160991

What is going on?
EDIT
As far as I can tell, it is fitting the weights correctly, this diagram purports to show the fitted model (semPaths) and the residual variances and loadings all look correct.  So perhaps it is the predict function where the issue lies?
Comment: Can you draw the path diagram you are trying to fit?
Comment: Why is $F_b \perp F_a$?
Comment: We know $F_A$ and $F_B$ are orthogonal from the problem definition - A and B are independent N(0,1).  In the real world case, we simply have reason to believe these are completely unconnected factors.
Comment: @AdamO I could draw the path diagram I'm attempting to fit, or that lavaan is fitting, but ultimately the more important question would be what is the correct path diagram for the generative model described.
Answer: You see a relationship between $Y_1$ and the latent factors $F_a$ and $F_b$ because of the indirect effect of having $F_a$ and $F_b$ manifested by $X$s which are manifested by $A$. If you drew the diagram, you'd see you don't have a proper DAG. If you want orthogonal components, why not set the loadings of $X$ to 0 in the manifestation of $F_a$?
Comment: I've tried that, omitting them from the formula is the same as setting the loading to zero in this case.  The fit is identical.  Likewise, I am specifying that FA and FB are orthogonal, but they are not coming out as that in the fit?
Answer: It appears my problem here is with a basic misunderstanding between factor scores and factor score estimates.
Factors A and B are indeed uncorrelated, but these are the latent hidden factors which are never computed in the model fit.  The fitted model shows all the correct weightings between the latent variables and observables.  The problem only appears when looking at the result of predict.
Predict tries to estimate the factor scores from the data, using a procedure like this described here: Mplus documentation
This paper discusses estimating scores for the related method of EFA, and discusses the pros and cons of different methods.  In particular noting that although the factors are uncorrelated, it may well be that the estimates of those factors are in fact correlated (e.g. Bartlett Scores and Regression Scores).
There are, it seems, methods to estimate the factors which force the estimates to have the same correlation properties as the true factors, but this reduces the accuracy with which they estimate the true latent factor.
Basically there appears to be an analogy between bias-variance trade off, of bias-covariance trade off.  You can either estimate the individual factors more accurately, but get the covariances wrong, or get the covariances right and the factor scores more wrong.


How can we output unfiltered HTML in a CCK field

Question: This seems like the simplest thing but for some reason we just cannot get this to work.
We have create 4 additional CCK fields for our "product" content type.
We enter simple HTML in to these fields and want to display these, as is, unfiltered on the node output.
Whatever we do, it always outputs as plain text, stripped of all html. Weve seen numerous references to the "Text Processing" options within the field settings, but they dont appear for us.
Ive even gone in and changed the text_processing value within the database for the field, Ive tried manually setting the filter type within the text.module code, weve spent days on what seems to be a simple and fundamental task.
How can we achieve this?
Answer: OK after searching high and wide for a solution, I finally came across this article: http://drupal.org/node/1100430
Basically the CCK component module "Text or Node Reference" causes an issues that hides the "Text Processing" options, disabling this module allowed us to change the input filter format!


How to fix: The description for event ID %i from source %s cannot be found?

Question: I need to troubleshoot some WMI crashes we are suffering from. Unfortunately the event log doesn't show any details as the descriptions are missing. This is what the log says:
The description for Event ID 5612 from source **Microsoft-Windows-WMI** cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

The following information was included with the event:

HandleCount
4116
4096
10508

I have already worked through Microsoft's knowledgebase article on how to troubleshoot the "event message not found" problem (https://support.microsoft.com/en-us/kb/166902) without any luck.
The registry key EventMessageFile under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\**WMI.NET Provider Extension** points to C:\Windows\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll which is existent.
Comparing the registry keys to a system where this specific event id gets shown correctly doesn't reveal any differences. Also the EventLogMessages.dll has the same version and checksum.
Am I looking at the right registry key?
The path HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\WinMgmt only contains a key called ProviderGuid. But that seems to be fine, as the descriptions are getting displayed on a system having the same (and only this) key.
[EDIT]
I indeed was looking at the wrong registry keys. The right one to look for is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\Microsoft-Windows-WMI which was completely missing. Also a key called Enabled and the ChannelReferences subkeys where missing within the provider configuration which can be found at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Publishers\{1edeee53-0afe-4609-b846-d8c0b2075b1f}.
Adding those keys made the WMI events to get displayed correctly. However it did only last till a reboot of the system. Now the registry keys are there as they should be, but still no proper display of the events... any ideas?
This are my exact registry settings that I have exported from a working system:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\Microsoft-Windows-WMI]
"ProviderGuid"="{1edeee53-0afe-4609-b846-d8c0b2075b1f}"
"EventMessageFile"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,\
  00,6f,00,74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,\
  5c,00,77,00,62,00,65,00,6d,00,5c,00,57,00,69,00,6e,00,4d,00,67,00,6d,00,74,\
  00,52,00,2e,00,64,00,6c,00,6c,00,00,00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Publishers\{1edeee53-0afe-4609-b846-d8c0b2075b1f}]
@="Microsoft-Windows-WMI"
"ResourceFileName"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,\
  00,6f,00,74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,\
  5c,00,77,00,62,00,65,00,6d,00,5c,00,57,00,69,00,6e,00,4d,00,67,00,6d,00,74,\
  00,52,00,2e,00,64,00,6c,00,6c,00,00,00
"MessageFileName"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,\
  6f,00,74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,\
  00,77,00,62,00,65,00,6d,00,5c,00,57,00,69,00,6e,00,4d,00,67,00,6d,00,74,00,\
  52,00,2e,00,64,00,6c,00,6c,00,00,00
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Publishers\{1edeee53-0afe-4609-b846-d8c0b2075b1f}\ChannelReferences]
"Count"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Publishers\{1edeee53-0afe-4609-b846-d8c0b2075b1f}\ChannelReferences\0]
@="Application"
"Id"=dword:00000009
"Flags"=dword:00000001

Comment: You seem to have gone through the basic troubleshooting steps, Maybe this is a 64-bit vs 32-bit issue. This article may also help: http://www.eventsentry.com/blog/2008/04/event-log-message-files-the-de.html
Answer: Missing event ids can easily be added using the EventCreate command line command.
More information can be found at https://technet.microsoft.com/en-us/library/bb490899.aspx.
Comment: Please expand you answer with the information from the link.
Answer: Restart Event Viewer. Had this same problem, googled it, and found the answer.
"Event Viewer was not restarted since you added the EventMessageFile entry in the registry.
Event Viewer caches the DLLs it loads for event sources. If you have changed the registry to give a proper directory or source name after the event viewer has been started, you need to restart Event Viewer." -ref: See point #6 https://support.microsoft.com/en-us/help/166902/howto-troubleshooting-the-event-message-not-found-message
Answer: Change format to Events from RenderedText
wecutil es
wecutil ss "subscription" /cf:Events


MS Access Queries to SQL Server Views/Proc/Trigger

Question: This is general question. I'm migrating MS Access DB where a table is created from 3 different tables using multiple update , select , delete and alter statements in several steps. When we are migrating to SQL Server what will be the best approach ?
I know this can't be accomplished in a view.
Answer: Use MS Access to connect to an external data-source, your SQL Server, then you can select from your Access tables directly into your SQL Server tables
Comment: Each month the data gets update so the logic should be kept intact. I created views for several other queries. But this table has multiple operations performed in 6 steps to create the table. The steps are run from a Macro.
Answer: It sounds like each month you creating a NEW table. This likely a bad idea, and makes reporting over several months VERY difficult, and forces a BIG list of issues likely having to change the table name in quires etc. You likely best have ONE table were you send the results to and THEN query by date range or using month(dateColumn) and year(dateColumn) to pull out the one month. So you likely having difficulty finding a solution because such solutions that need to create a NEW table each month or for each time some "process" is run also tend to be a "difficult" solution and one rarely required or used.
So I don't think the issue is creating a table, the issue is much thinking like a spreadsheet and "saving" a months worth of data into a NEW table each time.
So I would dump the idea of creating these new tables all the time and come up with a design that eliminates this requirement.
In fact if your Access back end database was a linked database, then this approach in Access would have also been VERY challenging also – especially in a multi-user environment.
So the real answer here is to avoid the monthly table creating. You find then you can care FAR better reporting on such data, and can thus report over multiple time periods (as opposed to trying to read data from multiple tables of the SAME structure).
So create ONE table to hold the results for each run, and add a column that differentiates the data in that table for each run. It makes little sense to have the Month/Year in the table name and create 12 tables for a year as opposed to adding a simple date column to the ONE table.
And often even better is to adopt a system that quires the LIVE data and eliminates all this sending of data to some table.
It possible you talking about a temp "scratch" table for data processing? You can send some data to a temp table that is tossed out, but then again that simply means you don't need to create a table on the fly every time you run those 6 steps.
So your cut + paste approach to data process, or the "idea" of making a copy of a spreadsheet data into a new month approach is one that works poorly for data processing.
This creating table each time is especially prone to maintains issues if the system is to be used in a multi-user environment.
If a new table has to be created each time your process is run, then some design changes to how this process works is like your better solution.
Last but not least: it is possible that I am misunderstand your goal, but feel free to expand on the "6" steps of data processing you have and where "eventually" the results of this data is supposed to land.
Comment: The table is created from text files on monthly basis. I have a SSIS jobs for it. There are some operations performed on the loaded data for creating several other tables. Most of them i have created them as views. But some need several steps. So i would use the Ssis again in different data flow. Between is there any transformation for update strategy. I know it can be accomplished in execute SQL task.
Comment: No issues I see UNLESS you plan to create new tables each month on SQL server. Do you plan to add the these new links every month to Access also? This is VERY messy approach. If you saying you plan to cunrch data to some local Access tables and THEN upload to exiting SQL server tables, then no problem. However creating new tables server side that you keep is really a spreadsheet approach and not one that works for data processing solutions.
Comment: The tables are not created every month. They are just loaded fresh via SSIS from flat files. The tables have fixed link to the FE.


How to find the formula of a function from its graph?

Question: I've got some data points (X/Y coordinates) that were apparently created using a certain formula that I want to reconstruct now. I've only got those points, and I can plot them (e.g. like in this).
I know how to measure maxima, minima, slopes etc, and could solve an equation to compute the values for parameters in a formula so that it closely approximates/interpolates my data points, but which formula should I use?
I somehow need to find a parametric formula that matches the shape of the (parts of the) graph(s). What are the steps to identify such shapes, and to what formula (parts) do they correspond?
A step function is rather easy to identify, but I'm having problems with curves. Are they polynomials, of what degree? Are they trigonometric functions, like a sinus, squared, cubed? Do they contain a fraction, an exponentiation, something else? Or is it even something completely different, like a bezier curve?
I'm not looking for a solution to a specific problem, but a generic guide, hoping that this is not too broad.
Comment: Similar questions like [this](http://math.stackexchange.com/q/1321512/258990) or [that](http://math.stackexchange.com/q/974223/258990) were quite specific, they didn't help me well. Please tell me whether there's something I can improve about my question!
Comment: For the curious, the example data is from [this StackOverflow question](http://stackoverflow.com/q/28495390/1048572), along with two rather crude approaches to approximate the points.
Answer: The best way to handle this kind of problem of modelling data is to use information theoretic approaches.
Kolmogorov complexity
The simplest and completely generic way is to find a (program,input) pair with the shortest total length over a fixed general purpose programming language that when run outputs the data exactly as it is. This is called Kolmogorov complexity. Of course this depends on the chosen programming language, and clearly if you first look at the data you can construct a language purposely tailored to it (see Code Golf SE for some egregious examples). That's not allowed; you must first choose the language once and for all, and use it for every subsequent problem that you want to measure the complexity of the data. Also, the language must be Turing-complete. Common languages such as C++14 or Java 7 are suitable. The lengths of the program and input string is always measured in bits.
Let $K_L(x)$ be the Kolmogorov complexity of string $x$ over Turing-complete programming language $L$.
Why would this work? It can be easily proven that, given Turing-complete languages $L,M$, there is some $c$ such that, for any string $x$ we have $|K_L(x)-K_M(x)| \le c$. Thus for any class of strings the Kolmogorov complexity will be asymptotically correct as the string length goes to $\infty$. For example, the Kolmogorov complexity of the string $x_n$ of exactly $n$ zeros would differ from $\log_2(n)$ by at most $c$, for some constant $c$ that is independent of $n$. So as $n \to \infty$ we have $K_L(x_n) \in θ(\log(n))$.
Since our choice of language does not affect asymptotic Kolmogorov complexity, it is an objective measure of complexity for sufficiently large samples, and using a common language like C/C++ or Java makes it impossible for over-fitting.
Suitability of Kolmogorov complexity
For exact data, Kolmogorov complexity captures precisely the amount of information contained within it (up to a constant as mentioned above). However, it can be proven that there is no Turing-complete language $L$ and program $P$ such that $P(x) = K_L(x)$ for every string $x$. So you cannot hope to determine Kolmogorov complexity in general, not to say find the (program,input) pair that witnesses the complexity!
What you can still do is to find an upper bound, which is exactly what compression algorithms are essentially doing. Given any string $x$, the total length of the string that $x$ is compressed to and the decompression algorithm (written in $L$) is an upper bound on the true Kolmogorov complexity $K_L(x)$.
Nevertheless, most scientific experiments do not produce exact data, so it is pointless to ask for a program that reproduces the measurements exactly, since they are already imprecise and inaccurate. But the same ideas still apply. We just need to cater for noise.
Kolmogorov complexity modulo noise
If the data is a list of pairs $(x_k,y_k)_{k\in\{1..n\}}$, such as in many empirical experiments, and we know that the noise is uniform across the list, we can model the data as $N(P(x_k))=y_k$ where program $P$ is the actual function we seek and $N$ is a random program that models a noisy channel that adds noise. $N$ is written in a Turing-complete language that is additionally allowed to call a function that returns a uniformly random bit (which is independent of previous call results).
Then we want to a pair $(P,N)$ that minimizes what I call the complexity modulo noise defined as $|(P,N)| - \frac{1}{n} \sum_{k=1}^n \log_2(\mathbb{P}(N(P(x_k))=y_k))$. Intuitively, this is the length of the description of the trend and the noise source plus the average information in the noise itself. This is such that if there is no meaningful trend mapping $x$ to $y$, then the complexity modulo noise would be just the number of bits required to specify the noise. On the other hand if there is a trend then it would be captured by a short $P$, and there would be an optimal $N$ since it must be noisy enough to cater for the discrepancies but not more than necessary. Also, $N$ would capture the actual noise distribution if the sample is large enough.
Again, it is not possible to deterministically find $P,N$, but we can find upper bounds. Furthermore, this provides a way to compare approximations of an unknown function given a noisy sample of points. If we have 2 polynomials, one with low degree and simple coefficients that fits close enough, and the other with very high degree and complicated coefficients but passing through all the points at the sample resolution, you can be sure that the low degree polynomial will have lower complexity modulo noise. Likewise, you can try as many approximations as you like and simply choose the one that has the lowest complexity modulo noise.
This also allows you to use your intuition to guide your attempts. For real-world measurements, they tend to suffer from Gaussian noise, so you can try $N$ being a normal random variable with various variances (the mean is already captured by $P$).
It should be impossible to over-fit using this method, which is the crucial property that you are looking for.
Comment: Thanks, this is a very interesting approach. Unfortunately, it doesn't seem to come down to a simple "curve classification check list", but rather either brute-forcing or using intuition.
Comment: @Bergi: That is one of my main points, which is that there cannot be a deterministic algorithm to classify a curve. However, it is not just about intuition, because this gives you a way to **quantify** how good your fit is. The complexity modulo noise tells you precisely how many bits your data intrinsically has, so if you find a very good fit, you can objectively compare its complexity against say the precision of the data itself. [continued]
Comment: [continued] However, this method has a drawback due to the choice of programming language, which causes a high overhead that requires high precision in the data to offset. Another way I thought of is to define **complexity modulo noise** to be $|(P,N)| - \frac{1}{\sqrt{n}} \sum_{k=1}^n \log_2(\mathbb{P}(N(P(x_k))=y_k))$, so that it is as if we have a upper bound on the confidence interval for the actual amount of information, since the central limit theorem suggests that the standard deviation of what we measure would be proportional to $\sqrt{n}$. But I can't properly justify this method.
Comment: @Bergi: Though I think the method in my above comment will work well since it heavily penalizes noise that is unnecessary, but if it is intrinsic then transferring noise into $(P,N)$ will incur greater cost. But there's a somewhat philosophical issue of how we should handle/ignore noise in experimental data when finding a model to fit it, which may be why I can't completely justify anything beyond the standard Kolmogorov complexity.
Comment: You say "it can be easily proven that for any two Turing complete languages L, M, there is a constant c such that for any string x, |K_L(x) - K_M(x)| <= c.  But this is false. Let L be C++ and let M be a language just like C++ except every character is doubled. i.e. in M you say iinntt mmaaiinn(()){{ instead of int main(){. The difference in lengths between programs in L and M is not bounded by a constant.
Comment: @causative: You are completely wrong. Let C be an interpreter for L written in M. Let P be an M-program that on input (Q,x) runs Q via C on x. Then for every string x we have K[L](x) = |(Q,x)| for some L-program Q and also K[M](x) ≤ |(P,(Q,x))| ≤ |P|+O(log(|P|))+|(Q,x)| (using the obvious pair-coding).
Comment: It's not right to say K[L](x) = |(Q, x)|. Isn't |(Q, x)| > |x|? That means you would have K[L](x) > |x| which is obviously not always the case (since it indicates no compression). Notation issues aside, I think you're trying to say that you can write an interpreter for L within M, called P, and then if Q is a shortest program in L that outputs x, then the program consisting of P and a quoted form of Q, call it (P,Q), would be a program in M that outputs x. That's true, but the problem is, the quoted form of Q within M is twice as long as Q, so (P,Q) within M is more than twice as long as Q.
Comment: @causative: Sorry, I accidentally reused the variable "x", but my comment was in principle correct: Let C be an interpreter for L written in M. Let P be an M-program that on input (Q,x) runs Q via C on x. Then for every string x we have K[L](x) = |(Q,y)| for some L-program Q and string y and so K[M](x) ≤ |(P,(Q,y))| ≤ |P|+O(log(|P|))+|(Q,y)| (using the obvious pair-coding). Like I said, you need to actually read and think properly through my definition of K-complexity in the post before you claim it is wrong.
Comment: There's still really no need for y. Anyway, like I said before, |(P, (Q, y))| within M, is about |P| + 2 |Q| + 2 |y|. Because you can't encode Q within M without doubling the length of Q.
Comment: @causative: You're wrong; there is a need for y precisely to avoid having the stupid phenomenon you insist it has. If you want to not have y, you need to use prefix-free K-complexity, which some textbooks do, but that's besides the point here, which is that *there is nothing wrong with my post*. (Maybe you're **still** not reading it; I explicitly defined K-complexity in my post in terms of a **(program,input) pair**, and the input **does not suffer** from restrictions to the language!!)
Comment: OK, I see what you're saying.
Comment: @causative: Good, I'm glad that's cleared up.
Answer: I do not know if I understood you correctly, but even if you want to find from a finite sequence of points (that have coordinates with a finite number of decimal places) in the plane whether the curve that goes through those points is polynomial or some non-polynomial continuous function it seems to me that it cannot be done because of the Stone–Weierstrass theorem which, roughly, says that you can uniformly approximate continuous function with polynomials to any degree of accuracy.
If it is the case that you have some finite set of points and you want to draw/find some, let us say, polynomial that goes through those points, then you have interpolation methods, see this one for example.
Comment: Thanks, yes, I know that I can approximate it using polynomials of high enough degree. But I'm looking for ways to establish that the curve was likely created from a polynomial at all, or maybe something else? If it was created with a polynomial, I want to restrict it to "simple" ones - that is, with few terms (many coefficients = 0) or of low degree.


Prove that If a closed curve on the unit sphere has length less than $2\pi$, then it is contained in some hemisphere.

Question: I found the following proof in a book:
"Pick any point P on the curve, travel half way around the curve to the
point $Q$, and let $N$ (standing for North Pole) be the point half-way between $P$ and $Q$. (Since the distance $d(P,Q)$ from $P$ to $Q$ is less than $\pi$, $N$ is uniquely defined). $N$ determines an "equator" and if the curve lies entirely in the northern hemisphere, we are done. Otherwise, the curve crosses the equator, and let $E$ be one of the points at which it does so. Then, we observe that $d(E,P) + d(E,Q) = \pi$, since if you poke $P$ through the equatorial plane to $P'$ on the other side, $P'$ is antipodal to $Q$; hence, $d(E,P') + d(E,Q) = \pi$.
However, for any point $X$ on the curve, $d(P,X)+d(X,Q)$ must be less
than $\pi$, and this provides the desired contradiction."
I don't quite understand how this works. I guess the idea is to construct a hemisphere so that the curve lies in it. But how does $N$ determine an equator? Don't we need at least need two Points?
And how does $d(E,P') + d(E,Q) = \pi$ indicate $d(E,P) + d(E,Q) = \pi$ ?
Thanks for any help.
Comment: I don't if it correct but my thought on this. In a sphere the longest curve is the curve that is right at the center, and the length of all other curves will be in set $[0, a]$ where $a$ is the length of the largest of them. In a unit circle at longest length will be $2\pi$ so the range of all other curves will be in set $[0, 2\pi]$. So all the curves of length less than $2\pi$ will be in either hemisphere.
Comment: One pole determines the other pole, and the equator is the set of points equidistant from the two poles.
Comment: @ ritwik sinha : the curve doesn't need to be a circle in any way. just needs to be closed.
@MJD: makes sense.
how do you find $d(E,P) + d(E,Q) = \pi$ though?
Comment: @J.Doe: What book is the proof from?
Answer: I'm referring to the following figure. The given loop has the same length $<\pi$ from $P$ to $Q$ along both connecting arcs. It follows that the spherical distance $d(P,Q)<\pi$, so that there is a unique great circle containing $P$ and $Q$, and there is a north pole $N$ midway on the shorter great circle arc connecting $P$ and $Q$. The eqator plane belonging to this north pole $N$ is depicted as a horizontal line in the figure. Reflect $P$ in the equator plane to obtain $P'$, which is antipodal to $Q$.
If the given loop intersects the equator in a point $E$ then
$$d(P,E)+d(E,Q)=d(P',E)+d(E,Q)\geq d(P',Q)=\pi\ .\tag{1}$$
On the other hand $d(P,E)+d(E,Q)$ is at most equal to half the length of the loop, hence $<\pi$. Together with $(1)$ we have a contradiction, hence such a point $E$ cannot exist.
Comment: This is a very clear explanation. Is there a known reference of this proof in the literature?


Finding Radius Of Converges

Question:
Find the radius of converges
  $$\sum_{n=o}^{\infty}\frac{(z-1+i)^n}{2^n+n} $$

Let $w=z-1+i$
$$\sum_{n=o}^{\infty}\frac{w^n}{2^n+n} $$
$$R=lim_{n \to \infty}|\frac{a_n}{a_{n+1}}|=lim_{n \to \infty}\frac{2^{(n+1)}+n+1}{2^n+n}=2$$
So there is series converge for $|w|<2$
for $|w|=2$ we need to look at $$\sum_{n=o}^{\infty}|\frac{w^n}{2^n+n}|=\sum_{n=o}^{\infty}\frac{|w|^n}{|2^n+n|}=\sum_{n=o}^{\infty}\frac{2^n}{2^n+n}$$
But $$\lim_{n\to \infty}\frac{2^n}{2^n+n}=1$$ so it does not converge.
$$|w|<2\iff |z-1+i|<2\iff (x-1)^2+(y+1)^2<4$$
So the series convarges at the interior of the circle around $(1,-1)$ or radius $2$
Is this correct?
Answer: Remember the ratio test says the series converges if
$$\lim_{n\to\infty}\left|\frac{a_{n+1}}{a_n}\right|<1$$
Comment: https://en.wikipedia.org/wiki/Radius_of_convergence#Theoretical_radius
Comment: He is calculating the radius of convergence.

Finding Radius Of Converges


How to add a javascript field to custom content type

Question: I have a custom content type called 'Visualisation'. I would like a user to be able to upload their own javascript file for each instance of the content type. I would then like to load this script on the page in which the content is displayed.
I have tried adding a custom field 'file', however Drupal doesn't allow javascript files and appends the file with 'txt'. How can I add a javascript file and then load when the content is displayed?
EDIT
As it seems unsafe to achieve this the way I've mentioned above I'll try and elaborate on what I'm trying to do.
The content type is for HTML5 canvas visualisations. Each visualisation will use a custom created script file. The whole content will consist of a title, canvas element, javascript file and description. I therefore need to attach a script to each visualisation.
Would it be better to have a field with just the name of the file and load it in the page template?
Many thanks for any help.
Comment: You may want to think of a different approach. This could open you up to cross site scripting attacks. Perhaps expand out your question a bit more to let the community advise you on alternate options.
Comment: Out of curiosity, what will the js files look like?
Comment: in this instance they'd be d3.js scripts but maybe not in every instance
Answer: First things first: a warning.
This sounds like an extremely dangerous idea. If you do this, please at least make sure that you're only opening this up to trusted users (as allowing people to place javascript on your page could lead to some very, very bad things, much like the php filter.)
That being said, if your sure you want to do this, your gonna need to add the js to your page programmaticly. You could easily do this through your theme functions of template_preprocess_node.
Find that function in your template.php file. You'll want to add a condition to check for the content type, then grab the js file and use drupal_add_js to grab the attached js file and attach it to the head.
Comment: Providing a limited number of js choices for the user might be a smart way to do it. Say you have 30 js files that your going to use stored in libraries or in the files folder, you could provide a drop down on the content type that would contain the js name, and then just go to the folder and pull it that way. Idea is, as Rich pointed out, you want to limit the chances for a cross site scripting attack as much as possible. Execution would be similar, but instead of pulling the file location from the node, you would just get it from known-location/+filename+.js
Comment: Ah. Is there a safer/better way to add an individual javascript file for each instance of content? Maybe pulling a javascript file from the libraries folder with the same name as the content title perhaps?
Comment: thanks for the help. So I just need a field with the name of the file and then I can pull the file from a set location.
Comment: Yeah, as long as you know where your files will be, that should be fine.


About topological group and a connected component

Question: If $G$ is a toplogical group and $H$ is a connected component of $G$ containing the identity $e$ of $G$, then how can we show that $H$ is a normal subgroup of $G$?
I get that $xHx^{-1}$ is a connected component of $G$. Now I need to know how to show that $H \subseteq xHx^{-1}$.  Because then $H= xHx^{-1}$ due to the fact that $H$ is maximal connected. So $H$ is normal...
So how can I show that $H \subseteq xHx^{-1}$?
Answer: Sketch of Proof: A subgroup $H$ is normal if $gHg^{-1} \subset H$ for all $g \in G$.  Note, however, that the map $x \mapsto gxg^{-1}$ is continuous. So, $gHg^{-1}$ must be a connected component of $G$ that contains $e$.

Actually, we never showed that $H$ is necessarily a subgroup of $G$.  To that end: consider any $g\in H$.

Claim: for any $g \in H$, $gH = H$.  Similarly, $Hg = H$.

Proof:
Note that the map
$$
x \mapsto gx
$$
is a homeomorphism, so $gH$ is a connected component.  Moreover, $gH$ contains $ge = g$.  So, $gH$ is a connected set with $gH \cap H \neq \emptyset$.  It follows that $gH \subset H$, so that $gH = H$.  $\square$

Claim: The map $\phi(x) = x^{-1}$ satisfies $\phi(H) = H$.

Proof: same argument as above, noting that $\phi(H)$ is a connected component containing $e$.
Comment: Excellent answer.
Comment: @samankumar and there it is! Yes, that's it.
Comment: How to show gHg* is contained in  H where g* is inverse of g .
Comment: That's what the second part of the hint is for.  What do you know about continuous maps?  What's special about connected components?
Comment: This map is homomorphism so gHg* is  connected .
Comment: Not only is $gHg^*$ connected, it also contains the identity element
Comment: Yes it contain e because H has e so geg*= gg* = e. Then i take any gxg* from gHg* . Now e= gyg* for some y in H.  Then now i how to show gxg* is in H.???
Comment: Nothing after your first sentence makes any sense to me, I'm sorry to say.  I think you will find it useful to consider the following: $gHg^*$ *is a connected set which contains $e$*.
Comment: I am enable to do this. I now we get then gHg* = H but how... Don't able to do. Please help.....
Comment: You are unable to consider a statement?  That's unfortunate.  Let me ask you this: what exactly does the phrase "$H$ is maximal connected" (as you put it) mean?
Comment: H is maximal connected. It means that if H is contained in  any connected set M   then  then M=H  ie there is no other conncted set containing H.....
Comment: Right! And there's an important consequence: if $M$ is connected and $M \cap H$ is non-empty, then $M \subset H$.
Comment: See my latest edit.
Comment: From this we get  that both  gH g* and H have  e  and now H is maximal and gHg*  is connected  having non empty intersection. so gHg* is contained in H .  Hence H is normal...
Comment: Thanks...for great explanation......
Comment: Now the map gxg* is homomorphism so can i say that gHg* is also a maximal connected. ????? So xHx* is contained in H implies that xHx* =H.  is this true?????
Comment: @samankumar it's a **homeomorphism**, i.e. an continuous map with a continuous inverse.  So, $H$ is a maximal connected subset implies that $xHx^*$ is a maximal connected subset.  So indeed, $xHx^* \subset H \implies xHx^* = H$.
Comment: In addition, H is closed since cl H is connected, whence cl H subset   H.


Is this understanding of sufficiency correct?

Question: If $X$ is a sufficient statistic for $\theta$, I know that any $g(X)$ where $g(X)$ is one-to-one is also a sufficient stat. However, does that mean that $(X,Y)$ is also a sufficient statistic for $\theta$?
On the one hand, I'm thinking it is because semantically, since $X$ is "sufficient". Doesn't that mean that adding more to it will not destroy its sufficiency?
On the other, I'm thinking it is not because, from the definition of sufficiency, it is possible that evaluating the conditional probability will not yield an expression that is independent of $\theta$ when $Y$ is added to the mix.
Answer: Yes, if you add information from the data in addition to a sufficient statistic you will still have a sufficient statistic. However, it is a minimal sufficient statistic that should be sought because the idea is to use the statistic that is smallest. For example, the sample mean from a normal distribution with known variance is a minimal sufficient statistic for the population mean.
Comment: Ok. The question in the problem that I am dealing with just wants me to determine if the random pair (X,Y) is s sufficient stat for $\theta$. The pdf of XY is difficult to derive but it is easy to show that X is a sufficient stat.
Comment: Are you referring to the joint distribution of the pair X, Y or the distribution of the product of X and Y?
Comment: Sorry, I meant the joint distribution of X,Y


Limite de carácteres em input

Question: Quero montar um jQuery que aplique um limite de 255 carácteres dentro do input.
Minha ideia e fazer algo assim:
$(".loading").on('input', function () {
  // aqui eu tenho que fazer o bloqueio
});

Comment: Pq vc não usa o maxlength: ``
Comment: pos tenho um projeto que já esta pronto, se eu for colocar `maxlength` vai levar muito tempo. sendo que alguns input já possui `maxlength` menor.
Comment: entendi, acredito q a resposta do @Mathias vai te ajudar.. :D
Answer: Existem muitas formas de fazer isso, como a @Jessika comentou:
<input type="text" class="loading" maxlength="255">

Caso queira fazer o mesmo, utilizando jquery
function limitaCampo(campo, tamanho){
    $(campo).attr('maxlength',tamanho);
}

Caso queira fazer da maneira como tu apresentou: só mudar de 'input' para 'keydown':
$(".loading").on('keydown', function (e) {
   if($(this).val().length >= 255){
      return false;
   }
});

Segue um snippet com limite de 2 caracteres:
*adicionei e.keyCode != 8 e 9 p/ permitir o click no backspace e no TAB

$(".loading").on('keydown', function(e) {
  if ($(this).val().length >= 2 && e.keyCode != 8 && e.keyCode != 9) {
    return false;
  }
});

<input class="loading">
Comment: Boa dica do keyCode !=8, não esqueça do TAB também
Comment: @GuilhermeNascimento perfeito, adicionado à resposta, ty.
Answer: Gostaria de sugerir algumas modificações ao que já foi proposto:

Primeiro keydown funciona bem, mas existe a limitação, mas se for usá-lo terá que combinar onpaste e oninput (ou ondrop talvez, se for arrastar algo) também.
Segundo, o evento .on do jQuery talvez seja melhor aplicado se for usado em um "contexto", ou seja ao invés disto $(seletor).on(function()) usar isto $(document).on(seletor, function()), pois desta maneira o jQuery detecta melhor as modificações no DOM por exemplo páginas em Ajax

No geral recomendo trocar por onchange (propertychange para versões antigas do IE) e remover o que for adicionado posteriormente:

(function () {

    var limite = 10;

    function limitaInput(input) {
        if (input.value.length > limite) {
            input.value = input.value.substr(0, limite);
        }
    }

    $(document).on("propertychange change keyup", ".loading", function () {
        if (this.timerLimitInput) {
           clearTimeout(this.timer);
        }

        this.timerLimitInput = setTimeout(limitaInput, 10, this);//Timeout para evitar conflitos
    });

})();

<input class="loading">

Desta maneira qualquer manipulação no <input> será detectada
Answer: Você pode usar o evento keydown ao invés de input e usar um atributo data-* para definir o limite (já que você disse nos comentários que não pode "confiar" no atributo maxlength.
A implementação tá bem ingênua, mas a ideia é essa.

$(".loading").on('keydown', function (evt) {
  var qtd = $(this).val().length;
  var limite = $(this).data('limite') || 255;

  if(qtd > limite && evt.keyCode != 8)
    return false;

  console.log(qtd, limite);
});

<textarea class="loading" data-limite="10"></textarea>
<textarea class="loading"></textarea>

Limite de carácteres em input


How to generate two groups of $n$ random numbers in $U(0,1)$ such that sum of these two groups equal?

Question: I want to have two groups of $n$ random numbers $u_i$ and $v_i$ in $U(0,1)$, such that $\sum u_i = \sum v_i$
What I tried is:
I can firstly get $u_i$ by $U\sim U(0,1)$, make $s=\sum u_i$.
Then I found it is very difficult to generate another $n$ uniformly distributed random numbers $v_i$ from $U(0,1)$ that sum to $s$, where $s$ can be any real value in $[0,n]$
Try to make the question clearer, my original problem is:
The random variables, of course, is not independent! But my question requires the sampled values for each parameter roughly distributed in range [0,1] such that the Monte Carlo sampling will effectively go over the whole parameter space for the system.
I have $8$ parameters $\kappa_i, i=1,\ldots,8$ from a system, each parameter $\kappa_i$ can be any value (better be uniformly distributed) in $[0,1]$. But I have a constraint on my parameters which is $\kappa_1+\kappa_2+\kappa_3+\kappa_4=\kappa_5+\kappa_6+\kappa_7+\kappa_8$. Now I want to sample the whole parameter space (is this counted as Monte Carlo?) with such constraint. What should I do?
Comment: There appears to be an interesting and important question here, but it is asked in a very confusing way.  Please edit it to address the comments.
Comment: I think it is crucial what kind of dependence you allow for. Your constraint *implies* a dependence structure, so the four samples $\kappa_i: 1 \leq i \leq 8$ *cannot* be independent from each other. (To see this, note that if all $\kappa_i$ are random and independent, the probability of your constraint holding is equal to $0$.) 'How independent' do they have to be? Which dependence structure do you allow for?
Comment: It's on hold so I can't post this as a solution but why not first sample $\kappa_1,\kappa_2,\kappa_3,\kappa_5,\kappa_6,\kappa_7\sim U(0,1)$. Then simulate one more $\kappa_i\sim U(0,1)$ and add it to whichever set $A=\{\kappa_1,\kappa_2,\kappa_3\}$ or $B=\{\kappa_5,\kappa_6,\kappa_7\}$ makes it such that $A>B$ or $B>A$.  So either $i=4$ and $\kappa_4$ gets added to $A$ or $i=8$ and $\kappa_8$ gets added to $B$. Then, for whichever $\kappa$ is left, set the last $\kappa_8=\kappa_1+\kappa_2+\kappa_3+\kappa_4-(\kappa_5+\kappa_6+\kappa_7)$ or (ctd)...
Comment: The problem of partitioning a set into two equal-in-sum (/as equal as possible) subsets is the [partition problem](https://en.wikipedia.org/wiki/Partition_problem), but it's not quite clear to me how your conditions on the distribution are supposed to work.
Comment: You want samples of numbers $\kappa_i$ such that $\sum_{i=1}^4 \kappa_i = \sum_{i=5}^8 \kappa_i$.  It sounds like you want the marginal distribution of each $\kappa_i$ to be uniform on $[0, 1]$.  But what conditions do you want to impose on their joint distribution?
Comment: Aren't you missing $=s$ at the end of the sum in the penultimate line?
Comment: @RichardHardy the $s$ is just a sum calculated by sampled $4$ random numbers, it can be any value in $[0,1]$
Comment: Do you require anything to be independent from anything else?  If not, you could draw a single $Z \sim U[0, 1]$ and make all the $X_i$ and $V_i$ equal to that $Z$.  But that's probably not what you want...
Comment: What I mean is that $\kappa_1+\kappa_2+\kappa_3+\kappa_4=\kappa_5+\kappa_6+\kappa_7+\kappa_8$ is not a constraint on parameters although you refer to it as such.
Comment: @whuber I wanted to at least follow through with what I started. I don't know if the answer I'm giving could possibly help the OP. It certainly doesn't have originality as I make it very clear. Please let me know if it'd be OK to leave the answer un-deleted.
Comment: @Antoni I'm afraid I haven't a clue what your answer is supposed to be telling us.  The output of your code, as shown, certainly isn't two sets of four numbers, so I have been unable to relate it to any interpretation of the question.
Comment: (ctd)... $\kappa_4=\kappa_5+\kappa_6+\kappa_7+\kappa_8-(\kappa_1+\kappa_2+\kappa_3)$ and I believe that should get you what you want. I.e., $\sum_{i=1}^4\kappa_i=\sum_{i=5}^8\kappa_i$.  Of course here the last $\kappa$ will depend on all of the other $\kappa$'s and so possibly not independent.
Comment: @RustyStatistician The approach is the same as I came up with yesterday!!! In addition, $A$ and $B$ need to be carefully calculated so that $|\sum A-\sum B|\le1$. Then choosing these two sets will also cost computational time.
Comment: I think it is best to ask a new question concerning your underlying problem of MC sampling with certain constraints on parameters. That is, if that is what you are ultimately interested in.
Answer: Here is a procedure to generate two $n$tuples of random variables $(u_k)$ and $(v_k)$, both i.i.d. uniform on $(0,1)$, with $u_1+\cdots u_n=v_1+\cdots+v_n$.
For every $k$, let $f_k$ denote the PDF of the sum of $k$ i.i.d. random variables uniformly distributed on $(0,1)$. Generate $n$ i.i.d. random variables $u_i$ uniform on $(0,1)$, and consider $s_n=u_1+\cdots+u_n$. Then generate $v_n$ distributed as $u_n$ conditionally on $u_1+\cdots+u_n=s_n$, that is, with density $$f_n(s_n)^{-1}\cdot f_{n-1}(s_n-x)\cdot\mathbf 1_{(0,1)}(x).$$ Next, define $s_{n-1}=s_n-v_n$ and generate $v_{n-1}$ distributed as $u_{n-1}$ conditionally on $u_1+\cdots+u_{n-1}=s_{n-1}$, that is, with density $$f_{n-1}(s_{n-1})^{-1}\cdot f_{n-2}(s_{n-1}-x)\cdot\mathbf 1_{(0,1)}(x),$$ and so on, until $v_2$ distributed as $u_2$ conditionally on $u_1+u_2=s_2$, that is, with density $$f_2(s_2)^{-1}\cdot f_{1}(s_2-x)\cdot\mathbf 1_{(0,1)}(x)=f_2(s_2)^{-1}\cdot \mathbf 1_{(s_2-1,s_2)}(x)\cdot\mathbf 1_{(0,1)}(x).$$ Finally define $v_1=s_2-v_2$. Then $(v_k)$ is i.i.d. uniform on $(0,1)$ and $u_1+\cdots u_n=v_1+\cdots+v_n$ almost surely.
To sum up, the procedure is exact but it requires to compute $n-1$ PDFs, each PDF $f_k$ being a polynomial of degree $k-1$ on each interval $(i-1,i)$ with $1\leqslant i\leqslant k$.
Comment: Can you elaborate on the notation for the $f_n(s_n)$ and $f_{n-1}(s_{n-1})^{-1}$, and / or in general computing the pdf $f_k$?
Comment: @AntoniParellada The factor is $$\frac1{f_{n-1}(s_{n-1})}.$$
Answer:
I have 8 parameters $κ_i,i=1,…,8$ from a system, each parameter $κ_i$ can be any value (better be uniformly distributed) in $[0,1]$. But I have a constraint on my parameters which is $κ_1+κ_2+κ_3+κ_4=κ_5+κ_6+κ_7+κ_8$. Now I want to sample the whole parameter space (is this counted as Monte Carlo?) with such constraint. What should I do?

If  understand your problem:
a) simulate freely 4 random numbers [0, 1]
b) let be its sum n1
c) simulate  THREE ALSO FREELY and add, say n2
d) if 0<= ni-n2 <= 1 then keep x=n1-n2, otherwise reject the attempt
e) repeat from a) to d) any times in order to get a large stock
Comment: There appear to be several problems with this proposal, not least of which are (1) the numbers won't usually sum to unity and (2) the asymmetric treatment of the last one leads to an unexpected marginal distribution.
Comment: Please stop the words in capitals and rather concentrate on the mathematical point @whuber made.
Comment: There is actually a neat little exam question for introductory courses on theoretical probability here. The text of the question could read as follows. Consider seven independent random variables $T$, $U$, $V$, $W$, $X$, $Y$, $Z$, and compute the distribution of $S=(U+V+W+T)-(X+Y+Z)$ conditionally on the event $[0<S<1]$. Check that this distribution is *not* the uniform distribution on $(0,1)$. Hint: Show that $S+3$ is (unconditionally) distributed like $U+V+W+T+X+Y+Z$. // @OP [This page](https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution) might interest you.
Comment: I'm afraid that doesn't fix the problems I mentioned.
Comment: For some kind of people only understands  numbers: Example 1: k1=0.3, k2=0.7, k3=0.5, k4=0.5, sum1 =2.0. if  k5=0.7, k6=0.7, k7=0.7, sum2=2.1.Then (because RND are <=1) reject. Example 2: k5=0.2, k6=0.1, k7=0.1, sum2=0.4, then k8 would be 1.6, impossible, reject.
Comment: many TIMES (NOT ANY)
Comment: CORRECTION  d) if           0<= |n1-n2|<=1  . . .so sorry . . .
Comment: of curse NOT whuber it was not demanded that th sums were
Comment: it was not demanded that the sums were equal to 1. Not at all!
Comment: A occurs or not to see  if B occurs too: B|A. My solution above solves completely the posted problem. Do not complicate what is so elementary.
Comment: The probability that the third RND (2nd set) be accepted to complete a sum equal to
Comment: the first 4 RND set is  precisely 0.716
Comment: the fourth RND (2nd set) of course.


Finding Eigenvalue for cubic equation

Question: I'm learning finding eigenvalues. I learned how to find simplistic eigenvalues for $3\times3$ matrix.
By using below way. With this way I can only solve if I have simple determinant equation, like quadratic.

Find eigenvalues of $\lambda_i$, which are roots of $\det(A-\lambda I)=0$. $$\det(A-\lambda I)=\begin{vmatrix} 4 & 6 & 10 \\ 3 & 10 & 13 \\ -2 & -6 & -8\end{vmatrix} - \lambda \begin{vmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1\end{vmatrix}$$

But for some of the matrices are big numbers and  becoming cubic equation which won't have integer numbers as eigenvalues.  I guess I need to simplify the matrix before somehow. Which I cannot find.
Can you please guide me how can I handle if matrices are not simple?
Any references or tutorials are appreciated.
I watched below video tutorial but author is using simple matrix in example:
Eigenvalue and Eigenvector Computations Example
Comment: I expect you're just meant to take the determinant of the whole thing. It simplifies rather nicely in the end :)
Comment: In your display, you have written $\det(A-\lambda I)$ on the left, but you have written $\det A-\lambda\det I$ on the right. They are not the same thing. You want to subtract $\lambda I$ from $A$ first, then take determinants.
Answer: It's only at school that Eigenvalues are integer numbers ;-)
For the 3x3 case, you have the option of using the Cardano-Tartaglia formulas to solve the third degree equation. http://en.wikipedia.org/wiki/Cubic_function#Roots_of_a_cubic_function. They involve complex numbers.
Fourth degree can also be addressed by explicit formulas. http://en.wikipedia.org/wiki/Quartic_function#Solving_a_quartic_equation
As induced by Evariste Galois at the age of 17, there is no similar formula for degree 5 and above.
In practice, numerical methods are used. http://en.wikipedia.org/wiki/Eigenvalue_algorithm.
Also have a look at http://en.wikipedia.org/wiki/Eigenvalue_algorithm#3.C3.973_matrices.
Comment: thank you for your answer! :) for 3x3 I've just found http://www.wikihow.com/Solve-a-Cubic-Equation I guess its the same thing as in Wiki, right?

I'm not quite sure, but I heard before doing determinant I should do some operation on existing matrix to make it simpler and solve it, how is this true? Thank you!
Comment: In the general case there is no simplification, but check my last pointer.

Finding Eigenvalue for cubic equation


Docker inside LXC starting container process caused "apply caps: operation not permitted"

Question: I'm trying to run a Docker container inside an LXC container.
However doing so causes me to get the following error:

[root@DH-DockerLXC01 alex]# docker run fedora bash
docker: Error response from daemon: OCI runtime create failed: container_linux.go:337: starting container process caused "apply caps: operation not permitted": unknown.
ERRO[0001] error waiting for container: context canceled

I presume I need to set some configuration to be more permissive, but since I've created the LXC container with virt-manager I'm not sure where to start.
Note that the LXC container is using a chroot for storage, which AFAIK should allow docker to use full AUFS without any problems, but if I'm wrong please correct me.
Answer: For privileged LXC managed by Proxmox this solution helps:
lxc.apparmor.profile: unconfined
lxc.cgroup.devices.allow: a
lxc.cap.drop:

Take care about security!
Source: Running Docker on Proxmox
Answer: As it turns out, LXC, by default, will not allow containers to have the CAP_MKNOD capability, as it could theoretically allow a container to take over a host.
This can be overridden, but it's not very well documented. Based on a pull request from 2015 in a mailing list, I've been able to piece together a bit of XML that does it. You just have to edit the container definition, which is located in /etc/libvirt/lxc/[container name]/
<features>
  <capabilities policy='allow'>
    <mknod state='on'/>
  </capabilities>
</features>

Note that the file may already contain a  definition, in that case, paste the  section inside that section.
You may have to restart libvirt before it takes effect with systemctl restart libvirtd.service (this will not restart existing containers or VMs, only the service).
Answer: J.F.Y.I.

tl;dr: Check the "Virtualization" settings in the BIOS.

On my Proxmox machine, after upgrading the RAM, it turned out that this error occurred because the "Virtualization" setting in the BIOS had been "disabled" for some reason.
I turned it to "Enable" and started to work again. Dah.

OS: Proxmox VE 7.4-4 (Debian GNU/Linux 11, bullseye)
Motherboard: GA-880GM-USB3 Rev. 1.1


Tenfold increase in size of pdf after burst and cat (with pdftk)

Question: I did pdftk burst a document with 300 pages.
I  pdftk cat 1 page every 3.
I got a document of 100 pages.
The size of the document increased from 800kb to 11Mb!!!
From this old post I undestand pdftk might be outdated. Should I use some other tool?
Answer: Are you transforming the burst pages in any way before putting them together? If you are, then you should probably go with another tool as suggested by the question you link to. Otherwise there is no need to burst first, just use a page range like
pdftk input.pdf cat `seq 1 3 300` output output.pdf


Shiny can not display different "webGLOutput" on different tab panels?

Question: I am trying to displaying different 3D plots in different tab panels, but I found that 3D plot only displayed in the first tab panel. According to this post, plotOutputs parameter outputId should be unique, and in my case IDs are unique over the entail shiny app. Some lines of my app are as follow:
ui.R
shinyUI(fluidPage(
  mainPanel(
    tabsetPanel(
      tabPanel("VWC", webGLOutput("VWC3DPlot")),
      tabPanel("TEMP", webGLOutput("TEMP3DPlot"))
    )
  )
))

server.R
shinyServer(function(input, output) {

    # set dir;
    dataDir <- "C:/Users/PH/Desktop/data/DATA/"

    # store dataframe of attribute to list;
    dfList <- readIntoDF(dataDir) # readIntoDF() is function that return a list

    # extract dataframe from list
    dfVWC <- dfList$VWC
    dfTEMP <- dfList$TEMP

    # processing of dataframes
    dfVWC <- transformDF(dfVWC)
    dfTEMP <- transformDF(dfTEMP)

    # prepare grid for kriging;
    grd <- expand.grid(x=seq(from=0, to=600, by=200),
                       y=seq(from=0, to=500, by=200))

    # Kriging;
    dfVWCkrige <- krigingFun(dfVWC, grd)
    dfTEMPKrige <- krigingFun(dfTEMP, grd)

    krigeList <- list("VWCKrige" = dfVWCkrige, "TEMPKrige" = dfTEMPKrige)

    return(krigeList)
  })  # end of dataInput

  ### create cubs;
   output$VWC3DPlot <- renderWebGL({
     createCubes(dataInput()$VWCKrige) # createCubes() is a function that use output of kriging and shinyrgl pkg to create cubes;
   })

  output$TEMP3DPlot <- renderWebGL({
    createCubes(dataInput()$TEMPKrige)
  })

})

Since there are hundreds of lines, I could not to post all of them.
According to this post, I updated the version of shiny, but had no effect on my case.
Comment: I wonder if it is an issue with webGL graphs. Does it work if you change it to normal R plots?
Comment: Thank you for your reply.  You are right, when I changed it to `plotOutput`, it worked. So how to handle this issue?
Comment: You should make sure you see the same behaviour in the latest versions of rgl and rglwidget from R-forge; if so, put together a bug report.  It needs to be self-contained, nobody else can run the code in your question.
Comment: @user2554330 I have updated package `rgl`, `shiny` and `rglwidget`, but I still got the same problem.
Comment: So simplify your example, and post a bug report in the appropriate place.
Answer: You appear to be using shinyRGL.  Don't use it, rgl has what you need.  Here's an example that works for me:
ui.R:
library(shiny)

shinyUI(fluidPage(
  mainPanel(
  tabsetPanel(
    tabPanel("red",
      rglwidgetOutput('thewidget1')),
    tabPanel("green",
      rglwidgetOutput('thewidget2'))
  ))
))

server.R:
library(shiny)
library(rgl)

options(rgl.useNULL = TRUE)
shinyServer(function(input, output, session) {

  x <- rnorm(100)
  y <- 2*rnorm(100)
  z <- 10*rnorm(100)
  open3d()
  plot3d(x, y, z, col = "red")
  scene1 <- scene3d()
  plot3d(z, y, x, col = "green")
  scene2 <- scene3d()
  rgl.close()

  save <- options(rgl.inShiny = TRUE)
  on.exit(options(save))

  output$thewidget1 <- renderRglwidget(
    rglwidget(scene1)
  )

  output$thewidget2 <- renderRglwidget(
    rglwidget(scene2)
  )

})

By the way, we would have got here a lot sooner if you had posted a reproducible example as requested.


Como buscar um determinado pacote pelo npm?

Question: Iniciei um projeto em React e quero saber como eu busco um determinado pacote instalado direto pelo npm ?
Comment: Para listar os pacotes instalado: `npm list -g --depth=0` e para listar um pacote em particular: `npm list -g --depth=0 | grep  nome-do-pacote`
Answer: Pra buscar um pacote, rode o seguinte comando:
npm search pacote_desejado

Por exemplo
npm search express

vai te trazer um resultado assim:

Valeu!
Answer: Rode o comando abaixo no terminal:
npm list | grep {pacote_desejado}


Como obter um indexOf() de um array com o mesmo elemento múltiplas vezes?

Question:
A ideia é ordenar as letras para escrever um element HTML5 neste caso o "tfoot". Mas quando eu troco a segunda letra t pelo o não me troca direito. Eu sei porquê. é porque o index que eu peguei corresponde ao primeiro elemento com esse innerHTML, neste caso o index do t será o primeiro t o que está errado. Eis o meucódigo javascript.
word = gameMechanics[1];
  let lettertoSwitch = 0; // To be in the scope of the function
  let letterToBeSwitchedWith = 0;
  let indexLettertoSwitch = 0;
  letters.forEach((letter) => {
    letter.addEventListener("click", (e) => {
      if(turn % 2 === 0){ // If its the first time the user clicks on the letter
        lettertoSwitch = letter.style.order; // Stores the position of the letter
        indexLettertoSwitch = word.indexOf(letter.innerHTML); // Stores the index of the letter
        turn ++;
      }else if(turn % 2 === 1){ // If its the second time the user clicks on a letter
        letterToBeSwitchedWith = letter.style.order; // Stores the position of the letter
        turn ++;

      }
      if(turn % 2 == 0 && turn !== 0){ // If the player has made to moves and its not the first turn
        letter.style.order = lettertoSwitch; // Switches the current letter with the first one clicked
        letters[indexLettertoSwitch].style.order = letterToBeSwitchedWith; // Switches the second clicked letter with first one clicked
        console.log(lettertoSwitch, letterToBeSwitchedWith);
      }
    })

Como é que eu posso obter o index da letra através da propriedade order do elemento, pois é a única propriedade única que consegue distinguir as mesmas letras? Poderia usar o evento para aceder ao index do elemento?
Answer: Acredito que o IndexOf() não resolverá seu problema.
Eu partiria para algo mais simples
1) Posicionar cada caracter em uma tag com um id específico
t
o
o
t
f

2) Ao clicar no caracter retorna o id do mesmo, o que já seria a posição.
function reply_click(clicked_id)
  {
      alert(clicked_id);
  }

Nota Claro que vc não fará o alerta, mas sim trocar o caracter
Veja este código aqui:

function reply_click(clicked_id)
  {
      alert(clicked_id);
  }
t
o
o
t
f

Espero que ajude.
Comment: Resultou! Boa lógica. Interessante que não haja uma função para obter o index pela propriedade de estilo.
Answer: Tudo depende da forma como estruturar o seu código HTML. Uma forma é definir cada letra num elemento independente e assim poder registar eventos em cada letra e executar lógica para efetuar a troca das letras.
O seguinte código baseia-se nesta estrutura e utiliza javascript para:

Gerar o HTML, dada uma palavra;
Registar os eventos para cada letra;
Executar lógica para troca de letras;
Verificar se a palavra corresponde à initial (acerto).

Acabei entusiasmando-me a implementei isto. Espero que ajude.

// Check if a given word is valid for the purpose of this example.
// A word is considered valid if it has at least 2 letters and not all the letters are the equals.
const isValidWord = (word) => {
  if (word.length < 2) return false;

  const wordArray = [...word];

  return wordArray.filter(
    (letter) => wordArray[0] === letter,
  ).length !== wordArray.length;
};

// Randomly shuffle letters in a given word and return it.
// It makes sure the shuffled word is not equals to the given word.
const shuffleWord = (word) => {
  const wordArray = [...word];
  const shuffledWord = wordArray.sort(() => Math.random() - .5).join('');

  return shuffledWord !== word ? shuffledWord : shuffleWord(word);
};

// Generate and return and HTML element representing a word.
// Example:
A

const generateWordElement = (word) => {
  const wordElement = document.createElement('div');

  wordElement.classList.add('word');
  [...word].forEach(
    (letter) => wordElement.appendChild(generateLetterElement(letter)),
  );

  return wordElement;
};

// Generate and return and HTML element repsenting a letter.
// Example: A
const generateLetterElement = (letter) => {
  const letterElement = document.createElement('span');

  letterElement.classList.add('letter');
  letterElement.appendChild(document.createTextNode(letter.toUpperCase()));

  return letterElement;
};

// Register a click event listener for every letter element.
// It calls switchLetter passing the letter element clicked as argument
// and then checks if the word is right by calling wordMatch.
const registerEventListeners = (word) => {
    document.querySelectorAll('.word .letter').forEach((letterElement) => {
    letterElement.addEventListener(
      'click',
      (event) => {
        switchLetter(event.target);
        wordMatch(word);
      },
    );
  });
};

// Try to switch letters between 2 clicked elements.
// It uses a global swap variable to store the 1st clicked element.
// When there's already a clicked element, it switch them and set the swap element back to null.
const switchLetter = (clickedLetterElement) => {
  if (!swapLetterElement) {
    swapLetterElement = clickedLetterElement;
    swapLetterElement.classList.add('letter--selected');

    return;
  }

  const swapLetter = swapLetterElement.textContent;
  swapLetterElement.textContent = clickedLetterElement.textContent;
  clickedLetterElement.textContent = swapLetter;
  swapLetterElement.classList.remove('letter--selected');
  swapLetterElement = null;
};

// Check if the current word element matches the initial word.
const wordMatch = (word) => {
  const currentWord = Object.values(document.querySelectorAll('.word .letter')).map(
    (letterElement) => letterElement.textContent,
  ).join('');

  if (currentWord === word.toUpperCase()) {
    document.querySelector('.word').classList.add('word--match');
  }
};

// Initialize the game
const init = (word) => {
  if (!isValidWord(word)) return;

  document.querySelector('body').appendChild(
    generateWordElement(shuffleWord(word))
  );

  registerEventListeners(word);
};

let swapLetterElement = null;
init('tfoot');
@import url('https://fonts.googleapis.com/css2?family=Play&display=swap');

.word {
  display: flex;
  justify-content: center;
  padding: 15px;
  font-family: 'Play', sans-serif;
  font-size: 30px;
}

.word.word--match {
  background-color: mediumspringgreen;
  pointer-events: none;
}

.word.word--match .letter {
  border-color: teal;
  color: teal;
}

.letter {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 5px;
  border: 3px solid darkgray;
  border-radius: 5px;
  background-color: lightgray;
  height: 50px;
  width: 50px;
  cursor: pointer;
  transition: all ease .25s;
}

.letter.letter--selected {
  border-color: teal;
  color: teal;
  background-color: white;
}
Answer: Algoritmo
Se entendi corretamente, precisa apenas do índice da letra clicada. Imagino que necessite de um algoritmo seguindo a lógica da função abaixo:
function getIndexOfNthLetter(array, nPositionInArray, letter) {
    // declarando as variáveis que serão usadas
    let currentLetter, position = 1;

    for (let i = 0; i < array.length; i++) {
        // resgatando letra atual
        currentLetter = array[i];

        /*
         *  caso a letra seja a mesma que deseja E a posição no array também, retorne
         *  a partir do índice atual, para não retornar o índice de uma letra passada
        */
        if (letter === currentLetter && position === nPositionInArray) {
            return array.indexOf(currentLetter, i);
        } else if (currentLetter === letter) {
            // caso contrário, a posição não é a desejada mas continuamos seguindo...
            position++;
        }
    }

    // retornando -1 caso nenhuma letra tenha sido encontrada no índice indicado
    return -1;
}

O uso da função acima seria:
getIndexOfNthLetter(array, 2, "t"); // Solicitando o segundo "t", índice: 3
getIndexOfNthLetter(array, 2, "r"); // Solicitando o segundo "r" (que não existe no array), índice: -1

Conclusão e uso do indexOf
Seu uso da função indexOf deveria conter dois argumentos: A letra e a partir de onde procurar, ou seja, no índice da letra atual, para que não retorne o índice do primeiro "t", como no seu caso de uso.
Se procurar pelo "t" a partir do segundo "t", terá o índice dele mesmo, pois o array só seria considerado a partir dali.
Espero ter ajudado de alguma forma.
Answer: guarde o índice da primeira ocorrência e use o index como offset para a próxima pesquisa "recursivamente":
var indexOcorrencias = [];
var text = 'tootf';
var toSearch = 't';
var index = text.indexOf(toSearch);
while (index>=0) {
  indexOcorrencias.push(index);
  index += toSearch.length;
  index = text.indexOf(toSearch, index);
}
//indexOcorrencias = [0,3];

função indexOf:
indexOf(find[,offset])

Comment: não percebi como é que isso me vai dar o index da letra clicada?! dá-me um array de indexes não o index da letra clicada
Comment: seria mais fácil de entender se tivesse dito isto invés de "Como obter um indexOf() de um array com o mesmo elemento múltiplas vezes?"


Find potential function for the vector field $\vec F(x)=\left \| x \right \|^px$

Question: Define a vector field $\vec F$ in $\Bbb{R}^n \setminus 0$ by $\vec F(x)=\left \| x \right \|^px$, where $p$ is a real constant.
How to find a potential function for $\vec F$? Shall I just directly integrate this? or do this case by case and use induction?
Answer: Let $r = \|x\|$. Consider $g(r) := \frac{r^{p+2}}{p+2}$. We have $$\operatorname{grad}g(r) = \frac{x}{r}\frac{d}{dr}\left(\frac{r^{p+2}}{p+2}\right) = \frac{x}{r}(r^{p+1}) = r^{p}x = \vec{F}(x),$$
so $g$ is a potential for $\vec{F}$.
In general, when given $\vec{F}(x) = A(r)x$, where $A$ is a continuous function of $r$, here's how we can find a potential for $\vec{F}$. We seek $g = g(r)$ such that $\vec{F} = \operatorname{grad} g$. Now $\operatorname{grad}g = \frac{x}{r}g'(r)$, so we solve
$$\frac{x}{r}g'(r) = A(r)x.$$
Taking the dot product with $x$, we get
$$\frac{x\cdot x}{r}g'(r) = A(r)x\cdot x.$$
Since $x\cdot x = r^2$, the equation reduces to
$$g'(r) = A(r)r$$
Thus, a solution for $g$ is
$$g(r) = \int^r A(u)u\, du.$$
Comment: thanks, then in case p=-2, there is no potential function?
Comment: @nancy if $p = -2$, a potential for $\vec{F}$ is $$g(r) = \int_1^r \rho^{-2}\rho\, d\rho = \int_1^r \rho^{-1}\, d\rho = \log(r).$$


Webforms - Is it safe to allow users to upload attachments?

Question: Is it safe to include a 'File' type field into a webform that allows users (anonymous or authenticated) to upload their files? After reading few articles on the web , it seems it makes a website vulnerable to hacking and malware.
I would like to know better about this so that I can make a decision on this and provide an answer for and against using it.
Answer: Here is a security advisory from drupal.org that explains some of the dangers of letting anonymous users upload files: https://www.drupal.org/psa-2016-003
tl;dr

Configure upload fields that non-trusted visitors, including
anonymous visitors, can upload files with, to utilize use the private
file system.
Consider forcing users to create accounts before
submitting content.
Audit your public file space to make sure that
files that are uploaded there are valid.
Comment: Even if you force users to create an account, the files should still not be placed in the public filesystem. Just because they took the time to register does not mean they can be trusted. Only let trusted users use the public filesystem.
Comment: @Neograph734 I agree and I too had the same thought. Thanks for your response
Comment: Thanks for your response @Wim. It means that it would make it safer by following all the 3 points and not by only utilising the private file system since people can still attach malicious pdfs.
Comment: Exactly, and preferably have people create an account before they can upload.


Jwt authorization in react app without storing token in local storage

Question: actually I am going to implement jwt authorization in my first react app and i have gone through many articles and all of them suggesting storing the token in local storage which somehow I am not finding it secure as the token is visible. So two solution came into my mind which obviously is not the best solution that y i am here asking the question
Solution
1. Generating the jwt token on my react side on every API request, but for doing this I have to use secret key on my client-side which obviously is a BAD IDEA exposing the secret key.
2. Having two express app one running the react app and one running the api, the api call from my react app will hit the react express side in where i will generate the token and hit the actually api with the token, i know its little confusing hope you guys understood what i am trying to explain.
That's what I have thought and I know both the solution are not a good one, so it would be very helpful if some of you suggest me how u have done authorization in you app
Answer:
Indeed, not a great idea to expose your secret key
Why use multiple express apps for this? You can authenticate directly in your "react express" app

This is a great article on React, Express and JWT
About storing the JWT in the browser (you primary concern), there isn't a definitive answer. This article explain benefits and cons of storing in cookies or in local/session storage. But you need to store it in the browser also, as you need to send it with each request.
Token being visible is not necessarily a security thread. The principle is that it cannot be manipulated, even when someone has it (for example to change the expiration date).


Drupal 7: mark as offensive flag

Question: I want to create a 'mark as offensive' flag for my site. However, I have no idea how to go about it. Is there a tutorial on the web that will guide me through the process?
Answer: To do this you could use a popular module http://drupal.org/project/flag.
There is also documentation here http://drupal.org/documentation/modules/flag.
Comment: Some more screencasts are here http://nodeone.se/learn-flag-part-1
Answer: Also, checkout the Flag Abuse module.

It works by giving a new permission for a role to be able to reset flags. If a role has this permission, the flag is changed to say 'Reset' instead of whatever the default text may be. When that user clicks this it resets all of the abuse flags on that object and makes to that it cannot be flagged as abuse anymore.
Answer: http://www.youtube.com/watch?v=b5xieuVf01E&feature=BFa&list=PL1A89955CCEB73A09&lf=iv
short and to the point

Drupal 7: mark as offensive flag