text:
Q: cakephp211 date insertion this is my variable:
     <?php
     //...
     $creat='2000-03-15'  ,from an input field.
     ?>

this is my insertion code:
     <?php
     //...
       $this->Comment->updateAll(
              array('Comment.c' => $creat ),
              array('Comment.id' => '3'  ));
     ?>

when i want to save it in a table which have a date field type, instead of '2000-03-15', i have '0000-00-00'?
why?
thanks for comments!

A: the updateAll function does not escape your input. It will also not wrap your data in quotes.
In your example, to properly escape your $creat variable, i would suggest using the following code:
<?php
App::uses('Sanitize', 'Utility');
$Comment->updateAll(array(
    'Comment.c' => "'" . Sanitize::escape($creat) . "'"
), array(
    'Comment.id' => 3
));

We wrap the date with quotes and also pass it through Sanitize::escape to make sure we protect ourselves against SQL injection.


text:
Q: Is there a definition for the "same" sequences? I am reading a book (Real Analysis 1 by Terence Tao), where the author presents a proof that $\lim_{n \rightarrow \infty} x^{n} = 0$ for $0 < x < 1$. In the middle of the proof, he says following:

...... But the sequence $(x^{n+1})_{i=1}^{\infty}$ is just the sequence $(x^{n})_{n=2}^{\infty}$ shifted by one, and so they must have the same limits ......

If one writes down the first elements of both sequences, it becomes obvious that these two sequences are indeed "the same":
$$(x^{2},x^{3},x^{4},\cdots)$$
However, these two sequences are not equal (unless I am misunderstanding the definition of the sequences). By definition (the one presented in the book), a sequence $(a_{i})_{i=m}^{\infty}$ is defined as a function $f: \{n \mid n ≥ m\} \rightarrow \mathbb R$, where $f(i) = a_i$. Using this definition, one can see that the sequences $(x^{n+1})_{n=1}^{\infty}$, $(x^{n})_{n=2}^{\infty}$ cannot be equal, since the function corresponding to the sequence $(x^{n+1})_{i=1}^{\infty}$ has $1$ in its domain, but the function corresponding to $(x^{n})_{n=2}^{\infty}$ does not (i.e., the underlying functions have different domains, hence they are not equal, which means the sequences are not equal).
In fact, even if one takes a simple sequence $(1,2,3,\cdots)$, one can find infinitely many ways to denote such sequence (e.g. $(n)_{n=1}^{\infty}$, $(n-1)_{n=2}^{\infty}$, $(n-2)_{n=3}^{\infty}$ etc.), and according to our definition, all of those denotations refer to the different sequences (i.e., $(n)_{n=1}^{\infty} ≠ (n-1)_{n=2}^{\infty}$, $(n)_{n=1}^{\infty} ≠ (n-2)_{n=3}^{\infty}$ etc.)
Question.
Is there an alternative definition that would allow us to equalize sequences like $(n)_{n=1}^{\infty}$, $(n-1)_{n=2}^{\infty}$, $(n-2)_{n=3}^{\infty}$ or sequences like $(x^{n+1})_{i=1}^{\infty}$, $(x^{n})_{i=2}^{\infty}$?

There is one particular reason why I think this alternative definition could be useful. Let's consider an example:
Let $0 < x < 1$. Also let's assume that we've already shown that the sequence $(x^{n})_{i=1}^{\infty}$ is convergent to $L$. It is clear that sequences $(x^{n-1})_{i=2}^{\infty}$,$(x^{n-2})_{i=3}^{\infty}$, $(x^{n-3})_{i=4}^{\infty}$ $\cdots$ are the "same" as $(x^{n})_{i=1}^{\infty}$, in a sense that they all correspond to the sequence
$$(x^{2},x^{3},x^{4},\cdots)$$
And hence is it quite reasonable to conclude that those sequences must also converge to $L$. However, since all those sequences are not equal to each other, without rigorous definition of "sameness", the claim should be justified for each sequence separately. For example, if we want to show that $(x^{n-1})_{i=2}^{\infty}$ also converges to $L$, we need to take $\epsilon > 0$ and find an $N$ such that for all $n ≥ N$, $|a^{n-1} - L| ≤ \epsilon$ (it is easy to do so, of course, but is rather cumbersome; what's worse, we still need to show the convergence for the sequences $(x^{n-2})_{i=3}^{\infty}$, $(x^{n-3})_{i=4}^{\infty}$). But if one can come with a rigorous definition of "sameness", the notion of convergence of the "same" sequences can be generalized.

A: The term you are looking for is the tail of a sequence. This is another sequence that starts at the $n$th element of the first one, where $n$ is some unspecified positive integer. You could then say that the sequences $(x^n)_{n=1}^\infty$ and $(x^{n-1})_{n=2}^\infty$ have the same tail, which would mean that there must exist integers $m$ and $k$ such that $(x^n)_{n=m}^\infty$ and $(x^{n-1})_{n=k}^\infty$ are the same sequence.
Because we leave the starting point of the tail unspecified, we can choose $m$ and $k$ freely and independently. A more rigorous way of saying this is that a sequence does not have one tail, but instead a set of tails: one for each starting point.
One would then speak of "a tail" instead of "the tail", and "There exist tails of these two sequences that are equal". This rigor does clog up the language though, hence the use of "the tail" in my example above.
This term is also useful for making concise statements about sequences whose first elements behave rather erratically. For example: let $(x_n)_{n=0}^\infty$ be the sequence specified by $x_0 = 5$, $x_1 = 123456789$, and $x_n = 0$ for all integers $n>1$, then the tail of this sequence consists of only zeros.
Note that only the behaviour of the tail of a sequence matters for determining its limit. This is the reason this term is so useful.

A: As suggested in a comment, you could define $(a_i)_{i=m}^\infty$ as the function $f:\Bbb N\to\Bbb R$, $f(i)=a_{m-1+i}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RootViewController of UINavigationController not getting deallocated while UINavigationController is presented by another UINavigationController I have a main UINavigationController for the App and now I wanted to present another navigationController for another flow. After completing the flow, I'm dismissing the another NavigationCotnroller but the rootViewController of another NavigationController is not getting deallocated.('deinit' is not getting called on rootViewController of another navigation controller).
below is example code to understand -
// main Navigation controller for the app
let navigationController = UINavigationController()

//another navigation controller to present separate flow of screens
let rootController = UIViewController()
let subNavigationController = UINavigationController(rootViewController: rootController)
navigationController.present(subNavigationController, animated: true, completion: nil)

//while dismiss - deinit on rootController is not getting called
navigationController.dismiss(animated: true, completion: nil)

A: In this exemple, the rootViewController is retain by the let declaration.


text:
Q: IndexOutOfRange exception Why is this giving a IndexOutOfRange exception?
string[] achCheckStr = File.ReadAllLines("achievements.txt");

if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs
{
    setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
    setAchievements(2);
}

A: Problem 1:
there mightbe no file exists with name achievements.txt.
this statement string[] achCheckStr = File.ReadAllLines("achievements.txt"); might be returning null.
Solution 1: so before accessing any files please check whether file exists or not by using File.Exists() method.
Problem 2: there might be no lines in your text file.
Solution 2: before accessing the string array which contains lines please make sure that it is not empty by checking its Length
Try This:
if(File.Exists("achievements.txt"))
{
    string[] achCheckStr = File.ReadAllLines("achievements.txt");
    if(achCheckStr.Length > 0)
    {
        if (achCheckStr[0] == ach1_StillBurning)
        {
            setAchievements(1);
        }
        if (achCheckStr[1] == ach2_Faster)
        {
            setAchievements(2);
        }
    }
}

A: Your code is assuming that the achCheckStr array has at least 2 elements without first checking how many there are.  If the file exists & the contents are empty, achCheckStr.Length will be 0 and the IndexOutOfRangeException will be thrown exactly where it's happening.

A: Where are you storing "achievements.txt"? It could be in the wrong place, so the code would not find it.
You can fully qualify the path or put the file within the bin directory where the .exe is generated.

A: Here's a way
string[] achCheckStr = File.ReadAllLines("achievements.txt");
        if (achCheckStr != null && achCheckStr.Any())
        {

            if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs
            {
                setAchievements(1);
            }
            if (achCheckStr[1] == ach2_Faster)
            {
                setAchievements(2);
            }
        }


text:
Q: C++/XAML UWP NuGet packages with managed dependencies Let's start with a C++/CX UWP project from scratch where i need a NuGet packages who use managed dependencies (like Newtonsoft.Json). This is actually impossible to install this because my project uses native C++ (not C#).
I red this post in github for my searchs : https://github.com/NuGet/Home/issues/6146
But i wondering if there exists a solution to get around or plan in the future ?

A: C++ cannot call C# (or any other managed code) directly in UWP. (Desktop C++ has C++/CLI, aka "Managed C++", but that is not available for UWP). The easiest way to call managed code from C++ is to create a WinRT component with the managed code and then reference it from your C++ code.


text:
Q: Set seed in R for Normal distribution i am doing a loop for normal distribution, skewed normal, and also skewed heavy. However, i can only manage to get the type I error for normal and skewed normal using the same set.seed. When i run the coding for skewed heavy, i get NA, and there is some missing value too in the data calculated in the coding. How can i fix this? Anyway, i already try a lot of value instead of val, but it did not give me the satisfaction for normal and skewed normal because i always get zero.
asim<-10000
pv<- rep(NA,asim)

for (val in 1:asim){

  set.seed(val)

  t=3
  n1=10
  n2=10
  n3=10
  N=n1+n2+n3

  data1<-rnorm(n1,0,1)
  data2<-rnorm(n2,0,1)
  data3<-rnorm(n3,0,1)

  # SKEWED HEAVY

  G=0.5
  h=0.5 # h=0 if skewed normal

  y1=((exp(G*data1)-1)/G)*(exp((h*data1^2)/2))
  y2=((exp(G*data2)-1)/G)*(exp((h*data2^2)/2))
  y3=((exp(G*data3)-1)/G)*(exp((h*data3^2)/2))

       g1=sort(y1)
  g2=sort(y2)
  g3=sort(y3)

  ybar1<-mean(g1)
  ybar2<-mean(g2)
  ybar3<-mean(g3)

  #BIWEIGHT

  med1=median(g1)
  med2=median(g2)
  med3=median(g3)

  mad=mad(c(g1,g2,g3))

  u1=(g1-med1)/(9*mad)
  u2=(g2-med2)/(9*mad)
  u3=(g3-med3)/(9*mad)

  idx1<- which(abs(u1)<1)
  idx2<- which(abs(u2)<1)
  idx3<- which(abs(u3)<1)

  #create empty list

  num1=c()
  num2=c()
  num3=c()
  den1=c()
  den2=c()
  den3=c()
  nume1=c()
  nume2=nume3=deno1=deno2=deno3=c()

  for(z in idx1){
    num1[z] = ((g1[z]-med1)^2)*((1-(u1[z]^2))^4)
    den1[z] = ((1-(u1[z]^2))*(1-5*(u1[z]^2)))
  }

  for(j in idx2){
    num2[j] = ((g2[j]-med2)^2)*((1-(u2[j]^2))^4)
    den2[j] = ((1-(u2[j]^2))*(1-5*(u2[j]^2)))
  }

  for(k in idx3){
    num3[k] = ((g3[k]-med3)^2)*((1-(u3[k]^2))^4)
    den3[k] = ((1-(u3[k]^2))*(1-5*(u3[k]^2)))
  }

  print(num1)

 }

after the print num1, there is NA value.

A: I think you may want to post in code review, but the single biggest recommendation I have is to rely more heavily on lapply rather than sequentially named objects (e.g., num1, num2, num3.
I assume at the end of this, you want the results of the simulations. To do so, we will make a list using lapply over each simulation. I have added some of your constants outside of the loop; we need to replicate 3 datasets during each simulation. We make extensive use of lapply to continually make the summary statistics that you need. Map is similar, except it allows us to pass multiple arguments when we need it.
asim<-10
t=3
n = rep(10, t)
N = sum(n)
pv<- rep(NA,asim)

lapply(seq_len(asim), function (val) {
  set.seed(val)

  data = lapply(n, rnorm, 0, 1)

  # SKEWED HEAVY

  G=0.5
  h=0.5 # h=0 if skewed normal

  y = lapply(data, function(x) ((exp(G*x)-1)/G)*(exp((h*x^2)/2)))

  g = lapply(y, sort)
  ybar = lapply(y, mean)

  #BIWEIGHT

  med = lapply(g, median)
  mad_=mad(unlist(g, use.names = FALSE))
  u = Map(function (g_, med_) (g_ - med_) / (9 * mad_), g, med)
  idx = lapply(u, function(x) which(abs(x) < 1))

  num = Map(function(g_, med_, u_, idx_) (((g_ - med_) ^ 2) * ((1 - (u_^2))^4))[idx_], g, med, u, idx)
  den = Map(function(u_, idx_) ((1 - (u_^2)) * (1 - 5 * (u_ ^ 2)))[idx_], u, idx)

  data.frame(sim = rep(seq_len(t), lengths(idx)),
             num = unlist(num, use.names = FALSE),
             den = unlist(den, use.names = FALSE))
  }
)


text:
Q: Google maps API MarkerManager I'm sure this question will be downvoted, but...
Is Google Maps MarkerManager still "a thing"? On some of the Google documentation I see it mentioned, and in other parts of I do not.
All of the information I can find on this library seems very outdated. It also causes an error if this library is included on the page before the Google Maps API is loaded. Is there a newer recommended method for handling lots of markers the way this library does?

A: 2 years Ago, when I was working on map based project, we used markerclusterer library. It might suit your needs. Here's a simple example
some more examples


text:
Q: Having trouble Loading a multilevel JSON file into Apache Pig and saving it as csv I'm super new to apache pig and was trying to load a multilevel json into pig and save it as csv.
Json file I have - home/vikaspattathe/dataset/sample.json
{"_id":{"$oid":"5a1321d5741a2384e802c552"},"reviewerID":"A3HVRXV0LVJN7","asin":"0110400550","reviewerName":"BiancaNicole","helpful":[4,4],"reviewText":"Best phone case ever . Everywhere I go I get a ton of compliments on it. It was in perfect condition as well.","overall":5.0,"summary":"A++++","unixReviewTime":1358035200,"reviewTime":"01 13, 2013","category":"Cell_Phones_and_Accessories","class":1.0}
{"_id":{"$oid":"5a1321d5741a2384e802c557"},"reviewerID":"A1BJGDS0L1IO6I","asin":"0110400550","reviewerName":"cf \"t\"","helpful":[0,3],"reviewText":"ITEM NOT SENT from Blue Top Company in Hong Kong and it's been over two months!  I will report this.  DO NOT use this company.  Not happy at all!","overall":1.0,"summary":"ITEM NOT SENT!!","unixReviewTime":1359504000,"reviewTime":"01 30, 2013","category":"Cell_Phones_and_Accessories","class":0.0}

Opened pig from the the directory(incase that is of any concern) - /home/vikaspattathe/dataset/
I tried the below commands to load the data and getting following errors.
grunt> sample_table = LOAD '/home/vikaspattathe/dataset/sample.json' USING JsonLoader('id:chararray, reviewerId:chararray, asin:chararray, reviewerName:chararray, reviewText:chararray, overall:int, summary:chararray, unixReviewTime:chararray, reviewTime:chararray, category:chararray, class:int');

2022-10-29 11:35:55,333 [main] INFO  org.apache.pig.impl.util.SpillableMemoryMan ager - Selected heap (PS Old Gen) of size 699400192 to monitor. collectionUsageThreshold = 489580128, usageThreshold = 489580128
2022-10-29 11:35:55,556 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
2022-10-29 11:35:55,572 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
2022-10-29 11:35:55,632 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled

Tried dumping sample_table as I believe the load wasn't successfull.
grunt> dump sample_table;
2022-10-29 11:42:24,535 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
2022-10-29 11:42:24,546 [main] INFO  org.apache.pig.tools.pigstats.ScriptState - Pig features used in the script: UNKNOWN
2022-10-29 11:42:24,558 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
2022-10-29 11:42:24,558 [main] WARN  org.apache.pig.data.SchemaTupleBackend - SchemaTupleBackend has already been initialized
2022-10-29 11:42:24,558 [main] INFO  org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer - {RULES_ENABLED=[AddForEach, ColumnMapKeyPrune, FilterConstantCalculator, ForEachConstantCalculator, GroupByConstParallelSetter, LimitOptimizer, LoadTypeCastInserter, MergeFilter, MergeForEach, NestedLimitOptimizer, PartitionFilterOptimizer, PredicatePushdownOptimizer, PushDownForEachFlatten, PushUpFilter, SplitConstantCalculator, SplitFilter, StreamTypeCastInserter]}
2022-10-29 11:42:24,559 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler - File concatenation threshold: 100 optimistic? false
2022-10-29 11:42:24,560 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer - MR plan size before optimization: 1
2022-10-29 11:42:24,561 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer - MR plan size after optimization: 1
2022-10-29 11:42:24,569 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
2022-10-29 11:42:24,571 [main] INFO  org.apache.hadoop.yarn.client.RMProxy - Connecting to ResourceManager at spam-ham-m/10.154.0.5:8032
2022-10-29 11:42:24,572 [main] INFO  org.apache.hadoop.yarn.client.AHSProxy - Connecting to Application History server at spam-ham-m/10.154.0.5:10200
2022-10-29 11:42:24,575 [main] INFO  org.apache.pig.tools.pigstats.mapreduce.MRScriptState - Pig script settings are added to the job
2022-10-29 11:42:24,575 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - mapred.job.reduce.markreset.buffer.percent is not set, set to default 0.3
2022-10-29 11:42:24,576 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - This job cannot be converted run in-process
2022-10-29 11:42:24,621 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/usr/lib/pig/pig-0.18.0-SNAPSHOT-core-h3.jar to DistributedCache through /tmp/temp500810153/tmp-403584597/pig-0.18.0-SNAPSHOT-core-h3.jar
2022-10-29 11:42:24,642 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/usr/lib/hadoop/lib/jackson-core-asl-1.9.13.jar to DistributedCache through /tmp/temp500810153/tmp-332868819/jackson-core-asl-1.9.13.jar
2022-10-29 11:42:24,663 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/usr/lib/pig/lib/automaton-1.11-8.jar to DistributedCache through /tmp/temp500810153/tmp759836349/automaton-1.11-8.jar
2022-10-29 11:42:24,683 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/usr/lib/pig/lib/antlr-runtime-3.4.jar to DistributedCache through /tmp/temp500810153/tmp-305484567/antlr-runtime-3.4.jar
2022-10-29 11:42:24,815 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/usr/lib/hive/lib/hive-exec-3.1.2.jar to DistributedCache through /tmp/temp500810153/tmp-1240067490/hive-exec-3.1.2.jar
2022-10-29 11:42:24,837 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/usr/lib/pig/lib/RoaringBitmap-shaded-0.7.45.jar to DistributedCache through /tmp/temp500810153/tmp-1911465994/RoaringBitmap-shaded-0.7.45.jar
2022-10-29 11:42:24,855 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Setting up single store job
2022-10-29 11:42:24,873 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 1 map-reduce job(s) waiting for submission.
2022-10-29 11:42:24,885 [JobControl] INFO  org.apache.hadoop.yarn.client.RMProxy - Connecting to ResourceManager at spam-ham-m/10.154.0.5:8032
2022-10-29 11:42:24,886 [JobControl] INFO  org.apache.hadoop.yarn.client.AHSProxy - Connecting to Application History server at spam-ham-m/10.154.0.5:10200
2022-10-29 11:42:24,906 [JobControl] INFO  org.apache.hadoop.mapreduce.JobResourceUploader - Disabling Erasure Coding for path: /tmp/hadoop-yarn/staging/vikaspattathe/.staging/job_1667038087507_0005
2022-10-29 11:42:24,908 [JobControl] WARN  org.apache.hadoop.mapreduce.JobResourceUploader - No job jar file set.  User classes may not be found. See Job or Job#setJar(String).
2022-10-29 11:42:24,960 [JobControl] INFO  org.apache.hadoop.mapreduce.JobSubmitter - Cleaning up the staging area /tmp/hadoop-yarn/staging/vikaspattathe/.staging/job_1667038087507_0005
2022-10-29 11:42:24,963 [JobControl] INFO  org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob - PigLatin:DefaultJobName got an error while submitting
org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: hdfs://spam-ham-m/home/vikaspattathe/dataset/sample.json
        at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:298)
        at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:310)
        at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:327)
        at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:200)
        at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1565)
        at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1562)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1762)
        at org.apache.hadoop.mapreduce.Job.submit(Job.java:1562)
        at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:336)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.pig.backend.hadoop.PigJobControl.submit(PigJobControl.java:128)
        at org.apache.pig.backend.hadoop.PigJobControl.run(PigJobControl.java:205)
        at java.lang.Thread.run(Thread.java:750)
        at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:298)
Caused by: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://spam-ham-m/home/vikaspattathe/dataset/sample.json
        at org.apache.hadoop.mapred.LocatedFileStatusFetcher.getFileStatuses(LocatedFileStatusFetcher.java:153)
        at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:280)
        at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:396)
        at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:283)
        ... 18 more
2022-10-29 11:42:25,375 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - HadoopJobId: job_1667038087507_0005
2022-10-29 11:42:25,375 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Processing aliases sample_table
2022-10-29 11:42:25,375 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - detailed locations: M: sample_table[1,15] C:  R:
2022-10-29 11:42:25,384 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 0% complete
2022-10-29 11:42:30,393 [main] WARN  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Ooops! Some job has failed! Specify -stop_on_failure if you want Pig to stop immediately on failure.
2022-10-29 11:42:30,393 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - job job_1667038087507_0005 has failed! Stop running all dependent jobs
2022-10-29 11:42:30,393 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 100% complete
2022-10-29 11:42:30,395 [main] INFO  org.apache.hadoop.yarn.client.RMProxy - Connecting to ResourceManager at spam-ham-m/10.154.0.5:8032
2022-10-29 11:42:30,396 [main] INFO  org.apache.hadoop.yarn.client.AHSProxy - Connecting to Application History server at spam-ham-m/10.154.0.5:10200
2022-10-29 11:42:30,404 [main] INFO  org.apache.hadoop.mapred.ClientServiceDelegate - Could not get Job info from RM for job job_1667038087507_0005. Redirecting to job history server.
2022-10-29 11:42:30,420 [main] ERROR org.apache.pig.tools.pigstats.PigStats - ERROR 0: java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING
2022-10-29 11:42:30,421 [main] ERROR org.apache.pig.tools.pigstats.mapreduce.MRPigStatsUtil - 1 map reduce job(s) failed!
2022-10-29 11:42:30,421 [main] INFO  org.apache.pig.tools.pigstats.mapreduce.SimplePigStats - Script Statistics:

HadoopVersion   PigVersion      UserId  StartedAt       FinishedAt      Features
3.2.3   0.18.0-SNAPSHOT vikaspattathe   2022-10-29 11:42:24     2022-10-29 11:42:30     UNKNOWN

Failed!

Failed Jobs:
JobId   Alias   Feature Message Outputs
job_1667038087507_0005  sample_table    MAP_ONLY        Message: org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: hdfs://spam-ham-m/home/vikaspattathe/dataset/sample.json
        at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:298)
        at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:310)
        at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:327)
        at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:200)
        at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1565)
        at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1562)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1762)
        at org.apache.hadoop.mapreduce.Job.submit(Job.java:1562)
        at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:336)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.pig.backend.hadoop.PigJobControl.submit(PigJobControl.java:128)
        at org.apache.pig.backend.hadoop.PigJobControl.run(PigJobControl.java:205)
        at java.lang.Thread.run(Thread.java:750)
        at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:298)
Caused by: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://spam-ham-m/home/vikaspattathe/dataset/sample.json
        at org.apache.hadoop.mapred.LocatedFileStatusFetcher.getFileStatuses(LocatedFileStatusFetcher.java:153)
        at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:280)
        at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:396)
        at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:283)
        ... 18 more
        hdfs://spam-ham-m/tmp/temp500810153/tmp929245825,

Input(s):
Failed to read data from "/home/vikaspattathe/dataset/sample.json"

Output(s):
Failed to produce result in "hdfs://spam-ham-m/tmp/temp500810153/tmp929245825"

Counters:
Total records written : 0
Total bytes written : 0
Spillable Memory Manager spill count : 0
Total bags proactively spilled: 0
Total records proactively spilled: 0

Job DAG:
job_1667038087507_0005

2022-10-29 11:42:30,421 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Failed!
2022-10-29 11:42:30,427 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1066: Unable to open iterator for alias sample_table. Backend error : java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING
Details at logfile: /home/vikaspattathe/dataset/pig_1667043341193.log

The load wasn't successful.
Also, is the below command correct for storing the file as samplecsv.csv, once it's successfuly loaded.
grunt> STORE sample_table INTO '/home/vikaspattathe/dataset/samplecsv' USING PigStorage(',');

A: HDFS doesn't have /home file paths. User data is stored under /user paths. As the error says, the input you gave doesn't exist in HDFS.
If you want to load local filesystem, then prefix the path with file://
You also don't need HDFS to use pig, if you start it with pig -x local
As for the output, start with
X = LOAD '/tmp/sample.json' USING JsonLoader('id:(oid:chararray), reviewerID:chararray, asin:chararray, reviewerName:chararray, helpful:tuple(int), reviewText:chararray, overall:int, summary:chararray, unixReviewTime:long, reviewTime:chararray, category:chararray, class:int');

But I don't know how helpful field should be added for arrays... I tried helpful:[int], and that produces the same result.
\DUMP X;
((5a1321d5741a2384e802c552),A3HVRXV0LVJN7,0110400550,BiancaNicole,,4,,,,,,)
((5a1321d5741a2384e802c557),A1BJGDS0L1IO6I,0110400550,cf "t",,3,,,,,,)


text:
Q: remove padding in jumbotron bootstrap 3? How to remove the default padding from jumbotron bootstrap 3? I am trying to set padding-top:5px; in jumbotron div. But there is some default padding, how to remove it?

A: The problem is that the CSS selector's specificity for jumbotron would be greater than the one you are applying.
You can read more about the CSS Selector Specificity here
You can add an ID to your jumbotron, and style that,
#jumbo {
  padding: 5px;
}


text:
Q: Finding all the keys in the array of objects Given that  I have an array that is return from database that contains object,
var jsObjects = [
   {a: 1, b: 2},
   {a: 3, b: 4, c: 66},
   {a: 5, b: 6, c: 55, d: 66},
   {a: 7, b: 8, c: 12, e: 15}
];

How can I get all the keys of the object? I've been using this to obtain the keys, however I notice that index 0 wont always have all the keys. Hence problem lays.
let columns = Object.keys(jsObjects[0]),

However, the first index won't always have all the columns.
My desired output:
["a", "b", "c", "d", "e"]

A: You could create an object with the count of the keys and get the keys from counts.

const
    objects = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 66 }, { a: 5, b: 6, c: 55, d: 66 }, { a: 7, b: 8, c: 12, e: 15 }],
    result = Object.keys(objects.reduce((r, o) => {
        Object.keys(o).forEach(k => r[k] = true);
        return r;
    }));

console.log(result);

A: You can use a Set(), which is like an array with the exception that it doesn't allow multiple occurances of elements.

var jsObjects = [
   {a: 1, b: 2},
   {a: 3, b: 4, c: 66},
   {a: 5, b: 6, c: 55, d: 66},
   {a: 7, b: 8, c: 12, e: 15}
];

var keys = new Set();
for(object of jsObjects) {
  for(key in object) {
    keys = keys.add(key);
  }
}

for (const key of keys) {
  console.log(key);
}

A: Sets are good at removing duplicates:

const jsObjects = [
   {a: 1, b: 2},
   {a: 3, b: 4, c: 66},
   {a: 5, b: 6, c: 55, d: 66},
   {a: 7, b: 8, c: 12, e: 15}
];

const keys = [...new Set(jsObjects.flatMap(Object.keys))];
console.log(keys);

A: I tried this solution: iterating on jsObjects elements and pushing keys
into columns array if not present.

var jsObjects = [
   {a: 1, b: 2},
   {a: 3, b: 4, c: 66},
   {a: 5, b: 6, c: 55, d: 66},
   {a: 7, b: 8, c: 12, e: 15}
];
let columns = [];
jsObjects.forEach(
    o => {
        Object.keys(o).forEach(
            t => {
                if (columns.indexOf(t) < 0 ) {
                    columns.push(t);
                }
            }
        )
    }
)
console.log(columns);


text:
Q: JAXB and validation against parts of a schema with schemagen? A very generalized and simplified scenario description:

*

*Application builds JAXB instances through UI,

*The JAXB instances are built in different steps are composed in the end,

*As this is done, I must perform validation of the JAXB instances created in each step against the XSD to verify that the UI tier does not build nonsense.

Now the schema defines complex types A, B and C. The schema specifies that XML document must have top level element A and this can contain multiple B and this can optionally include C. I create JAXB instance for B and absolutely want to validate this against the complex type definition in the XSD before nesting it under A. However validation of this will fail if I validate against the entire XSD.
Questions: How to validate JAXB instance against only a part of the XSD from which its class has been generated from?
How about using schemagen to generate schema from the JAXB class which instance I want to validate and then validate against that? Do you think that can work? Any other ideas?
I have no previous experience with schemagen and will start prototyping of this solution soon.
Note: in reality, the schemas are not as simple as in the above example and the solution of creating some always-valid mock of A is not feasible option. Not to mention that this kind of validation will be on hundred places to say the least.

A: create separate schema for element you want to validate, where this element is on root level.
to workaround missing @xmlRoottag see 101 ways to marshal objects with JAXB

A: Well it turns out that using xsi:type let's one accomplish this.
http://www.w3.org/TR/xmlschema-1/#xsi_type

A: While working with xjc and schemagen tools please consider same concept which we use in java. In java, every class is a skeleton and object is an instance. Same as we need to consider XSD as skeleton and XML as instance.

xjc tool:- Xsd to Java Class Or Unmarshaling

Consider the below XSD with namespaces for example. The xjc tool will generate the java class along with package-info and object-factory.
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ir="http://irctc.org/service" targetNamespace="http://irctc.org/service">
    <xsd:element name="Customer" type="ir:CustomerType"/>
    <xsd:complexType name="CustomerType">
        <xsd:sequence>
            <xsd:element name="name" type="xsd:string"/>
            <xsd:element name="src" type="xsd:string"/>
            <xsd:element name="dest" type="xsd:string"/>
            <xsd:element name="price" type="xsd:float" minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

Use below command
D:\>xjc Customer.xsd
parsing a schema...
compiling a schema...
org\irctc\service\CustomerType.java
org\irctc\service\ObjectFactory.java
org\irctc\service\package-info.java
Note :- If you have multiple java class then you can use jaxb.index file instead of using ObjectFactory.java.

schemagen tool:- Java Class to Xsd Or Marshaling

Let us suppose we want to generate the Xsd file using java class then first we need to create the ObjectFactory.java Or jaxb.index file and package-info.java in the same package where we have the CustomerType.java.
package org.irctc.service;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement("Customer")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CustomerType", propOrder = {
    "name",
    "src",
    "dest",
    "price"
})
public class CustomerType {

    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = true)
    protected String src;
    @XmlElement(required = true)
    protected String dest;
    protected Float price;

    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }
    public String getSrc() {
        return src;
    }
    public void setSrc(String value) {
        this.src = value;
    }
    public String getDest() {
        return dest;
    }
    public void setDest(String value) {
        this.dest = value;
    }
    public Float getPrice() {
        return price;
    }
    public void setPrice(Float value) {
        this.price = value;
    }
}

Use below command
D:\>schemagen org.irctc.service.CustomerType
Note: Writing D:\schema1.xsd
The above command will generate the xsd file. The package of java class will considered as xsd namespaces.
The above details are only for understanding marshaling and unmarshaling process using tools in Jax-B API.
For more details , check below examples
Jax-B Hello World Example
Java-XML mapping with Jax-B 2.0


text:
Q: How to add duplicates in intersection of two sets in python Let suppose I have two sets
a = {1,2,3,4}
b = {2,2,5,7,3,3}

So when I take a intersection of these two sets , I also want duplicates in my result
c = a.intersection(b)
print (c)
{2,2,3,3}

A: first if you define a set like this, you'll lose duplicate elements at once. So define lists instead:
a = [1,2,3,4]
b = [2,2,5,7,3,3]

Now my suggestion: count elements of the lists using collections.Counter, intersect & take max count, then expand the counter:
import collections

c1 = collections.Counter(a)
c2 = collections.Counter(b)

c3 = collections.Counter({k:max(c1[k],c2[k]) for k in set(a).intersection(b)})

print(list(c3.elements()))

result:
[2, 2, 3, 3]

A: As pointed out by @MohitSolanki, sets are not the right data structure for your use-case, because they cannot contain duplicates.
Thus, b = {2,2,5,7,3,3} will print {2, 5, 7, 3} if you access your variable b and this is likely not what you want.
May I suggest using lists? A possible solution might look like this:
def intersection(x: list, y: list):
    s = set(y)
    return [v for v in x if v in s]

a = [1,2,3,4]
b = [2,2,5,7,3,3]
print(intersection(a, b))
print(intersection(b, a))

''' Output:
print(intersection(a, b)) -> [2, 3]
print(intersection(b, a)) -> [2, 2, 3, 3]
'''

Do you have questions in regards to my solution proposal? Also, please let me/us know if this answer is helpful to you! In case it is not, please provide me/us with more feedback. Cheers :-)
EDIT Incorporated the feedback from user @Jean-FrançoisFabre to improve the search complexity (imho by a constant → O(n-c) with n=len(y) and c=len(y)-len(set(y))) by introducing s = set(y) and performing a v in s in the intersection method. Thanks for pointing that out! This is in particular useful when the second argument contains A LOT of duplicates.

A: A set cannot contain duplicates, that's sort of the point of them.
so to extend your code:
>>> a = {1,2,3,4}
>>> b = {2,2,5,7,3,3}
>>> a
{1, 2, 3, 4}
>>> b
{2, 3, 5, 7}

Note that the duplicates in b have been automatically removed by being part of a set.
So first you must re-define your variables a and b as lists:
a = [1,2,3,4]
b = [2,2,5,7,3,3]

Then I think your question is answered by: Intersection of two lists including duplicates?


text:
Q: Trying to use ArrayUtils.removeElement I have added the correct library - common net 3.6 to NetBeans and my project.
However, there's still an error shown.
I'm using there imports;
import java.lang.Object;
import org.apache.commons.lang.ArrayUtils;

Here's the included library.
included library
I watched a tutorial so I know I added this library correctly, yet I still can't use ArrayUtils.
What may be the problem?

A: One way to avoid this hassle is using ArrayList instead of Array in the first place.
But you can refer to
How to use ArrayUtils for array of objects, it doesnt deleted the content of an array
its already been answered here.


text:
Q: How to add sheets to a new workbook based of array list I am trying to create sheets in a new workbook using apache poi.
However, I want the sheets created to be the name of studies in an arraylist.
I don't know how many studies there are, or what they are beforehand. I am having trouble setting it up.
public static void addSheets() {
XSSFWorkbook finalizing = new XSSFWorkbook();
    for (int i = 0; i < studies.size(); i++) {
        finalizing.createSheet(studies.get(i));
    }

    makeWorkBook(finalizing);
}

I have also tried
XSSFSheet firstSheet = finalizing.createSheet(studies.get(i));

instead of the finalizing.createSheet
But neither work.
I was hoping to get advice from anyone?

A: This code is working for me:
public void createExcel(String filename){
    List<String> sheetNames = new ArrayList<String>();
    sheetNames.add("S1");
    sheetNames.add("S2");
    sheetNames.add("S3");
    try{
        File file = new File(filename);
        if(!file.exists()){
            file.createNewFile();
        }
        XSSFWorkbook workbook=new XSSFWorkbook();
        for(String sheetName: sheetNames){
            workbook.createSheet(sheetName);
        }
        FileOutputStream fileOut =  new FileOutputStream(filename);
        workbook.write(fileOut);
        fileOut.close();

    } catch ( Exception ex ) {
        System.out.println("Exception creating the excel file: " + ex.getMessage());
    }
}

Please, could you add what you are doing in your method makeWorkBook. It seems that probably there is your problem.
Also, be sure that you are adding a valid sheet name.

*

*The name must be unique within a single workbook.

*A worksheet name cannot exceed 31 characters.

*You can use all alphanumeric characters but not the following special
characters: \ , / , * , ? , : , [ , ].


text:
Q: How to open folder as a playlist in Audacious from context menu In older Ubuntu versions I could right-click on a folder and I would have the option to open it with Audacious. I can't in 13.04.
P.S.: I don't know what thunar is.

A: This is the way I did.
I ran the following command:
sudo apt-get install nautilus-actions

Then run the Nautilus-Actions Configuration Tool, and create a new item:

*

*Label => Open with audacious

*Path => /usr/bin/audacious

*Parameters => %U

*Working directory => %D -
Good luck.

A: If you set the 'view', 'interface' to winamp, and then 'view', 'always on top' audacious is small and always displays. Then its really easy to drag and drop folders into it. Just something I tried, and it worked...


text:
Q: Indent as much as the width of a word Here is my basic problem:
I want to write on a line
Thesis: "something really long that
         should continue here like this"

How can I do that? (without tabular)
Edit:
I am using this inside a tabular environment like this:
\documentclass[a4paper,10pt]{article}

\begin{document}
\begin{tabular}{r|p{11cm}}
other lines & text here \\
&Thesis: "something really long that\\
&should continue here like this"\\
\end{tabular}

\end{document}

A: Use \phantom{Thesis:}. This will leave as much space as would be taken up by Thesis:
Here are two methods for your specific case:
\documentclass{article}

\begin{document}
\begin{tabular}{r|l}
other lines & text here \\
&Thesis: "something really long that\\
&\phantom{Thesis: }should continue here like this"\\
\end{tabular}

\hrule
\begin{tabular}{r|p{11cm}}
other lines & text here \\
&Thesis: "something really long that\\
&\noindent\phantom{Thesis: }should continue here like this"\\
\end{tabular}
\end{document}

A: You can use the hanging package for this sort of thing:
Here I've created a command which takes one argument, and creates a hanging paragraph with the indent equal to the width of the argument. (I've changed your column width to show the wrapping.)
\documentclass{article}
\usepackage{hanging}
\usepackage{calc}
\newlength{\hangwidth}
\newcommand{\myhang}[1]{\settowidth{\hangwidth}{#1}\hangpara{\hangwidth}{1}#1}
\begin{document}
\begin{tabular}{r|p{3cm}}
other lines & text here \\
&\myhang{Thesis: }``something really long that
should continue here like this''\\
\end{tabular}
\end{document}


text:
Q: Url.openConnection() is throwing ProtocolException I'm trying to request a url which contains my app config. Requesting the url on a desktop is working. However, when trying to make the request in my Android app, I'm getting the following error.
W/System.err: java.net.ProtocolException: Too many follow-up requests: 21
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:417)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
...

I tried to request the same link with Http protocol and got a different error
W/System.err: java.io.FileNotFoundException: http://www-dev...
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:258)
W/System.err:     at .networking.ResourceLoaderTask$override.doInBackground(ResourceLoaderTask.java:45)
W/System.err:     at .networking.ResourceLoaderTask$override.access$dispatch(ResourceLoaderTask.java)
W/System.err:     at .networking.ResourceLoaderTask.doInBackground(ResourceLoaderTask.java:0)
W/System.err:     at .networking.ResourceLoaderTask.doInBackground(ResourceLoaderTask.java:19)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
...

In the documentation it says that I can disable redirects, but the problem is that the redirection is a must in my case. Even when requesting the Url in my browser it is redirecting to a new link.
My AsyncTask#doInBackground is like the folloing
@Override
    protected String doInBackground(String... params) {
        URL url;
        HttpURLConnection ucon = null;
        try {
            String uri = params[0];
            url = new URL(NetworkUtil.wrapURL(uri));
            ucon = (HttpURLConnection) url.openConnection();
            ucon.setRequestProperty("User-Agent", params[1]);
            logUrl(ucon, url);
            InputStream input = ucon.getInputStream();

            java.util.Scanner s = new java.util.Scanner(input).useDelimiter("\\A");
            String resource = s.hasNext() ? s.next() : "";
            ucon.disconnect();

            return resource;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ucon.disconnect();
        }
        return null;
    }


text:
Q: CakePHP 3.7 - Intervention ImageUpload error "Unable read image from path" I suddenly have and image upload error in my cakephp application. Everything was working normaly but then suddenly this error. Check this screenshot:
https://prnt.sc/ssazr5
I make and updates once in a while but I havenot made any changes regarding image upload.
I really have no clue why is this happening?
Maby something cache related?
That is where I have made some updates - deleted some files and compiled new translation files.
Here is my controller
public function edit($id = null)
    {
        $product = $this->Products->get($id, [
            'contain' => [
                'Images',
                'Categories',
                'ChildProducts',
                'AttributeValues',
                'AttributeValues.Attributes'
            ]
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {
            if (!$this->request->getData('images')) {
                $this->request->data['images'] = [];
            }

            $product = $this->Products->patchEntity($product, $this->request->getData(), [
                'associated' => ['Images', 'AttributeValues']
            ]);

            if ($this->Products->save($product, ['associated' => ['Images', 'AttributeValues'] ])) {
                $this->Flash->success(__('The product has been saved.'));
                return $this->Redirecter->goBack();
            }
            $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }

        $this->AttributesHandler->setAttributes(
            !empty($product->category_id) ? $product->category_id : null,
            $product->id
        );

        $categories = $this->Products->Categories->find('list');
        $this->set(compact('productType', 'product', 'categories'/*, 'attributes'*/));
        $this->set('_serialize', ['product']);
    }

And here is Images upload method
 public function upload()
    {
        $this->autoRender = false;
        $this->RequestHandler->renderAs($this, 'json');

        if ($this->request->is(['post', 'put'])) {
            $image = $this->Images->newEntity($this->request->getData());

            if ($this->Images->save($image)) {
                $response = [
                    'id' => $image->id,
                    'url_sm' => '/upload/images/' . $image->id . '/sm_' . $image->image,
                    'url_md' => '/upload/images/' . $image->id . '/md_' . $image->image,
                    'url_lg' => '/upload/images/' . $image->id . '/lg_' . $image->image,
                    'status' => 'success'
                ];
                echo json_encode($response);
                return;
            }
        }

        echo json_encode([
            'status' => 'error'
        ]);
    }

And here is the model initialize
public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('images');
        $this->displayField('filename');
        $this->primaryKey('id');

        $this->addBehavior('ImageUpload.ImageUpload', [
            'image' => [
                ['width' => 1500, 'height' => 850, 'quality' => 90, 'mode' => 'resize'],
                ['prefix' => 'md', 'width' => 320, 'height' => 180, 'quality' => 85, 'mode' => 'resize'],
                ['prefix' => 'sm', 'width' => 600, 'height' => 340, 'quality' => 80, 'mode' => 'fit']
            ]
        ]);
    }

Nginx error.log
recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 77.219.8.56, server: example.com, request: "GET /info.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock:", host: "example.com"

cakephp error.log
Caused by: [ImagickException] no decode delegate for this image format `JPEG' @ error/constitute.c/ReadImage/504

/vendor/intervention/image/src/Intervention/Image/Imagick/Decoder.php(22): Imagick->readimage('/tmp/phpkBXa15')
#1 vendor/intervention/image/src/Intervention/Image/AbstractDecoder.php(338): Intervention\Image\Imagick\Decoder->initFromPath('/tmp/phpkBXa15')
#2 vendor/intervention/image/src/Intervention/Image/AbstractDriver.php(64): Intervention\Image\AbstractDecoder->init('/tmp/phpkBXa15')
#3 vendor/intervention/image/src/Intervention/Image/ImageManager.php(52): Intervention\Image\AbstractDriver->init('/tmp/phpkBXa15')
#4 plugins/ImageUpload/src/Model/Behavior/ImageUploadBehavior.php(115): Intervention\Image\ImageManager->make('/tmp/phpkBXa15')
#5 vendor/cakephp/cakephp/src/Event/EventManager.php(353): ImageUpload\Model\Behavior\ImageUploadBehavior->beforeSave(Object(Cake\Event\Event), Object(App\Model\Entity\Product), Object(ArrayObject))
#6 vendor/cakephp/cakephp/src/Event/EventManager.php(330): Cake\Event\EventManager->_callListener(Array, Object(Cake\Event\Event))
#7 vendor/cakephp/cakephp/src/Event/EventDispatcherTrait.php(114): Cake\Event\EventManager->dispatch(Object(Cake\Event\Event))
#8 vendor/cakephp/cakephp/src/ORM/Table.php(1987): Cake\ORM\Table->dispatchEvent('Model.beforeSav...', Array)
#9 vendor/cakephp/cakephp/src/ORM/Table.php(1921): Cake\ORM\Table->_processSave(Object(App\Model\Entity\Product), Object(ArrayObject))
#10 endor/cakephp/cakephp/src/ORM/Table.php(1634): Cake\ORM\Table->Cake\ORM\{closure}()
#11 vendor/cakephp/cakephp/src/Database/Connection.php(738): Cake\ORM\Table->Cake\ORM\{closure}(Object(Cake\Database\Connection))
#12 vendor/cakephp/cakephp/src/ORM/Table.php(1635): Cake\Database\Connection->transactional(Object(Closure))
#13vendor/cakephp/cakephp/src/ORM/Table.php(1922): Cake\ORM\Table->_executeTransaction(Object(Closure), true)
#14 src/Controller/Admin/ProductsController.php(407): Cake\ORM\Table->save(Object(App\Model\Entity\Product), Object(ArrayObject))
#15 vendor/cakephp/cakephp/src/Controller/Controller.php(610): App\Controller\Admin\ProductsController->edit('103159')
#16 vendor/cakephp/cakephp/src/Http/ActionDispatcher.php(120): Cake\Controller\Controller->invokeAction()
#17 vendor/cakephp/cakephp/src/Http/ActionDispatcher.php(94): Cake\Http\ActionDispatcher->_invoke(Object(App\Controller\Admin\ProductsController))
#18 vendor/cakephp/cakephp/src/Http/BaseApplication.php(235): Cake\Http\ActionDispatcher->dispatch(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response))
#19 vendor/cakephp/cakephp/src/Http/Runner.php(65): Cake\Http\BaseApplication->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response), Object(Cake\Http\Runner))
#20 vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php(162): Cake\Http\Runner->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response))
#21 vendor/cakephp/cakephp/src/Http/Runner.php(65): Cake\Routing\Middleware\RoutingMiddleware->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response), Object(Cake\Http\Runner))
#22 vendor/cakephp/cakephp/src/Routing/Middleware/AssetMiddleware.php(88): Cake\Http\Runner->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response))
#23 vendor/cakephp/cakephp/src/Http/Runner.php(65): Cake\Routing\Middleware\AssetMiddleware->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response), Object(Cake\Http\Runner))
#24 vendor/cakephp/cakephp/src/Error/Middleware/ErrorHandlerMiddleware.php(96): Cake\Http\Runner->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response))
#25 vendor/cakephp/cakephp/src/Http/Runner.php(65): Cake\Error\Middleware\ErrorHandlerMiddleware->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response), Object(Cake\Http\Runner))
#26vendor/cakephp/cakephp/src/Http/Runner.php(51): Cake\Http\Runner->__invoke(Object(Cake\Http\ServerRequest), Object(Cake\Http\Response))
#27 vendor/cakephp/cakephp/src/Http/Server.php(98): Cake\Http\Runner->run(Object(Cake\Http\MiddlewareQueue), Object(Cake\Http\ServerRequest), Object(Cake\Http\Response))
#28webroot/index.php(37): Cake\Http\Server->run()

Any help would be much appreciated.


text:
Q: ¿Cómo editar posición de .rptdesign antes de imprimir? Estoy desarrollando un sistema web y los reportes los realizó en Birt, el único problema es que existe una plantilla predefinida para dicho reporte y la impresión varia en base a la impresora utilizada.
Quisiera encontrar un método para pre visualizar la impresión y poder mover algunos componentes en el eje X o Y antes de imprimir.
Me sería de mucha ayuda sus consejos.


text:
Q: Video Call in Ionic and Overlay Screen In Ionic Application How can I integrate Mesibo Video APIs in Ionic? Gone through the docs but couldn't see anything IONIC specific.
Is there any IONIC Demo Application ?
Is there any other way to use Mesibo Android sdk in Ionic application?
I want to implement video call overlay screen concept where 'while one to one video call in place and user can work on all the application pages in parallel'. Please let know if this feature can be implemented in Ionic application using Mesibo APIs.

A: mesibo provides native APIs for Android (Java & Kotlin), iOS (obj-c, Swift), C++, Javascript, and Python. You need to write a plugin if you like to using mesibo (or any native android library) from ionic
https://cordova.apache.org/docs/en/latest/guide/platforms/android/plugin.html


text:
Q: datalist different behaviour with FF/chrome I am facing an issue with the datalist element when the list of values exceeds 20 values.
The list in Chrome is complete whereas it is limited to 20 values while using Firefox.
Is there a way to solve this issue?
Is it also possible to display an arrow on the right side of the field in Firefox as in Chrome?
Thanks for your help!
Stéphane
Here below is my code:

<input list="lstCont1" type="text" id="Choice"><datalist id="lstCont1">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
<option value="Choice 4">Choice 4</option>
<option value="Choice 5">Choice 5</option>
<option value="Choice 6">Choice 6</option>
<option value="Choice 7">Choice 7</option>
<option value="Choice 8">Choice 8</option>
<option value="Choice 9">Choice 9</option>
<option value="Choice 10">Choice 10</option>
<option value="Choice 11">Choice 11</option>
<option value="Choice 12">Choice 12</option>
<option value="Choice 13">Choice 13</option>
<option value="Choice 14">Choice 14</option>
<option value="Choice 15">Choice 15</option>
<option value="Choice 16">Choice 16</option>
<option value="Choice 17">Choice 17</option>
<option value="Choice 18">Choice 18</option>
<option value="Choice 19">Choice 19</option>
<option value="Choice 20">Choice 20</option>
<option value="Choice 21">Choice 21</option>
<option value="Choice 22">Choice 22</option>
<option value="Choice 23">Choice 23</option>
<option value="Choice 24">Choice 24</option>
<option value="Choice 25">Choice 25</option>
</datalist>


text:
Q: How to get uploader lenght in plupload jQuery('form').submit(function(e) {
        var dosya = jQuery('#uploader').plupload();
        if (dosya.files.length > 0) {
            alert("gg");
          dosya.bind('UploadProgress', function() {
                if (dosya.total.uploaded == dosya.files.length)
                    jQuery('form').submit();

            });
            dosya.start();
        } else if (dosya.files.length <= 0) {
            alert('alert alert alert');
        }
        e.preventDefault();
    });

I'm getting this error during the post process
     Uncaught TypeError: Cannot read property 'length' of undefined
     ** Can someone help me**

A: dosya.files is undefined (Null), this mean you don't have value to this variable, that why you don't have the property 'length' and you get the exception

A: I soloved this problem it's working
  jQuery('form').submit(function (e) {
        var uploader = jQuery('#uploader').plupload('getUploader');
        if (uploader.total.uploaded == 0) {
            if (uploader.files.length > 0) {
                uploader.bind('UploadProgress', function () {
                    jQuery('#uploader').on('complete', function () {
                        jQuery('form').submit();
                    });
                });
                jQuery('#uploader').plupload('start');
            } else { jQuery('form').submit(); }
            //alert('alert alert alert');

            e.preventDefault();
        }
    });


text:
Q: Make a slide show by fading in background images I want to turn the banner image on this page into a slide show. I know how to write HTML and CSS but I'm less adept at scripting.
My idea is to have the text stay in place while the the banner image behind it is replaced. I would like to see the new image fade in.
How can I implement this with JavaScript or jQuery?

A: I implemented a simple fade-out/fade-in slide show for you. The demonstration below uses the three large files you specified in your comments. The slide show won't work until the images have been loaded, so you may want to work on improving the load times.
To use this slide show in your project, merge the CSS rules below into your CSS file, then insert the JavaScript into your page and modify the parameters slideDelay, fadeLength, and imageSources to suit your needs.

SlideShow = {
  slideDelay: 5,  // Number of seconds to wait before showing a new slide.
  fadeLength: 1,  // Number of seconds to spend fading in or fading out.
  hertz: 60     // Number of times per second to update the fade effect.
};

SlideShow.imageSources = [
  'http://preview.impactdesigns-ad.com/HBP/img/basecamp009.jpg',
  'http://preview.impactdesigns-ad.com/HBP/img/biohazard007.jpg',
  'http://preview.impactdesigns-ad.com/HBP/img/Header.png'
];

SlideShow.showSlide = function (newImage, oldImage) {
  var g = SlideShow,
      opacityIncrement = 1 / g.hertz,
      fade = { interval: {}, count: {} };
  function fadeOut() {  // Gradually makes the old image vanish.
    oldImage.style.opacity = fade.count.out * opacityIncrement;
    if (--fade.count.out == 0) {
      window.clearInterval(fade.interval.out);
      oldImage.style.visibility = 'hidden';
    }
  }
  function fadeIn() {  // Gradually makes the new image appear.
    newImage.style.opacity = 1 - fade.count.in * opacityIncrement;
    if (--fade.count.in == 0) {
      window.clearInterval(fade.interval.in);
    }
  }
  function newSlide() {  // Starts the fade-in process.
    newImage.style.opacity = 0;
    newImage.style.visibility = 'visible';
    fade.count.in = g.hertz;
    fade.interval.in = window.setInterval(fadeIn, g.fadeLength * 1000 / g.hertz);
  }
  if (oldImage) {  // Fade out the old, then fade in the new.
    window.setTimeout(newSlide, g.fadeLength * 1000);
    fade.count.out = g.hertz;
    fade.interval.out = window.setInterval(fadeOut, g.fadeLength * 1000 / g.hertz);
  } else {  // If there is no old image, immediately fade in the new image.
    newSlide();
  }
}

SlideShow.replaceSlide = function () {  // Updates slideIndex and calls showSlide.
  var g = SlideShow,
      images = g.images,
      oldImage = images[g.slideIndex];
  g.slideIndex = ++g.slideIndex % images.length;
  var newImage = images[g.slideIndex];
  g.showSlide(newImage, oldImage);
};

SlideShow.stop = function () {
  var g = SlideShow,
      interval = g.interval;
  window.clearInterval(interval);
}

SlideShow.start = function () {
  var g = SlideShow,
      imageSources = g.imageSources,
      images = g.images = [],
      container = document.getElementById('slideContainer'),
      background = g.background = document.createElement('div');
  background.className = 'background';
  for (var i = 0; i < imageSources.length; ++i) {
    var image = document.createElement('img');
    image.src = imageSources[i];
    image.style.visibility = 'hidden';
    images.push(image);
    background.appendChild(image);
  }
  container.appendChild(background);
  var startInterval = window.setInterval(function () {
    for (var i = 0; i < images.length; ++i) {
      if (images[i].height == 0) {  // Wait until all images are loaded.
        return;
      }
    }
    window.clearInterval(startInterval);
    g.slideIndex = 0;
    g.showSlide(images[g.slideIndex]);
    g.interval = window.setInterval(g.replaceSlide, g.slideDelay * 1000);
  }, 100);
};

SlideShow.start();
#slideContainer {
  font-family: sans-serif;
  font-weight: bold;
  font-style: italic;
  font-size: 48px;
  color: #cb4949;
  width: 1000px;
  height: 700px;
  overflow: hidden;
  position: relative;
}
#slideContainer span {
  padding: 20px;
  text-align: center;
  position: absolute;
  z-index: 10;
}
#slideContainer .background, #slideContainer .background img {
  position: absolute;
  left: 0;
  top: 0;
}

 This is some text over the slide.

<button onclick="SlideShow.stop()"> stop slide show </button>


text:
Q: Are special terminals required for connecting thermocouple wires to a PCB? I'm currently trying to integrate a type K thermocouple into an electronics project. I intend on interfacing this thermocouple with the MAX31855 cold-junction compensated thermocouple-to-digital converter IC.
I am not an expert on thermocouples and the Seebeck effect, so I'm somewhat curious as to how I should actually land the thermocouple onto the PCB. Assume I'm using loose thermocouple wires.
Questions:

*

*Can I use any type of terminal (say a simple through hole screw terminal) to land the wires onto the PCB? Or will these new junctions introduce errors?

*Is the termination method dependent on the thermocouple type? E.g. use this terminal for type K, use this other terminal for type J, etc.

A: Any change in material will introduce an error on the signal. However if the changes are the same (in terms of both material and temperature) on both terminals then those errors will cancel out.
So you can use just about any method you like as long as you keep things symmetrical.
Two things to watch out for - Firstly the temperature that is measured is the difference between the thermocouple junction and the temperature where the two wires become the same material, normally the copper trace on your PCB or the terminal block. This means that if you use screw terminals then your cold junction temperature sensor needs to be at the same temperature as those screw terminals. Any difference will be reflected as an error in your measurement.
Secondly be careful of temperature gradients on your PCB e.g. if one terminal is closer to the power supply or further away from some source of airflow it could be a tiny bit warmer which will impact the end result. If the terminals are on the outside of the box and the cold junction reference is inside getting heated by a CPU then you're going to get a big error.

A: You must change metals at some point, to connect to the 31855.
I order to do cold junction compensation, the 31855 must know the temperature of this point. Any difference between the temperature of this point, and the point that the 31855 senses, will appear as an error in the temperature reading.
The 31855 measures its die temperature as the 'cold junction'. This means that as long as the 31855 and your 'thermocouple wires to copper' junction are at the same temperature, all will be good. This generally means make the junction as close to the IC as possible, and don't have hot components producing thermal gradients anywhere near the IC.

A: The quick answer: Yes.
The long answer: thermocouples use the difference between two metals at temperatures to generate a voltage that is representative of the temperature. This means that all of the cable, from the thermocouple to the sensor, needs to be this special combination of metals to give you the temperature measurement accurately. You can buy thermal couple wire for this purpose.
That being said, I have used systems where we had a K-type thermocouple, going into a standard header on a PCB, through standard tracks before going into the sensor, and that could give us a value. The issue with using something other than a proper header is the accuracy of the reading. We knew roughly what the offset was (appeared to be an offset of around +4C at the temperatures we were interested in) and just adjusted accordingly. But that was the advantage of being in our own test cells, where we had other sensors to compare the value to.
So, while you should use proper connectors, you can get away without doing so.

A: Each time you change to a different metal thermocouple wire->connector metal->solder->copper, you are adding another thermocouple junction. Fortunately, you always add a pair of junctions at a time- one in the wire going to the thermocouple and one in the wire coming back- and as long as both of the junctions are at the same temperature, the two will cancel out.
The overall effect will be the same as having just two junctions: the one at the end of the thermocouple (hot) and the one at the junction between the two thermocouple wires and the connector (cold).
Ideally you should do your cold junction compensation by measuring the temperature of the cold junction (ie the connector). If the chip that that you are using is doing the CJC, you should place it as close as possible to the connector, and as far away as possible from any heat sources.

A: I know this was originally asked 5 years ago, but every answer here seems to assume that the voltage is generated at the junction. This is NOT the case! Both sides of the junction are at the exact same potential. The voltage is generated along the length of the wires! It's due to the temperature gradient in each of the two wires, and is independent of length. Different metals generate different voltages.
The ONLY thing that matters when measuring temperature differences is that the terminations of both wires be at the same temperature! But since it's only relative temperature that is measured, you also need to know the temperature of the 'cold' (reference) side of the wires. This is where the cold junction compensation comes in, and the only thing that matters is that the temperature you measure is that of the reference end of the TC wires! If you are using an external thermistor to measure the reference temperature, this is easy to arrange. If it's an on-chip measurement, then you would want the reference ends of the TC wires to be at the same temperature as the chip, which would generally mean terminating them as close to the chip as possible (or otherwise ensuring that the temperatures match).
Now, if you're measuring a kiln, for example, an error of a few degrees is no big deal. But for more demanding needs, you would want to minimize the offset. But if you wanted high precision measurement of non-extreme temperatures, you'd probably be using an RTD instead.

A: Using a terminal block made with ordinary materials is quite sufficient for a relatively modest accuracy system as you're aiming for.
The cold junction compensation depends on the cold junction sensor (in this case, the chip itself) being at the same temperature as the two junctions where the thermocouple wire transitions to copper. In other words, all three should be isothermal- so you want to minimize gradients caused by dissipation on the PCB and by gradients caused by heat flowing down the wires. You can help this along greatly with ground planes or at least pours and by keeping anything that dissipates a lot of heat well away from the T/C block. Keep air currents away from the terminal block too. Of course you will put the chip as close as practical to the terminal block, physically as well as thermally.
There is no great difference between most sensors as far as this goes as most thermocouples are fairly linear (a couple percent) so 1°C error at the cold junction is around 1°C error in the temperature reading.
If the connection is out hanging in the breeze or is at an elevated (for example) temperature, it's better to use connectors that are made of thermocouple materials, and this is typically done for panel-mount connectors and inline connectors. They are usually color coded. In North America we use the ISA color codes, and type K (Chromel-Alumel) is yellow, type J (Iron-Constantan) is black. You could, for example, have a bulkhead K connector and connect that inside an enclosure to the PCB. You MUST use the proper thermocouple extension wire on the inside as well as outside in this example, and it MUST be connected the correct way (if you swap the polarity the error is actually doubled). Keep in mind that red = negative in North America T/C color codes.

A: Lets put some numbers on the PCB design. Standard copper foil is 70 degree Cent per watt per square. Thus 1cm or 1mm or 100micron or 10cm squares, with one watt injected uniformly along one edge and that heat flowing ONLY to the opposite edge, will have 70 degree Cent temperature gradient. Should you have a 100 millWatt MCU (its usually busy handling USB data for a bunch of other ICs) needed to dump that 100mW to a metal bolt 3 squares away, the temperature gradient will be 0.1W * 3 * 70 degC/watt = 21 degrees. C.
Get a quadrille pad, and start drawing heat sources and heat exits, and slits in the PCB to guide the heat flows. And consider using VDD and GND planes to thermally move the heat around.
If you perform a finite-element model, using a grid of resistors in SPICE, with low value Rs to model the copper, and Rs 100X higher to model the FR-4, you'll get an idea how much overlap of planes is needed to dump half the heat in the hotter plane into the cooler plane.


text:
Q: coloured matrix R save latex I have this "coloured" matrix in R
library(gplots)

#Build the matrix data to look like a correlation matrix
x <- matrix(rnorm(64), nrow=8)
x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

#Format the data for the plot
xval <- formatC(x, format="f", digits=2)
pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

#Plot the matrix
x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none", main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal, tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8, keysize = 1.5, margins=c(5, 5))

and I would like to import it in Latex. How can I do?
Thank you for your help!

A: gplots::heatmap.2 only prints the image of a colored matrix, it doesn't actually return one. Nevertheless, we can recreate it ourselves and convert it into a latex table (although the comment of saving the image and using \includegraphicsin latex is just as good). Here's the .Rmd file you can use. Make sure to Knit as a PDF!
---
title: "Hey Stack"
header-includes:
   - \usepackage[table]{xcolor}
output: pdf_document
---

```{r, include = FALSE}
library(gplots)
library(xtable)

#Build the matrix data to look like a correlation matrix
x <- matrix(rnorm(64), nrow=8)
x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

#Format the data for the plot
xval <- formatC(x, format="f", digits=2)
pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none",
  main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal,
  tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8,
  keysize = 1.5, margins=c(5, 5))
```

```{r, results = 'asis'}
color_m <- apply(round(x, 2), 2, function(r) {
  col <- cut(r, x_hm$breaks, gsub("#", "", x_hm$col), include.lowest = TRUE)

  paste0("\\cellcolor[HTML]{", col, "}{", r, "}")
})

print(xtable(color_m), sanitize.text.function = identity, comment = FALSE,
      include.rownames = FALSE, include.colnames = FALSE)
```


text:
Q: Facebook Load Thumbnail I'm looking to try and mimmic facebook's thumbnail function.
Let me be more specific:
When you paste a link into your Facebook feed it will load thumbnail images from that link before you post it.
Does anybody out there know how to do this?
Thanks guys
Alex

A: Facebook "scrapes" the given URL, and looks for Open Graph meta elements, or in case it doesn't find any, it tries to figure out relevant images & content from the HTML code itself.


text:
Q: How to break line in jQueryUI tooltip The new version of jQueryUI (1.9) comes with the native tooltip widget. After testing with it, it works fine if the content (value of the title attribute) is short. But if the content is long, the tooltip, once displayed, will overlap the input text.
There is a demo on the official site.
When you hover the mouse cursor over the Your age text <input>, the tooltip displayed overlaps the text input. I am not sure if this is the desired behaviour of the widget.
I would like it to stay on the right side of the text input and break lines if necessary.
Edit: The demo page no longer shows the original problem since the demo has been updated to use jQueryUI v1.10 in which the position code was updated to better place the tooltip - see http://api.jqueryui.com/tooltip/#option-position
I have re-created a demo of the original problem on jsFiddle.

A: The placement of the tooltip is controlled by a jQueryUI Position object and the default settings are:
{ my: "left+15 center", at: "right center", collision: "flipfit" }

The Position Object, in particular the collision attribute can be changed to force placement of the control somewhere else. The default for tooltips is flipfit which means the if the default (on the right) does not fit it will flip to the left and try that position and if that doesn't collide with anything, try to fit the control by moving it away from the edge of the window. The result is that it now collides with the <input>. There doesn't seem to be an option to force a long tooltip to cleverly wrap.
However there are two ways to wrap the content:
Add a custom CSS class to the configuration with a max-width to force wrapping, for example:
JavaScript
$('input').tooltip({
    tooltipClass:'tooltip'
});

CSS
.tooltip {
    max-width:256px;
}

Or insert hard line-breaks
 in the title attribute, for example
title="Lorem ipsum dolor sit amet,
consectetur adipisicing elit"

Edit: So it looks like jQueryUI changed the tooltip content option between v1.9 and v1.10 (according to the changelog). For reference here is the difference:
v1.9.2
content: function() {
    return $( this ).attr( "title" );
}

v1.10
content: function() {
    // support: IE<9, Opera in jQuery <1.7
    // .text() can't accept undefined, so coerce to a string
    var title = $( this ).attr( "title" ) || "";
    // Escape title, since we're going from an attribute to raw HTML
    return $( "" ).text( title ).html();
}

So you can put back the older functionality that does not escape
 tags in the title attribute by using the .tooltip() like this:
$('input').tooltip({
    content: function() {
        return $(this).attr('title');
    }
});

Also, see jsFiddle demo.

A: This works:
HTML

AB PNEU 700 X 23 FOLD CORPRO

JavaScript
$(document).tooltip({
    content: function() {
        var element = $( this );
        if ( element.is( "[title]" ) ) {
            return element.attr( "title" );
        }
    },
    position: {
        my: "center bottom-20",
        at: "center top"
    }
});

A: This is my trick to do it with latest jquery / jqueryui
It's assuming all of the items you want to have tooltips have class 'jqtooltip', they have title tags, and the title has a pipe character for a line separator.
$('.jqtooltip').tooltip({
  content: function(callback) {
     callback($(this).prop('title').replace('|', '
'));
  }
});

A: I have a solution for jQuery 2.1.1, similar to @Taru's solution.
Basically, we have to use tooltip's content call to dynamically get the data from the element. The element itself can have any html markup in it. Note that you need to import
So, onload, I do this:
$(function() {
    $( document ).tooltip({
      content:function(){
        return this.getAttribute("title");
      }
    });
  });

And my example element is this:
hover me

A: According to the official jQuery UI's documentation https://api.jqueryui.com/tooltip/ for the tooltip widget (version 1.13), I've used this syntax to set an html content with linebreaks :
$( ".selector" ).tooltip( "option", "content", "1st line.
2nd line.
3rd line." );

It works fine on my side.
Also works the solution provided by andyb here that aims at valuing the content by the title attribute's value :
$('input').tooltip({
 content: function() {
    return $(this).attr('title');
 }
});


text:
Q: How to open developer page on Google Play Store (market://) Recently, Google Play lets developers create developer page.
Here is the example : https://play.google.com/store/apps/dev?id=5700313618786177705
I try to find developer page Uri link (market://...) that I can use but I can't find it on Android Developer page. (http://developer.android.com/distribute/tools/promote/linking.html)
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://..."));
startActivity(intent);

A: This works for me:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=7809285959465313029")));

Using market URI does not work for me.

A: You can simply call market://dev?id=xxx
e.g.:
market://dev?id=5700313618786177705

I hope, this suits your needs!
Best,
Jacko

A: //Method for intent to Google playstore developer page

 private void M_Intent2developerpage() {
       Intent intentdev = new Intent(Intent.ACTION_VIEW);
       intentdev.setData(Uri.parse("market://search?q=pub:Google Inc."));
   //here Developer Name is very case-sensitive . change your developer name as shown in developers page.
       if (!MyStartActivity(intentdev)) {
           intentdev.setData(Uri.parse("https://play.google.com/store/apps/dev?id=5700313618786177705"));
           if (!MyStartActivity(intentdev)) {
               Toast.makeText(this, "Could not open Android Google PlayStore, please install the Google play app.", Toast.LENGTH_SHORT).show();
           }
       }
   }

//Method checks if any problem when Intent

 public boolean MyStartActivity(Intent aIntent) {
        try {
            startActivity(aIntent);
            return true;
        } catch (ActivityNotFoundException e) {
            return false;
        }
    }

A: Kotlin with the developer name instead of the developer Id:
startActivity(Intent(Intent.ACTION_VIEW,
     Uri.parse("https://play.google.com/store/apps/developer?id=MyDeveloperName")))

A: To open app on google play: you can use:
getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=<developer_id>)));

OR
getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://dev?id=<developer_id>)));


text:
Q: multiple human language collation in sql server I'm a little embarrassed to admit that I've never really needed to worry about Unicode text before in a SQL Server so I'm fumbling here.
I downloaded the Geonames Cities1000 data file and loaded it into SQL Server, with all the text fields as large nvarchars so as to avoid truncation. When I did a search for a city I know well (Bucerias, Mexico), I queried my table and found it but it's listed like this:
Bucerías

The actual spelling (what's in the file I imported and what's on the city sign when you drive in), is this:
Bucerías

Do I need to re-make my table with different collation? I'm handling city names from all over the globe so I'm sort of at a loss here on how to set up the collation for this, or if that's even my problem.
In short, I want Bucerías to appear as Bucerías, and مورای، یوتا,穆雷 to appear as مورای، یوتا,穆雷, etc.

A: What ended up helping was picking the 65001 (UTF-8) code page. When I checked the Unicode box there it caused the parser to miss the deliminator control characters, so that's unchecked.

*

*Make sure the output column is set for Unicode text.

*Make sure the code page is set for 65001.

*Make sure the destination column (of the SQL table) is nvarchar.

Now my SQL query retruns Bucerías !


text:
Q: Padrão Singleton para comunicação com banco de dados Em PHP quando faço um Singleton é criado uma instância para cada requisição que tenta abrir uma conexão com o banco de dados ou instanciando uma única vez ela "sempre" vai ficar em memória para todas as requisições?
exemplo:
class Connect{

    private static $conn;//qual o escopo dessa variavel?

    /**
    *   Padrão singleton
    */
    public static function getConnection(){
        if(self::$conn==NULL){
            //vai entrar aqui toda vez que uma requisição do usuario tenta uma comunicação com o bd?
            self::$conn= new PDO(...);
        }
        return self::$conn;
    }

A: O padrão Singleton é justamente isso (eventualmente pode ser um pouco mais sofisticado). Por ser estático não há instanciação de fato, e a lógica do método garante que a conexão seja aberta apenas uma vez, afinal, a primeira vez a variável privada $conn, que tem escopo privado (só a classe a vê), é nula então é estabelecida uma conexão, após isso, não entra mais no if e só retorna o objeto da conexão. Então ficará na memória enquanto o script estiver rodando.
Eu costumo dizer que esse tipo de coisa é muita complicação para algo que será bem efêmero, mas tá na moda fazer assim. Design patterns costumam ser abusados, o Singleton é o campeão disto, em PHP então...

*

*Mais sobre o assunto.

*Específico para PHP.

*Resposta no SO.


text:
Q: How to show InkWell's ripple effect above container with background image decoration I'm trying to add a ripple effect when tapping on a movie card which is a container widget that has a background image decoration.
Screenshot:
Before tapping:

While tapping:

You can see that the overlay is being rendered behind the card.
Here is some code:
MovieCard widget tree:
Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          image: DecorationImage(image: AssetImage("assets/in.jpg"), fit: BoxFit.fitWidth)),
        width: (MediaQuery.of(context).size.width / 2) - 10,
        height: 250,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              decoration: BoxDecoration(
                color: colorScheme.surface,
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10))
              ),
              width: double.infinity,
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Text("Interstellar",
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 16)),
                    ),
                  ],
                ),
              ),
            ),
          ],
));

How the MovieCard widget is being used in the parent's widget:
Material(
  type: MaterialType.transparency,
  child: InkWell(
  child: MovieCard(), onTap: () => print("lol"), enableFeedback: true)
),

Note that the MovieCard() widget is a child of a GridView widget, just in case if that has any effect on this behavior.
Thanks in advance!


text:
Q: Android, trying to enlarge text if it's on a bigger screen I am trying to enlarge the size of text in a button as the screen gets wider.  At first it seemed my code worked, but on different android devices it does not work. It will change the font to a big size on a small screen.
This is what I'm doing:
 int w=getWindowManager().getDefaultDisplay().getWidth();

        Button but1=new Button(this);
//        but1.setTextColor( Color.parseColor("#ffd79825"));
        if (w<400)
            but1.setTextSize(10.0f);
        else
        if (w<650)
            but1.setTextSize(14.0f);
        else
             if (w>470)
                but1.setTextSize(18.0f);

A: Why are you making it more complicated, than it is?
Just use dimensions in your values folder:
values:
<dimen name="txtSize">10dp</dimen>

values-sw400:
<dimen name="txtSize">14dp</dimen>

And so on.
You can obtain the value like this:
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.txtSize);


text:
Q: Items in another layout do not respond to user events Please have a look at the following code
game_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Game" >

    //Please note the GUI Has been removed

        <include layout="@layout/common_status_bar"/>

</RelativeLayout>

Game.java
package game.games;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;

public class Game extends Activity {

    private ImageView goToLanguageSelection;
    private ImageView goToInternet;
    private Button giveUp;

    private LayoutInflater layoutInflater;
    private View commonView;

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

        layoutInflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        commonView = layoutInflater.inflate(R.layout.common_status_bar, null);

        //Intializing instance variables
        goToLanguageSelection = (ImageView)commonView.findViewById(R.id.backToLanguageSelectionButton);
        goToInternet = (ImageView)commonView.findViewById(R.id.internetButton);
        giveUp = (Button)commonView.findViewById(R.id.giveUpButton);

        flag = getIntent().getBooleanExtra("LANGUAGE", true);

        //Add listeners

        goToLanguageSelection.setOnClickListener(goToLanguageSelectionClicked);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.game, menu);
        return true;
    }

    //Will get activated when the ThunderBolt image is clicked
    private OnClickListener goToLanguageSelectionClicked = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getBaseContext(),LanguageSelector.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

        }

    };

}

common_status_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="#373734"
    android:orientation="horizontal" >

        <ImageView
            android:id="@+id/backToLanguageSelectionButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="15dp"
            android:paddingTop="5dp"
            android:src="@drawable/thunderbolt" />

        <ImageView
            android:id="@+id/internetButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"
            android:paddingTop="5dp"
            android:src="@drawable/globe_small_2" />

        <ImageView
            android:id="@+id/justForFun"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingBottom="5dp"
            android:paddingTop="5dp" />

         <Button
            android:id="@+id/giveUpButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:text="Button" />

</LinearLayout>

Here, the common_status_bar.xml is a common layout. I have added this layout to game_activity.xml by <include layout="@layout/common_status_bar"/>.
It displays everything fine, no issue. But the case is I can't make any of it's elements to work. I have attached a OnClickListener to the first element of it, the goToLanguageSelection but it is not responding to the Click. I tested this by adding the click event to all other buttons, images as well (one at a time) and I got the same result. It is not responding to user click, or whatever.
Why this button and images in separate layout do not respond to the user events?

A: The commonView should not be created again.
If you want keep a reference of the common_status_bar.xml, you can give name it by an id, like the code below:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp" >

        <include
            android:id="@+id/common_status_bar"
            layout="@layout/common_status_bar" />

    </RelativeLayout>

Then, change this code:
       commonView = layoutInflater.inflate(R.layout.common_status_bar, null);

to:
       commonView = findViewById(R.id.common_status_bar);


text:
Q: Android Studio offline option is not showing up I faced following issue, so I needed to uncheck offline option in Android Studio but my offline option is not there, I am also attaching the screenshot and 3 errors. My android studio version is 3.6.1
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ':classpath'.

Second:
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve com.android.tools.build:gradle:3.5.3.

Third:
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: No cached version of com.android.tools.build:gradle:3.5.3 available for offline mode.

A: From the Android Studio 3.6 new features blog post:
New location to toggle Gradle's offline mode To enable or disable Gradle's offline mode, first select View > Tool Windows > Gradle from the menu bar. Then, near the top of the Gradle window, click Toggle Offline Mode Gradle offline button
Or try with offline icon


text:
Q: Canvas won't appear in browser My canvas wont show in my browser.
I'm guessing the reason is because of some newbie jquery  mistakes.
The codes below are in two separate folders, Game.html and game.js
Game.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <canvas id="gameCanvas">

    </canvas>
        <script src="Scripts/jquery-2.0.3.js" type="text/javascript"> </script>
        <script src="Scripts/game.js" type="text/javascript">  </script>
</body>
</html>

game.js:
var canvasWidth = 800;
var canvasHeight = 600;

$('#gameCanvas').attr('width', canvasWidth);
$('#gameCanvas').attr('height', canvasHeight);

var canvas = $('#gameCanvas')[0].getContext('2d');
canvas.strokeRect(0, 0, canvasWidth, canvasHeight);

A: Here is tested your code is working perfectly.
Look in your Scripts folder content files jquery-2.0.3.js and game.js.
the only possibility is error path, look at this.
And what browser are you testing? html5 canvas is then only works in some new browsers.
checked here if your browser does have canvas support
Code Equals

working example here

A: Are you sure your reference to the script file is correct.  If both html and script are in two different folders, then the reference might need to be:
<script src="../Scripts/jquery-2.0.3.js" type="text/javascript"> </script>
<script src="../Scripts/game.js" type="text/javascript">  </script>