gcloud job can't access my files, either they are in GCS or in my cloud shell

Question: I'm trying to run my code of machine learning from images using tensorflow in Google CloudML. However, it seems the submitted job can't access to my files in my cloud shell or in GCS. Even though it is working fine in my local machine, I get the following error once I submit my job using the command gcloud from the cloud shell:
ERROR   2017-12-19 13:52:28 +0100       service         IOError: [Errno 2] No such file or directory: '/home/user/pores-project-googleML/trainer/train.txt'

This folder can be found for sure in cloud shell, and I can check it when I type:
ls /home/user/pores-project-googleML/trainer/train.txt

I tried putting my file train.txt in GCS and access to it from my code (by specifying the path gs://my_bucket/my_path), but once the job submitted, I got a 'No such file or directory' error with the corresponding path.
To check where the job I submitted using gcloud is running, I added print(os.getcwd()) in the beginning of my python code trainer/task.py, which printed as a result in the logs: /user_dir. I couldn't find this path using the cloud shell, not even in GCS. So my question is how can I know in which machine my job is running? If it's in a certain container somewhere, how can I access from it to my files using the cloud shell and in GCS?
Before I do all of this, I succesfully completed the 'Image Classification using Flowers Dataset' tutorial.
The command I used to submit my job is:
gcloud ml-engine jobs submit training $JOB_NAME --job-dir $JOB_DIR --packages trainer-0.1.tar.gz --module-name $MAIN_TRAINER_MODULE --region us-central1

where:
TRAINER_PACKAGE_PATH=/home/use/pores-project-googleML/trainer

MAIN_TRAINER_MODULE="trainer.task"

JOB_DIR="gs://pores/AlexNet_CloudML/job_dir/"

JOB_NAME="census$(date +"%Y%m%d_%H%M%S")"

Comment: You will need to put your files on GCS. IIUC, when you try to access train.txt on GCS you see an error message about `/home/user/ ...`, is that correct? If so, it would seem the logic to your code is still trying to access `/home/user/` rather than the GCS bucket.
Comment: I have actually no problem accessing train.txt on GCS. with the command `gsutil ls gs://pores/AlexNet_CloudML`, I get all my files listed, including `train.txt`. When I tried with the GCS path instead of the one in cloud shell, I got `No such file or directory: 'gs://pores/AlexNet_CloudML/train.txt'`. So, using the path in GCS didn't really solve the problem.
Comment: Was the GCS bucket created in the same project that you submitted your training job from? Our service can only access the GCS buckets that were created in the same project where you enabled our service. A side note on cloud shell: Cloud Shell is running on a VM managed by Google, so all the files in Cloud Shell are not accessible to other services.
Comment: To make sure that my GCS bucket is in the same project from which I submitted my job, I did the following: `PROJECT_ID=$(gcloud config list project --format "value(core.project)")` , `BUCKET_NAME=gs://${PROJECT_ID}-jobs` and `gsutil mb -l $REGION gs://$BUCKET_NAME` I then copied all my files to the new bucket and changed the paths in my code to point there. I still got a "No such file or directory" error with the new gs://path
Comment: Can you share your project number and the gcs path with us via sending an  email to firstname.lastname@example.com please?
Comment: It's done. I remain at your disposal for any complementary information.
Comment: I was able to check that my job can actually access GCS, by adding to my code `print(tf.gfile.ListDirectory('gs://pores-187611-jobs/trainer/')`. However, I still can't read the file train.txt which contains the paths and labels to my images. I didn't succeed to do it with `numpy.loadtxt()`, with `open()` neither with `with open():`.
When I tried with those commands, I got no such file or directory..
Is it possible to simply read a txt file with tensorflow? If not, is it possible to do with another library that can access to GCS??
Many thanks !!
Answer: Regular Python IO library is not able to access files on GCS. Instead, you need to use GCS python client or gstuil cli to access GCS files.
Note that TensorFlow itself has native support of GCS (i.e., it can read GCS files directly).
Comment: You can use the gsutil cli by calling os.system('gsutil cp YOUR_GCS_FILE .') to copy your GCA file to the VM.
Comment: I am trying to use the function open() of the package `cloudstorage`. The problem is that this package works only in Python3, while my job is running under Python 2.7. Now, I get invalid syntax at this line: `def get_driver(driver: DriverName) -> Driver:`. Is there anyway to run my job under Python3? Otherwise, is there another function working on python 2.7 to read my files in GCS??
Comment: Or use the tensorflow.python.lib.io library as suggested in this [post](https://stackoverflow.com/questions/47942299/cloud-ml-unable-to-find-the-file-on-google-cloud-storage)
Comment: Thanks Guoqing Xu! that solves my problem of accessing my data once my job submitted! The Python library I am now using is gcs_client. and it is supported in Python 2.7.


use c++ preprocessor to autogenerate repetitive code

Question: I'm currently dealing with a piece of extremely repetitive code that is implementing and instantiating a series of template constructors. The general pattern is somewhat like this:
// preamble: some dummy classes to work with
class A{};
class B{};
class C{};
class D{};
class E{};
class F{};
class G{};

class X{};
class Y{};

// the actual class declaration, located in some header file

class MyClass {
  A* _a;
  B* _b;
  C* _c;
  D* _d;
  E* _e;
  F* _f;
  G* _g;

 public:
  template<class T> void foo(const std::vector<T>& args){};

  MyClass(A* a = NULL, B* b = NULL, C* c = NULL, D* d = NULL, E* e = NULL, F* f = NULL, G* g = NULL);
  template<class T> MyClass(A* a, B* b, C* c, D* d, E* e, F* f, G* g, std::vector<T> args1);
  template<class T> MyClass(A* a, B* b, C* c, D* d, E* e, F* f, std::vector<T> args1);
  template<class T> MyClass(A* a, B* b, C* c, D* d, E* e, std::vector<T> args1);
  template<class T> MyClass(A* a, B* b, C* c, D* d, std::vector<T> args1);
  template<class T> MyClass(A* a, B* b, C* c, std::vector<T> args1);
  template<class T> MyClass(A* a, B* b, std::vector<T> args1);
  template<class T> MyClass(A* a, std::vector<T> args1);
  template<class T> MyClass(std::vector<T> args1);
};

// default constructor, this is still fine

MyClass::MyClass(A* a, B* b, C* c, D* d, E* e, F* f, G* g) : _a(a),_b(b),_c(c),_d(c),_e(e),_f(f),_g(g) {};

// here the horribly repetitive part begins
// there are lots of repetitions of this block, every time with a slightly different signature

template<class T> MyClass(A* a, B* b, C* c, D* d, E* e, F* f, G* g, std::vector<T> args1) : MyClass(a,b,c,d,e,f,g) {
  foo<T>(args);
}
template MyClass<X>(A*, B*, C*, D*, E*, F*, G*, std::vector<X> args1);
template MyClass<Y>(A*, B*, C*, D*, E*, F*, G*, std::vector<Y> args1);

template<class T> MyClass(A* a, B* b, C* c, D* d, E* e, F* f, std::vector<T> args1) : MyClass(a,b,c,d,e,f) {
  foo<T>(args);
}
template MyClass<X>(A*, B*, C*, D*, E*, F*, std::vector<X> args1);
template MyClass<Y>(A*, B*, C*, D*, E*, F*, std::vector<Y> args1);

template<class T> MyClass(A* a, B* b, C* c, D* d, E* e, std::vector<T> args1) : MyClass(a,b,c,d,e) {
  foo<T>(args);
}
template MyClass<X>(A*, B*, C*, D*, E*, std::vector<X> args1);
template MyClass<Y>(A*, B*, C*, D*, E*, std::vector<Y> args1);

template<class T> MyClass(A* a, B* b, C* c, D* d, std::vector<T> args1) : MyClass(a,b,c,d) {
  foo<T>(args);
}
template MyClass<X>(A*, B*, C*, D*, std::vector<X> args1);
template MyClass<Y>(A*, B*, C*, D*, std::vector<Y> args1);

template<class T> MyClass(A* a, B* b, C* c, std::vector<T> args1) : MyClass(a,b,c) {
  foo<T>(args);
}
template MyClass<X>(A*, B*, C*, std::vector<X> args1);
template MyClass<Y>(A*, B*, C*, std::vector<Y> args1);

template<class T> MyClass(A* a, B* b, std::vector<T> args1) : MyClass(a,b) {
  foo<T>(args);
}
template MyClass<X>(A*, B*, std::vector<X> args1);
template MyClass<Y>(A*, B*, std::vector<Y> args1);

template<class T> MyClass(A* a, std::vector<T> args1) : MyClass(a) {
  foo<T>(args);
}
template MyClass<X>(A*, std::vector<X> args1);
template MyClass<Y>(A*, std::vector<Y> args1);

template<class T> MyClass(A* a, std::vector<T> args1) : MyClass() {
  foo<T>(args);
}
template MyClass<X>(std::vector<X> args1);
template MyClass<Y>(std::vector<Y> args1);

// here some main function just to make it compile

int main(){
  std::vector<X> x;
  MyClass c(NULL,NULL,NULL,x);
  return 1;
}

As you can see, there is a specific type of block that is repeated over and over again
template<class T> MyClass(ARG* arg, ..., const std::vector<T> &args) : Myclass(arg,...) { foo<T>(args); }
template MyClass<X>(ARG* arg, ..., const std::vector<X>& args)
template MyClass<Y>(ARG* arg, ..., const std::vector<Y>& args)

This code is, of course, a nightmare to maintain, and I find myself repeatedly using sed to edit the code, which is of course bad practice and bound to fail at some point.
I think the repetition could be abstracted away using some preprocessor macro
#define GENERATE_CONSTRUCTOR(...) ???

GENERATE_CONSTRUCTOR(A,a,B,b,C,c,D,d)

I would imagine that it would be possible to write GENERATE_CONSTRUCTOR  as some variadic preprocessor macro with a FOREACH loop, but unfortunately, all the documentation I could find on the topic of variadic preprocessor macros was highly confusing to me, and not terribly helpful since most examples are centered around some technique to wrap printf.
What would be a nice way to abstract away such repetitive code segments, possibly using preprocessor magic?
Comment: https://en.wikipedia.org/wiki/Variadic_template
Comment: `boost` has some kind of preprocessor `FOREACH` macro helper.
Comment: Aside: why not one constructor `template MyClass(std::vector args = {}, A* a = NULL, B* b = NULL, C* c = NULL, D* d = NULL, E* e = NULL, F* f = NULL, G* g = NULL);`?
Comment: @Caleth: good suggestion actually. In the specific scenario at hand, this is not an option because `A`, `B`, `C`, etc. partially inherit from each other, such that in some circumstances, the final object is needed to resolve confusing ambiguities in the way the function is called, but this is not a very good design anyway, so thanks for the suggestion!
Answer: My skills aren't enough to attempt variadic macros, but you can remove a lot of the repetitive code via regular old non-variadic macros, like this:
#include <stdio.h>
#include <vector>

#define PARAMS_1 A* a,                                     std::vector<T> args1
#define PARAMS_2 A* a, B* b,                               std::vector<T> args1
#define PARAMS_3 A* a, B* b, C* c,                         std::vector<T> args1
#define PARAMS_4 A* a, B* b, C* c, D* d,                   std::vector<T> args1
#define PARAMS_5 A* a, B* b, C* c, D* d, E* e,             std::vector<T> args1
#define PARAMS_6 A* a, B* b, C* c, D* d, E* e, F* f,       std::vector<T> args1
#define PARAMS_7 A* a, B* b, C* c, D* d, E* e, F* f, G* g, std::vector<T> args1

#define ARGS_1 a
#define ARGS_2 a,b
#define ARGS_3 a,b,c
#define ARGS_4 a,b,c,d
#define ARGS_5 a,b,c,d,e
#define ARGS_6 a,b,c,d,e,f
#define ARGS_7 a,b,c,d,e,f,g

#define DECLAREHEADER(x) template<class T> MyClass(PARAMS_##x)

// preamble: some dummy classes to work with
class A{};
class B{};
class C{};
class D{};
class E{};
class F{};
class G{};

class X{};
class Y{};

// the actual class declaration, located in some header file
class MyClass {
  A* _a;
  B* _b;
  C* _c;
  D* _d;
  E* _e;
  F* _f;
  G* _g;

 public:
  template<class T> void foo(const std::vector<T>& args){};

  MyClass(A* a = NULL, B* b = NULL, C* c = NULL, D* d = NULL, E* e = NULL, F* f = NULL, G* g = NULL);

  DECLAREHEADER(7);
  DECLAREHEADER(6);
  DECLAREHEADER(5);
  DECLAREHEADER(4);
  DECLAREHEADER(3);
  DECLAREHEADER(2);
  DECLAREHEADER(1);
};

// default constructor, this is still fine
MyClass::MyClass(A* a, B* b, C* c, D* d, E* e, F* f, G* g) : _a(a),_b(b),_c(c),_d(d),_e(e),_f(f),_g(g) {}

#define DECLAREALL(x) template<class T> MyClass :: MyClass(PARAMS_##x) : MyClass(ARGS_##x) { foo<T>(args1); }

DECLAREALL(7);
DECLAREALL(6);
DECLAREALL(5);
DECLAREALL(4);
DECLAREALL(3);
DECLAREALL(2);
DECLAREALL(1);

int main(){
  std::vector<X> x;
  MyClass c(NULL,NULL,NULL,x);
  return 1;
}

Note that I omitted the template MyClass<X> and template MyClass<Y> lines because I wasn't sure what their intent was, but you should be able to add them back into the DECLAREALL macro's definition easily enough.


The totient of a factor of a number divides the totient of the number.

Question: Given any number and one of its factors, how can you show that the totient of the factor divides the totient of the original number?
Comment: What do you mean $\phi(mn)=\phi(m)+\phi(n)$?
Comment: I know that the totient of a number is equal to the sum of the totient of each of its factors so could we not make that statement since mn can be factored into m and n?
Answer:
If $p\mid n$ then $\phi(pn)=p\phi(n)$.
If $p\nmid n$ then $\phi(pn)=(p-1)\phi(n)$.
Comment: How would I exactly use this? I don't have that either m or n are prime.
Answer: Expanding on Hagen's answer: Let $m\mid n$, we need to show that $\phi(m)\mid\phi(n)$. If $m$ is prime then we are done, since $\phi(pm)=p\phi(m)$. If $m$ is not prime, then it can be decomposed into a product of primes, say $\prod p^\alpha$. Then
$$\phi(m)=\phi(\prod p^\alpha)=\prod p^{\alpha-1}\prod(p-1).$$
Now, $\phi(n)$ can be expressed as this product times the totient function of all the extra prime factors $n$ has that is not in $m$. Think of this as because we have "taken out" all the prime powers of $m$ to get that product, and we can do the same thing for $n$ and still have "leftovers". The conclusion follows.


htmlText not showing bold or italics font

Question: So I have a MovieClip asset with a dynamic textfield sitting inside of it.  I export my .fla as a .swc to use within Flash Builder 4, and create instances of the asset with code, populating the text dynamically from XML.
My issue is that even though I have htmlText enabled, bold and italics tags don't appear to be working.  I have a feeling it is because when I created the asset in Flash CS4, the text field makes you specify the font, and the subset of that to use (Regular, Bold, Oblique, etc).
Is there any way to get the htmlText to render bold and italics tags properly without having to completely rethink the way I'm creating all these fields?
Answer: Okay I found a good solution, you need to make sure that the Linkage settings for the embedded fonts are set to export for actionscript OR that that font is used in some textfield in the SWF, otherwise, Flash thinks that the font is not being used and just doesn't embed it.
Answer: Without seeing how you are formatting your htmlText, I am guessing that you are trying to use the
< bold >  and      tags?
I had a lot of trouble with these myself. I solved the majority of issues by loading an external stylesheet and applying it to the htmlText TextField. However, there were times when I did not want to define an entire style for one or two instances of italic or bold text.
So, I found a simple solution by using the   tag and set the bold, or italics through the style property:
this is italic

Hope this helps.
Answer: I think it's worth noting that Flash wants the old  and  tags, according to the documentation.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html#htmlText
Comment: Also, if your font is split up into several files, you'll need to embed those other fonts too. For example, if I used Helvetiva Neue 45 Light, and I added  tags to parts of the dynamic text, then I would also have to embed Helvetica Neue 45 Light Italic (into another textfield) so that it's available to the Flash piece.
Hope this helps someone.


How to set new AUTO_INCREMENT value?

Question: I have the following statement in my module code:
db_query("ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = :number", array(':number' => $start_value));

During SimpleTest I get the following error message:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near ''20000'' at
line 1: ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = :value; Array (
[:value] => 20000 ) in _tripletex_add_invoice_log() (line 1769 of
/var/www/d7/sites/all/modules/tripletex/tripletex.module).

Why?
Answer: Parameter replacement only works for WHERE clauses, it won't work for the kind of query you're trying to run.
You need to insert $start_value directly into the query string. If that value comes from an un-trustworthy source then obviously you need to sanitise it and make sure it falls within the correct bounds yourself:
$start_value = (int)$start_value; // Make sure it's an integer

// Do any other checks you need to here (bounds checking, etc.)

// Build the query string and run it
$sql = "ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = $start_value";
db_query($sql);

How to set new AUTO_INCREMENT value?


Show that the set $A=\{x\in l_2:|x_n|\le \dfrac{1}{n}\}$ is compact in $l_2$.

Question:
Show that the set $A=\{x\in l_2:|x_n|\le \dfrac{1}{n}\}$ is compact in $l_2$.

A set is compact iff it is complete and totally bounded.
Step 1: To show that $A$ is complete.
Let $(x_k)$ be a Cauchy sequence in $A$ such that $(x_k)\to x$.
Taking $x_k=(x_1^{(k)},x_2^{(k)},\ldots ,x_n^{(k)})\to (x_1,x_2,\ldots,x_n)$.
To show that $\sum x_i^2<\infty$ which can be shown using Minkowski and Triangle Inequality.
Step  2: To show that $A$ is totally bounded.Let $r>0$. We have to find a finite subset $A_r$ of $A$ such that $A=\cup_{a\in A_r} B(a,r)$.
I am stuck here.Will you please say how to find that finite subset.
Answer: The idea here is to reduce the problem to a finite dimensional one.
Choose $\epsilon>0$, then we need to find a finite $\epsilon $ net.
Choose $N$ such that $\sqrt{\sum_{k=N+1}^\infty {1 \over k^2}} < {1 \over 2} \epsilon$.
Consider the space $A'=\{ x \in A | x_k = 0, k > N \}$, and note that it
is compact (can identify with a closed and bounded subset of $\mathbb{R}^{N}$), hence there is a finite ${1 \over 2} \epsilon $ net
for $A'$, let this set be $F$.
Now choose $x \in A$, and let $x'=(x_1,....,x_n,0,0,...)$. Note that
$\|x-x'\| \le \sqrt{\sum_{k=N+1}^\infty |x_k|^2} \le \sqrt{\sum_{k=N+1}^\infty {1 \over k^2}} < {1 \over 2} \epsilon$.
Now choose $x'' \in F$ such that $\|x'-x''\| < {1 \over 2} \epsilon$, then
we have $\|x-x''\| < \epsilon$.
Hence $F$ is a finite $\epsilon$ net for $A$.
Comment: I can't understand why $A'$ is compact (or totally bounded)
Comment: @Beginner Do you understand what an $\epsilon$ net is?
Comment: Yes, but $A'$ is so big(infinite), how can it be covered by a $\epsilon$-net
Comment: @Beginner $A'$ is essentially a closed and bounded subset of a finite dimensional space and so it compact.
Comment: I got it, so "this truncated sequence space" is like a $N$-dimensional space $R^N$. Thank you for your help.


Domain Name language negotiation and mobile prefix m

Question: I have a question regarding the domain name language negotiation.
I have 3 languages and the following domains:

de.domain.com
en.domain.com
fr.domain.com

When I set this as the domains for each language and use the domain name language negotiation everything works as expected.
My problem is that I have an adaptive mobile theme and I have to use following domains for that:

m.de.domain.com
m.en.domain.com
m.fr.domain.com

How can I achieve that those urls point to the correct language (de, en, fr). Now, all point to the default language (de).
Any help?
Comment: Just curious - why m prefix? Can't you detect from http headers if user is on mobile? Can't your theme hide things based on actual screen it gets displayed on?
Comment: In my oppinion its not a good thing to have different content served from the same url. think about a caching in front of the web server (varnish for example).
Comment: That's some valid point all right. On the other hand current mobile devices can usually accept normal page and you can do the most of small-screen logic in CSS with [media set to handheld](http://www.w3schools.com/css/css_mediatypes.asp).
Comment: That's totally true. But the customer has preferred adaptive over responsive for this project. So i have to deal with that now. Responsive would make my live easier at all ;)
Comment: can you make it `de.m.` instead of `m.de.`? If it's technically impossible / not easy, it's a shame both mechanisms insist on using first part for detection.
Comment: Hmm, what would that change ? de.m or m.de, both are different domains. Or what do you think ?
Comment: Language recognition looks on first part of a domain, right? so if you could put `.de` as first part, it would be properly recognized as language prefix, no matter if there is `.m` after it or not.
Answer: Take a look at the Language Negotiation API, specifically hook_language_negotiation_info_alter.  With this hook, you can replace the default URL based language negotiation callback function with one that respects the m. prefix.
Something like this should get you started.
function mymodule_language_negotiation_info_alter(&$negotiation_info) {
  // Replace the core function with our own function.
  module_load_include('language', 'inc', 'language.negotiation');
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['callbacks']['language'] = 'mymodule_from_url';
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module';
}

function mymodule_from_url($languages) {
    // Your version of locale_language_from_url() that ignores the m. prefix.
}

For reference, the core function that handles language negotiation based on URL is locale_language_from_url.
Comment: Thank you zroger. I think this way i can achieve my goal :)


Has there ever been a sport where the world's best player won so much they got bored?

Question: Per title. Are there any sports where the best player is so dominant and wins so many tournaments that they got bored and retired to do/play something else? I'm not asking about people who quit or retired while ranked world number #1, but about people who state that they're leaving because there's no challenge left for them in the discipline.
Offhand I can't think of any examples. The closest is Chess world champion Magnus Carlsen, who recently decided not to defend his World Champion title because he lost motivation. Still, he isn't quitting chess entirely - only World Championship matches.
Comment: Potentially also Michael Jordan retiring from basketball to play baseball?
Comment: It's stretching it a bit, but there are plenty of boxers/MMA fighters who have quit one weight class to fight at another. I'm pretty sure the *real* reason in those cases is "make more money" but the claim is often "beaten everyone here, moving onto more challenges".
Comment: Eric Cantona won six league titles in seven years, and then retired from football aged only 30. He'd be a pretty good candidate too, though I can't find a statement from him to that effect.
Answer: Ronnie O'Sullivan
In 2013, English snooker player Ronnie O'Sullivan retired from the game to work on a pig farm.
The Independent

Why do we want Ronnie O'Sullivan to soldier on through another year of angst? Why do we argue with those who say that he should make up his mind about either playing snooker or hiding away down on the farm and then give us all a bit of peace?

Comeback
Ronnie O'Sullivan has since come back from his retirement, but has again expressed his boredom with the sport.
Daily star

Ronnie O'Sullivan has said that despite his recent victory in the European Masters ealier this week, he now finds snooker boring and does not give a "monkey's" about winning the World Championship again

World number one
Despite Ronnie O'Sullivan being the current world champion, and world number one, Ronnie O'Sullivan has once retired from snooker, and continues to express his boredom with the sport.
Wikipedia

Ronald Antonio O'Sullivan OBE (born 5 December 1975) is an English professional snooker player who is the current world champion and world number one. Widely recognised as one of the most talented and accomplished players in the sport's history, he has won the World Snooker Championship seven times, a modern-era record he holds jointly with Stephen Hendry. He has won a record seven Masters and a record seven UK Championship titles for a total of 21 Triple Crown titles, the most achieved by any player. He holds the record for the most ranking titles, with 39, and has been world number one on multiple occasions.
Answer: Hm, she did not state in that she was actually bored but Ashleigh Barty quit playing tennis while at the no 1 postion in the rankings. OK, you discarded being at no 1 but still, she said she wanted to pursue other ventures.


Find the more appropriate fit by using term.plot in GAMLSS

Question: I'm comparing several GAMLSS models and was wondering how I might use the term.plot to identify the best model/fit. What type of information can we get from this graph? Can I argue that the model with a wider confidence interval performs worse (just looking at this plot, how do you determine on the model's performance)?
Answer: Selecting the best model can be
(i) by choosing the fitted model with lowest generalized Akaike information criterion GAIC(k) for a user chosen penalty k for each effective degree of freedom in the model.
[e.g k=2 for AIC or k=log(n) for BIC,
although I prefer k=4 for a Chi-squared test (Chi-Sq with 1 df at 5% =3.84, approx 4]
(ii) looking at the residual (multiple) worm plots and Q-statistics.
This especially highlights problems in the tails of the fitted models.
Comment: thanks so much for the reply. I made the question more clear here,

https://stats.stackexchange.com/questions/601860/how-to-find-the-appropriate-model-to-apply-gamlss
 so I would be so thankful if you share your thouth with me regarding the question. I am using GAMLSS to calculate the centile curves based on LMS method including two independent variables. For the several dependent variables, the worm plots look fine but not the Q-statitics (as there are the Z-score >2)


How to find out the combinations of Views arguments that have the most Views result

Question: I have a node view with 2 arguments in URL my-view/%1/%2.
Both arguments %1 and %2 are Taxonomy Term ID.
I would like to make a page that lists the number of the View result per argument combination and order them by the number of the result.
For example, Something looking like this:
  %1 |  %2  | Resulst
  10 |  20  | 13
  10 |  21  | 7
  13 |  21  | 5

Is there anyway to make this kind of page?
My goal is to find out what the top 20 combinations of the 2 arguments that have the most nodes attached to.
Comment: I am not sure what you mean by top 20 combinations. With two taxonomy terms you have 4 combinations: nodes with neither the terms, nodes with term A, nodes with term B, nodes with both the terms.
Answer: Inside Drupal, this would take some real custom magic. But, let's say for example, you wanted to show
pets/birds,
pets/cats
both birds and cats would be arguments off the main Views page of pets. BUT - if you had a Google Analytics account, which does not understand Drupal arguments, you could easily decipher which page received what number of visitors.
Because Google will never discriminate vs what is a page and what is an argument, you can easily see what would be most popular as a result.
Comment: Thanks. but there seems to be some misunderstanding. "Result" I'm talking about is not the result of page visitors but the result of View (the number of nodes in my case). I also change the tilt of this question a bit.
Answer: You could certainly do something like this in the crude but effective dull ax category:
function YOURMODULE_menu() {
  $items=array();

  $items['xyzzy'] = array(
    'title' => 'Two Tax Terms',
    'page callback' => 'YOURMODULE_xyzzy',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // any other custom menu items here

  return $items;

}

function YOURMODULE_xyzzy() {

  $first=array();
  $second=array();

  $matrix=array();

  // get all of the term ids on your system...

  $query=db_query('SELECT tid FROM {term_data}');

  while ($result=db_fetch_object($query)) {
    $first[]=$result->tid;
    $second[]=$result->tid;
  }

  // cycle through all of the possible permutations of a node tagged with both of them
  // (skip nodes tagged with both in opposite order, eg tagged with 1 & 2 == 2 & 1)

  $start=microtime(TRUE);
  foreach ($first as $f) {
    foreach ($second as $s) {

      $foo=0;
      $query=db_query('SELECT node.nid AS nid FROM node node INNER JOIN term_node term_node ON node.vid = term_node.vid LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid AND term_node2.tid != %d WHERE (term_node.tid = %d ) AND (term_node2.tid = %d )', $f, $f, $s);
      while ($result=db_fetch_object($query)) {
        $foo++;
      }
      if ($foo && empty($matrix[$s . ' & ' . $f])) {
        $matrix[$f . ' & ' . $s]=$foo;
      }

    }
  }
  $stop=microtime(TRUE);
  $total=$stop - $start;

  arsort($matrix);

  $top20=array_slice($matrix, 0, 20);

  return '
' . print_r($top20, true) . '

TOOK ' . $total . ' SECONDS
';
}

but be prepared for a long wait if you have lots of terms.  Also, I just copied and pasted the second db_query sql out of Views when I ran out of memory calling one over and over inside those two foreach()'s so it's not using {table}s and all the other good stuff it could.
I am also sure there is a COUNT(*) sql construct that is much more efficient than my $foo but $query->num_rows isn't universally available as I found out when I tested this on a production site instead of just locally on my mac :)
Comment: and as an FYI, with 250 terms, this took about 8 secs to run locally on a mac and about 70 seconds on a pantheon hosted site so to say it's inefficient is being polite.
Comment: Thanks. Can you please tell me how to use this code? I created a custom module and then installed it but then what should I do? Sorry for my question but I'm not a coder ;)
Comment: this would be a page callback to a menu item defined in your module.  it is for drupal 6.  if you are running drupal 6, which you've tagged this with, I'll gladly flesh it out more, but if drupal 7, you're on your own as the sql calls are totally different there.
Comment: Thanks. Yes I'm on Drupal 6.  I'd greatly appreciate your help.
Comment: I've added the menu hook you'd need.  Just copy and paste all of the code above into YOURMODULE.module (after the opening php :) and clear your caches and if all is good in the world you should be able to goto www.yourhost.com/xyzzy and see the results :)
Comment: Thaks a lot. I tried it but due to the timeout I couldn't get it work as I have a few thousand terms. So I'll make a local copy site and try it again.
Comment: Yeah, 1000 items will result in 1000 x 1000 or a million queries :)


Is correlation equivalent to association?

Question: My statistics professor claims that the word "correlation" applies strictly to linear relationships between variates, whereas the word "association" applies broadly to any type of relationship. In other words, he claims the term "non-linear correlation" is an oxymoron.
From what I can make of this section in the Wikipedia article on "Correlation and dependence", the Pearson correlation coefficient describes the degree of "linearity" in the relationship between two variates. This suggests that the term "correlation" does in fact apply exclusively to linear relationships.
On the other hand, a quick Google search for "non-linear correlation" turns up a number of published papers that use the term.
Is my professor correct, or is "correlation" simply a synonym of "association"?
Comment: Conversely there is also 'linear association'.
Answer: No; correlation is not equivalent to association.  However, the meaning of correlation is dependent upon context.
The classical statistics definition is, to quote from Kotz and Johnson's Encyclopedia of Statistical Sciences "a measure of the strength of of the linear relationship between two random variables".  In mathematical statistics "correlation" seems to generally have this interpretation.
In applied areas where data is commonly ordinal rather than numeric (e.g., psychometrics and market research) this definition is not so helpful as the concept of linearity assumes data that has interval-scale properties.  Consequently, in these fields correlation is instead interpreted as indicating a monotonically increasing or decreasing bivariate pattern or, a correlation of the ranks.  A number of non-parametric correlation statistics have been developed specifically for this (e.g., Spearman's correlation and Kendall's tau-b).  These are sometimes referred to as "non-linear correlations" because they are correlation statistics that do not assume linearity.
Amongst non-statisticians correlation often means association (sometimes with and sometimes without a causal connotation).  Irrespective of the etymology of correlation, the reality is that amongst non-statisticians it has this broader meaning and no amount of chastising them for inappropriate usage is likely to change this.  I have done a "google" and it seems that some of the uses of non-linear correlation seem to be of this kind (in particular, it seems that some people use the term to denote a smoothish non-linear relationship between numeric variables).
The context-dependent nature of the term "non-linear correlation" perhaps means it is ambiguous and should not be used.  As regards "correlation", you need to work out the context of the person using the term in order to know what they mean.
Comment: +1 A thoughtful and knowledgeable answer.  Please consider qualifying the initial "no," because it takes a bit of reading and thought to understand whether it means "no, the professor is not correct" or "no, 'correlation' is not a synonym for 'causation'," or the conjunction of the two.
Comment: So what is association, then?
Comment: This is an excellent answer (and question) that gets some wider issues about terminology, language and communication in general that we all need to take care about.
Comment: Thanks for the comment; I've edited my answer accordingly.
Answer: I don't see much point in trying to disentangle the terms "correlation" and "association."  After all, Pearson himself (and others) developed a measure of nonlinear relationship which they named the "correlation ratio."
Comment: Yes it seems at this point they are quite hard to disentangle, especially given history (e.g., as you mention) and social perception.
Answer: There seems to be misunderstanding of association. Measures of association (effect size) are inherent in quantitative analysis, not qualitative.
Comment: Maybe you should think of turning that into a comment. Answers are usually a bit more extended
Comment: @Alessandro Yup, more needed for an answer, but the OP doesn't have enough reputation (>+50) to comment quite yet. Maybe the moderator can convert it into a comment for him.
Answer: I would say that correlation applies to quantitative data and association to qualitative data and both have no obligatory causal relationship.
Comment: What do you mean by "association to qualitative data"?
Answer: The idea that the weight (of a man) is not correlated with the height (because the corresponding function is of 3rd degree, not linear) seems very strange to me. Linear correlation should be treated as a special case of association.
Comment: But which (or whose) idea are you arguing against? Correlation can be calculated here as (b) correlation between observed and predicted values from any combination of terms as well as (presumably) (a) non-zero correlation between weight and height.
Answer: Correlation and association are different. Correlation describes the three types of relationship positive, negative and non-correlated. It also describe the magnitude of correlation from 0 to 1, from -1 to 0. The association does not reveals what types of association and how much association.
Comment: What is the question here?
Comment: As you don't define association or explain how it differs, it is hard to see why you think you answered the question. This doesn't add to previous answers.
Answer: As far as the linearity is concerned the response by Tim and Nick Cox covered it completely. Where I thought I might be able to contribute is a clean way to think about the difference between association and correlation.
Association --- measures how closely related two variables are (i.e. whether they are dependent or independent).
Correlation --- measures in what way two variables are related (i.e. positive or negative).

In the end, I would argue that you can never go wrong treating them distinctly it will help with interpretion and analyses in the long run. Hope this helps.
Comment: I didn't downvote this, and thanks for the positive comment ( I just applied an edit). Unfortunately, it muddies the discussion. Association  measures often have nothing  to do with which variable if any is dependent.  Correlation measures "how closely" too: each definition of correlation is based on a specific definition of the way in which variables are (ideally) related (linearly, monotonicly, etc.) The family examples really don't help, even as analogies: e.g.mother, father, uncle are not quantitative variables in the example. So, sorry, but the distinction you make isn't clean at all.
Comment: Also, "shared blood" and "estrangement" are quite different!


Offscreen Canvas in Web Worker not Updating when Editing Rendering Context

Question: context: I am using a mapping library called openglobus to render a 3d planet. Openglobus has a tile layer, where you can give a function that generates tiles, that function can return canvasses. So what I made is a function that generates these canvasses to get rendered as a map layer on that globe. To keep things performant, this function is asynchronous and calls upon a webworker to do the actual tile generation. So the canvas is made in the main thread by the tile generator function. Then the canvas transfers its control to offscreen. next the webworker gets on it with all required parameters. And when the web worker finishes, the canvas is applied to the globe.
Tile generator function looks like this (WM stands for Worker Manager that distributes requests over the multiple workers):
export default function BaseLayer(WM) {
  return new layer.CanvasTiles(`cnv`, {
    isBaseLayer: true,
    drawTile: function (material, applyCanvas) {
      const { tileZoom, tileX, tileY } = material.segment;
      const extent = material.segment.getExtentLonLat();
      const res = 700;

      const cnv = document.createElement("canvas");
      cnv.width = res;
      cnv.height = res;

      const offscreen = cnv.transferControlToOffscreen();

      WM.makeBaseTile({
        extent,
        tileX,
        tileY,
        tileZoom,
        res,
        offscreen,
      }).then(_ => applyCanvas(cnv));
    },
  });
}

Workers are created when the page loads and are not destroyed. they are reused for every tile and cache data that is used often. Worker code that draws these tiles is structured like this (simplified):
self.onmessage = async (e) => {
  const { id, extent, tileX, tileY, tileZoom, res, offscreen } = e.data;

  const cnv = offscreen
  const ctx = cnv.getContext("2d");

  // draw fallback background color
  ctx.fillStyle = g.biomeColors[13]; //"#85a478";
  ctx.fillRect(0, 0, res, res);

  // Fetching data from online resources to draw
  let [biomeRes, waterRes, hillshade] = await Promise.all([...axios get requests]);

  // before water is added, draw the color of the biome (background)
  biomeRes.data.forEach((BIOME) => {
    BIOME.forEach((b) => {
      // custom function to draw geometries onto canvasses
      drawShape(ctx, b, color, "#000000", e.data, false, 0, false);
    });
  });

  // if water is an empty array, there is no water in this tile
  if (waterRes.length) {
    // jiggle is a custom function to add noise to geometries
    const water = jiggle(waterRes, extent, tileZoom, 3, 2);

    water.forEach((p) =>
      drawShape(ctx, p, "#5b99a6", "#2d4d54", e.data, false, g.outline)
    );
    }
  }

  // toggle tile borders on/off
  if (true) {
    ctx.beginPath();
    ctx.rect(0, 0, cnv.width, cnv.height);
    ctx.lineWidth = 3;
    ctx.strokeStyle = "black";
    ctx.stroke();
    ctx.closePath();

    ctx.font = "50px serif";
    ctx.fillStyle = "black";
    ctx.fillText(`${tileZoom}`, 10, 60);
  }

  // draw hillshade, but blend by multiply to avoid white background
  // make opacity fade out when it reaches zoom level of 15, start at 10
  const img = await createImageBitmap(await hillshade.blob());
  ctx.globalCompositeOperation = "multiply";
  ctx.globalAlpha = Math.max(0, 1 - (tileZoom - 10) / 5);
  ctx.drawImage(img, 0, 0, res, res);
  ctx.globalCompositeOperation = "source-over";
  ctx.globalAlpha = 1.0;

  // ctx.commit();
  postMessage({ origin: JSON.stringify([id, tileX, tileY]) });

problem: When I coded it this way, I had issues with some tiles not loading. Some of them do, but some of them don't. It happens on both Chrome and Firefox so I don't think it is related to this post, or this existing Chrome bug (that bug also is marked as fixed already).

The issue seems to be most prevalent on complexer tiles that take longer to generate. But it is all asynchronous so I don't understand why that could be the reason.
I did find a fix however. That's why I don't think this is an issue with the openglobus library, but with the way offscreencanvasses work. By using the commit() function on the OffscreenCanvasRenderingContext2D at the end of the worker's process, I get a perfectly working example:

However this commit function is only available for Safari en Firefox browsers, and not for Chrome(ium) based browsers. Does anyone better understand why this happens without the commit function, or how this can be fixed in Chrome? I have been looking for a while already but there doesn't seem to be an equivalent to the commit function.
Comment: I see, so this code is not using `requestAnimationFrame` from inside the Worker. So when it sends its message back, the browser hasn't updated the placeholder canvas yet. I shared the 2 common ways to deal with that, but I leave you find which is best for your library. (IMO, and I said in my answer, if possible the *best™* would be to pass `ImageBitmap` objects directly to your library.)
Comment: Please show the worker side code. Are you drawing in `requestAnimationFrame` callbacks? Is the worker killed every frame? Also note that [we're in the process of removing `commit()`](https://github.com/whatwg/html/pull/9979) from the standards.
Comment: Thanks for the response @Kaiido! I have added a snippet of the worker-side code. The openglobus library does use the requestAnimationFrame callbacks, but that is abstracted away in the library. I do not interact with that directly, nor do I know the ins and outs of how exactly it is implemented. The workers are not killed every frame. They are reused and cache a lot of frequently used data.
Answer: The content of a placeholder <canvas> to which the controlling OffscreenCanvas has been sent to a worker is only updated in the "update the rendering" steps of the Worker. You need to wait for that "update the rendering" happened before being able to access the content on the placeholder <canvas>.
The code you shared is not using requestAnimationFrame from inside the Worker. So when it sends its message back to the main thread (which I assume causes the Promise to resolve), the browser may not have updated the placeholder canvas yet, and when the library will try to use the placeholder <canvas>, it will still be empty.

Keep using a placeholder <canvas> and wait for the next painting frame, e.g. in your Worker you'd execute the drawing in a requestAnimationFrame() callback, then notify your main thread through postMessage() which should be handled in the next task, after the update has been done.

Do not use a placeholder <canvas> and instead transfer your OffscreenCanvas content to ImageBitmap objects, with the transferToImageBitmap() method which will force a synchronous rendering into the ImageBitmap. The best would be to feed your library's code directly with the returned ImageBitmap, but if it really needs to use a <canvas> element, then you can create an ImageBitmapRenderingContext from the element (getContext("bitmaprenderer") and feed it the ImageBitmap (ctx.transferFromImageBitmap(bmp)).

Also note that we're in the process of removing commit() from the standards. It's best to not think of it as a solution at all.
Comment: (In Chrome and probably in Safari), Transferring an ImageBitmap is way more performant than dealing with raw pixel data. You just move a pointer to a bitmap that can be reused by the GPU with almost no overhead. You can even transfer it from your Worker to the main thread. I know Firefox still hasn't developped ImageBitmap appropriately but rather ise some CPU baked shenanigans, and thus in some cases it might be slower than other solutions there, but I don't think it applies to this case.
Comment: Sending back the Bitmap also required very little rewriting and works like a charm! Because there is no need for it to happen on the main thread, the worker will now also create its own offscreen canvas. everything behaves like expected on Chrome and there indeed does not seem a noticeable difference between Chrome and Firefox. I cannot find the words to express my gratitude! This issue has been on my radar for too long, thanks!
Comment: Thanks for the elaborate explanation! It does make sense to me and I didn't know you could call a requestAnimationFrame from a Web Worker. I see how that could be a valid solution. The idea of sending an image texture back from the worker is an idea I had tried before (raw pixel data, so not performant at all), but added a lot of overhead. Would that also be the case when sending back an ImageBitmap? Because you do mention in your comment on the question itself that that would be the best™ solution, even over the requestAnimationFrame-route?
Comment: One more thing. although it works on Chrome now, there is a lot of lag and the main thread freezes or sometimes even crashes to a black screen during moments where a lot of tiles should finish rendering. The main thread freezes but in the profiler the main thread is practically empty. It appears as if transferring the bitmap using cnv.transferToImageBitmap() and posting that result back to the main thread goes not as smooth. On firefox however, this is not an issue. Do you think this could still be related to this issue? If not, I'd gladly open a new issue.


Get scanf to quit when it reads a newline?

Question: If I input 5 5 at the terminal, press enter, and press enter again, I want to exit out of the loop.
int readCoefficents(double complex *c){
    int i = 0;
    double real;
    double img;
    while(scanf("%f %f", &real, &img) == 2)
        c[i++] = real + img * I;

    c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1
    return i;
}

Obviously, that code isn't doing the job for me (and yes, I know there is a buffer overflow waiting to happen).
scanf won't quit unless I type in a letter (or some non-numeric, not whitespace string). How do I get scanf to quit after reading an empty line?
Comment: In case you needed more reasons to avoid using `scanf`: http://c-faq.com/stdio/scanfprobs.html
Answer: Use fgets to read console input:
   int res = 2;
   while (res == 2) {
       char buf[100];
       fgets(buf, sizeof(buf), stdin);
       res = sscanf(buf, "%f %f", &real, &img);
       if (res == 2)
           c[i++] = real + img * I;
   }
   c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1
   return i;

Comment: That declaration is perfectly fine.
Comment: Giving you the credit since you mentioned fgets and sscanf first.
Comment: Thanks, just realised c probably won't let you declare the buffer inside the while loop but the concept is there.
Answer: The specific problem you're having is that a scanf format string of %f will skip white space (including newlines) until it finds an actual character to scan. From the c99 standard:

A conversion specification is executed in the following steps:
     -   Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a '[', 'c', or 'n' specifier.

and, elsewhere, describing isspace():

The standard white-space characters are the following: space ' ', form feed '\f', new-line '\n', carriage return '\r', horizontal tab '\t', and vertical tab '\v'.

Your best bet is to use fgets to get the line (and this can be protected from buffer overflow very easily), then use sscanf on the resultant line.
The scanf function is one of those ones you should look at very warily. The following piece of code is one I often use to handle line input:
#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        // Extra NL since my system doesn't output that on EOF.
        printf ("\nNo input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long [%s]\n", buff);
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

Testing it with various combinations:
pax> ./prog
Enter string>[CTRL-D]
No input

pax> ./prog
Enter string> a
OK [a]

pax> ./prog
Enter string> hello
OK [hello]

pax> ./prog
Enter string> hello there
Input too long [hello the]

pax> ./prog
Enter string> i am pax
OK [i am pax]

What I would do is to use this function to get a line safely, then simply use:
sscanf (buffer, "%f %f", &real, &img)

to get the actual values (and check the count).

In fact, here's a complete program which is closer to what you want:
#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

int main (void) {
    int i = 1, rc;
    char prompt[50], buff[50];
    float real, imag;

    while (1) {
        sprintf (prompt, "\nEnter real and imaginary for #%3d: ", i);
        rc = getLine (prompt, buff, sizeof(buff));
        if (rc == NO_INPUT) break;
        if (*buff == '\0') break;

        if (rc == TOO_LONG) {
            printf ("** Input too long [%s]...\n", buff);
        }

        if (sscanf (buff, "%f %f", &real, &imag) == 2) {
            printf ("Values were %f and %f\n", real, imag);
            i++;
        } else {
            printf ("** Invalid input [%s]\n", buff);
        }
    }

    return 0;
}

along with a test run:
pax> ./testprog

Enter real and imaginary for #  1: hello
** Invalid input [hello]

Enter real and imaginary for #  1: hello there
** Invalid input [hello there]

Enter real and imaginary for #  1: 1
** Invalid input [1]

Enter real and imaginary for #  1: 1.23 4.56
Values were 1.230000 and 4.560000

Enter real and imaginary for #  2:

pax> _

Comment: +1 Using `scanf` to read input from the user often introduces problems like this.  It is usually much less error-prone to simply read the input as a string and then parse the string.
Answer: There's a way to do what you want using just scanf:
int readCoefficents(double complex *c) {
    int i = 0;
    double real;
    double img;
    char buf[2];
    while (scanf("%1[\n]", buf) == 0) {         // loop until a blank line or EOF
        if (scanf("%lf %lf", &real, &img) == 2) // read two floats
            c[i++] = real + img * I;
        scanf("%*[^\n]");                       // skip the rest of the line
        scanf("%*1[\n]");                       // and the newline
    }
    c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1
    return i;
}

If the user only enters 1 float on a line, it will read the next line for the second value.  If any random garbage is entered, it will skip up to a newline and try again with the next line.  Otherwise, it will just go on reading pairs of float values until the user enters a blank line or an EOF is reached.
Answer: re PAXDIABLO solution: it does not work properly with EMPTY line entered by user, so this line shall be added in your getLine() function
if (strlen(buff) <= 1) return NO_INPUT;

after the line:
if (fgets (buff, sz, stdin) == NULL)
    return NO_INPUT;

So it will become :
...
   if (strlen(buff) <= 1) return NO_INPUT;
   if (fgets (buff, sz, stdin) == NULL) return NO_INPUT;
....

Answer: Instead of
while(scanf("%f %f", &real, &img) == 2)

try
while(scanf("%f %f%*c", &real, &img) == 2)

scanf("%f%*c", &myfloat); // will read a float and all eventual characters after it


Insert data in selected columns

Question: I am using cakephp with php, I have table with field id having data type auto number.
In my form I do not have any field with id that's why it sets blank in my model and when I tries to save data it gives error.
how can I insert data into selected columns using model in cakephp?
Answer: When you pull the form data, make sure you are using an array with the model name and field names. For example, if you are saving a book to the book model, the array would look something like:
<code>$data['Book']['name'] = 'Title of Book';
$data['Book']['author'] = 'Name of Author';
$data['Book']['pages'] = 205; // number of pages
</code>
Then when you save the data, you must call create, then save:
<code>$this->Book->create();
$this->Book->save($data);
</code>
This will automatically add the ID (whether auto-increment or UUID) and save the new record.

Insert data in selected columns


C# Events and Control Interaction

Question: I am currently refactoring some of my old code that is pretty terrible.  I will have a class that creates a Treeview, populates the node, etc and is displayed on a Winform.
Each node on the Treeview represents some data and when the user clicks on that then a datagridview is also displayed on the Winform.  The datagridview will be generated within a new class also.
My idea on this is, when the Winform Loads, create and display the Treeview and use an event to monitor for node clicks.  When the Winform handles such an event, then it creates the datagrid object and diplays that.
IS this the best way to architect this?
Thanks.
Answer: Yes, what you describe is a standard way to do things in WinForms.
You don't need to create the DataGridView every time though - just place it on the Form and in the event handler load the data from somewhere and change the contents of the DataGridView by assigning to DataGridView.DataSource.
In the form designer, define columns for DataGridView and set their DataPropertyName to the names of the corresponding properties of the data objects in the collection.
Note: the data assigned to the DataGridView.DataSource can be a collection of objects or also a DataTable if you are using ADO.NET to read the objects from a database.
Answer: Just use the TreeView.AfterSelect event.  It fires anytime the user selects another node, either by keyboard or mouse.  Be sure to dispose the old DGV if you replace it completely.

C# Events and Control Interaction


Vue3 how send props to created child component

Question: Props are initialized, but after .mount they disappear. How should I properly setup props with dynamically loaded components?
import {createApp} from 'vue'

blockView = createApp(Block);
blockView.props = {
    type: json['type'],
    title: json['title'],
    subtitle: json['subtitle']
}
blockView.mount(this.$refs.container)

Answer: Props are not available to the App, just components, however I've found that these work for passing values to an appplication.
1. Use inject/provide
const app = Vue.createApp({
    inject: ['name'],
    // ...etc
})
app.provide("name", "Ludwig")
app.mount('#app2')

This is not exactly a prop (and needs to be passed before mount), but could work for you.
more info:  https://v3.vuejs.org/api/application-api.html#provide
2. Nest as render function and wrap
By wrapping in render function, you can pass the props. If you wrap that again in your custom mount function, you can  customize to allow passing props.
// the app as a component
const appComponent = Vue.defineComponent({
  name: "appComponent",
  props: {
    name: {}
  },
  // ...etc
})

// wrap mount function
const mountApp = (selector, props) => {
  // the actual app is just a simple render function
  const app = Vue.createApp({
    components: { appComponent },
    render() {
      return Vue.h(appComponent, props)
    }
  })
  // mount to the passed selector
  app.mount(selector);
}

// call function with props
mountApp('#app1', {
  name: "Darla"
});

example fiddle
Comment: there are another method to create child component in vue3 with props? Instead of .createApp
Comment: `createApp` creates a vue app. Components are created using `defineComponent` or `component` if you have the app instance


Time series analysis: multiplicative model and seasonal adjustment of data

Question: I am trying to help a friend in statistics and this question involving time series came up and I did not know what to do. I tried searching different stack exchange forums for answers, but I believe this might be to basic because I could find none. Now to the problem at hand:

The product sales in a business (billions of swedish crowns, SEC) have been the follwoing during the last three years.
+------+------+-------+--------+-------+
| Year | Q. I | Q. II | Q. III | Q. IV |
+------+------+-------+--------+-------+
| 2012 | 2.4  | 2.9   | 2.8    | 3.8   |
+------+------+-------+--------+-------+
| 2013 | 2.7  | 3.2   | 3.2    | 4.3   |
+------+------+-------+--------+-------+
| 2014 | 3.2  | 3.7   | 3.6    | 4.8   |
+------+------+-------+--------+-------+
a) Seasonally adjust the time series with multiplicative model.

I am sorry for the bad table, this was the best I could do. How do we seasoanlly adjust the data? I know that this means that we try to account for the variability of different seasons, but how do we go about this in this example? I have found out that the multiplicative model is
\begin{align}
\hat{y} = T\cdot S\cdot C\cdot I
\end{align}
where $T$, $S$, $C$ and $I$ denote trend, seasonal, cylical and irregular component, respectively. So how do I compute these components? (I found this on wikipedia).
Comment: Your question essentially seems to be "how to estimate seasonal factors for a time series?". There are a number of methods of doing this, which makes this question too broad. For starters, see [this](https://otexts.com/fpp2/decomposition.html).
Comment: @Dayne Yes this is what I am trying to figure out. Thank you.
Answer: Step 0: Need annual data, so add up the quarters. Then, apply a log transform to all the annual data converting from a multiplicative to a linear model analysis. You will also need the average of the annual logs.
Step 1: Working with just annual figures as logs, take the first difference between points. If there is only a simple underlying linear trend for the annual data this should produce a near constant differences between years (equates to a slope estimate upon, for example, 'averaging' differences). This is the Trend estimate here based from 2 differences produced from taking the difference of 3 annual figures converted to logs.
Step 2: Take second differences (the difference in the two 1st differences expressed in log values). This results here in just one number. If large then likely a Cyclical component, otherwise assume a value of zero and this is then a measure of the noise level (here referenced as the irregular component).
Step 3: Construct a fitted 3 point trend model for the log data. This annual log model is: Average of logs + Trend x time + Cyclical x time^2 where possible time values are 1, 2 and 3.
At this point, I would take the anti-log (for base 10, compute 10^(log)) for all of the fitted annual log points going back to a dollar analysis (and not the log of dollars).
Note, if there is both no Trend or Cyclical components (values are/near zero), then, the geometric mean (from the inverse of the average of the logs, the remaining term in log fit model) is the forecast for each year with a random irregular component (with an expected mean of zero).
Step 4: Compare (by dividing) say Quarter 1 to the [fitted model value (note: real dollars and not log value of dollars) for that year divided by four]. Similarly, repeat for the other quarters comparing again to respective Annual dollar Fit/4. 'Average' these respective quarter seasonal effects to arrive at your Seasonal quarter adjustment factors. Note, a functional value of 0.25 implies no seasonal effect, you are obtaining 1/4 of the annual. One could, per the cited Wikipedia reference, represent this season factor as 100 (from 400 times 0.25, and in the case of 400 times 0.30, this would be 120 implying a strong seasonal effect and to forecast the full year from this one quarter only, then multiply by 4 and divide by 1.2 as it usually over-represents the full year).
Done, you have a full Seasonal Trend Cyclical model.
Note: I have used the term average in quotes (namely 'average'), where one may decide to perform a more advanced weighting procedure to arrive at say a Trend estimate using, for example, a Least-Squares or even more advanced fitting algorithm data permitting.
Comment: -1 This is a grossly overcomplicated answer to a simple question.
Comment: Or, I view it as a potentially very complex issue (namely, seasonal time series analysis) obviously being introduced with more simple assumptions in likely a non-technical course. The concept of taking differences is not complex and accurately relates to trend analysis. Let the consumer of my suggested steps be the judge.
Comment: Now, it is true my answer is perhaps more complex than needed to answer this apparent homework exercise, but in such a course there could be a more data extensive project! My answer could be of aid in such a product as well.
Comment: If my step by step answer is indeed too complex, has anyone reviewed the reference provided by Dayne in a comment above (that was upvoted)? The latter includes topics of 'exponential smoothing', which I would suggest is, indeed,  a "grossly overcomplicated"  topic for this introductory question, and the source still, I would argue, does provides but limited assistant in directly answering the question.
Comment: Thank you for the extensive answer @AJKOER. It seems as though the fitted model you used is not dependent on the seasonally adjusted data, since you compute season adjustment factors at step 4. Is season adjustment implicit in some way?
Comment: In practice, I have used the latest quarter year-to-date x its historical relativity to full year as an added piece of input in deriving an adjusted full year forecast derived from an annual model. Quarter results, by themselves, are just too noisy as a full year forecasting tool. More advanced time series forecast programs may use totally integrated approach, however.


Translate python datatype to datatype of other language, using a dictionary

Question: this is a follow up of this post. To reiterate, I have text file with metadata and measurement data of a given location. I want to write this data to spatial mapping software called ArcGIS for which I have to specify for each value in the list the data type as defined in ArcGIS. For example:
type("foo")

Gives str in Python, but is known as text in ArcGIS. So, I want to translate the datatype of every element in my list, to the appropriate datatype in ArcGIS. Something like this:
# This is the raw data that I want to write to ArcGIS
foo= ['plot001', '01-01-2013', 'XX', '10', '12.5', '0.65', 'A']
# The appropriate datatypes in Python are:
dt= [str, str, str, int, float, float, str]
# In ArcGIS, the datatypes should be:
dtArcGIS= ['text', 'text', 'text', 'short', 'float', 'float', 'text']

The question is: how can I come from dt to dtArcGIS? I was thinking of a dictionary as:
dtDict= dict{str:'text', int:'short', float:'float'}

But this gives a syntax error. Any help would be appreciated, thanks!
Comment: Remove `dict`, the curly braces already define it as a dict there's no need to tell Python to do it again, `dtDict= {str:'text', int:'short', float:'float'}`
Comment: `type('10')` is `str`, not `int`
Answer: You are mixing two formats, just remove the dict like this
dtDict = {str:'text', int:'short', float:'float'}

And this is how you should convert the types
foo = ['plot001', '01-01-2013', 'XX', '10', '12.5', '0.65', 'A']
from ast import literal_eval

dt = []
for item in foo:
    try:
        dt.append(type(literal_eval(item)))
    except:
        dt.append(str)

dtDict = {str:'text', int:'short', float:'float'}
print map(dtDict.get, dt)

Output
['text', 'text', 'text', 'short', 'float', 'float', 'text']


Show that a random variable is not dominated

Question: Let $((0,1], \mathcal{B}_{(0,1]}, \lambda)$ be a probability space, and define
$$
X_n = n 1_{(0,1/n]}
$$
This is an example where $\lim E(X_n) \neq E( \lim X_n)$, and the dominated convergence theorem doesn't apply because $X_n$ can't be dominated by an integral random variable.
I can see intuitively that this random variable can't be dominated by an integrable random variable; $X(\omega) = 1/\omega$ "connects the dots" and its expectation isn't finite. However, how could one prove that $X_n$ can't possibly dominated by an integrable random variable? I was thinking about a proof by contradiction, but I didn't succeed.
I suppose that one way to prove it is by saying that since 1) $\lim E(X_n) \neq E( \lim X_n)$, 2) $X_n \rightarrow 0$, and 3) DCT doesn't apply, we can't have domination (the result doesn't follow, so at least one premise of the DCT must be false, which in this case is domination). But I was looking for something more "constructive".
Thanks!
Answer: If $X_n\leqslant X$ for every $n$, then $X\geqslant Y$ where $Y=\sup\limits_{n\geqslant1} X_n$. Note that
$$
Y=\sum_{n\geqslant1}n\mathbf 1_{(1/(n+1),1/n]},
$$
hence
$$
E[Y]=\sum_{n\geqslant1}n\left(\frac1n-\frac1{n+1}\right)=\sum_{n\geqslant1}\frac1{n+1},
$$
which is infinite. One sees that $Y$ is not integrable, and that neither is any dominating random variable $X$.


Computer That Is Member Of A Domain Can't See Domain Groups

Question: So, I have joined to my workplace local domain. I logged in a couple of times using my domain user but now the computer won't be able to see any users or groups from the domain. Actually in the objects "Search" dialog box I can only select the current computer as "Location" to search from.
Curious thing is that the computer properties says that the machine is actually part of the domain.
Any thoughts on this matter?
Thanks!
EDIT:
Apparently I am able to ping the DC. Even though I can't list users by using the NET USERS /domain command at the command prompt. It fails with error 1355 - The specified domain either does not exists or could not be contacted.
Comment: This likely won't work. See my answer
Comment: Is your DNS using the same DNS as your domain controllers?
Comment: possibly a permissions thing?
Comment: Don't think so. I used to be able to lookup for users.
Comment: No. DCs are aver a VPN.
Answer: Your PC/Server has to be able to find the DCs and to do so needs to share the same DNS as the DCs.  Active Directory is VERY sensitive to DNS and all clients and domain controllers need to point to a common DNS or it just won't work. In my experience, almost EVERY AD issue is due to an underlying DNS issue.
Answer: The Computer Browser service must be running in order to view computers on the domain.  You can check to see if this is running in the Services snap-in.  Many organizations disable this service via Group Policy to comply with security requirements (so you may not have the option to turn it on).
Comment: Apparently the service is started.
Answer: The problem that you describe is likely to be resolved by simply leaving the donain and rejoining it:

In sysdm.cpl, leave the domain and join WORKGROUP.
Reboot.
Log into the domain controller, open Administrative Tools -> Active Directory Users and Computers, and verify that this machine's computer account has been deleted. (Right click on the domain, choose Find, change the type of search from Users/Groups to Computers, and search for the name of the workstation that you have removed from the domain.) If the computer account still exists, delete it.
In sysdm.cpl, rejoin the domain.
Reboot.
Comment: Same thing. I could not rejoin the domain. It is not contacting the DC.
Comment: Run `ipconfig /all`. Note the IP address of your DNS server. Is it set to the IP address of the DC? If not, run `ncpa.cpl` and edit the properties for your active network connection. Be sure that your primary DNS server is a domain controller for the domain that you are trying to join.
Answer: In my case, as uSlackR suggests, the issue was origined by the order of the DNS in the adapter, i put the primary DNS the AD instead of second, and i recover the domain "location"
Answer: If windows firewall is enable, you need to disable it. Since you already behind a firewall no need for windows firewall on the machine to be enable.
go to control panel disable windows firewall on the pc
then go to command prompt run :gpupdate and :ipconfig /flushdns
and then run :net view all the machine on the domain should be listed
Comment: Windows Firewall would have nothing to do with this as it has default settings to allow domain traffic anyway. Most firewall software already disables the built-in one on install, anyway.
Answer: I had the same issue while trying to reinstall peachtree on a windows 10 machine on the domain. Ultimately I just mapped the drive via the name of the server instead of the IP. I also changed the network type to domain via static DNS as pointed out above because it got switched to private. With both of these setup I was able to install without a problem. Hope this helps someone.
Answer: I had the issue that I couldn't browse my domain users on a Windows 7 Pro, when I set the my network config as my DC (DNS and gateway, because we have two different gateways) all it's fine and now I can browse my domain users inside my Win7 pc.


How can solve this equation in $\mathbb N^{2}$

Question: Let $A= \{ \frac{1}{n} / n\in \mathbb N^*\} $ and $B= \{ \frac{1}{3} - \frac{1}{n} / n\in \mathbb N^*\}$.
Given that $\frac{1}{4} \in (A\cap B)$, I can not to solve in  $\mathbb N^{2}$, the following equation
$$ 3x+3y-xy = 0 .$$
thanks in advance
Comment: How are A and B related to the equation?
Comment: @Ivan Neretin: Let $x \in (A\cap B) $, so $x \in A$ and $x \in B$, so $\exists n,p \in \mathbb N^*$:  $x =\frac{1}{n}$  and $x=\frac{1}{3} - \frac{1}{p}$, so $x \in (A\cap B) $ returns to $\frac{1}{n} = \frac{1}{3} - \frac{1}{p} \Leftrightarrow 3n+3p-np = 0$.
Comment: OK, I got it. Not sure whether it is really helpful in solving the equation, but whatever.
Answer: Well, the equation is quite simple if we put it this way:
$$3x = xy-3y$$
$$3x = (x-3)y$$
$$y={3x\over x-3}=3+{9\over x-3}$$
For that to be an integer, $9$ must be divisible by $x-3$, which leaves us with a pretty short list of options.
Answer: Rearrange the equation this way:
$$3x=xy-3y$$
$$\frac1y=\frac13-\frac1x$$
So 1/4 can be on both sides of the equation.


How to set and use direct files folder path in a multisite installation

Question: Drupal 8 multisite install where

First site is on a subdomain one.example.com
Second site is in a subfolder one.example.com/two

How can files folder for both sites to be accessible via URL/files and not URL/sites/domain/files

current: one.example.com/sites/one.example.com/files
desired: one.example.com/files
current: one.example.com/two/sites/two/files
desired: one.example.com/two/files

I tried several variants listed here https://www.drupal.org/node/53705 and put them at following locations, but nothing worked.

Drupal8/.htaccess
Drupal8/files/.htaccess
Drupal8/sites/two/files/.htaccess

Setup information is provided below

Filesystem setup
--Drupal8
  --index.php
  --one.example.com (sym link ln -s . one.example.com)
  --two (sym link ln -s . two) Not required in D8, but could not get the subfolder site to work without it.
  --sites
    --default (sym links to one.example.com)
    --one.example.com
      --settings.php, services.yml
      --files, modules,etc
    --two
      --settings.php, services.yml
      --files, modules,etc

Sites.php
$sites = [];
$sites['one.example.com'] = 'one.example.com';
$sites['one.example.com.two'] = 'two';

Apache setup : One virtual host for one.example.com
Comment: What did you actually put in /.htaccess that did not work? We use something like:

      RewriteCond %{HTTP_HOST} ^(foo\.bar\.com
      RewriteRule ^files/(.*)$ sites/foo/files/$1 [NC,L]
Comment: I tried `RewriteRule ^files/(.*)$ /sites/%{HTTP_HOST}/files/$1 [L, R] and RewriteRule ^(.*)$ /sites/%{HTTP_HOST}/files/$1 [L, R]` Which .htaccess file are you adding this to?
Comment: The root .htaccess in the site directory, where Drupal is installed. Note, this is an edit of the .htaccess provided by Drupal. Does HTTP_HOST match the multisite directory name in every case on this site?
Comment: The subdomain site matches the HTTP_HOST, but sub folder does not, as it will be more cryptic (one.example.com.two) and won't match HTTP_HOST anyways. I tried your suggestion to see if at least the  subdomain site's files would work, but it did not.
Comment: I also tried to hardcode path on subdomain `RewriteCond %{HTTP_HOST} ^one\.example\.com$ [NC] RewriteRule ^files/(.*)$ sites/one.example.com/files/$1 [NC,L]` this did not work
Comment: Do I need to make a change in public file system path after the rewrite rule from sites/one.example.com/files to files?
Comment: I got subdomain file to work, by adding the the rule above the rule that directs everything to index.php in Drupal's root .htaccess
Comment: Oh, I thought that was obvious. Sorry.
Answer: In /.htaccess, above other rewrite rules, use something like this example for foo.bar.com:
RewriteCond %{HTTP_HOST} ^foo\.bar\.com
RewriteRule ^files/(.*)$ sites/foo.bar.com/files/$1 [NC,L]

Comment: This works on the site (one) which is on subdomain, but not for the site (two) which is in a subfolder
Comment: This worked, as we'll need separate rule for sub folder
  RewriteCond %{REQUEST_URI} /two/
  RewriteRule ^files/(.*)$ sites/two/files/$1 [L]

  RewriteCond %{REQUEST_URI} !/two/
  RewriteRule ^files/(.*)$ sites/%{HTTP_HOST}/files/$1 [L]
Answer: Since in this case one site is on subdomain the other on subfolder, single rule as mentioned by @cilefen is not sufficient. So we need to make two rules in this case, one for the subfolder site and other for the subdomain site. The subfolder site rule is hardcoded as we can't generalize it.
The rewrite rules need to be added to Drupal core's .htaccess (i.e one next to index.php). This will also require changes to .htaccess on every Drupal upgrade as the stock file won't have these rules.
  # Subfolder site
  # match subfolder site url path and amend its file path
  RewriteCond %{REQUEST_URI} /two/files/
  RewriteRule ^files/(.*)$ sites/two/files/$1 [L]

  # Subdomain site
  # if the url path matches subfolder site skip this rule
  RewriteCond %{REQUEST_URI} !/two/files/
  RewriteRule ^files/(.*)$ sites/%{HTTP_HOST}/files/$1 [L]

These rules need to be above the following, else they won't work
  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

Thanks to @cilefen for putting me on the correct path.
Answer: No need for any server config. You can do this by setting $settings['file_public_path'] = 'files'; in both your sites settings.php files.
See default.settings.php (click "View source")

/**
 * Public file path:
 *
 * A local file system path where public files will be stored. This directory
 * must exist and be writable by Drupal. This directory must be relative to
 * the Drupal installation directory and be accessible over the web.
 */

# $settings['file_public_path'] = 'sites/default/files';


errors, random and approximations

Question: Hello good evening all!
If a reading is reported as R = 200.045 + 0.001 or 200.045 - 0.001 Ohm. Does +0.001 or -0.001 Ohm represents a systematic or random error?
Thanking you.
Answer: It represents random error. Random error is a bit of 'spreading out', but systematic error means the data is centered around the wrong spot. Put another way:
Say your wife asks you your anniversary.
If you guess the date slightly wrong, that's random error. You know roughly what's going on, but the data isn't exact.
If you give the correct date of her birthday instead, that's systematic error. Accurate, but at the same time completely off the mark.
Having both is either awful science or grounds for divorce.
Random error can be calculated through standard deviation, which you can learn more about here. The wiki page on variance gives a good sense of where this formula comes from.
Systematic error is different. Say I measure your height and get a bunch of values within a few millimetres of each other. These are just numbers, and so I can compute how spread out they are just fine. However, nothing about the numbers can tell me that you didn't take your shoes off. Systematic error is when the value you get is wrong. What makes it wrong can't be determined mathematically, and can only be ensured by being very careful about how you run your experiment.
Comment: ! what a wonderful example you have given. Ok fine. can you show the random error in mathematical way. I mean take some small data and classify the random and systematic error. for more and better understanding.  please...
Comment: edited with an explanation of how we think about these types of errors.
Comment: ! is there any other kind of errors? then how we generalize such errors exists? could you answer please. Your answer is more effective and interesting...
Comment: Systematic error is what statisticians call bias.  It indicates that the estimate has its distribution centered around the wrong point.  Random error comes about because of sampling variability.  Each time you take an observation you have the true value plus some random noise (e.g. measurement error)  Model parameters can be estimated from noisy data.  The estimate should be close to the true parameter but due to the random error which generally is symmetrically distributed around 0.
Comment: The estimate has a resulting standard eror a the + or- 0.001 in your example indicates that the standard error of your estimate is 0.001.
Comment: Ok fine is there any such kind of other errors? can you list by example. How to encounter it?
Comment: I am looking model, which will differentiate all errors. Please...
Comment: I want a model on any data, which will describe systematic and random error. Also, I want know, how one conclude that random data by any mathematical formula etc.
Comment: You can't model *any* systematic error. Systematic error isn't a property of the data itself; it has to do with how that data corresponds to the real world. You won't get a mathematical formula for it. Random error is calculated through variance or standard deviation. Or, in your case, it's calculated by the manufacturer and given to you. I'm not sure what you're asking when you say "how one conclude that random data by any mathematical formula". Do you want to determine if two variables are independent or not?
Comment: yes I  want to determine if two variables are independent or not?
Comment: There are many tests. ([see here](http://en.wikipedia.org/wiki/Correlation_and_dependence)), though which one you want depends on what you mean by 'dependent'. Two variables are fully independent If the odds of one happening aren't changed by the other. This is something you say *for sure* about models, not about data. To determine *how* independent data sets seem to be, you can use those measures. Some of the ideas are intuitive (e.g, whether they rise and fall together), but I would do more research if you're just starting to learn probability. Posting a new question will get better results.
Comment: also you'll probably want to go here:

http://stats.stackexchange.com/

errors, random and approximations


Change select tag option in cefsharp winforms

Question: I'm trying to change select tag options using this code in cefsharp
Browser.MainFrame.ExecuteJavaScriptAsync("document.getElementById(\"REG_CATSEQ\").selectedindex = 1;");

This is the select code
<select id="REG_CATSEQ"  name="REG_CATSEQ"  class="form-control select2">
                      <option value="">Select a value...</option>
                                                  <option value="1">تسجيل لأول مرة</option>
                                                  <option value="2">الواقعات الحياتية</option>
                                            </select>

Comment: Looks like you have a typo. https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex I'd suggest using DevTools to test JavaScript, check for errors etc. https://github.com/cefsharp/CefSharp/wiki/Trouble-Shooting#javascript-debugging
Answer: Looks like you have made a typo. Both languages are case sensitive. https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex
Browser.MainFrame.ExecuteJavaScriptAsync("document.getElementById(\"REG_CATSEQ\").selectedIndex = 1;");


For every thousand the number gets

Question: Infinite loop for every 1000
Lets say i have a number 1000, and when it gets to 2000 or 3000, etc. I want to do a function. I want it to go to the infinite.
Tried almost everything...
Comment: Can you share the things that you have done? no one can help you without this
Comment: I ment it like i have a clicker game. So you when you click you get 1 score. If you have 1000 score, 2000, 3000, etc. it will do something. So i just want to follow my number of score and do a function.
Answer: If I understood well, you can do
while(true){
  if(number%1000){
   //call function here
  }
  //increase the number here, for example:
  number++;
}

Comment: Now i have a score of 12042. I want it that when it gets to 13000 it does something... like play a sound or something.
Comment: So, where I putted `//call function here` you can call a function that will do what you wanna do. The idea of the block of code above, is to call a generic function each time that number is equal to a multiple of 1000.
Answer: You can create a counter that uses a setTimeout to increase the value of the count, and when the count divided by 1000 is zero, call the function.
Here I've used 10 instead of 1000 to simplify the example.

function fn() {
  console.log('Function called');
}

function counter() {
  function loop(count = 1) {
    console.log(count);

    // You would use count % 1000 here
    if (count % 10 === 0) fn();

    // Change the 1000 to what inverval you need
    // Here it's one second
    setTimeout(loop, 1000, ++count);
  }
  loop();
}

counter();

For every thousand the number gets


How to disable events when runtime Delphi VCL Style changes

Question: I want to use VCL Style's in my application.
I have some code in events OnShow, OnResize...
When changing styles triggered other form events.(FormShow, FormResize)
How to disable events when on change style.
For change style i use code:
TStyleManager.TrySetStyle(cbStyles.Items[cbStyles.ItemIndex], True);

Sample Code:
procedure TForm1.AddLog(AMsg: String);
begin
  if cbEnableLog.Checked
  then  Memo1.Lines.Append(AMsg);
end;

procedure TForm1.bChangeClick(Sender: TObject);
begin
  TStyleManager.TrySetStyle(cbStyles.Items[cbStyles.ItemIndex],True);
end;

procedure TForm1.FormResize(Sender: TObject);
begin
  AddLog('FormResize');
end;

procedure TForm1.FormShow(Sender: TObject);
begin
  AddLog('FormShow');
end;

Comment: There's no automatic way to do this. You'll have to code it up yourself. Have all of your events bail out early by testing a boolean that you set.
Answer: Declare a boolean variable, f.ex. InStyleChange: boolean;. Set it True before you call TStyleManager.TrySetStyle() and reset to False right after.
In all event handlers where you want to bypass the event write code like:
procedure TForm1.FormResize(Sender: TObject);
begin
  if InStyleChange then exit;
  AddLog('FormResize');
end;

Comment: With the code you have shown for the two event handlers, it is impossible that the modification I suggested would be the reason for the exception. Show the **real and complete code** of the event handler that raises the exception.
Comment: @zgn, what type of exception? If you log before and after `TrySetStyle`, are there events coming later?
Comment: When i use like this code. its running few times. Then raises exception in my application.
Comment: @zgn The change suggested in this answer cannot result in the behaviour you describe. Don't expect us to debug what we can't see. It's time for you to learn to debug your own code.
Comment: @LU-RD Exception is : Error creating windows device context. Thank you.
Comment: @DavidHeffernan My question is clear. Please be patient. I'm looking for a real solution. ok?


Is there a module for saving current block setup?

Question: Would be handy to be able to save the current block setup, so after one changes around blocks, it could be reset to a previous state.
Answer: You can try either of these modules (quotes included are from their project pages):

Features Extra:

... provides faux exportables (via Features) of several site-building components.
To export a block, install FE Block, edit your block, give it a "machine name," export it with Features. You can export block settings (region settings, visibility settings, ...) of any block, and the content of blocks created with the Block module from Drupal core.
  The D7 version supports the Block Class, i18n block and Block Cache Alter modules.

Boxes:

... a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.
The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.


Absolute extrema of $\sin x+\cos y+\sin (xy)$ on a square

Question: I want to find the absolute extrema of the function $f(x,y)=\sin x+\cos y+\sin (xy)$ on $\{ (x,y) \mid 0\le x\le 2\pi,~0\le y \le 2\pi \}$.
I tried by finding the gradient of the function $f$, but it is hard to find $(x,y)$ to satisfy $\operatorname{grad} f(x,y)=(0,0)$. I need your help.
Comment: @FelixMarin Why did you add all these extra spacing and make $f$ roman? The edit was unnecessary and made things look worse imo.
Comment: @epimorphic There is a convention to write functions names in Roman. 0 k.: Last time I edit any thing in SE.
Comment: @FelixMarin What? No there isn't. _Generic_ functions (not special functions such $\sin$) are almost always italicized. Look in any textbook or paper.
Comment: i think the equation system $\cos(x)+y\cos(xy)=0$ $-\sin(y)+\cos(xy)x=0$ has no solutions in the given domain, the solution must be located on the lines of the given domain
Answer: Contrary to the claim by the doctor below, the gradient $\nabla f$ has zeros in the domain. Below are the graphs of the zero contours of the partial derivatives $\partial_x f$ and $\partial_y f$, plotted in Mathematica. The zeros of the gradient are precisely the points where the contours intersect.
ContourPlot[{Cos[x] + y Cos[x y] == 0, x Cos[x y] - Sin[y] == 0},
    {x, 0, 2 \[Pi]}, {y, 0, 2 \[Pi]}]

You can prove the existence of solutions to $\nabla f(x,y) = 0$, thanks to Taylor's theorem, by either

Approximating the two zero contours near any point where the computer suggests they intersect, or
Bounding $f$ on the boundary and then showing that $f$ exceeds those bounds in the interior.

Method 2, by the way, would also show that the global extrema on this domain lie in the interior. I won't bother writing down the excruciatingly tedious details because it will bore everyone (including myself), and would probably exceed the character limit of this answer box.
Anyways, in general you shouldn't expect to be able to find nontrivial closed-form solutions to all but the simplest of equations. This appears to be one of those non-simple situations. So, let's approach the problem numerically instead.
Since $f$ has multiple local extrema, we first need to identify which of those extrema are global. Here is the contour plot of $f$ where $f \geq 2$:
ContourPlot[Sin[x] + Cos[y] + Sin[x y], {x, 0, 2 \[Pi]}, {y, 0, 2 \[Pi]},
    PlotRange -> {2, 3}, PlotLegends -> Automatic]

Zooming in on the yellow region, we find that the global maximum lies at approximately $(1.27, 6.22)$, and $\max f \approx 2.95$.
ContourPlot[Sin[x] + Cos[y] + Sin[x y], {x, 1.22, 1.32}, {y, 6.05, 2 \[Pi]},
    PlotRange -> {2.94, Automatic}, PlotLegends -> Automatic,
    GridLines -> {{1.26, 1.27, 1.28}, {6.21, 6.22, 6.23}}]

ContourPlot[{Cos[x] + y Cos[x y] == 0, x Cos[x y] - Sin[y] == 0},
    {x, 1.22, 1.32}, {y, 6.05, 2 \[Pi]},
    GridLines -> {{1.26, 1.27, 1.28}, {6.21, 6.22, 6.23}}]

Similarly, here is the contour plot of $f \leq -2$:
ContourPlot[Sin[x] + Cos[y] + Sin[x y], {x, 0, 2 \[Pi]}, {y, 0, 2 \[Pi]},
    PlotRange -> {-3, -2}, PlotLegends -> Automatic]

Zooming in on the deep blue region would locate the minimum at around $(4.95, 3.48)$ and yield $\min f \approx -2.91$.
If you need higher precision, you can keep zooming in. Or, you can unleash one of any number of optimization methods, such as gradient descent (applied to $f$) or Newton's method (applied to $\nabla f$), using the approximate coordinates we found above as starting points.


Non-linear function optimisation using nlminb function in R

Question: I have been getting error messages in my attempt to estimate parameters in a non-linear function using nlminb function. The following is the code:
func=function(par,x){
    data[,1] ~ ((x[,5]*x[,4])^((par[1]-1)/par[1]) + ((x[,3]*x[,6])^((par[2]-1)/par[2])+ (x[,2]*x[,7])^((par[2]-1)/par[2]))^(((par[1]-1)/par[1])*(par[2]/(par[2]-1))))^(par[1]/(par[1]-1))
}
nlminb(start=c(0.8,0.6), func, x=data)

The data I have is a set of time series. The following is the error I am getting:
Warning messages:
1: In nlminb(start = c(0.8, 0.2), model, x = data) :
  NA/NaN function evaluation

The following is the data
1   103.84660   7695.040    124.8315    115.2998    1.0080483   1.001325    0.9938076   1
2   113.16377   7742.493    124.5868    116.2914    1.0052380   1.004880    1.0171624   2
3   110.24519   7797.469    124.4623    117.2707    0.9944189   1.011406    1.0281476   3
4   103.17992   7864.746    124.4574    118.2496    1.0179428   1.015610    1.0517229   4
5   122.83588   7902.960    124.5721    119.2821    1.0208074   1.019282    1.0735748   5
6   116.58633   7921.277    124.8066    120.2782    1.0090971   1.019724    1.0669756   6
7   98.73047    7947.280    125.1614    121.2992    1.0171887   1.024867    1.1092066   7
8   110.92299   7976.375    125.6375    122.3042    1.0084163   1.026991    1.1456070   8
9   118.06808   8003.961    126.2360    123.2945    1.0351463   1.031189    1.1499949   9
10  102.28658   8022.360    126.9587    124.3334    1.0292670   1.031507    1.1574415   10
11  92.99516    8045.384    127.8074    125.3624    1.0251884   1.035247    1.1869132   11
12  101.39479   8036.162    128.7846    126.4021    1.0479171   1.038441    1.2017964   12
13  101.30144   8020.789    129.6421    127.4284    1.0357224   1.039799    1.2341470   13
14  96.95292    8034.624    130.3773    128.4379    1.0399284   1.042869    1.2725077   14
15  106.64892   8063.858    130.9879    129.4655    1.0346895   1.043092    1.2802305   15
16  103.65601   8073.111    131.4721    130.5830    1.0294096   1.047213    1.3211646   16
17  107.57715   8122.403    131.8282    131.7203    1.0352389   1.048407    1.3464485   17
18  113.64242   8177.897    132.7665    132.8507    1.0494784   1.049540    1.3783562   18
19  120.05998   8233.438    134.2970    134.0168    1.0509931   1.050161    1.4049428   19
20  117.94485   8289.026    136.4372    135.0831    1.0475881   1.052968    1.4100514   20
21  125.46768   8261.399    139.2131    136.2520    1.0676247   1.054175    1.4409652   21
22  120.57292   8252.264    142.6594    137.2626    1.0688130   1.059272    1.4969188   22
23  121.85877   8260.101    145.5310    138.2797    1.0452529   1.058159    1.5132735   23
24  118.93148   8291.103    147.7873    139.3569    1.0653257   1.059835    1.5295049   24
25  117.74407   8320.588    149.3949    140.4136    1.0680230   1.062398    1.5748625   25
26  120.81597   8351.646    150.3290    141.4838    1.0791235   1.064557    1.6218405   26
27  117.08652   8422.914    150.5735    142.5232    1.0682042   1.064907    1.6616629   27
28  116.37610   8472.598    150.4380    143.7123    1.0616077   1.065997    1.6701485   28
29  119.92723   8390.855    149.9225    144.7475    1.0702911   1.066648    1.7159248   29
30  113.26243   8256.443    149.0300    145.7908    1.0611327   1.068071    1.7417198   30
31  115.85483   8155.983    147.7663    146.8241    1.0787689   1.070899    1.7752797   31
32  114.01433   8149.909    146.1400    147.8764    1.0899623   1.071713    1.8460021   32
33  121.58956   8185.661    145.4177    148.9278    1.0771952   1.074088    1.8647514   33
34  124.28517   8229.194    145.5807    149.9583    1.0801203   1.075055    1.9123212   34
35  123.83632   8314.625    146.6266    150.9679    1.0799208   1.078315    1.9214472   35

Comment: Try reparameterizing. Make parnew[1] = (par[1]-1)/par[1] .    parnew[2] = (par[2]-1)/par[2] .  Then use parnew[1], parnew[2] as your parameters to be estimated. You will still have the recirpocals of these in one place. Combine that with sensible lower and upper bounds on parnew[1] and parnew[2].
Comment: I tried this too, did not work :(
Comment: Anyhow, that's a whole heck of a lot of exponentiation. Do you have a good rationale for this function?
Comment: This is a constant elasticity of substitution function used in economic analysis of input and output data. The parameters are basically elasticities of substitution between input factors. Theory suggests the parameters are positive and usually less than one. This study discusses the various non-linear estimation methods and algorithms: http://ftp.zew.de/pub/zew-docs/dp/dp12007.pdf Thanks
Answer: Its likely that while exploring parameter space the algorithm generates non-real numbers (by dividing by 0, taking the square root of a negative number, or something else). To avoid this consider setting the upper and lower bounds on your parameters using the upper and lower settings in the nlminb function. I would start with:
nlminb(start=c(0.8,0.6), lower=c(0, 0), upper=c(1000,1000), func, x=data)

However, if you provide example data I could test this more fully.
Comment: I tried using these, no success. I've now edited the original post to include the data set. Will you please have a look? Thanks.