Listing all possible trebles from multiple sets where you can only select one element of each set

Question: I'm stuck on a combinatorics problem and was hoping someone could help me.
I would like to know the number of possible trebles (order not important) from sets of elements where only one element can be chosen from each set.
For example, say we have 6 sporting events with possible number of outcomes in brackets:
Man Utd, Draw1, Arsenal (3)
England, Draw2, Germany (3)
Barcelona, Draw3, Real Madrid (3)
Murray, Federer (2)
Djokovic, Nadal (2)
Warriors, Cavaliers (2)
I want to find out how many ways I can choose exactly 3 outcomes from the 6 events, with the restriction that I can't choose 2 outcomes from the same sporting event, E.G:
(Arsenal, Germany, Nadal), (England, Murray, Warriors),.....
I know how that the number of combinations of events, without the added complication of having multiple elements, is just 6 Choose 3 = 20.
I also know that the number of ways of choosing one element from all 6 events is just the product rule: 3*3*3*2*2*2 = 216.
However, I can't work out the solution when you combine the two problems of having to choose one thing from each set and having to choose a certain number of sets. It's probably really simple but I just can't get my head round it.
My next problem is working out how to list all of the combinations programmatically but I'll be content for today if I can just work out how many of them there are as a start!
Thanks in advance for your help!
Answer: It's simple but complicated...
There's one way each to choose all two-way and all three-way events, giving $2^3$ and $3^3$ options each. Then there are ${3 \choose 2}{3\choose 1}2^23^1$ and ${3 \choose 1}{3\choose 2}2^13^2$ ways of selecting from mixed-type events. Total:
$$ 8+9\cdot12 + 9\cdot 18 + 27 = 8+108+162+27 = 305 \text{ options}$$


A comprehension problem in Gambler's fallacy and calculating sample mean

Question: The following problem and solution appears in Judgment under uncertainty: Heuristics and Biases; Page 24

The mean IQ of the population of eighth graders in a city is known to be 100. You have selected a random sample of 50 children for a study of educational achievements. The first child tested has an IQ of 150. What do you expect the mean IQ to be for the whole sample?
The correct answer is 101.

Question: how is it 101? How to arrive at that number?
Answer: Based on the given information we know that the population mean $\mu$ is equal to $100$, i.e $\mu=100$.
Then we extract a sample $n=50$, where the first child has IQ, i.e. $X_{1}=150$. And based on that we want to know what is the expected mean $\bar{X}_{50}$.
We start by taking the expected value of the sample mean $\bar{X}_{50}$
$$\mathbb{E}[\bar{X}_{50}]= \mathbb{E}[\frac{X_{1}+X_{2}+...+X_{50}}{50}]=\mathbb{E}[\frac{X_{1}}{50}+\frac{X_{2}+X_{3}+...+X_{50}}{50}]$$
however $X_{1}$ is known so it can get outside of the expected value
$$=\frac{X_{1}}{50}+\mathbb{E}[\frac{X_{2}+X_{3}+...+X_{50}}{50}]$$
and inside the expected value we have to construct the sample mean but this time for only the $49$ values.
$$=\frac{X_{1}}{50}+\mathbb{E}[\frac{X_{2}+X_{3}+...+X_{50}}{49}]\frac{49}{50}$$
We also, know that the sample mean is an unbiased estimator of the population mean i.e. $\mathbb{E}[\bar{X}]=\mu$. Hence,
$$=\frac{X_{1}}{50}+100\frac{49}{50}=\frac{150}{50}+\frac{4900}{50}=101$$


Counting nested Navigation table rows with LINQ

Question: I am very new to c# and LINQ, now I need to do some aggregation on the navigation tables nested one after the other, the result was generated as below:
[{
    "ForumMain":"General Forum",
    "Forums": [{
            "Title":"My First Forum",
            "TopicCount":4,
            "PostCount":[2,0,1,0]
        },
        {
            "Title":"My Second Forum",
            "TopicCount":0,
            "PostCount":[]
        }]
}]

I wanted PostCount also be the sum, but it is giving debug null error when I try to sum PostCount, please see my linq query below:
var data = ForumCategories.Select(f => new
{
    ForumMain = f.CategoryName,
    Forums = f.Fora.Select(t => new
    {
        Title = t.ForumName,
        TopicCount = t.Topics.Count,
        PostCount = t.Topics
        .Select(m => m.ForumPosts.Count == null ? 0 : m.ForumPosts.Count)
    })
});

Comment: want to count the items in PostCount or SUM the items in PostCount. because in your linq query you do a count and not a SUM. m.ForumPosts.Sum()
Comment: yes I should have said the Count, but seeing the outcome result of my postcount, I  said it to sum [2,0,1,0] = 3. Anyway, my problem has been solved. thanks for your input
Answer: From what I understand what you want under PostCount to have the total number of post you have for all the topics in that Forum. Right?
If so:
var data = db.ForumCategories.Select(f => new
{
    ForumMain = f.CategoryName,
    Forums = f.Fora.Select(t => new
    {
        Title = t.ForumName,
        TopicCount = t.Topics.Count,
        PostCount = t.Topics.SelectMany(x => x.ForumPosts).Count()
    })
});

Comment: @Khalil - look at the [SO Documentation](http://stackoverflow.com/documentation/c%23/68/linq-queries#t=20160803064328417214) for `SelectMany`
Comment: Yes, very well done, did what I wanted. I will ready the documentation you provided. It looks like you will welcome me if I ask you more questions in future
Comment: Thanks man. to clarify the sum and count, because when I was getting an array of counts in the postcount so I thought sum would work, but it was throwing error when the the array was empty. Can you please explain the SelectMany scenario here what was happening that the Select didn't work.
Comment: @Khalil - Yes. Under each `Topic` you have many `ForumPosts`. If you just perform a `Count` on the `Topic` you count how many items you have in that collection - but what you want is to know how many items you have all together within all the inner lists. `SelectMany` enables you to iterate a collection and output for each item a collection of items (in this case for each Topic all the posts). Then all these collections are merged (by the `SelectMany`) and that is what you want to count


Unable to run a jar or sparkApplication on aws EMR

Question: I have a very simple app that I'm trying to run on  aws emr. The jar has been built using assembly with spark a provided dependency.  It resides on S3 along with a test text file that I wanted to test.
In the EMR UI I select to add a step and add the details telling it the location of the jar and the argument file location.
It runs but always fails with an error - I then set up a new cluster(sanity checking) and rna again only to get the same result, any help is appreciated.
Thank you
The error from the log:
<code>    16/03/18 11:40:56 INFO client.RMProxy: Connecting to ResourceManager at ip-10-1-1-234.ec2.internal/10.1.1.234:8032
16/03/18 11:40:56 INFO yarn.Client: Requesting a new application from cluster with 1 NodeManagers
16/03/18 11:40:56 INFO yarn.Client: Verifying our application has not requested more than the maximum memory capability of the cluster (11520 MB per container)
16/03/18 11:40:56 INFO yarn.Client: Will allocate AM container, with 1408 MB memory including 384 MB overhead
16/03/18 11:40:56 INFO yarn.Client: Setting up container launch context for our AM
16/03/18 11:40:56 INFO yarn.Client: Setting up the launch environment for our AM container
16/03/18 11:40:56 INFO yarn.Client: Preparing resources for our AM container
16/03/18 11:40:57 INFO yarn.Client: Uploading resource file:/usr/lib/spark/lib/spark-assembly-1.6.0-hadoop2.7.1-amzn-1.jar -> hdfs://ip-10-1-1-234.ec2.internal:8020/user/hadoop/.sparkStaging/application_1458297951763_0003/spark-assembly-1.6.0-hadoop2.7.1-amzn-1.jar
16/03/18 11:40:57 INFO metrics.MetricsSaver: MetricsConfigRecord disabledInCluster: false instanceEngineCycleSec: 60 clusterEngineCycleSec: 60 disableClusterEngine: false maxMemoryMb: 3072 maxInstanceCount: 500 lastModified: 1458297958626
16/03/18 11:40:57 INFO metrics.MetricsSaver: Created MetricsSaver j-DKMA93DFZ456:i-91bff215:SparkSubmit:20036 period:60 /mnt/var/em/raw/i-91bff215_20160318_SparkSubmit_20036_raw.bin
16/03/18 11:40:58 INFO metrics.MetricsSaver: 1 aggregated HDFSWriteDelay 590 raw values into 1 aggregated values, total 1
16/03/18 11:40:59 INFO fs.EmrFileSystem: Consistency disabled, using com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem as filesystem implementation

16/03/18 11:41:00 INFO metrics.MetricsSaver: Thread 1 created MetricsLockFreeSaver 1
16/03/18 11:41:00 INFO yarn.Client: Uploading resource file:/mnt/tmp/spark-030f9d29-f7ca-42fa-9caf-64ea103a2bb1/__spark_conf__7615049662154628286.zip -> hdfs://ip-10-1-1-234.ec2.internal:8020/user/hadoop/.sparkStaging/application_1458297951763_0003/__spark_conf__7615049662154628286.zip
16/03/18 11:41:00 INFO spark.SecurityManager: Changing view acls to: hadoop
16/03/18 11:41:00 INFO spark.SecurityManager: Changing modify acls to: hadoop
16/03/18 11:41:00 INFO spark.SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)
16/03/18 11:41:01 INFO yarn.Client: Submitting application 3 to ResourceManager
16/03/18 11:41:01 INFO impl.YarnClientImpl: Submitted application application_1458297951763_0003
16/03/18 11:41:02 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:02 INFO yarn.Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: N/A
     ApplicationMaster RPC port: -1
     queue: default
     start time: 1458301261052
     final status: UNDEFINED
     tracking URL: http://ip-10-1-1-234.ec2.internal:20888/proxy/application_1458297951763_0003/
     user: hadoop
16/03/18 11:41:03 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:04 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:05 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:06 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:07 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:08 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:09 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:10 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:11 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:12 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:13 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:14 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:15 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:16 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:17 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:18 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:19 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:20 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:21 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:22 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:23 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:24 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:25 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:26 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:27 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:28 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:29 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:30 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:31 INFO yarn.Client: Application report for application_1458297951763_0003 (state: ACCEPTED)
16/03/18 11:41:32 INFO yarn.Client: Application report for application_1458297951763_0003 (state: FAILED)
16/03/18 11:41:32 INFO yarn.Client:
     client token: N/A
     diagnostics: Application application_1458297951763_0003 failed 2 times due to AM Container for appattempt_1458297951763_0003_000002 exited with  exitCode: 15
For more detailed output, check application tracking page:http://ip-10-1-1-234.ec2.internal:8088/cluster/app/application_1458297951763_0003Then, click on links to logs of each attempt.
Diagnostics: Exception from container-launch.
Container id: container_1458297951763_0003_02_000001
Exit code: 15
Stack trace: ExitCodeException exitCode=15:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:545)
    at org.apache.hadoop.util.Shell.run(Shell.java:456)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:722)
    at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:211)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

Container exited with a non-zero exit code 15
Failing this attempt. Failing the application.
     ApplicationMaster host: N/A
     ApplicationMaster RPC port: -1
     queue: default
     start time: 1458301261052
     final status: FAILED
     tracking URL: http://ip-10-1-1-234.ec2.internal:8088/cluster/app/application_1458297951763_0003
     user: hadoop
Exception in thread "main" org.apache.spark.SparkException: Application application_1458297951763_0003 finished with failed status
    at org.apache.spark.deploy.yarn.Client.run(Client.scala:1029)
    at org.apache.spark.deploy.yarn.Client$.main(Client.scala:1076)
    at org.apache.spark.deploy.yarn.Client.main(Client.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
16/03/18 11:41:32 INFO util.ShutdownHookManager: Shutdown hook called
16/03/18 11:41:32 INFO util.ShutdownHookManager: Deleting directory /mnt/tmp/spark-030f9d29-f7ca-42fa-9caf-64ea103a2bb1
Command exiting with ret '1'
</code>
Answer: Referring to issue Running Spark Job on Yarn Cluster
It can mean a lot of things, for us, we get the similar error message because of unsupported Java class version, and we fixed the problem by deleting the referenced Java class in our project.
Use this command to see the detailed error message:
<code>yarn logs -application_id application_1458297951763_0003
</code>
Comment: I could hug you right now.  Knowing where to look for the logs is fantastic, thank you so much - found a couple of issues - mainly the url of the file I was passing in couldn't be found. Thank you so so much for taking time out of your day to post that answer


Can we say that RNN for time series is an example of semi-supervised learning?

Question: I am learning neural nets, esp. focusing on RNN for my research problem. This question has nothing exactly to do with my research.
With my understanding of RNN, I can think of it as an example of semi-supervised learning rather than supervised learning.
It is because we do not have an exact data set (unsupervised, since no actual labels), but we use the shifted value of the input as the data set (makeshift labels). Hence this makes RNN a semi-supervised learning algorithm (at least for time series).
Am I correct in this understanding?
Answer: An RNN (or any neural network for that matter) is basically just a big function of the inputs and parameters. There are supervised models which use RNNs, unsupervised models which use RNNs, and semi-supervised models which use RNNs. How something is supervised is generally independent of the architecture used.
The most "classic" use of RNNs is in language modeling, where we model $p(x) = \prod_i p(x_{i} | x_{j<i})$, and each conditional factor is computed by the RNN. This is an unsupervised model.
Answer: Semi-supervised refers to using a combination of a labeled dataset (usually quite small) and a (usually much larger) unlabeled dataset.
When the labels are automatically derived from the data itself, this is these days called self-supervised learning or self-supervision. Examples in time series include predicting the next time step, or filling in a gap in the sequence.
This website by Lillian Weng is a good reference for some of the many possible strategies. https://lilianweng.github.io/lil-log/2019/11/10/self-supervised-learning.html
Answer:
It is because we do not have an exact data set (unsupervised, since
no actual labels), but we use the shifted value of the input as the
data set (makeshift labels).

If by this you mean that you predict something like
$$
y_t = f(y_{t-1}, y_{t-2}, \dots)
$$
then it is supervised because you have the values that are predicted. If you observed the thing that the model predicts, it is a supervised learning problem. Unsupervised learning would be when the predicted values would not be observed, like in clustering where there are no given cluster labels that are predicted.
Semi-supervised learning would be something different:

Semi-supervised learning is a class of supervised learning tasks and
techniques that also make use of unlabeled data for training –
typically a small amount of labeled data with a large amount of
unlabeled data.

So most of the time-series problems would be supervised learning problems, though a little bit different from others because the same data (but shifted) would be used both as inputs and outputs. Of course, there are unsupervised time-series models, e.g. for clustering, detecting changepoints, etc.


Report Builder not showing IIF result

Question: I'm trying to modify a Report Builder report (Visual Studio 2013) and it's not displaying four expressions.  The following field is coded like this and works just great!
<code>=First(Microsoft.VisualBasic.Interaction.IIF(Fields!ISPASS.Value = "Y", "YES", "NO"), "DataSet1")
</code>
However, I have 4 other fields coded exactly the same way but with different field values like this:
<code>=First(Microsoft.VisualBasic.Interaction.IIF(Fields!ISSUCCESSFUL.Value = "Y", "YES", "NO"), "DataSet1")
</code>
That don't display a "YES" or "NO".  In this particular field, I am supplying it with a "N".  Here is the RB snipit where the PASS expression works great:

And here is a portion of my PDF from this report:

Here is what the data looks like for those fields I'm having the issue with (don't worry about the misspelling on EXCEPTIONAL, it is misspelled everywhere and that isn't the issue):

Here is the C# code used to populate the XSD file:
<code>if (result.Any()) {
  foreach (var item in result) {
    dtResult.Rows.Add(new object[] {
      item.FULLNAME.ToUpper(), item.STORENUM, item.SSID, item.EVALDATE,
      item.EVALYEAR, item.ISEXEPTIONAL, item.ISHIGHSUCCESS,
      item.ISSUCCESSFUL, item.ISUNSUCCESS, item.ISPASS,
      item.JUSTIFICATION, item.OVERALPERFORMANCE,item.SUPERCOMMENT,
      item.curManager.ToUpper(), item.empType, item.questionNo,
      item.questionDescript, item.questionShortTitle, item.questionPass,
      item.questionComment
    });
  }
}
</code>
And here is my XSD layout:

I know this isn't going to be easy to figure out what's wrong, but watching the data I provide to the report looks just fine.  If no one has any ideas, then I guess I will have to rewrite this thing in Crystal Reports and go from there (??).
Comment: Just as an elimination process, have you tried just dumping out the Field values instead of using an expression, just to make sure the data getting passed to the report is exactly how you expect it to be?
Comment: I tried things like the following, is that what you meant?  =First(Fields!ISEXEPTIONAL.Value, "DataSet1")
Comment: That's what I meant. Did you get the expected "n" or "y" ?
Comment: Nope, simply blanks.
Comment: SO it looks like it's your dataset that is the issue. Try creating a table and adding all the fields from your dataset just by dragging them onto it. You should then be able to see exactly what is coming from the dataest.
Comment: That did it, Alan!!  After displaying the data in a table, I could see that they weren't coming through!  Thank you very much.  Can someone tell me how I mark this as the correct answered?  I see only two little icons by people's suggestions:  1) A little up-arrow that says: "This comment adds something useful to the post"; or 2) A little flag that says: "Flag this comment for serious problems or moderator attention."
Answer: Just as an elimination process, have you tried just dumping out the Field values instead of using an expression, just to make sure the data getting passed to the report is exactly how you expect it to be?
It looks like it's your dataset that is the issue. Try creating a table and adding all the fields from your dataset just by dragging them onto it. You should then be able to see exactly what is coming from the dataest.

Report Builder not showing IIF result


Number of sequences of positive integers

Question: Let $n>1$ be a fixed positive integer. Find the number of possible sequences of positive integers $0<j_1<j_2<\ldots<j_i<n,i\geq 1$ with exactly two $q'$s such that $j_q-j_{q-1}>1,q\geq 2.$
Answer: HINT: Basically you're choosing a subset $A$ of $[n-1]=\{1,2,\ldots,n-1\}$ that consists of $3$ blocks of consecutive integers. Such a subset is completely determined by the $6$-tuple
$$\langle j_1,j_{q_1-1}+1,j_{q_1},j_{q_2-1}+1,j_{q_2},j_i+1\rangle\;,\tag{1}$$
where $q_1<q_2$ are such that $j_{q_1}-j_{q_1-1},j_{q_2}-j_{q_2-1}>1$.
A $6$-tuple $\langle a_1,a_2,a_3,a_4,a_5,a_6\rangle$ of elements of $[n]$ is of the form $(1)$ if and only if it is strictly increasing.

Examples. Suppose that $n=7$; the $6$-tuple $\langle 2,3,4,5,6,7\rangle$ corresponds to $j_1=2$, $j_{q_1-1}+1=3$, $j_{q_1}=4$, $j_{q_2-1}+1=5$, $j_{q_2}=6$, and $j_i+1=7$, so $j_{q_1-1}=2$, $j_{q_2-1}=4$, and $j_i=6$. It follows that $q_1-1=1$, so $q_1=2$, and $j_2=4$. Thus, $q_2-1=2$, $q_2=3$, and $j_3=6.$ Finally, this means that $i=3$, and the sequence is $2<4<6$.
The $6$-tuple $\langle 1,3,4,5,6,7\rangle$ corresponds to $j_1=1$, $j_{q_1-1}+1=3$, $j_{q_1}=4$, $j_{q_2-1}+1=5$, $j_{q_2}=6$, and $j_i+1=7$, so $j_{q_q-1}=2$, $j_{q_2-1}=4$, and $j_i=6$. The first block is therefore $12$, the second is $4$, and the third is $6$, the sequence being $1<2<4<6$.

In such a $6$-tuple $a_1$ is the first number in the first block, $a_2$ is the successor to the last number in the first block, $a_3$ is the first number in the second block, $a_4$ is the successor to the last number in the second block, $a_5$ is the first number in the last block, and $a_6$ is the successor to the last number in the last block.
Thus, you need only count the strictly increasing $6$-tuples from $[n]$.
Comment: Sir, one more question, what is the solution if $i$ is fixed?
Comment: @user389160: Yes, $\binom{n}6$ is correct. The situation when $i$ is fixed is quite different; it would be better to make that a new question.


prime division problem

Question: $a,b,c \in$ {0,1,2,...,9} with at least one of $a,b,c$ nonzero.  Prove that the six-digit integer $abcabc$ is divisible by at least 3 distinct primes.
My thinking is not to use induction as there is a definite size to the integer.
So $abcabc$ comes to $c1001 + b10010 + a100100$ with at least one of them nonzero.  This factors to $7^{1}11^{1}13^{1}c + 7^{1}11^{1}13^{1}2^{1}5^{1}b + 7^{1}11^{1}13^{1}2^{2}5^{2}a$ which factors to $7^{1}11^{1}13^{1}(c + 2^{1}5^{1}b + 2^{2}5^{2}a$) so with one of $a,b,c$ nonzero $abcabc$ is divisible by at least 3 primes $7,11,13$.
Comment: More briefly, $$(abc)(abc)=abc(1000+1)$$
Comment: Yes, that is true. Did you just want verification, or was there more that you were trying to ask?
Comment: @qaphla It just asked to prove it.
Comment: @labbhattacharjee, Can you prove that? :)
Comment: @user2008730, Prove what?
Comment: @labbhattacharjee, was just asking you to prove (abc)(abc)=abc(1000+1)
Answer: $$\overline{abcabc}=\overline{abc}(1001)$$
as:
$$\overline{abcabc}\\=10^5a+10^4b+10^3c+10^2a+10^1b+10^0c\\=10^2a(10^3+1)+10^1b(10^3+1)+10^0c(10^3+1)\\=(10^2a+10b+c)(10^3+1)$$
Since $1001$ is divisible by $7,11$ and $13$; you're done.
Comment: Thank you for the explanation.
Comment: What do the * and line over abcabc mean?  Thanks.
Comment: @user2008730 if a=1,b=2,c=3, then $\overline{abc}=123$ just to avoid confusion with $abc=1\times2\times3=6$ and the asterik is just a refernce, i just removed it

prime division problem


WooCommerce REST API - Get Custom Fields for Order

Question: I'm using the WooCommerce REST API (http://woocommerce.github.io/woocommerce-rest-api-docs/#introduction) and are able to download Customers, Orders etc successfully.
My customer has added some custom fields to the checkout page, e.g.:
po_number
accounts_email

I would like to be able to GET these custom fields when requesting an ORDER, e.g.:
/wp-json/wc/v1/orders/4568

At the moment none of the custom fields are returned when I GET an Order. I've tried adding
?filter[meta]=true

to the request URL but that doesn't make any difference. Is there a way I can modify the GET URL to include all custom fields? Couldn't find any reference in the REST API docs to custom fields.
Answer: I have struggled like you did, but then it turns out using the newer v2 REST API solves the issue for me. So instead of:
/wp-json/wc/v1/orders/4568

I now use:
/wp-json/wc/v2/orders/4568

And custom fields will be included in the response with the key meta_data, even with those hidden fields starting with _.


ListView - Details View: Does 'this' belong to 'this'?

Question: In Details View for the ListView Control, how can I do something like this, in the simplest way?
if(listView1.SelectedItem belongs to listView1.Groups["BaseballGroup"])
{
   MessageBox.Show("The selected item is inside the Baseball Group");
}

Answer: Actually there's no property SelectedItem but a list of SelectedItems, then:
if(listView1.SelectedItems[0].Group == listView1.Groups["BaseballGroup"])
{
   //...
}

N.B.
Check if something is selected (SelectedItems.Count > 0) to do SelectedItems[0] safely.
Comment: This'll be inside a SelectedIndex event, so I think it's pretty safe to assume something's selected, but yeah, thanks for pointing that out! :)
Answer: Perhaps you could try
listView1.Groups["BaseballGroup"].Contains(listView1.SelectedItem.ToString())


Getting error:No adapter attached; skipping layout in recyclerview

Question: I tried to fetch the json values from url and shows in listview with adapter in recylerview. but the listview is empty and getting this error 'No adapter attached; skipping layout'. When I tried with the below code its working
for (int i = index; i < end; i++) {
    User user = new User();
    user.setName("Name " + i);
    mUsers.add(user);
}

Here is my part of code, if needed I'll upload complete code
public class OtherNews extends AppCompatActivity {

JSONArray jsonarray;
private RecyclerView mRecyclerView;
private List<User> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
    mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    mUserAdapter = new UserAdapter();

    new DownloadJSON().execute();

    mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            Log.e("haint", "Load More");
            mUsers.add(null);
            mUserAdapter.notifyItemInserted(mUsers.size() - 1);
            //Load more data for reyclerview
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.e("haint", "Load More 2");
                    //Remove loading item
                    mUsers.remove(mUsers.size() - 1);
                    mUserAdapter.notifyItemRemoved(mUsers.size());
                    //Load data
                    int index = mUsers.size();
                    int end = index + 20;
                    for (int i = index; i < end; i++) {
                        User user = new User();
                        user.setName("Name " + i);
                        user.setEmail("alibaba" + i + "@gmail.com");
                        mUsers.add(user);
                    }
                    mUserAdapter.notifyDataSetChanged();
                    mUserAdapter.setLoaded();
                }
            }, 5000);
        }
    });
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall("http://xxxxxxxxx.in/projects/falcon/getallnews.php?page=2");
        if (jsonStr != null) {
            try {
                JSONObject jsonobject = new JSONObject(jsonStr);
                jsonarray = jsonobject.getJSONArray("news");
                // Getting JSON Array node
                for (int i = 0; i < jsonarray.length(); i++) {
                    User user = new User();
                    String title = jsonobject.getString("title");
                    user.setName(title);
                    mUsers.add(user);
                }
            } catch (final JSONException e) {
            }
        } else {
            Log.d(TAG, "someOther)");
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void args) {
        mRecyclerView.setAdapter(mUserAdapter);
    }
}

I get the value in this line of code, but couldn't set in list view.
String title = jsonobject.getString("title");
user.setName(title);

Answer: The issue is exactly like it sounds, an adapter is not being attached when it needs it. You don't attach it until onPostExecute. Just attach it right from the beginning:
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mUserAdapter = new UserAdapter();
mRecyclerView.setAdapter(mUserAdapter);

As you modify the adapter in other parts of the code, your RecyclerView will update automatically, so long as you call notifyDataSetChanged() or some related method.


C++ - Ler o nome dos arquivos de um diretório

Question: Eu estou fazendo um programa para ler todos os arquivos de uma pasta, e limpar o nome dos mesmos ( tirar qualquer acento ).
Gostaria de saber se existe uma biblioteca padrão para trabalhar com diretórios(Ler). Estou utilizando Windows 10, Visual Code com MinGW.
O único exemplo que me atendeu parcialmente é:
<code>#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  struct dirent *ep;

  dp = opendir ("./");
  if (dp != NULL)
    {
      while (ep = readdir (dp))
        puts (ep->d_name);
      (void) closedir (dp);
    }
  else{
    perror ("Couldn't open the directory");
  }
  system("pause");
  return 0;
}
</code>
Answer: Você pode utilizar da biblioteca Boost o componente filesystem exemplo:
<code>#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

int main(int argc, char* argv[])
{
   path Desktop("C://Desktop");
   recursive_directory_iterator end;

   for(recursive_directory_iterator i(Desktop); i != end; ++i)
   {
       path file_name = *i;
       std::cout << file_name.string() << std::endl;
   }
   return 0;
}
</code>
https://www.boost.org/doc/libs/1_71_0/libs/filesystem/doc/index.htm


Save Link field in custom form

Question: I'm brand new at making custom forms and I'm having trouble getting the link field to save to the database.
The text body field saves fine but the link field object defined below it does not. I'm sure that this is an easy fix but I haven't been able to find proper documentation on adding the link field to custom forms.
Thanks in advance.
    /**
* Implements hook_block_configure().
*/

function My_Module_block_configure($delta='') {
$form = array();

switch($delta) {
case 'my_module' :
    // Text field form element
    $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
     );

     //link field
    $form['link'] = array(
        '#type' => 'link_field',
        '#size' => 20,
        '#field_name' => 'link',
    );

    break;
}
return $form;
}

/**
* Implements hook_block_save().
*/
function My_Module_block_save($delta = '', $edit = array()) {
    switch($delta) {
    case 'my_module' :
        // Saving the WYSIWYG text
        variable_set('text_variable', $edit['text_body']['value']);
        variable_set('link_variable', $edit['link']['value']);

        break;
    }
}

Answer: I get success with this. It needs to be improved though, especially the '#language' bit. What I found to be important was to wrap the link field in a container and set '#tree' to true to group it under its key. And the link field is a multi-value field with a link title and url, so you have to take care of that.
function MYMODULE_block_configure($delta='') {
  $form = array();

  switch($delta) {
    case 'my_module' :
      // Text field form element
      $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
      );

      //link field
      $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
      );
      $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und', // how to fix this??
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
          'title' => variable_get('link_title', ''),
          'url' => variable_get('link_url', ''),
        ),
      );
      break;
  }
  return $form;
}

/**
 * Implements hook_block_save().
 */
function MYMODULE_block_save($delta = '', $edit = array()) {
  switch($delta) {
    case 'my_module' :
      // Saving the WYSIWYG text
      variable_set('text_variable', $edit['text_body']['value']);
      variable_set('link_title', $edit['link_container']['link']['title']);
      variable_set('link_url', $edit['link_container']['link']['url']);
      break;
  }
}

Comment: Success! I have also wondered about the language issue. When working with fields I have utilized the Entity API to take care of it however Im not to sure to to handle it here while defining forms either.
Answer: You need to add format in your custom form field as  'format' => 'filter_html' or full_html
So form look like this way
$form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
        'format' => 'filter_html'
     );

Also please check  tags are allowed in text format or not on path 'admin/config/content/wysiwyg/profile/filtered_html/edit' and 'admin/config/content/formats/filtered_html'
Hope it will help
Comment: Hi, I was actually asking about the link field that is defined below the text body. I just left the text_body in the code to show that its working as intended. Do you have any advice for the link form object?
Comment: Just output its value in submit function and pass string to variable_set() rather than passing object. I think it should work.

Save Link field in custom form


How to grab everything but the first line from .txt with JavaScript FileReader?

Question: I have text file and I would like to grab everything but my first line. Also I would like to check how many columns have each of my rows. How that can be done with JavaScript File Reader? I have used code bleow for reading just the first row:
var fileExist = $('#fileUpload')[0];
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function(e) {
    var text = reader.result;
    var firstLine = text.split('\n').shift();
    var columnNames = firstLine.split('\t');

    console.log(columnNames);
}
reader.readAsText(file, 'UTF-8');

Comment: So you can have it read the first line, and you want it to read everything **but** the first line.  Can you show code that demonstrates what you have tried in order to read everything **but** the first line since that is your problem?
Comment: I used this console.log(text.split(/\r\n|\n/));  and that grabs entire text file and split in a separate row. I would like to skip the first line.
Answer: Just get rid of the first line with pop() and then iterate through the Array.
var fileExist = $('#fileUpload')[0];
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function (e) {
    var text = reader.result;
    var allLines = text.split('\n');

    // Print the colomn names
    console.log(allLines.pop().split('\t'));

    // Get rid of first line
    allLines.pop();

    // Print all the other lines
    allLines.forEach(function (line) {
        console.log(line.split('\t'));
    });
}
reader.readAsText(file, 'UTF-8');

Comment: Change pop() to shift() if you want to get rid of the first item in an array (first row in your case)


horzcat error with Eval in Matlab

Question: I am trying to use eval to assign a cellValue to a field in a struct.  The struct has been pre-initialized.  I am getting a horzcat error that I can't remove.  Can you please help me out here.  Also, I know using eval is not recommended.  Can you suggest a better alternative to it that can be used here.  cellValue is a big cell with almost 200,000 rows and this step would be run repeatedly.  So vectorization and efficiency is needed.  Thanks!
varA = struct('Raw', -1, 'ttm', -1, 'USD', -1) ;
cellValue = { 'AAPL' [10010] 'abc' ;
              'AAPL' [10020] 'abc' ;
              'AAPL' [10030] 'abc' } ;

eval([varA '.Raw = ' cellValue ]) %gives horzcat ERROR

% Desired result from varA.Raw = cellValue
varA =
    Raw: {3x3 cell}
    ttm: -1
    USD: -1

Comment: Judging by your own answer, you actually wanted to write `somevar=struct(...);varA='somevar';`... otherwise your proposed solution would still fail.
Comment: ... and in your second code block, it wouldn't be the variable `varA` which contains that data, but the variable whose name is stored in the string variable `varA`.
Answer: EDIT:
You can add another nesting level, and use dynamic field names to reference the variable names:
varName = 'A';
vars.(varName).Raw = value;

Now vars is a structure whos fields are also structures. So you would access them as:
>> vars
vars =
    A: [1x1 struct]
    B: [1x1 struct]
    C: [1x1 struct]

>> vars.A
ans =
    Raw: {3x3 cell}
    ttm: -1
    USD: -1

>> vars.A.Raw
ans =
    'AAPL'    [10010]    'abc'
    'AAPL'    [10020]    'abc'
    'AAPL'    [10030]    'abc'

Comment: @Maddy: global variables and EVALs, you are probably doing it wrong :) http://blogs.mathworks.com/loren/2006/01/04/more-in-eval/, http://www.mathworks.com/support/tech-notes/1100/1103.html
Comment: During runtime, varA keeps changing. So you can have varA,varB,varC...etc in any order.  This is run being inside a loop.
Comment: @Maddy: see my edit above. Although a cleaner approach would be to use an array of structures (use indices instead of variable names to refer to the various components)...
Comment: @Amro..this would also not work.  Actually varA, varB etc example was wrong. The variables names are actually ni, equity, cogs etc.  Everytime I get a big matrix with 1,2,3 or 4 of these names in it in 10000s of rows.  What you are suggesting may requires me to change my global variable design itself!  Can you please suggest any other assignment approach?  Thanks!
Comment: @Amro... Please comment on a 30,000 feet approach to this design problem.  You have 300 functions.  They use variety of data: say 80 data items (matrices) and the names of these matrices are not sequential (i.e. say 'ni' 'equity' etc and NOT mat1, mat2 etc.).  OOP approach is not possible as these 300 functions are grouped into 7 categories.  Dataitems are used across all categories.  By making them global, you can easily use them anywhere.  Inside function you assign global values to local matrices and do your stuff.  What else would work?  OOP approach is not possible for now.  Thanks!
Answer: This expression:
[varA '.Raw = ' cellValue ]

is trying to concatenate a struct, a string, and a cell together into one matrix, which is not possible. That's why you get a horzcat error. What I'm not sure of is why you are using eval. This achieves your desired result:
varA.Raw = cellValue;

If you really want that in an eval, you could do
eval('varA.Raw = cellValue;')

Answer: well this works:
str = strcat(varA,'.Raw = cellValue ')
%varA changes every time. cellValue name is constant.

eval(str)

horzcat error with Eval in Matlab


Block index.php everywhere except in the root directory with .htaccess

Question: I have a folder structure like this:
subdir
|_ subsubdir
  |_ index.php
  |_ other_stuff.php
  |_ images
    |_ pic.jpg
.htaccess
config.ini
index.php

Content of the .htacces file:
Options +FollowSymLinks -MultiViews -Indexes

Order Deny,Allow
<FilesMatch "(\.ini$)|(\.php$)|(^\.)">
    Deny from all
</FilesMatch>
<Files index.php>
    Allow from all
</Files>

My goal is to keep users from viewing subdir/subsubdir/index.php (and all other *.php files, no matter where, but this works already) but allow them to see the index.php in the root directory.
Currently, the user is obviously still able to see subdir/subsubdir/index.php, because all files named "index.php" are allowed, but I have no idea how to allow just the one in the root directory and deny all others. I have tried different things but endet up either completely denying or allowing them all.
I feel like this should be a very easy task but I just can't figure it out.
Things I have tried:
<FilesMatch "\.\/index\.php">
    Allow from all
</FilesMatch>

---

<FilesMatch "^index\.php$">
    Allow from all
</FilesMatch>

---

<Files ./index.php>
    Allow from all
</Files>

---

<Files /index.php>
    Allow from all
</Files>

Answer: Comment out both FilesMatch blocks:
And use this code:
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/index\.php$ [NC]
RewriteRule ^\.|\.(ini|php)$ - [F,NC]

Comment: This works! Didn't think of using mod_rewrite for this... Seems so obvious now. Thank you for the quick answer!


Method or tool to migrate Bugzilla to Team Foundation Server (TFS)

Question: What's is the best method or tool Bugzilla posts to the Team Foundation Server (TFS)?
Answer: Check out this Codeplex project.
Migration Sync Toolkit
It supports Bugzilla
Answer: You could use the Migration and Sync Toolkit from the TFS team and hosted on Codeplex.
Personally I just get the data into a CSV file from my old work item system and then use Excel to get it imported into TFS.  TFS comes with an excellent (no pun intended) Excel integration that is good for bulk actions on TFS work items.  When you are importing, probably easiest to include the orginial systems bug id in the new work item title to make it easier to cross reference to begin with.


Choice of the First Term in Legendre Polynomials

Question: The two solutions of the Legendre's Differential Equation obtained by series solution method are :

and

Now according to my textbook, for the useful polynomial for n equal to a positive integer, the constant $a_{0}$ in the first case is chosen as $a_{0}={\frac{1.3.5...(2n-1)}{n!}}$ and the solution is then called Legendre's polyinomial or coffecient or Zonal Harmonics of the first kind.
For n being the negative integer the constant $a_{0}$ in the second case is chosen as $a_{0}={\frac{n!}{1.3.5...(2n+1)}}$ and the corresponding polynomial is defined as Legendre's function of the second kind.
Now the choice of $a_{0}$ seems rather arbitrary and exactly how is such a choice useful?
P.S.: While solving the Hermite Equation we choose $a_{0}$  in a similar (and apparently) arbitrary manner. Is the reason behind the choice somehow related?
The complete solution of Legendre's equation using series solution method can be found here
Comment: I have a _gut feeling_ that the constants were chosen in such a way, so that terms were identical to those obtained using the generating function. But I can not find any credible source to back my intuition.
Answer: It is in fact not $a_0$ for which a value is chosen. For Legendre polynomials $P_n$, the "normalization" is to set $P_n(1) = 1$. That choice leads to Rodrigues' formula
$$P_n(x) = \frac{1}{2^nn!}[(x^2-1)^n]^{(n)}$$
from which we derive
\begin{equation}
\begin{split}
P_n(x) &= \frac{1}{2^nn!}[(x+1)^n\cdot(x-1)^n]^{(n)}
\\ &= \frac{1}{2^nn!}\sum_{k=0}^{n}\binom{n}{k}[(x+1)^n]^{(k)} \cdot [(x-1)^n]^{(n-k)}
\\ &= \frac{1}{2^nn!}\sum_{k=0}^{n}\binom{n}{k}\frac{n!}{(n-k)!}(x+1)^{n-k} \cdot \frac{n!}{k!}(x-1)^k
\\ &= \frac{1}{2^n}\sum_{k=0}^{n}\binom{n}{k}^2(x+1)^{n-k}(x-1)^k
\end{split}
\end{equation}
so
\begin{equation}
\begin{split}
a_0 &=\frac{1}{2^n}\sum_{k=0}^{n}\binom{n}{k}^2 = \frac{1}{2^n}\binom{2n}{n} = \frac{(2n)!}{2^nn!^2}
\\ &= \frac{(2n)(2n-1)(2n-2)\cdot\cdot\cdot2\cdot 1}{2^n\cdot n(n-1)(n-2)\cdot\cdot\cdot2\cdot 1 \cdot n!}
\\ &= \frac{(2n-1)(2n-3)\cdot\cdot\cdot3\cdot 1}{n!}
\end{split}
\end{equation}
which is exactly the value you found in your textbook.


Question about density in $\mathbb{R}^2$

Question: Let $(\mathbb{R}^2,\tau)$ a topological space where $\tau=\{\emptyset,\mathbb{R}^2\}\cup \{D_k\}_{k\in\mathbb{R}}$ such that $D_k=\{(x,y)\in\mathbb{R}^2,x+y<k\}$
I have to prove that $A=\{(x,y)\in \mathbb{R}^2; ax+by+c=0, a,b,c\in \mathbb{R}, a\neq b\}$ is dense in $\mathbb{R}^2$ i.e., $\overline{A}=\mathbb{R}^2$
I know that we have $\overline{A}\subset\mathbb{R}^2$ but i don't know how to prove that $\mathbb{R}^2\subset \overline{A}$
If i take $(x,y)\in \mathbb{R}^2$ then $(x,y)\in\overline{A}$ iff $~\forall V\in \mathcal{V}_{(x,y)}, V\cap A\neq \emptyset $
but how is defined the neighborhood $V$ of $(x,y)$ ?
Thank you.
Answer: Draw some pictures. Here's a picture of a typical set $D_k$: it's everything below the line $x+y=k$.

The set $A$ is just the line $ax+by+c=0$. If $a\ne b$, the slope of this line is not $-1$, so it's not parallel to the boundaries of the sets $D_k$. Thus, $A$ intersects every line of the form $x+y=k$. That in turn means that for each $k\in\Bbb R$ there are points on the line $ax+by+c=0$ (i.e., points of $A$) that are below the line $x+y=k$ and hence are in the set $D_k$.
Comment: I like this solutions, but I find Hagen's solution really not helpful...
Comment: @FromCuba: You may not realize what it gives you. Pick a number less than $k$, say $k-1$, and plan on choosing $x$ and $y$ so that $x+y=k-1$. Then $$ax+by+c=a(x+y)+(b-a)y+c=a(k+1)+(b-a)y+c\;,$$ and since $b-a\ne 0$, you can solve for a value of $y$ that makes the expression $0$. Then let $x=(k-1)-y$, and you have a point in $A\cap D_k$. (I prefer not to leave this up too long, so I'll delete it shortly.)
Comment: Please don't delete it Sir. This is helpful. I love the way you communicate maths. Maybe Hagen's solution is just too terse, or too dark, but you are a light in such darkness. THANKS!
Comment: @BrianM.Scott thank you for your answer please have you an idea about how to prove that $B=\{D_k,k\in \mathbb{Q}\}$ is a basis for $\tau$ ? thank you
Answer: Take $(x,y)\in \mathbb{R}^2$ then $(x,y)\in G\in \tau$, WLOG, we can assume $G\neq \mathbb{R}^2$. Then $(x,y)\in G=D_k$ for some $k$, that is $d=x+y<k$
Hence consider $l=\{(x,y)\in \mathbb{R}^2|x+y-d=0\}\subset D_k$, note $A=\{(x,y)\in \mathbb{R}^2; ax+by+c=0, a,b,c\in \mathbb{R}, a\neq b\}$ is a line. Since $a\neq b$, $A$'s slope is different from $-1$. So $A$ and $l$ is not parallel, hence they must intersect at some point $P$.
So
$P\in l\cap A\subset D_k\cap A\neq \emptyset $ We have done.
Comment: $a\neq b$ so why $D_k\cap A\neq \emptyset $ ? please
Comment: @Vrouvrou Note given $a,b,c$,$A$ is a fixed line. Given $D_k$, we aim to show $D_k \capA$ is not empty. What we do is construct a line $l$ which is contained in $D_k$, and prove $l$ intersects $A$ is non-empty. Since $l$ has slope -1, $A$ has slope different from $-1 (a\neq b)$, so the two lines must intersect.
Comment: May I know what is the reason for a downvote?
Comment: @JohnZHANG: I'm rather curious about that myself, but experience suggests that an answer is unlikely to be forthcoming. I've upvoted both your answer and Hagen's elegant approach.
Answer: It is sufficient to show that any nonempty open subset intersects $A$. Since $ax+by+c=a(x+y)+(b-a)y+c$, it is not hard to find $x,y$ such that $x+y<k$ and yet $ax+by+c=0$.
Comment: I dont understand your methods !


How to change a method in DOM objects prototype

Question: I want to change open() method in XMLHttpRequest objects. actually I need to change every url that will send trough xhr. how can I do this?
for example when xhr objects open one request for http://domain.com/ I want to change it to https://domain.com/
Comment: I wouldn't advise that you actually change the default method. Just create your own function that returns XHR objects made to your liking.
Comment: This may be possible, but either way it is terrible practice to alter the prototype of native constructors, even more existing ones. What if you or a future extension ever need to make a request with the `http` protocol? It will be broken and fixing it will then break the rest of your application.
Answer: You can intrupt any method on native DOM objects but that is not recommnended. Don't do this.
Anyway if you want to know how to manipulate XMLXttpRequest's open method, this is how you do it:
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){
   // do stuff you want
   // for example console.log:
   console.log('test');
   // then let open method happen
   open.apply(this, arguments);
}

For your very use case that is changing protocol of URL, you can do this:
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){
   var link = document.createElement('a'); // make an anchar element
   link.href = arguments[1]; // make it's href equal to second argument which is URL
   link.protocol = 'https:'; // force https to the link
   arguments[1] = link.href; // write back URL form link that is now start with 'https'
   // then let open method happen
   open.apply(this, arguments);
}

Comment: dear mohesen I have a question and hope you can answer me :X
Comment: how I can trap all http requests by javascript? I need to change all of them


Angular2 checkbox - uncheck event

Question: Hello I have dropdown menu with checkboxes and I have a problem with call function when click on dropdown menu item. Here is my code:

              <input type="checkbox" value="" #checkbox [(ngModel)]="filter.checked"
                 (ngModelChange)="onSelectFilter(column)">{{filter.value}}

Function onSelectFilter() is not called when checkbox is checked (I need to call with uncheck).
What event I must use when I need call method with check and uncheck?
Thanks
Comment: [**It works for me**](http://plnkr.co/edit/2U3vDKQcBWlz1MXAsMTe?p=info).
Answer: Take away the value="" and just set the initial model (filter.checked) to what you want it to start out as.
The value="" thing will just get in the way! :)
Also, it seems like you're using an ngFor to give you a list of checkboxes... but in the (ngModelChange), you are passing through the entire column (which has multiple checkboxes)... This may not be what you are intending to do?
eg. I think this might be more what you want?
(ngModelChange)="onSelectFilter(filter)"

Comment: Thanks, when I edited checkbox, it works: `

{{filter.value}}

`
Comment: Excellent :) It's very easy to get caught out doing little "standard html" things that angular doesn't like!

Angular2 checkbox - uncheck event


How to select react function in getdocumentbyclass?

Question: I dont know how to select function react in document.getElementsByClassName.
I have this
document.getElementsByClassName('card-list__card grid-layout-item grid-list-item')[0]

return

"__reactInternalInstance$6xvjhfpf2k": Object { tag: 5, key: "545570876", elementType: "div", … }

This function __reactInternalInstance as random variable.
when I reload the page the function changes name
how I can select this to recover the key ?
document.getElementsByClassName('card-list__card grid-layout-item grid-list-item')[0].__reactInternalInstance*

is there an equivalent?
Thank's for your help.
Comment: You could iterate over the dom object's properties and see which one has the prefix `__reactInternalInstance`
Comment: iterate return undefined
var els = document.getElementsByClassName("card-list__card grid-layout-item grid-list-item")[0];
for (item in els){
 if(item.includes("__reactInternalInstance")){
  document.getElementsByClassName("card-list__card grid-layout-item grid-list-item")[0].item
 }

}
Comment: you used the wrong syntax, to use a variable as a key you use the `[]` notation, eg `els[item]`
Answer: Use an id and use document.getElementById("yourIdGoesHere")
Comment: I don't have an id, the element is a class
Comment: Can you provide more code so we can help you further from where you are struggling?


How to prove that $\mathrm{E}\left[ \left \| \sum_{i=1}^n \mathbf{x}_i \right \|^2 \right] = n$ for random vectors of unit-length?

Question: While tinkering with some numerical simulations of random walks using random vectors of unit-length, I stumbled upon the following:
Say, we have $n$ random vectors, $\mathbf{x}_i \in \mathbb{R}^{d+1}$, where "random" means uniformly sampling the unit $d$-sphere, then it appears that the following is true:
$$
\mathrm{E}\left[ \left \| \sum_{i=1}^n \mathbf{x}_i \right \|^2 \right] = n
$$
where $\left\|\cdot\right\|$ is the Euclidean norm, and $\mathrm{E}\left[\cdot\right]$ is the expected value. To me, this is the kind of thing you would derive as an approximation at large $n$ using the central limit theorem, but numerically this expression seems to be exactly true for all $n$ and $d$, even for small $n$.
For $d=1$, this is just a simple random walk and easy to prove. But I don't know how to prove this generally for arbitrary $n$ and $d$.
Comment: Your question should be rephrased as if $n$ points are selected uniformly, **Independently** and randomly from the unit sphere. Then $E(||\sum_{k=1}^{n}x_{i}||^{2})=n$
Answer: \begin{align}
\mathbb E\left[\left\|\sum_{i=1}^n \mathbf x_i\right\|^2\right] &= \sum_{i=1}^n \sum_{j=1}^n \mathbb E\left[\left\langle \mathbf x_i, \mathbf x_j\right\rangle\right] \\
&= \sum_{i=1}^n \mathbb E\left[\left\|\mathbf x_i\right\|^2\right] + \sum_{i=1}^n \sum_{j=1,\, j\neq i}^n \left\langle \mathbb E\left[\mathbf x_i\right], \mathbb E\left[\mathbf x_j\right]\right\rangle\\
&= n
\end{align}
Comment: @XYZT The "uncorrelatedness" has to be assumed beforehand
Comment: @AlexOrtiz Korki is writing $E(\langle x_{i},x_{j}\rangle)=\langle Ex_{i},Ex_{j}\rangle$ that requires independence.
Comment: Ah, I see! The cross-terms disappear because they are uncorrelated on average, so $\mathrm{E}\left[\left\|\sum x_{i}\right\|^{2}\right] = \mathrm{E}\left[\sum\left\| x_{i}\right\|^{2}\right] = n$
Comment: Ah, never mind - you got rid of your hints and replaced it with an answer.
Comment: @AlexOrtiz Otherwise if you really think about it, if we just restrict to two vectors and chosing $x_{2}=-x_{1}$ would result you with $0$ norm.


Requests to Django web app are hanging; simple debugging tips?

Question: Update - solved
The issue turned out to be the servers had a mount pointing at a file server that was retired earlier this week; so not related to django / mod-python / etc after all. Updating the mount solved the problem.
Many thanks for the comments & help, and apologies for a wild goose chase ... I'll look into upgrading off mod-python in any case:-)
Summary
I'm maintaining a Django webapp that was working fine until a few days ago, but now all web requests just hang for ages. I'm not aware that anything has changed, so the problem is probably something fairly simple.
I've tried restarting the webserver, and restarting httpd. 'top' shows the server is doing fine for CPU and memory.
Can anyone suggest other simple things that are liable to go wrong, or other things to check?
More details
I didn't create the web server, so unfortunately I'm not entirely sure of the full details, or where to look for all the logs etc. I know the web server is made of the following components: implemented using Django; runs on a Linux server; uses PostgreSQL database; lighttpd for static content; Apache to handle incoming HTTP requests and pass them through to Django via mod_python; uses memcached to cache rendered pages. I do have full access to the Linux server and the database, so can happily poke around in anything if I know where to look.
/var/log/httpd/access_log and error_log show lines like the following whenever I make a new request. I don't know if the mod_python line indicates an error or not (nothing obvious when I googled this log).
access_log:
<code>127.0.0.1 - - [13/Jan/2011:10:56:11 +0000] "GET /testruns/testrun2176/ HTTP/1.0" 301 - "http://myapp/testruns/" "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:188.8.131.52) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729; .NET4.0E)"
</code>
error_log:
<code>[Thu Jan 13 10:34:19 2011] [notice] mod_python: (Re)importing module 'django.core.handlers.modpython'
</code>
Output from running development server
<code># python manage.py runserver 0.0.0.0:8088
Validating models...
0 errors found

Django version 1.0-final-SVN-unknown, using settings 'myapp.settings'
Development server is running at http://0.0.0.0:8088/
Quit the server with CONTROL-C.
[13/Jan/2011 14:23:31] "GET /testruns/testrun2176/ HTTP/1.1" 301 0
</code>
Then nothing happens. Webpage just stuck loading.
I can load one of the pages that is slightly simpler. Via the dev version the pictures don't load but it's otherwise fine. The simple page is at /testruns/ - though for some reason I don't see that page in the runserver output:
<code># python manage.py runserver 0.0.0.0:8088
Validating models...
0 errors found

Django version 1.0-final-SVN-unknown, using settings 'myapp.settings'
Development server is running at http://0.0.0.0:8088/
Quit the server with CONTROL-C.
[13/Jan/2011 14:27:42] "GET /static/myapp.css HTTP/1.1" 404 1113
[13/Jan/2011 14:27:42] "GET /static/myapp_print.css HTTP/1.1" 404 1113
[13/Jan/2011 14:27:42] "GET /static/myapp_ticks_crosses.css HTTP/1.1" 404 1113
</code>
I should point out again, this was all working fine a few days ago. I haven't explicitly changed anything since then - I just suddenly found that the required pages won't load, and I'm trying to find out why.
The /var/log/httpd/ log files don't seem to show anything particularly interesting, and I'm not sure what else I should look at.
We're running a second server that works on a different set of test results. Running the development server on that shows that the 301 redirect is expected (.../testrunX/ redirects to .../testrunX/broken/page1/).
<code>// This trace, on a different server but with a similar setup, shows that the
// 301 redirect is expected, and is not the source of the problem
[server2]# python manage.py runserver 0.0.0.0:8088
Validating models...
0 errors found

Django version 1.0-final-SVN-unknown, using settings 'myapp.settings'
Development server is running at http://0.0.0.0:8088/
Quit the server with CONTROL-C.
[13/Jan/2011 14:47:59] "GET /testruns HTTP/1.1" 301 0
[13/Jan/2011 14:47:59] "GET /testruns/ HTTP/1.1" 200 11568
[13/Jan/2011 14:47:59] "GET /static/myapp.css HTTP/1.1" 404 1131
[13/Jan/2011 14:47:59] "GET /static/myapp_print.css HTTP/1.1" 404 1131
[13/Jan/2011 14:47:59] "GET /static/star.png HTTP/1.1" 404 1131
[13/Jan/2011 14:47:59] "GET /static/myapp_ticks_crosses.css HTTP/1.1" 404 1131
[13/Jan/2011 14:47:59] "GET /static/star.png HTTP/1.1" 404 1131
[13/Jan/2011 14:48:02] "GET /static/star.png HTTP/1.1" 404 1131

[13/Jan/2011 14:48:12] "GET /testruns/testrun1879/ HTTP/1.1" 301 0
[13/Jan/2011 14:48:12] "GET /testruns/testrun1879/broken/page1/ HTTP/1.1" 200 309477
[13/Jan/2011 14:48:12] "GET /static/myapp.css HTTP/1.1" 404 1131
[13/Jan/2011 14:48:12] "GET /static/myapp_print.css HTTP/1.1" 404 1131
[13/Jan/2011 14:48:13] "GET /static/myapp_ticks_crosses.css HTTP/1.1" 404 1131
</code>
So I don't think there's an infinite loop. Just for some reason the request / database query / something else is taking far too long or is completely stuck.
memcached info
memcached on the bad server seems pretty empty. But that's probably expected if the web requests are failing, ie nothing's been returned to be stored in the cache (and the cache expiry time is 12 hours).
Bad server:
<code>// Top - only using 6K memory (VIRT)
PID   USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
30743 nobody    15   0  6640 4972  476 S  0.0  1.9   0:00.01 memcached

// memcache-top from http://code.google.com/p/memcache-top/
// only using 0.2% available space
memcache-top v0.6       (default port: 11211, color: on, refresh: 3 seconds)
INSTANCE                USAGE   HIT %   CONN    TIME    EVICT/s READ/s  WRITE/s
127.0.0.1:11211         0.2%    0.0%    5       0.8ms   0.0     2       161
AVERAGE:                0.2%    0.0%    5       0.8ms   0.0     2       161
TOTAL:         111.0KB/ 64.0MB          5       0.8ms   0.0     2       161
</code>
Good server:
<code>// Top - using ~68K memory (VIRT)
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2503 nobody    15   0 67900 8256  396 S  0.0  3.2   0:01.68 memcached

// memcache-top - using 63% space
memcache-top v0.6       (default port: 11211, color: on, refresh: 3 seconds)
INSTANCE                USAGE   HIT %   CONN    TIME    EVICT/s READ/s  WRITE/s
127.0.0.1:11211         63.2%   0.0%    3       1.2ms   0.0     0       0
AVERAGE:                63.2%   0.0%    3       1.2ms   0.0     0       0
TOTAL:          40.5MB/ 64.0MB          3       1.2ms   0.0     0       0
</code>
Comment: 301 resonse suggest a redirect...seems like the url might be causing an infinite loop
Comment: If the images won't show up when on the dev server you're most likely missing a correctly configured static view to serve them! As you describe the problem it's probably more related to the url configuration and your view...
Answer: Just some points to mention:

You should try to get away from using mod_python as soon as possible, since its usage is deprecated and it will not be supported by django in the future.
Can you reproduce the problems using the development server?
Can you reproduce it using a different database backend?
Try to use django-debug-toolbar to check if too complex database queries or similar problems occur!
The line in your error log doesn't indicate an error!
Comment: Running the development server hits the same problem - the request hangs. At the moment I'm trying to concentrate on why this doesn't work now, when it did a few days ago. I don't think any of the setup has changed; except more data is in the database perhaps.
Longer term moving off mod_python may be an option, but in the meantime I don't see how that could have cased the current issue.
Comment: @sam, you said you tried runserver. What is the output of runserver when you request a page. If you see no output, there might be firewall or ohter connection problems. You might be trying to access page with wrong url.
Comment: @Skirmantas - I've updated the question to show this output. I'm fairly certain that this isn't a URL / firewall etc problem, as this was all working fine until yesterday.


No option to create 'custom apps/tabs' in business page?

Question: I'm trying to add a page tab, or sometimes referred to as custom app/tab to our Facebook Business Page but when I log into our account I can't find the option anywhere.
I am logged in with the "manager" role, which actually is the only account for the page.
I can log into my own personal facebook account and create all the apps for the pages I manage no problem, but the difference is I want to create tabs/app pages for this business page I'm working on.
Please any help would be appreciated, I can't believe how hard it is to find any information on this.
Answer: Not sure if its of any help in your case but you could try the following, just replace "YOUR_APP_ID" and "YOUR_URL" with the ID and URL of the app you want to add as a tab.
"http://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_URL"
Source.
http://developers.facebook.com/docs/appsonfacebook/pagetabs/
Example
http://www.facebook.com/dialog/pagetab?app_id=102452128776&next=https://apps.facebook.com/onthefarm/
The above example will give you the option to add "Farmville" to a page that you manage.
Comment: Thx. I need the custom tab to appear on the facebook business page however, so the link in in itself is not really the issue.
Comment: Are you able to add an app to the page but it is not showing up? I have just now added an app to one of my pages and it seems to work just fine, for me anyway, might be the page type, have you the Page Tab URL's in the developers section filled in? sorry I can't be of more help.


Spotify player not showing in emulator

Question: I'm working with the spotify api and I have one song ready to play. When i open my app, the song plays but I cannot see the spotify player (i.e. media control). any insight on this? I'm new to android studio. Here is some code I have. It authenticates the user as a premium user and plays the track.
public class MainActivity extends Activity implements
        PlayerNotificationCallback, ConnectionStateCallback {

    //redirect uri and other stuff

    private Player mPlayer;

    private static final int REQUEST_CODE = 1337;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(CLIENT_ID,
                AuthenticationResponse.Type.TOKEN,
                REDIRECT_URI);
        builder.setScopes(new String[]{"user-read-private", "streaming"});
        AuthenticationRequest request = builder.build();

        AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        // Check if result comes from the correct activity
        if (requestCode == REQUEST_CODE) {
            AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
            if (response.getType() == AuthenticationResponse.Type.TOKEN) {
                Config playerConfig = new Config(this, response.getAccessToken(), CLIENT_ID);
                Spotify.getPlayer(playerConfig, this, new Player.InitializationObserver() {
                    @Override
                    public void onInitialized(Player player) {
                        mPlayer = player;
                        mPlayer.addConnectionStateCallback(MainActivity.this);
                        mPlayer.addPlayerNotificationCallback(MainActivity.this);
                        mPlayer.play("spotify:track:3G69vJMWsX6ZohTykad2AU
    ");
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("MainActivity", "Could not initialize player: " + throwable.getMessage());
                    }
                });
            }
        }
    }
    @Override
    public void onLoggedIn() {
        Log.d("MainActivity", "User logged in");
    }

    @Override
    public void onLoggedOut() {
        Log.d("MainActivity", "User logged out");
    }

    @Override
    public void onLoginFailed(Throwable error) {
        Log.d("MainActivity", "Login failed");
    }

    @Override
    public void onTemporaryError() {
        Log.d("MainActivity", "Temporary error occurred");
    }

    @Override
    public void onConnectionMessage(String message) {
        Log.d("MainActivity", "Received connection message: " + message);
    }

    @Override
    public void onPlaybackEvent(EventType eventType, PlayerState playerState) {
        Log.d("MainActivity", "Playback event received: " + eventType.name());
    }

    @Override
    public void onPlaybackError(ErrorType errorType, String errorDetails) {
        Log.d("MainActivity", "Playback error received: " + errorType.name());
    }

    @Override
    protected void onDestroy() {
        Spotify.destroyPlayer(this);
        super.onDestroy();
    }
}

EDIT: I was not including an implementation of a UI whatsoever.  I further fixed this problem by writing the following xml.
<EditText
        android:id="@+id/songName"
        android:layout_width="358dp"
        android:layout_height="61dp"
        android:inputType="text"
        android:hint="Song"
        android:ems="10"
        android:gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout3"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp" />

    <EditText
        android:id="@+id/artistName"
        android:layout_width="358dp"
        android:layout_height="64dp"
        android:inputType="text"
        android:ems="10"
        android:gravity="center_horizontal"
        android:hint="Artist"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        app:layout_constraintTop_toBottomOf="@+id/songName"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp" />

    <fragment
        android:id="@+id/fragment"
        android:name="com.example.joeberg.jamstest.fragments.LyricsFragment"
        android:layout_width="358dp"
        android:layout_height="400dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="56dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/artistName"
        tools:layout="@layout/fragment_lyrics" />

    <Button
        android:id="@+id/playButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="104dp"
        android:layout_marginTop="0dp"
        android:onClick="playSongButton"
        android:text="Play/Pause"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/artistName" />

    <Button
        android:text="Pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/pauseButton"
        android:onClick="pauseSongButton"
        app:layout_constraintLeft_toRightOf="@+id/playButton"
        app:layout_constraintTop_toBottomOf="@+id/artistName"
        android:layout_marginTop="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="0dp"
        android:onClick="pauseSongButton"
        android:text="Reset"
        app:layout_constraintLeft_toRightOf="@+id/playButton"
        app:layout_constraintTop_toBottomOf="@+id/artistName" />

This allowed me to control song playback with play and pause buttons. It also allowed me to search for songs.
Answer: When you're using Spotify's API to play music, you only get the music playback. You don't get any UI included. You will have to build that yourself.

Spotify player not showing in emulator


Alterar linguagem no github

Question: Tenho um projeto desenvolvido em Python com Django.
Acabei de criar um repositório e dar o pull no github e o projeto foi setado como sendo de PHP no site do Github:

Algumas imagens do meu projeto e seus arquivos:

Então:

Alguém sabe como e porque o Github fez essa escolha? Eu não tenho nenhum arquivo php nesse projeto. (Quando criei essa pergunta eu me enganei. Veja na minha resposta que eu tinha 2 arquivos .php sim)
Como eu altero a linguagem para Python?
Comment: Vc só enviou para o repositório ou vc está tentando publicar como GitPage ?
Comment: Eu criei um repositório no site do github e subi o projeto nele.
O estranho é que subi o mesmo projeto no GitLab e não aconteceu isso.
Queria entender o que o Github usou como base para decidir por PHP, sendo que nao tenho nenhum arquivo php no projeto
Comment: @hugocsl não tem nada haver com gitpage a questão é sobre o repositório mesmo.
Comment: Não tem como saber porque ele apontou PHP se você não detalhar a pergunta, algo tem que ter no teu repositório.
Comment: Por acaso [este usuário](https://github.com/bussola?tab=repositories)? Pois bem, na listagem geral não mostra nada em PHP
Comment: @GuilhermeNascimento eu perguntei pq o GitPagem não aceita nada além de html/css/js, então poderia estar dando algum alerta "genérico" caso ele estivesse tentando publicar como Page
Comment: É porque o repositório está como particular. Somente eu tenho acesso a ele @JeffersonQuesado
Comment: Engraçado que você afirmou ***"Eu não tenho nenhum arquivo php nesse projeto."***, suas palavras, mas aceitou a pergunta que elimina no linguist os arquivos .php, ou seja na verdade existe sim arquivos .php, eu ia responder, mas evitei pelo simples fato de poderem ser arquivos com "extensões primas" no php como `.phtml` ou `.php3`, ai se eu responde-se poderia dar certo ou não, faz o que eu disse no outro comentário, clique na bolinha azul ao lado do "PHP" e veja os arquivos que aparecem e tira um print.
Comment: @hugocsl a pergunta é sobre o LINGUIST e não sobre PHP funcionar em githubpages, tanto que ele não mencionou nada sobre executar PHP, mas sim sobre o linguist não funcionar como esperado quando usado no automático.
Answer: O Github usa a biblioteca Linguist para determinar a porcentagem de cada linguagem em um projeto e gerar aquela barra maneira lá em cima, contudo, não está livre de falhas.
O método mais rápido de resolver isso é criar um arquivo chamado .gitattributes na raiz do seu diretório e lá colocar as seguintes linhas:
* linguist-vendored
*.php linguist-vendored=false

Assim ele vai ignorar os arquivos do tipo .php. Na teoria é pra correção funcionar retroativamente já no commit deste arquivo, mas caso não funcione você pode deletar e criar um novo projeto com este arquivo já por default.
Você pode também dizer qual linguagem quer que ele aponte como sendo a do projeto:
*.python linguist-detectable=true

Não esqueça também de ir no repo da biblioteca e abrir uma issue com o seu problema.
Comment: Ok, isto resolve, mas claramente o que o autor afirmou então não é verdade, porque se é necessário o false para `*.php` então significa que tem sim arquivos .PHP, o que foi o motivo de ninguém ter respondido até agora, porque ele disse exatamente isto: **Alguém sabe como e porque o Github fez essa escolha? Eu não tenho nenhum arquivo php nesse projeto.**, e poderia ser outra extensão que teria causado o problema, alguma extensão coincidentemente "prima do php", como .php3 ou phtml.
Comment: @GuilhermeNascimento realmente não existem arquivos .php no repositório...
O projeto é todo em python mesmo...
Comment: @ViniciusBussola mas não importa, o problema é que tem alguma extensão "prima" que não é de fato PHP mas esta confundindo, o repositório é PUBLICO ou privado? Com certeza tem algo errado, faça o seguinte, clique na bolinha azul ao lado do "PHP", ele vai exibir os arquivos que causaram isto no linguist.
Comment: @GuilhermeNascimento o repositorio é privado infelizmente..
A bolinha azul nao é clicavel tb..
Assim que descobrir o que causou isso compartilho aqui
Answer: Descobri o que era.
Primeiramente, como o @GuilhermeNascimento já tinha alertado em algum comentário, minha pergunta está errada, pois descobri que dentro do meu arquivo static existem sim 2 arquivos .php.

Então sim, existem arquivos .php no meu projeto (Apesar de serem somente 2);
A resposta do @Max infelizmente não funcionou, não sei o porque;

Conclusão dos meus testes com o arquivo .gitattributes:

Colocando apenas * linguist-vendored o github retira a informação da linguagem, deixando esse campo em branco;
Precisei desconsiderar minha pasta static, onde haviam os 2 arquivos .php;
Como o projeto foi desenvolvido em Django, tive que desconsiderar as pastas dos meus templates, para que o github nao entenda o projeto como sendo .html

Meu arquivo .gitattributes ficou assim:
static/* linguist-vendored
site_cartao/static/* linguist-vendored
site_cartao/templates/* linguist-vendored

E o resultado:

Alterar linguagem no github


How to use metatags_quick to add no-cache meta tags in D7?

Question: I'd like to add the following to the meta tags for a single page on my D7 site:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

Taken from here
However, when I try to use metatags_quick to accomplish this, it names all my metatags as
<meta name="Cache-Control" content="no-cache, no store, must revalidate">

with the "name=" attributes rather than "http-equiv".  How can add these tags?
Answer: I want to say that, in some cases, you can add by template way your meta tags to your specific page.
you can locate html.php.tpl in modules > system file. copy and paste it inside your template directory. then add your meta tags using some php code to show these tags only in that specific page:
  <?php
  if(isset($_GET['q'])){
      $path = $_GET['q'];
      if(preg_match('/test/', $path)){
      ?>
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="0">
      <?
      }
  };
  ?>

(you can add this snippet before, for example, the <title> tag line)
remember that if you need your meta in more pages, you can replace the pattern of preg_match() php function (in this example is /test/) for several pages (for example /(test|another_test_page|another)/ )
Update: if you do not see changes, is very important clear cache to see changes.
Update2 drupal_get_path_alias() could be an useful function to get the current alias: Given an internal Drupal path, return the alias.
Comment: I'm dumb---had to clear cache.  Your solution worked perfectly.  Thanks.
Comment: I copied this into the html.tpl.php (it's that way, right?  You wrote html.php.tpl) just above the  line, and changed '/test/' to 'Page-Name', since I'm looking to do this on "www.mysite.com/Page-Name".  I moved this into my active template directory.  It did not seem to have any effect, and isn't visible when I view source on that page.  Any suggestions on what I've done wrong?
Comment: hello @Mittenchops. change Page-Name by /Page-Name/ (please do not remove // characters, are important delimiters of string, and not is related with paths). Also remember that you can debug each php line, for example, see with `echo $_GET['q'];` if is getting the correct string. also review if changing delimiters in preg_match() function help (change /Page-Name/ for #Page-Name#)

 one note: please remember do not change the html.php.tpl in `modules > system`. you must change a copy used inside your template directory.
Comment: That's really strange---I added the slashes back, and noticed that even when I add `if(true){ ... ` as the conditional statement, it still isn't displaying.  I am editing the copy in my theme's template directory, rather than in `modules > system`, so I wonder what the issue is.   The place I need to copy the file is in my theme's template directory, right?
Comment: you have reason, clear cache! I will add this in the answer! Thanks to you.


How do I add custom tab in the user profile page?

Question: I need to add a custom tab in user profile page. I defined my route like below:
mymodule.routing.yml
mymodule.account:
path: '/user/{user}/custom'
defaults:
  _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
  _title: 'Custom Settings'
  user: \d+
requirements:
  _permission: 'access content'

mymodule.links.task.yml
mymodule.account:
  title: Mymodule Settings
  route_name: mymodule.account
  base_route: entity.user.canonical

mymodule.links.menu.yml
mymodule.account:
  title: My module Settings
  parent: entity.user.canonical
  route_name: mymodule.account

Then after clear cache tab is appearing in the profile page. But when I open the url /user/1/custom I see the page not found message.
Comment: user: \d+ should go under requirements - make that change, clear all cache, see if you still get page not found.
Answer: Your problem is in the mymodule.routing.yml file, the big problem is the place of user: \d+, this line must be under the requirements: section, the other problem is the indentation. So the final code should be:
mymodule.account:
  path: '/user/{user}/custom'
  defaults:
    _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
    _title: 'Custom Settings'
  requirements:
    _permission: 'access content'
    user: \d+

And of course you need the form class definition in src/Form/MyModuleUserSettingsForm.php
<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class MyModuleUserSettingsForm.
 *
 * @package Drupal\mymodule\Form
 */
class MyModuleUserSettingsForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'simple_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#maxlength' => 64,
      '#size' => 64,
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
    ];

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {  }

}

And a mymodule.info.yml file to complete your module (in this case named mymodule)
name: My Module
type: module
description: 'My module'
core: 8.x
package: Custom

Reference:
Structure of routes
Comment: Interesting that the [Structure of routes](https://www.drupal.org/docs/8/api/routing-system/structure-of-routes) does not mention the key `user:` nor where it should go... Perhaps the docs need to be improved/edited? or did I miss something?
Comment: nvm, I see, it's under **_entity_access:** and they used node as an example there, hence why my CTRL + F "user:" did not find anything.
Answer: There are two ways to load a form using a route.  You can either load up a callback that loads a form and returns it as part of the build array, or you can load up the form directly by setting the _form parameter under defaults.
You can search the codebase to find working examples, copy them into your mymodule.routing.yml, edit them to your needs and then rebuild the cache.
Loading form from callback:
There's a working example in the contact module:
/core/modules/contact/contact.routing.yml
entity.user.contact_form:
  path: '/user/{user}/contact'
  defaults:
    _title: 'Contact'
    _controller: '\Drupal\contact\Controller\ContactController::contactPersonalPage'
  requirements:
    _access_contact_personal_tab: 'TRUE'
    user: \d+

Then in /core/modules/contact/src/Controller/ContactController.php
you can see an example of how to load a form in the callback:
  public function contactPersonalPage(UserInterface $user) {
    // Do not continue if the user does not have an email address configured.
    if (!$user->getEmail()) {
      throw new NotFoundHttpException();
    }

    $message = $this->entityManager()->getStorage('contact_message')->create(array(
      'contact_form' => 'personal',
      'recipient' => $user->id(),
    ));

    $form = $this->entityFormBuilder()->getForm($message);
    $form['#title'] = $this->t('Contact @username', array('@username' => $user->getDisplayName()));
    $form['#cache']['contexts'][] = 'user.permissions';
    return $form;
  }

Loading form directly from the route:
If you would like to load the form directly using the _form default, there's an example in the shortcut module at /core/modules/shortcut/shortcut.routing.yml
shortcut.set_switch:
  path: '/user/{user}/shortcuts'
  defaults:
    _form: 'Drupal\shortcut\Form\SwitchShortcutSet'
    _title: 'Shortcuts'
  requirements:
    _custom_access: 'Drupal\shortcut\Form\SwitchShortcutSet::checkAccess'
  options:
    _admin_route: TRUE
    user: \d+

In this case, the user is passed in as a parameter to the form, see
/core/modules/shortcut/src/Form/SwitchShortcutSet.php
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {

Answer: A few things I can spot off hand...
You've got EVERYTHING named mymodule.account. I'd diversify that a bit. Consider going with this for the tasks page:
mymodule.account_tab:
  title: Mymodule Settings
  route_name: mymodule.account
  base_route: entity.user.canonical

I also do not believe you need anything in the menu either for this.
Between those two, you should be good to go! Feel free to reach out to me directly if you can't figure this out because I --JUST-- got this to work on my D8 port of Apply For Role!
Answer: In modulename.routing.yml you have to pass user argument like below
profile.user_information:
  path: '/user/{user}/profile'
  defaults:
    _form: '\Drupal\profile\Form\UserInformation'
    _title: 'UserInformation'
  requirements:
    _permission: 'access content'
  options:
    user: \d+

and in modulename.links.task.yml you have the code like below
profile.user_information:
  title: User profile
  route_name: profile.user_information
  base_route: entity.user.canonical


rearrange array elements

Question: In an array T we have values [e,t,m,a]. How to reorder this array in a single loop in the aim to get [t,e,a,m]?
Comment: Your question makes no sense. Do you mean you want to sort it? Or do you mean you want to have it in an arbitrary order? Please add more context
Answer: var T = ['e','t','m','a']
var ordered = order(T)
function order(T){
  return [T[1],T[0],T[3],T[2]]
}

... or ...
T.concat(T.splice(0,2)).reverse()

Answer: I think even though it's phrased poorly and doesn't seem to make sense why you'd need to do this, if I'm deciphering your question correctly this is what you're trying to do:
var goal = ['a','t','o','m','i','c'],
    scramble = ['c', 't', 'm', 'a', 'o', 'i'],
    index,
    holder;

for (var i = 0, gl = goal.length; i < gl; i++) {
    index = scramble.indexOf(goal[i]);
    holder = scramble.splice(index, 1)[0];
    scramble.splice(i, 0, holder);
}

alert(scramble); // -> a,t,o,m,i,c

rearrange array elements


Why is extended grep not working?

Question: When I try extended grep like this it does not work.
const char *grep[] = { "grep", "-E", "'JOBS|COMPIZ'" };
If I do it just for one string without single quotes then it works. Why? Why can't I build up arguments to extended grep like above? The following with just one string is working.
const char *grep[] = { "grep", "-E", "JOBS" };
My program should do printenv | sort | grep <parameter-list> | less and if no arguments to main then the program should do printenv | sort | less. I already achieved the latter functionality and now I need to achieve the grep of parameter list but I can't seem to do extended grep from within C code.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct command
{
    const char **argv;
};

int
spawn_proc (int in, int out, struct command *cmd)
{
    pid_t pid;

    if ((pid = fork ()) == 0)
    {
        if (in != 0)
        {
            dup2 (in, 0);
            close (in);
        }

        if (out != 1)
        {
            dup2 (out, 1);
            close (out);
        }

        return execvp (cmd->argv [0], (char * const *)cmd->argv);
    }

    return pid;
}

int
fork_pipes (int n, struct command *cmd)
{
    int i;
    pid_t pid;
    int in, fd [2];

    /* The first process should get its input from the original file descriptor 0.  */
    in = 0;

    /* Note the loop bound, we spawn here all, but the last stage of the pipeline.  */
    for (i = 0; i < n - 1; ++i)
    {
        pipe (fd);

        /* f [1] is the write end of the pipe, we carry `in` from the prev iteration.  */
        spawn_proc (in, fd [1], cmd + i);

        /* No need for the write and of the pipe, the child will write here.  */
        close (fd [1]);

        /* Keep the read end of the pipe, the next child will read from there.  */
        in = fd [0];
    }

    /* Last stage of the pipeline - set stdin be the read end of the previous pipe
       and output to the original file descriptor 1. */
    if (in != 0)
        dup2 (in, 0);

    /* Execute the last stage with the current process. */
    return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

int
main (int argc, char ** argv)
{
    printf("in main...");
    int i;

    if (argc == 1) {
        const char *printenv[] = { "printenv", 0};
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };

        struct command cmd [] = { {printenv}, {sort}, {less} };
        return fork_pipes (3, cmd);
    }
    if (argc > 1) {
    /*char *tmp = argv[1];
    sprintf(tmp, "%s%s", "'", tmp);*/
        for( i=1; i<argc-1; i++)
        {
           /* tmp = "%s%s%s", tmp, "\\|", argv[i];
            printf("tmp:%s", tmp);
        sprintf(tmp, "%s%s%s", tmp, "|", argv[i]);
        sprintf(tmp, "%s%s", tmp, "'");*/
        }

        const char *printenv[] = { "printenv", 0};
        const char *grep[] = { "grep", "-E", "JOB" };
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };

        struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
        return fork_pipes (4, cmd);
    }

}

Comment: That's not really right either, it should be e.g. `const char *grep[] = { "grep", "-E", "JOB|COMPIZ", NULL };`
Comment: The `argv` array provided to the `exec` family of function needs to be terminated by a `NULL` pointer.
Comment: @JoachimPileborg Thanks! This works: `const char *grep[] = { "grep", "-E", "JOB|COMPIZ\0" };`
Answer: Don't use single quotes in the argument. They are needed only on the command line to prevent shell from interpreting the vertical bar.

Why is extended grep not working?


Check if string matches regex pattern Swift 2.2

Question: I have this regex (([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}) for email adresses and I am trying to make a function to check if a string correspondes to it.
I already tried
func matches() -> Bool
{
    let emailRegex : String = "([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
    return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(self) //I use self because this is an extension of String
}

and
func matches() -> Bool
{
    let emailRegex : String = "([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
    return self.rangeOfStringrangeOfString(emailRegex, options: .RegularExpressionSearch) != nil
}

but they either give me a runtime error (with NSPredicate) or say that every single email adress is invalid (with .rangeOfString)
I found also a Regex class declaration at this link that is written in Swift 1.x (but I can easily convert it to Swift 2.x to build it) but it doesn't work neither.
I googled up and down without finding a working or understandable method (I'm a bit new to Swift) so my question is: how do I check if a string matches a regex in Swift 2?
Answer: There appears to be a (somewhat strange) opening parenthesis at the start of your regular expression. Remove that and see what happens:
let emailRegex : String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"

works for me.

NB: validating email using a regular expression is generally a bad idea. It's better to try and send the email, and see what error you get.
For example, your regular expression will fail for some of the examples given at the Wikipedia page on email addresses (in particular quoted strings, such as "very.unusual.@.unusual.com"@example.com).
Comment: sweet Jesus it works, **thanks a lot**. Apparently all my hours of struggling on Google have been a complete waste of time thanks to my dumbness
Comment: I can't send a validation email for two reasons: 1) it's an adress book 2) it's just a command line tool...
Comment: @NOVA99 Command line tools can perfectly send emails (`/usr/bin/mail` being a classic example). However, with the address book in mind, you could consider leaving the responsibility for the email correctness to the user. For example, are you also checking the validity of the street address (in particular, international addresses)?


Remove a block in preprocess

Question: I'm working on a Drupal 6 site made by other people, and I need to remove some block on the homepage for my language only.
I'm trying to use a Context and, by use of hook_context_init(), check if the context is active and remove the undesired blocks.
But i have a problem: How can I remove block in a hook function?
I hope my question is clear.
I don't want to hide the blocks with CSS because of the dirty markup..
[RESOLVED]
I did a preprocess like:
function wfp_homepage_context_preprocess_block(&$vars, $hook) {
    $to_delete = array('block_delta_1', 'block_delta_2')

    if(in_array($vars['block']->delta , $to_delete)){
        $vars['template_files'][0] = 'block-empty';
    }
}

and i add an empty block-empty.tpl.php in my theme.
Answer: You can use hook_page_alter() to do this. For example, if you wanted to remove the system navigation block from the "sidebar_first" region, you would do something like this:
function MYMODULE_page_alter(&$page) {
  if ($my_condition) {
    $region_name = 'sidebar_first';
    $block_name = 'system_navigation';

    if (isset($page[$region_name][$block_name])) {
      $page[$region_name][$block_name]['#access'] = FALSE;
    }
  }
}

Comment: I'm sorry but i forgot to say i'm using drupal 6 not drupal 7
T______T
So i can't use the hook_page_alter().. any other ideas?
Comment: I'd like to do this in Drupal 8. Any pointers as to how? That hook was removed.
Answer: [SOLVED] I did a preprocess like:
function module_preprocess_block(&$vars, $hook) {
    $to_delete = array('block_delta_1', 'block_delta_2')
    if(in_array($vars['block']->delta , $to_delete)){
        $vars['template_files'][0] = 'block-empty';
    }
    }

and i add an empty block-empty.tpl.php in my theme.
Answer: The hook you're looking for is hook_block_view_alter(), or it's delta cousin.
You'd check against $module['delta'] to see if it's the block you care about, and then unset the subject and content of $block.
Comment: I'm working on Drupal 6 and hook_block_view_alter() is a drupal 7+ function..
Answer: There doesn't seem to be an easy way to do this in D6. You if you are using the i18n internationalization module, you could define your paths, that are prepended with your language code, as exceptons in the block config menu. so something like es/* for spanish.
Haven't tested myself, just a thought.
Answer: from Drupal8, an example of not displaying 2 blocks on 404 page:
 //exemple of condition
 $route_name = \Drupal::request()->attributes->get('_route');
 if ('system.404' === $route_name) {
    $region_name = 'content';
    $block_names = ['oneBlockID', 'andAnother'];
    foreach ($block_names as $block_name)
    if (isset($variables['page'][$region_name][$block_name])) {
      $variables['page'][$region_name][$block_name]['#access'] = FALSE;
    }
  }

Remove a block in preprocess