Submitting form automatically using javascript instead of pressing button

Question: Using javascript how I can extract all states information at one go?
This page list in form, states to see the local service center address:
http://www.lenovowarranty.co.in/contacttech.asp
Should I save the page and modify the javascript?
Which debugger is best for javascript?
Answer: You could post your form using jQuery Forms. To automatically submit you should be able to do something like:
$(function(){
    $('#myFormId').ajaxForm().ajaxSubmit();
});

The ajaxSubmit function takes the same arguments as the regular $.ajax().
For debugging javascript and many other things I think Firebug for Firefox is the best.
Here's a short introduction http://getfirebug.com/video/Intro2FB.htm
Answer: You can submit a form by calling its submit method:
document.forms[0].submit();

This excellent page shows how to work with forms in JavaScript - submit them, check the values of the input elements etc.
Comment: I think he wants all results in one go, without refreshing the page.
Answer: If you check the form, you'll see that it makes POST requests:
<form name="splocator" method="post" action="serviceproviders.asp" ...>

You can see which variables get sent and then you can make requests for all states via AJAX and interpret the responses.
You should consider using something like jQuery for this, especially if you're not experienced with JS.


What happens to the calls to Azure Storage Account DURING a FAILOVER?

Question: We have an Azure Storage Account in US EAST 2 location which has RA-GRS replication.
In case of a disaster, either client(us) or Azure(Azure Managed Failover) can initiate a FAILOVER and once FAILOVER is completed (lets say it takes 10 minutes to complete) the secondary region's storage account becomes primary and caters the requests(both read and write.
My question is, what happens to the "read" calls during those 10 minutes when FAILOVER is happening ? Will those "read" calls be fulfilled by secondary region storage account since we have RA-GRS or is there any catch ? I have this confusion because, although secondary region's storage account is always available for "read" requests, but the application has to specifically point to that secondary storage account to make a call otherwise the call goes to primary storage by default.
Comment: Welcome to SO. Please read https://stackoverflow.com/help/how-to-ask and post your question
Answer: From the description in the official document, read requests can be redirected to the secondary region.
Comment: Ok, to sum up your response, can I say that, if handled programmatically(meaning may be using resiliency to check failure), in case of a outage and DURING FAILOVER, the read requests can be fulfilled by secondary region, right ? @Frank Gong
Comment: I did not understand what you said `if handled programmatically(meaning may be using resiliency to check failure)`, but my understanding is that as long as you use a `RA-GRS` type of storage account, in case of a outage and DURING FAILOVER, the read requests can be fulfilled by secondary region.@KarunAhluwalia
Comment: Thanks @Frank Gong


BufferedWriter write() method not working

Question: When I check the "Dir" directory, the file is created properly (with name writtenfile1), but nothing gets written inside and I do not understand why.
Is this a common pitfall with BufferedWriter?  Because my code looks perfectly reasonable.
    int i = 1;
    Path path = Paths.get("Dir//writtenfile" + i + ".txt");
    Charset charset = Charset.defaultCharset();
    try {
        BufferedWriter writer = Files.newBufferedWriter(path, charset);
        writer.write("Message written!");
        //writer.write("This is file number " + i);
    } catch (Exception e) {
        System.out.println(e);
    }

Answer: As the name BufferedWriter implies, the data is buffered. It or the last part is only written on explicitly flushing or closing the writer instance.
This is not a bug; it is normal behaviour of this class.
Comment: Oh wow. It's working now. Good to know that .close() or .flush() have such a tremendous impact on the program's behavior.


Remove any line beginning with specific string?

Question: I have the following string:
Q: What is your favorite color?
A: Red
Q: Who is your favorite actor?
A: George Clooney

I want to be left with:
A: Red
A: George Clooney

There are hundreds of possible questions (Q: xyz?), so I can't just str_replace each specific question.
Is there a function in PHP with regex that would allow me to delete all lines beginning with the following string: "Q: "
Comment: Is that an array of strings?
Comment: No there's no such function. You should combine function which reads lines from file (`fget` for example) and function which checks position of `Q:` in a string (`strpos`).
Answer: You can use this simple regex
 $string = preg_replace('/^Q:.+$/m', '', $string);

I used the m flag which should make ^ match the start of a line and $ match the end, but some of it depends on what the input is like.
When testing above
Sandbox
it may leave the line endings.  So I modified it to this
 $string = preg_replace('/^Q:.+(?:\r\n|\r|\n)/m', '', $string);

Which should remove them.
Sandobx
Which "duh" I just remembered that the $ doesn't capture anything, so because it doesn't capture it, it wont be replace.
You could also break the data into lines first and test with match, like this
$string = 'Q: What is your favorite color?
A: Red
Q: Who is your favorite actor?
A: George Clooney';

$lines = preg_split("/[\r\n]+/",$string);

$fixed = [];

foreach($lines as $line) if(!preg_match('/^Q:/', $line)) $fixed[] = $line;

echo implode(PHP_EOL, $fixed);

Sandbox
Comment: You're missing the colon here.
Comment: `.+` includes colon ;-)
Comment: This leaves empty lines where likes begin with Q
Comment: Yeah, I suppose if the input only starts with A: or Q:, that's fine but this would also match any other line starting with Q
Comment: bla bla .... lol  :)
Comment: Works perfectly. The other solutions do as well, but some of these strings have important text outside of the "Answer" lines, so this solution (which only removes the Q lines) does the trick.
Comment: @jm92 I have updated my answer below
Answer: Id use explode() then array_filter(), for example:
<?php
$str = 'Q: What is your favorite color?
A: Red
Q: Who is your favorite actor?
A: George Clooney';

$array = explode(PHP_EOL, $str);

// get answers
$answers = array_filter($array, function ($value) {
    return substr($value, 0, 3) === 'A: ';
});

print_r($answers);

https://3v4l.org/6UKLZ
Result:
Array
(
    [1] => A: Red
    [3] => A: George Clooney
)

And implode() it back for desired result:
https://3v4l.org/Esj98
A: Red
A: George Clooney

Comment: upvote +1  for not using regex
Comment: good answer but I would have used `return 0 === strpos($value,'A:');`  It should be faster then substr.  By using `0` we know it was the start of the string :-), so we can still be sure if there is a Q: in the middle it wont remove that.
Comment: I guess the performance is marginal, over 1m iterations, `strpos 1.0296 seconds` and `substr 1.0770 seconds` .. lol
Comment: Your right, can be done either way, I just picked substr as it was the first that popped into my head.
Answer: You can use preg_match_all and capture all answers.
preg_match_all("/^A:.*$/m", $str, $m);
Echo implode(PHP_EOL, $m[0]);

The pattern
/^A: //must start with A:
.*   // Then anything
$    // to end of line
/m   // and make it multilined

https://3v4l.org/LPB25

If any of the answers are multilined, as in they have a line break you can use this code to get both lines.
The other answers will only capture single line answers.
This finds the next question and stops there
$str = "Q: What is your favorite color?
A: Red.
As in the color of a rose.
Q: Who is your favorite actor?
A: George Clooney";
preg_match_all("/(A:.*?).Q: /ms", $str . "\nQ: ", $m);
Echo implode(PHP_EOL, $m[1]);

I add a "extra question" with $str . "\nQ: "
This outputs
A: Red.
As in the color of a rose.
A: George Clooney

https://3v4l.org/UCArm


Understanding the recursive function

Question: Maybe this function is very simple for you. but i have problems with how this functions works.please explain how to compile this function.
It is zero the count in the run loop ?
function countChars(elm) {
  var i, count = 0;

  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }

  for (i = 0, child; child = elm.childNodes[i]; i++) {
    count += countChars(child);
  }
  return count;
}

Comment: Put a few console.log s inbetween, add some breakpoints in the debugger, take a simple example, run it, and see that it isnt really complicated.
Comment: Just translate it into words: if the current node is a text node, return its length, otherwise - loop over its child and call the function again (for every child) and sum the result. Return the result.
Comment: It counts the combined length of all the text stored in the tree's *leaf* nodes
Comment: The function will recursively call its self until it reaches a TEXT_NODE.

But the for loop is not testing for var i value, and so will never exit. (var i will increment indefinitely).

If you change the for loop to:-

`for ( var i = 0;  i < elm.childNodes.lenfth; i++ ) { var child = elm.childNodes[i].....  }`

you may have more luck.
Comment: @Jonasw I did, but still did not get the result.
Comment: @user3094755 no, the loop should work properly.
Comment: I fully understand how much this function repeats and what it does. My question is thatEvery time the loop is executed, the count is zeroed? And if so, how is the sum returned?
Comment: @AlonEitan no this worked Absolutely true. The function runs perfectly and works. But I do not understand this function.
Comment: @miladasghari That's good to know. Please check the answers below and see if it helps (They are both good answers), you can upvote/accept if you think they are helpful
Comment: `count` is a local variable in the function instance, meaning every instance of the function has its own unique, private variable. It's not one single variable that gets zeroed every time the function runs. A new variable is created with the value `0`.
Answer: Some Text

The DOM will look like this:
[
Textnode {"Some Text"}
]

The upper code is valid HTML, actually it is a text node. So if we want to get its length we simply take its length:
if (elm.nodeType == 3) { // TEXT_NODE
   return elm.nodeValue.length;
}

Lets imagine a more complicated case:
Some Text  nested

DOM:
[
Textnode {"Some Text"},
Span {
  children:[
    Textnode {"nested"}
  ]
 }
]

Now weve got four nodes. A text node and a span node, and a text node nested in the span node. And theyre all nested in some kind of body. So to get its text length, we need to iterate over the nodes, and then go deeper ( have a look into tree traversal ):
var count = 0;
for (var i = 0, child; child = elm.childNodes[i]; i++) {
  count += countChars(child);
}
return count;

So the upper example will work like this:
count=0
iterate over body:
  child textnode:
      count+="Some Text".length
  child span:
      inner count=0
      iterate over span:
          child textnode
               inner count+="nested".length
     count+=inner count
finished

Answer: /**
** This function counts the characters of a given node.
**
** @param : The current node to work on
**/
function countChars(elm) {

  // Set local variables
  var i, count = 0;

  // Check to see if the current node is text.
  // If its a text it cannot have any other children so simply
  // return the text length int his node
  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }

  // This is not a text node so driil doen in to its all
  // children and loop into them to count the number of
  // character they have
  for (i = 0, child; child = elm.childNodes[i]; i++) {
    // dive into the current child in count the number of
    // characters it contains. since we use recursion the count will
    // be returned form the previous run and will return the number of
    // characters collect from all "previous" children

    count += countChars(child);
  }

  return count;
}

Understanding the recursive function


Opening an eclipse project through command prompt or batch file

Question: I am building an application that is for testing using Selenium Java tool.
Is there any way to open an existing eclipse project from the command line or through a batch file so that I can allow the users to select the testproject which is in Java with just a click of a button?
I found that this command if for building a project
eclipsec.exe -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild

But I couldn't find one for opening one.
Answer: If you omit -application and simply run eclipse.exe -data "D:\Source\MyProject\workspace", then your workspace will be opened. If you have only one project there then issue is resolved. If not, you can easily create new workspace with a link to your existing project.


Evaluate: $\lim_{y\to x} \dfrac {y\sec y - x\sec x}{y-x}$

Question: Evaluate: $\lim_{y\to x} \dfrac {y\sec y - x\sec x}{y-x}$
My Attempt:
$$=\lim_{y\to x} \dfrac {y\sec y - x\sec x}{y-x}$$
$$=\lim_{y\to x} \dfrac {y\cos x-x\cos y}{\cos x\cos y \cdot (y-x)}$$
Comment: $\lim_\limits {y\to x} \dfrac {y\sec y - x\sec x}{y-x}$ is the very definition of $\frac {d}{dx} x\sec x$
Comment: @Doug M, Can't it be done without derivative?
Comment: Perhaps, but why?  What is important is to recognize the definition of the derivative when you see it.
Answer: HINT:
What is the derivative of $f(x)=x\sec(x)$?
Answer: $\lim_\limits{y\to x} \frac {y\sec y - x\sec x}{y-x}$ is the definition of $\frac {d}{dx} x\sec x$
But since you requested a solution to this limit that was algebraic, here goes:
$\frac {y\cos x - x\cos y}{(y-x)\cos x\cos y}\\
\frac {y\cos x - y\cos y + y \cos y- x\cos y}{(y-x)\cos x\cos y}\\
\frac {y(\cos x - \cos y) + (y-x)\cos y}{(y-x)\cos x\cos y}\\
\frac {-2y \sin(\frac {y+x}{2})\sin (\frac {x-y}{2})} {(y-x)\cos x\cos y}+\frac {1}{\cos x}\\
\frac {y\sin(\frac {y+x}{2})}{\cos x\cos y}\frac {(-2 \sin (\frac {x-y}{2}))} {(y-x)}+\frac {1}{\cos x}\\
\lim_\limits{y\to x}\frac {y\sin(\frac {y+x}{2})}{\cos x\cos y}\lim_\limits{y\to x}\frac {(2 \sin (\frac {y-x}{2}))} {(y-x)} + \lim_\limits{y\to x}\frac {1}{\cos x} = \frac {x\sin x}{\cos^2 x} + \frac{1}{\cos x}\\
x\sec x\tan x + \sec x$
Comment: as a side note, you can use `\dfrac` as an alternative to `\frac` to avoid small sized text here.
Answer: Personally I prefer using definition of derivative as well.
Here is an approach using L'hopital's rule,
\begin{align}&\lim_{y\to x} \dfrac {y\cos x-x\cos y}{\cos x\cos y \cdot (y-x)}\\
&= \sec x \left(\lim_{y\to x} \frac{\cos x + x\sin y}{(-\sin y)(y-x) + \cos y}\right)\end{align}
Try to evaluate the limit.


how should i divide a 100GB for ubuntu installation, if i want to have more space in partition where all the softwares, etc. will be installed?

Question: I'm dual booting window with Ubuntu and i have 100 gigabits free space for Ubuntu installation. How much space should i give to /root, /home, /swap, /user, etc. If i want a large space for software and other packages installation and appropriate space for some music files, etc? My system has 4 gigabits of ram.
I had installed it before on another system and gave it 30 gigabits of space with /root having 10 gigabits but it get filled after 2-3 days and now i'm installing it again so want some help to part the space.
If anyone can tell me exact space i should give to the partitions given in the link below:-
https://skorks.com/2009/08/partitioning-your-hard-drive-during-a-linux-install/
under manual partitioning.
Answer: This is a preference based question.
I prefer going for a single partition as I am running only Ubuntu on my device. This adds flexibility of adjusting space between your files and software as well. Regarding loss of data, I keep regular backups for safe-keeping in additional hard-disks.
Comment: Sir i had written my preference about the space allocation just need some idea how  much should i give to differet partitions because i don't know generally which partition stores softwares files and which is used for other file and which partition stores ubuntu files itself.
Comment: When you partition, the partition u select for installing ubuntu will store all the software related files while all other partitions will appear as saperate disks
Like C:/ for windows store all software and OS, because u choose C:/ for installation of windows, and D etc are for storing files
Depends on what software you want to install. But in 100GB hard-disk, i'd still prefer not to partition


How do I scrape a website and put data into a file?

Question: I have a apple music link as seen here, I want to get all the song names and put them into a file.
This is what I have tried:
for i in soup.findAll('div', {'class':'song-name typography-body-tall'}):
    with open("playlist.txt", "w") as f:
         f.write(i)

But nothing is writing into the file, please can I get some help for this - thanks in advance.
Answer: Besides using Beautiful Soup, if you want to scrape content of a website in details then one of the best libraries in the business is Scrapy. An easy way by which Scrapy crawls content from a website is by Xpath selectors.
Here's the scrapy documentation: https://docs.scrapy.org/en/latest/
Xpaths tutorial for scraping meta content, with Scrapy: https://linuxhint.com/scrapy-with-xpath-selectors/
Answer: Firstly make sure you are actually scraping the website:
import requests
import sys
from bs4 import BeautifulSoup

a = requests.get("https://music.apple.com/gb/playlist/eminem-essentials/pl.9200aa618dc24867b2aa7f00466fd404")
soup = BeautifulSoup(a.text,features="html.parser")

Then collect the songs:
songs = soupfindAll('div', {'class':'song-name typography-body-tall'})

And finally put it in a loop to go through it all and put them into a file:
    song = [song.get_text() for song in songs if song]

    original_stdout = sys.stdout
    with open('playlist.txt', 'w') as f:
        sys.stdout = f
        for idx in range(len(song)):
            print(f'{song[idx]}')
        sys.stdout = original_stdout

Make sure to import everything I have, importing sys is important to print out everything into the file


The relativity of " in index.html, is a image file to the js file 'image.png' or '../image.png'
Comment: It depends. Please clarify what you mean by "everything". What kinds of URLs are you using in what context?
Answer: JavaScript has no concept of files.  Although certain extensions may provide file read/write APIs, everything is relative to the document.
Comment: @Pekka: I believe that's [a work in progress](http://firstname.lastname@example.com/msg23015.html) (and already supported in Firefox) :-)
Comment: this probably answers the OP's question. In fact, it's close to impossible to find out the name of the current script file in an embed context
Answer: Just like the php include(), it relates to the path of the file where you have attached the script. like here index.html
Answer: Your images should be relative to the JavaScript file, not the calling document.

The relativity of "<script src="


IndexError caused by ""[0] in Python 3

Question: s = ''
# case 1
print(s[0])
# case 2
print(s[:1])
print(s[0:1])

In the first case I get an IndexError: string index out of range, yet the second case is perfectly correct. I'm confused; shouldn't they be the same? In both cases we're printing the character at position 0 in the string. I can get the idea of the the Error, after-all, there are no characters in the string, but I'd expect both cases to give the same Error.
Thanks!
Comment: The 2nd and 3rd are an empty subset, same as `s[100:2000]`, they don't give index errors.  Conceptually that is fine, because lists have a way to represent no match (`[]`), while indexes do not (e.g. can't be `None`, or any value, since that could be the content of that index)
Comment: Why do you expect an error?  The documentation on slicing is quite clear on how it handles slice bounds out of range.
Answer: Slices are more forgiving than indexing.  If your slice indexes are out of bounds, you'll get an empty sequence or string.  If you index a character that doesn't exist, you get an error as you've discovered.

IndexError caused by ""[0] in Python 3


realizing questionnaire (survey) constructor using gwt

Question: in my current project i need to realize questionnaire (survey) constructor functionality (kind of google forms).
In my case there is list of questionnaires, every questionnaire has list of question groups, every question group has list of questions and every question can have  some number of answers. It should be possible to add/edit/delete such composite object inline.
To present such nested (kind of tree) data structure I thought of using CellTable, containing CompositeCells but I have come to necessity of doing second and third level composition (e.g. every CompositeCell will contain another CompositeCell etc.)
So finally it turned out to be a bit tricky to populate/update such a table using CellTable and ListDataProvider.
With one nesting (Questionnaire->Criterias) it was simple but not with second and third level composition Questionnaire->Criterias->Questions->Answers.
I thought maybe you have some ready tips regarding presenting such data structure? What is better to use FlexTable or CellTable?
Thanks in advance
Answer: If you want to (or have to) use Widgets go with FlexTable, otherwise go with CellTable.
CellTable will have better performance, and you get a lot out of the box.
Widgets in a FlexTable can offer a better (richer) user experience in some cases (DND, etc).


How do I aggregate every 5 seconds in bigquery using SQL?

Question: I need sql help for BigQuery to find the total quantity every 5 seconds.
Table:

id
quantity
created_at

1
100
2023-08-09 1:32:23.123456

2
150
2023-08-09 1:32:26.123456

3
110
2023-08-09 1:32:27.123456

4
10
2023-08-09 1:32:28.123456

5
10
2023-08-09 1:33:18.123456

6
10
2023-08-09 1:33:20.123456

Expected SQL output:

timestamp_interval_5sec
total_quantity

2023-08-09 1:32:20
100

2023-08-09 1:32:25
270

2023-08-09 1:33:15
10

2023-08-09 1:33:20
10

In addition to the timestamp floor function, I was also looking for solutions with "partition by" and "group by"
Answer: You may use the TIMESTAMP_SECONDS and TIMESTAMP_ADD methods to round down the created_at timestamp to the nearest 5-second interval when aggregating data in BigQuery using SQL. Then, to obtain the required result, utilize a mix of PARTITION BY, GROUP BY, and aggregate functions.

WITH intervals_rounded AS (
  SELECT
    TIMESTAMP_SECONDS(5 * (UNIX_SECONDS(created_at) / 5)) AS interval_start,
    SUM(quantity) AS total_quantity
  FROM
    your_table_name
  GROUP BY
    interval_start
)
SELECT
  interval_start,
  total_quantity
FROM
  intervals_rounded
ORDER BY
  interval_start;

check this out: https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators
Comment: Thanks a lot. Minor correction as TIMESTAMP_SECONDS(INT64).
TIMESTAMP_SECONDS(DIV(UNIX_SECONDS(created_at), 5) * 5) worked.
Answer: Consider below approach (BigQuery Standard SQL)
select
  timestamp_seconds(5 * DIV(unix_seconds(timestamp(created_at)), 5)) as timestamp_interval_5sec,
  sum(quantity) as total_quantity
from your_table
group by timestamp_interval_5sec
order by timestamp_interval_5sec

if applied to sample data in your question - output is
Comment: Thanks for posting the results as well. No GPT can replace the super stack overflow community. I fixed the question with the correct output.
Comment: i am sure, SO was "heavily" used to train their model


prove that a function is monotonically increasing

Question: I want to show that the function
$ f(b)= \dfrac{2^a-2^b}{\ln(a)-\ln(b)}$
is an increasing function of $b \in [0,a)$, where $a$ is a real constant.
I have tried the following things:

To prove that the derivative of the function is positive. However, it is not obvious from the expression.
Plotted the function in matlab for a range of values of $a$. It is seen that the function is increasing.

Please let me know how to analytically show that the function is increasing in $b$.
Comment: have you tried comparing how quickly the numerator and the denominator increase with respect to each other? If you know their signs, knowing their individual rates might give you a clue
Comment: Note that $b \neq 0$. That is, $b \in (0,a)$.
Answer: $$ f(b)= \frac{2^a-2^b}{\ln a-\ln b}$$
Then,
$$f'(b)=\frac{-2^b\ln 2(\ln a-\ln b)-(2^a-2^b)\cdot (-1/b)}{(\ln a-\ln b)^2}$$
$$=\frac{2^b}{b(\ln a-\ln b)^2}(-b\ln 2(\ln a-\ln b)+2^{a-b}-1)$$
Let $g(b)=-b\ln 2(\ln a-\ln b)+2^{a-b}-1$.
Then,
$$g'(b)=-\ln 2\ln a+\ln 2(\ln b+1)-2^{a-b}\ln 2=\ln 2(-\ln a+\ln b+1-2^{a-b})\lt 0$$
since $-\ln a+\ln b\lt 0$ and $1-2^{a-b}\lt 0$.
So, $g(b)$ is decreasing with $g(a)=0$, and so $g(b)\gt 0$ for $0\lt b\lt a$.
Therefore, since we have $f'(b)\gt 0$, we know that $f(b)$ is increasing.


How to stop series of postDelayed handlers

Question: I have a series of postDelayed handlers. I'm having trouble to set a mathode that stops the handlers when the user is tapping on the stop button at any time I he wants.
I'll appreciate any help someone able to provide.
Thanks
while (!lessonIsRunning) {
        Handler handler0 = new Handler();
        handler0.postDelayed(new Runnable() {
          @Override
          public void run() {
              plate1.setVisibility(ImageView.VISIBLE);
              plate2.setVisibility(ImageView.VISIBLE);
              plate3.setVisibility(ImageView.VISIBLE);
          }
        }, 6000);

        Handler handler1 = new Handler();
        handler1.postDelayed(new Runnable() {
          @Override
          public void run() {
              apples1.setVisibility(ImageView.VISIBLE);
          }
        }, 9000);

        Handler handler2 = new Handler();
        handler2.postDelayed(new Runnable() {
          @Override
          public void run() {
              plus1.setVisibility(TextView.VISIBLE);
          }
        }, 9250);
}
public void stopLesson(View V){

}

Comment: Why are you using several handlers? Why not a single handler?
Answer: instead of writing the Runnable task in an anonymous way you must define it with a name, so that later you will have a link to it to remove:
//there is no need for multiple handlers
//handler must be declared outside all functions, in order for you to use it everywhere.

Handler handler = new Handler();
Runnable myFirstTask  = new Runnable (){
         @Override
              public void run() {
                  plate1.setVisibility(ImageView.VISIBLE);
                  plate2.setVisibility(ImageView.VISIBLE);
                  plate3.setVisibility(ImageView.VISIBLE);
              } };

    Runnable mySecondTask = new Runnable(){
        @Override
              public void run() {
                  plus1.setVisibility(TextView.VISIBLE);
              }

    };

    Runnable myThirdTask = new Runnable(){
        @Override
              public void run() {
                  apples1.setVisibility(ImageView.VISIBLE);
              } }

    //you can put different tasks on the same handler object

    while (!lessonIsRunning) {
            handler.postDelayed(myFirstTask,6000);
            handler.postDelayed(mySecondTask,9250);
            handler.postDelayed(myThirdTask,9000);
}
public void stopLesson(View V){
    //notice that you don't need these, because the handlers are not recursive
    //you don't have lines "handler.postDelayed(sameTask,someTime);"
    //in your run Method of the runnable
 if(handler!=null){
    handler.removeCallbacks(myFirstTask);
    handler.removeCallbacks(mySecondTask);
    handler.removeCallbacks(myThirdTask);
    //if this method is inside onPause or onDestroy add this line as well:
    handler=null;

}
 }

Comment: Have you tried the method removeCallbacksAndMessages(null), instead the three lines of removeCallback(runnable)? I am ok with that, i am asking just to know if it works, as documentation says.
Comment: There may be other callbacks that you don't want removed
Comment: I know, but in this specific case? Works? Because @RBZ got i problem.
Answer: you can give
handler0.removeCallbacksAndMessages(null);
handler1.removeCallbacksAndMessages(null);
handler2.removeCallbacksAndMessages(null);

a try. The doc says when you submit a null token all callbacks and message are removed.
Comment: @RBZ: Also, only call those methods from the handler's main thread (e.g., the main application thread).
Comment: +1, haven't tried this but I always prefer passing object rather than null
Comment: Thanks for the quick answer! the problem is that I get nullPointerException on handler1.removeCallbacksAndMessages(null);
when I stop it while handler0 is playing. is there a method that checks the status of a handler? or any boolean condition that you can think about?
Comment: the problem is not relate to the removeCallbacksAndMessages argument. Probably handler1 is null.


App crash on using RecyclerView

Question: I am using RecyclerView in my app. My application crashes with the following error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onMeasure(android.support.v7.widget.RecyclerView$Recycler, android.support.v7.widget.RecyclerView$State, int, int)' on a null object reference

While searching on stackoverflow I found that this error usually comes when layoutmanager was not added. But I have added the layout manager. Please help me find what is causing this crash.
Edit - Code for the fragment using Recyclerview
public class FeedFragment extends Fragment implements HJAppConstants {

    private RecyclerView mRecyclerView;

    private FeedRecyclerAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.hj_feed_layout, null);
        mRecyclerView = (RecyclerView) view
                .findViewById(R.id.feeds_recycler_view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        LinearLayoutManager layoutManager = new LinearLayoutManager(
                getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new FeedRecyclerAdapter();
        mRecyclerView.setAdapter(mAdapter);
        addData();

    }

    /**
     * Adds static data
     */
    private void addData() {
        ArrayList<HJFeedItemObject> itemObjs = new ArrayList<HJFeedItemObject>();
        itemObjs.add(new HJFeedItemObject(HJ_FEED_TYPE_PHOTO,
                "potala_palace.jpg", "This is an article about Potala Palace",
                "Thu 7, 07:45pm", new HJUserObject("Umesh", "")));
        itemObjs.add(new HJFeedItemObject(HJ_FEED_TYPE_PRODUCT, "pokhara.jpg",
                "A beautiful place to visit - Pokhara ", "Thu 7, 07:45pm",
                new HJUserObject("Umesh", "")));
        itemObjs.add(new HJFeedItemObject(HJ_FEED_TYPE_ARTICLE, "patan.jpg",
                "A Tourist attraction - Patan", "Thu 7, 07:45pm",
                new HJUserObject("Umesh", "")));
        itemObjs.add(new HJFeedItemObject(HJ_FEED_TYPE_PHOTO,
                "potala_palace.jpg", "This is an article about Potala Palace",
                "Thu 7, 07:45pm", new HJUserObject("Umesh", "")));
        itemObjs.add(new HJFeedItemObject(HJ_FEED_TYPE_PRODUCT, "pokhara.jpg",
                "A beautiful place to visit - Pokhara ", "Thu 7, 07:45pm",
                new HJUserObject("Umesh", "")));
        itemObjs.add(new HJFeedItemObject(HJ_FEED_TYPE_ARTICLE, "patan.jpg",
                "A Tourist attraction - Patan", "Thu 7, 07:45pm",
                new HJUserObject("Umesh", "")));
        mAdapter.addData(itemObjs);
    }

Comment: show code there is no way to help without it
Comment: I have posted my code
Comment: i take it this is a fragment and thus moving the code from onActivityCreated to onViewCreated should solve the issue
Comment: I moved the content to onViewCreated but still having the same problem.
Comment: have you moved the onActivityCreated code to onViewCreated or just put it in the onCreateView, the onActivityCreated just tells the fragment that the activity is done with its own onCreate, it does not mean that the fragment has been created yet.
Comment: show me the R.layout.hj_feed_layout layout
Comment: See the given link same issue I can resolve using this link:
http://stackoverflow.com/q/27416834/1896677
Answer: This issue occurs when no LayoutManager was provided for the RecyclerView.
Change your code, and move the layoutManager setup to onCreateView.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState){

   View view = inflater.inflate(R.layout.hj_feed_layout, null);
   mRecyclerView = (RecyclerView) view
                .findViewById(R.id.feeds_recycler_view);

   LinearLayoutManager layoutManager = new LinearLayoutManager(
                getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

   return view;
}

App crash on using RecyclerView


Which keys are the most likely to yield Forma?

Question: High-level Warframe takes a lot of Forma. You need 1-4 Forma to build any of the clan research weapons or sentinels. You need several Forma to fit all the best mods into any weapon or frame. And the alerts that reward Forma are few & far between.
Clearly the solution to this is void/tower keys; pretty much every tower mission includes Forma in its drop list. Which keys are the most efficient for acquiring Forma, though?
Comment: Just placing this here for any future-comers: You no longer need Keys to access the Void.
Answer: Statistically, tower IV levels yield the most forma. T4 defenses have a chance to award a blueprint at the end of each 5 rounds and survivals have a chance to award a blueprint after periods B and C. (10, 15, 25, 30, 40, 45, 55, 60,...)
Personally, I prefer to do Tower 3 survival because after every 15 minutes you have a chance of getting either a forma or a forma blueprint (or something else of course) and you you don't have to worry about Vor coming in and messing you up.
Answer: Having not played in a while, I will be going off of my old farming methods. Use T4 or T3  Survival/Defense. You can grab a lot of Forma Blueprints, and even a couple of full built Forma.
Comment: I did Orokin Derelict Defense to get my forma. You can easily get to wave 40 with a well specced nova and vauban.


How remove mdiChild form shrink button?

Question: I already disabled maximize and minimize buttons. Now i want to remove shrink button. How can i do that?
Answer: You need to use this code in the LoadEvent form the form:
base.MinimizeBox = false;

or
this.MinimizeBox = false;

How remove mdiChild form shrink button?


Guild Wars 2 LFG Tool Abbreviations

Question: I've been playing Guild Wars 2 for years, but it's only within the last couple of days where I actually decided to hook up with others and do some dungeons.
There's a lot I don't understand in the Looking For Group tool, some abbreviations that users post to help people understand what their run of the dungeon will be.
For example, one I saw last night was: p3 2.5g
Comment: I disagree with this question being closed as too broad. The answer fits the question nicely. The OP isn't asking for a list of all MMO LFG terms.
Comment: I have to agree with @DavidYell. OP is clearly looking for abbreviations specific to the LFG tool in GW2. I've played it since it's release, running dungeons like a maniac and there are really only a handful abbreviations in use, which [Shunwoo's answer](http://gaming.stackexchange.com/a/194287/78254) cover pretty well.
Comment: `p3` would most likely mean `path 3`, but I'm not sure about the other one. Also don't necessarily expect logical or consistent abbreviations. From my experience in MMORPGs, people tend to develop lots of different abbreviations, especially in a game split between many different servers and sub-communities. As such I'd even say this might be off-topic here since you can't get a complete list. You may only try to list the most popular abbreviations, but even those are subject to change depending on which server you are, which time zone, region, etc.
Comment: Path 3 and around 2.5 gold gain would be my guess
Comment: This is being marked as too broad because it's not specifically asking about any abbreviations other than p3 2.5g. If there was a specified list, a specific area of abbreviations (classes, areas, pvp, pve) or even a couple of scenarios, it would be a better question. As of the way it's currently worded, it's too broad by just simply asking for abbreviations in general about a game.
Comment: @DavidYell I voted to close as unclear. The question provides **one** *example* unclear abbreviation, while the question indicates that there are more (How many? unknown). The OP may not intend to ask for *all* MMO LFG terms, but as there is only one example with an unknown number of others, it might ask for them all. (Although I will assume based on the tags that it is limited to those used in GW2). Additionally the presence of a good answer does not necessarily make the question not 'too broad', but it would indicate that the question is likely salvageable and can be edited to be acceptable.
Comment: @ChaseC The single example given isn't the subject of the question.
Comment: @TrentHawkins How could this question be edited to make it acceptable? Even though the list is very short, the OP does not know how many abbreviations exist. Would asking for an unofficial list, to the best of the communities ability, still be considered too broad?
Comment: Edits not by the asker should **never** change what the question is asking.  Suggested edits are for cleaning up grammar and making the question clearer, not for altering what the question is about.  I have rolled back the edit for that reason.
Answer: It is a habit present in the majority of MMO's to make the information readable in one glance.
In this case it means : path 3 of the dungeon, participating costs 2.5 gold
By the way this is against Arena.net politics, the gold is about paying for the dungeon run. 1-2 people that can solo/duo the run offer the last slots of the group at X gold to make profit.
In general in GW2 you can find those abbreviations too :

AP, with for example : 5000AP min. This means 5000 Achievement Points are required to be accepted in the group
AR, with for example 10+ AR. It stands for Agony Resistance, the statistic specific to fractals, and so 10+ means that you need at least 10 in this statistic to be accepted.
Zerk for people requiring full Berserker gear
80s requires people to be at level 80 as some dungeons start being available before level 80
Exp stands for Explorable mode, in opposition to story mode
GC Gearcheck : people will make you link your gear to verify if it meets their requirements

And now in general in MMO's those are really frequent :

LFG : Looking For Group (it can be LFP if you mean Party instead of Group)
LFM : Looking For More (When a group is needing more people) (Credit to DavidYell)
Exp : Experienced (you must know the instance/dungeon already)

(Credit to DavidYell for LFM meaning, to Amos M.Carpenter for 80s abd Exp in GW2 and to Daft for GC)
Comment: I always read LFM as 'Looking for more' meaning there is a number of players already in the team and they want more people.
Comment: @DavidYell You're totally right, I'm changing that, thanks.
Comment: And of course there's the famous LOL: "Look Out, Lemurs!"
Comment: +1; one more I'd add is "80s", a requirement for participants of a lower-level dungeon to be level 80 to prevent people from using the dungeon to level up. On the other hand, "swapping alts" or similar is sometimes used to indicate that a person will run the dungeon with a level 80 and swap to a lower level alt to get the completion experience (sometimes having another party member watch the final cut scene to give the alt time to enter the dungeon can help). Incidentally, "Exp" is used by some to indicate "explorable mode" as opposed to "story mode", which can lead to confusion.
Comment: @AmosM.Carpenter Thank you I'll add "80s", but "swapping alts" isn't really an abbreviation right ? And for "Exp" I didn't put it in GW2 specific to prevent this confusion ^^
Comment: The OP said "there's a lot I don't understand" in the LFG tool; I took "some abbreviations" to just be an example, but that's up for interpretation of course :-). And yes, "experienced" is the most common meaning of "exp" - I was merely pointing out the possible confusion, not saying you should change that part of your answer.
Comment: @AmosM.Carpenter Well i made a GW2 specific "Exp" and a general case "Exp" to be sure haha.
Comment: I've seen GC. Which usually means a Gear Check. (I hate gear checks)
Comment: @Daft Thank you, I added it, and I actually think GC is ok. Some people have fun by running dungeons casually, normally and some others like doing them to farm or for the challenge of getting the fastest clear. Then GC becomes necessary to find people that share your definition of "having fun" in GW2 :)
Comment: @Shunwoo oh yeah I totally understand why people do it, and I usually run 100% zerk, which is what people wanna see, but for some reason it still bugs me!
Comment: @Daft I haven't seen gear checks since they removed magic find from gear.
Comment: Note: Arenanet is not against selling paths in a dungeon, they are against people exploiting bosses/terrain to reach the final boss (and then selling party slots). If you legitimately solo/duo the dungeon to sell slots, it's fine.

Guild Wars 2 LFG Tool Abbreviations


Proving that the Cantor Set is perfect

Question: In his book "The elements of Cantor Sets - With Applications" the author Robert Vallin defines on page 102 that a set $A$ is called perfect if $A$ is equal to the set of it's limit points. Immediately after that he cites the Cantor Set as an example for a perfect set.
I do not find this conclusion trivial, do I overlook something
?
I already know that the Cantor set is compact.
Could you explain this to me please?
Answer: To prove that the Cantor set $C$ is perfect, for each $x \in C$ and for each $\epsilon > 0$ one must find a point $y \in C - \{x\}$ such that $|x-y| < \epsilon$.
To search for $y$, recall that $C$ is constructed as the intersection of sets $C_0 \supset C_1 \supset C_2 \supset C_3 \supset \cdots$ where $C_n$ is a union of $2^{n}$ disjoint intervals each of length $3^{-n}$, and recall also that $C$ has nonempty intersection with each of those $2^n$ intervals.
Choose $n$ so that $3^{-n} < \epsilon$.
Let $[a,b]$ be the interval of $C_n$ that contains $x$.
When the middle third is removed from $[a,b]$, one gets two intervals $[a,b']$, $[b'',b]$ of $C_{n+1}$. The point $x$ is contained in one of those two intervals, and there is a point $y \in C$ that is contained in the other one of those two intervals. So $y \ne x$ and $|x-y| < \epsilon$.

Proving that the Cantor Set is perfect


how to retrieve one record when multiples exist

Question: I need help only retrieving one record per job in this dataset. There are over 900 rows in the actual result set so this is a small sample but all rows look like the below. I am already using Distinct in the query but I get more than one record for the same job,suffix,and part. I need to be able to pull only one job,suffix,part but I need each value for workcenter,hours_estimated, and hours_actual associated with each job. I'm not sure if this should/could be done in the query or by using array methods in PHP. I almost found what I am looking for here but pervasive doesn't use CTE. Can anyone assist me in trying to get my data to look like below?
Sample Data
|Job   |suffix| part |PL|qty|  seq |workcenter|hours_estimated|hours_actual|
----------------------------------------------------------------------------
|A02043| 001  |913036|01| 2 |000400|   0710   |     0.7491    |   2.5700   |
|A02043| 001  |913036|01| 2 |000402|   0805   |     0.6420    |   0.0000   |
|A02043| 001  |913036|01| 2 |000500|   0901   |     16.1290   |   33.1600  |
|A02043| 001  |913036|01| 2 |000600|   1520   |     0.5000    |   0.0000   |
|A02900| 001  |913104|01| 1 |000500|   0710   |     0.5280    |   1.2000   |
|A02900| 001  |913104|01| 1 |000600|   0650   |     0.8540    |   0.0000   |

What I need my PDO object/array to look like
|Job   |suffix| part |PL|qty|   workcenter      |     hours_estimated         | hours_actual             |
-------------------------------------------------------------------------------------------------------------------
|A02043| 001  |913036|01| 2 |0710,0805,0901,1520| 0.7491, 0.6420,16.1290,0.500| 2.57,0,33.16,0  2.5700   |
|A02900| 001  |913104|01| 1 |0710,0650          |0.5280,0.8540                |1.200,0.0000   |

Query:
select distinct v_job_header.job,v_job_header.suffix,v_job_header.part,v_job_header.product_line,v_job_header.qty_order,v_job_operations_wc.seq,v_job_operations_wc.LMO,v_job_operations_wc.workcenter,v_job_operations_wc.hours_estimated,v_job_operations_wc.hours_actual,v_job_operations_wc.flag_closed,gab_source_cause_codes.source,gab_source_cause_codes.cause
from v_job_header
left join v_job_operations_wc on v_job_operations_wc.job = v_job_header.job and v_job_header.suffix = v_job_operations_wc.suffix
left join gab_source_cause_codes on gab_source_cause_codes.job = v_job_operations_wc.job and gab_source_cause_codes.suffix = v_job_operations_wc.suffix and gab_source_cause_codes.seq = v_job_operations_wc.seq
where v_job_header.product_line = '01' and v_job_header.date_closed < '2019-01-01' and v_job_operations_wc.LMO = 'L' and v_job_operations_wc.seq < '99000'

Comment: Look into using group_concat so for example workcenter would be group_concat(table.workcenter) as workcenter …..
Comment: @Yeak Thank you for the suggestion. While pervasive doesn't have a group_concat, I was able to find a few people who had a similar issue and I was able to work out a solution. Thanks!
Comment: Glad you got it worked out - sorry must of skipped the part of pervasive and assumed mysql.
Comment: add `TOP 1` , see: https://docs.actian.com/psql/psqlv11/wwhelp/wwhimpl/js/html/wwhelp.htm#href=sqlref/syntaxref.03.71.html
Answer: I had to change my query
select concat(concat(v_job_header.job,'-'),v_job_header.suffix) as Job,v_job_header.part,v_job_header.qty_order,
sum(case when v_job_operations_wc.workcenter = '0750' then v_job_operations_wc.hours_actual end) as WaterJet,
sum(case when v_job_operations_wc.workcenter IN ('0705','0710','0715') then v_job_operations_wc.hours_actual end) as Laser,
sum(case when v_job_operations_wc.workcenter IN ('0600','0610','1006','0650','1315') then v_job_operations_wc.hours_actual end) as Prep,
sum(case when v_job_operations_wc.workcenter IN ('1310','0755') then v_job_operations_wc.hours_actual end) as Machining,
sum(case when v_job_operations_wc.workcenter IN ('1515','1000','1002','1003','0901','1270') then v_job_operations_wc.hours_actual end) as Fab,
sum(case when v_job_operations_wc.workcenter = '1100' then v_job_operations_wc.hours_actual end) as Paint,
sum(case when v_job_operations_wc.workcenter = '1000' then v_job_operations_wc.hours_actual end) as Belts,
sum(case when v_job_operations_wc.workcenter = '1001' then v_job_operations_wc.hours_actual end) as Electrical,
sum(case when v_job_operations_wc.workcenter = '1520' then v_job_operations_wc.hours_actual end) as Crating_Skids,
sum(case when v_job_operations_wc.workcenter IN ('1004','1005','1350','1201') then v_job_operations_wc.hours_actual end) as Final_Assy,
sum(case when v_job_operations_wc.workcenter = '4330' then v_job_operations_wc.hours_actual end) as Shipping,
sum(v_job_operations_wc.hours_estimated) as total_hours_estimated,
gab_source_cause_codes.source,gab_source_cause_codes.cause
from v_job_header
left join v_job_operations_wc on v_job_operations_wc.job = v_job_header.job and v_job_header.suffix = v_job_operations_wc.suffix
left join gab_source_cause_codes on gab_source_cause_codes.job = v_job_operations_wc.job and gab_source_cause_codes.suffix = v_job_operations_wc.suffix and gab_source_cause_codes.seq = v_job_operations_wc.seq
where v_job_header.product_line = '01' and v_job_header.date_closed < '2019-01-01' and v_job_operations_wc.LMO = 'L' and v_job_operations_wc.seq < '99000'
group by Job,v_job_header.part,v_job_header.qty_order,gab_source_cause_codes.source,gab_source_cause_codes.cause


Dota 2 matchmaking server priority

Question: In Dota 2 when you select more than one server region and start the matchmaking, the background image has only US West server colored. Is that actually a map bug or does the game really search the US West server first and then other locations? Or are they all grouped together?
Answer: As far as I can tell this is merely a visual glitch; the background image does not correctly reflect your selected regions. Accurate feedback is available from the options sidebar, which properly lists the selected regions.

Dota 2 matchmaking server priority


Should I insulate water pipes in exterior walls?

Question: I am replacing some crumbling hardboard siding panels on the back of my house (north facing wall) in Austin Texas. I discovered under the kitchen sink window that the water pipes come up out of the concrete VERY close to the outer face of the foundation. The copper pipes are in one of those plastic sleeves to protect them from the concrete and they have black foam insulation on them. There is a part right where they exit the concrete that is uninsulated and the wall cavity had some fiberglass stuffed into it. I am trying to decide what I should do with this situation, if anything. I considered filling the void with expanding foam, but as people in other threads have pointed out, the inner face of the pipes should be left clear to allow heat absorption from the interior.
Our standard practice in freezing weather is to drip faucets and open cabinet doors under sinks. We haven't had any issues, even when it got to 5º during the winter apocalypse in 2021. While I have the wall open, I want to improve this situation - if I need to.
Any thoughts?
Comment: Don't know if this was the intent in this case but what that sleeve insulation actually does for you is keep the pipes from sweating.  Moisture from hot humid air can condense on them when they're cold on the outside from the cold water inside.
Answer: Texas plumbing. It freezes, but y'all pretend it never does, making it an apocalypse when it does.
I would suggest removing the fiberglass (in this stud space, anyway) entirely and installing either XPS or Polyisocyanurate rigid foam sheets between the pipes and the outer wall surface. Perhaps even a U shape so there's also sheet foam between the pipes and the studs, since studs are not very good insulators themselves.
Do a really nice job and save some on your AC bill too by sheathing with an inch of foam before you get to the siding, over the studs. That may be difficult if you are only working on a limited part of the wall rather than the whole wall, though.
Comment: Yeah, the only good solution is to properly insulate the building envelope, which is _outside_ the plumbing. Put foam on the entire wall.
Comment: Agree, except this wall is the ground floor on a two story house. If I added a layer of rigid insulation, the siding panels would stand proud of the upper panels with no way to direct water to the right places. I have a full energy retrofit planned and hope to start that soon, but for now I can't justify expanding this project to add that foam. This is however exactly what I plan to do in the future - adding out-sulation over the the entire building envelope and adding a modern WRB instead of the tarpaper used in 1993. None of it was installed properly back then.


DIY Kitchen LEDs start blinking when plugged in

Question: I wanted to do some DIY under cabinet LED lighting with RGBWW strips. These ones to be exact: https://www.amazon.com/dp/B0B5SLM235?ref=ppx_yo2ov_dt_b_product_details&th=1
I am using an arduino and this wiring schematic to control the lights

Instead of +12V and RGB as in the image, I have +24V CW RGB WW. I have two strip sections wired in parallel to the arduino. One section has 3 separate strips that are connect through CAT5e wire and the other section is just a single strip. I have it configured this way because the outlet i want to power the strips and arduino with is in the middle of the kitchen, not at one end or the other.

When I plug in the left section, it all works fine. But when I also plug in the right section, everything blinks once and doesn't do anything. When I lower the analog write value from a max of 255 to 150ish everything works fine. I am wondering why this is occurring and if it can be fixed so I can use max brightness. The power supply I'm using is one that came with the lights and that I cut open to power the LEDs and the Arduino (using a buck converter to 5v). The power supply is 24V and 1 amp. I suspect that its not providing enough current to the LED for all the strips but I don't see how that would make sense if I am using the provided power adapter. Any throughts?
Comment: This should probably be in the Electronics stack exchange. You will also get better answers if you provide an actual schematic and designed current loads.
Comment: Does the right section work by itself? If each section works separately, but not together, you might have exceeded a current limit, e.g. a polyfuse on the arduino (if powering through that) or the overload protection in your power supply (which is not shown). Be aware that if you have more than maybe 500mA of lighting current, you should try to make sure it flows around the arduino and not through it.
Comment: A picture labelled "FET N" doesn't tell us what the actual specs on the drive transistors are.  That could matter.  The current at the amazon link is described as 1A, but it's not clear what operating mode that's in but 100 lumens per Watt would be reasonable for white mode.  You may need to supply more than 1A per strip, or at least >1A for the whole lot.  Also double-check your wiring, in case you're shorting something when you plug in both strips at once
Comment: ... but (only with the additional details) this would make more sense at electronics.se than here
Answer: If I had to guess, something is not right with the wiring / voltage.
Why am I making a broad statement about "wiring / voltage"? Because I don't quite understand your different set ups and the resulting voltages.
It seems you're driving multiple 12V LED strips with 24V. This can be fine, if your wiring is set up for every strip to get 12V. I personally drive two 12V fans wired in series using a 24V power supply.

When I plug in the left section, it all works fine.

Here your wiring seems ok-ish, resulting in the correct voltage. At least it's within bounds, because 24V / 3 is 8V, which although not matching the specified 12V might still be close enough. Note that if the three strips on the left are wired in series they only get 1/3 of the voltage. Think of voltage as difference between two points: Those three LED strips connected in series split the difference between them. If you connect them in parallel each will see the full difference between the connection points.

when I also plug in the right section, everything blinks once and doesn't do anything.

The right section seems to either

get 24V, overheat and temporarily drop out (if so, be grateful, if the LED strip still works),
add the drop to overflow the bucket, i.e. take too much amperes, so the voltage drops (remember it might already be as low as 8V, depending on wiring of the left side)
cause a short (if so, be grateful, if your power supply still works)

taking the rest of the circuit with it.
My guess is on the first or second option, because miraculously

When I lower the analog write value from a max of 255 to 150ish everything works fine.

150ish/255th seems to be close enough to 1/2 and 1/2 of 24V is 12V, which is the correct voltage for a single LED strip. Yes, I am aware that you're using PWM to switch on/off the full 24V, however real circuits do have continuous rise/drop of voltage and so there's the correct voltage some of the time. Alternatively, think of it flickering and going out just to come back up with the next PWM cycle. If it flickers fast enough, your eyes won't notice.
Have you perhaps wired the right LED strip so that it is connected as a single LED strip?

The power supply is 24V and 1 amp. I suspect that its not providing enough current to the LED for all the strips but I don't see how that would make sense if I am using the provided power adapter.

This totally makes sense: It's the power supply for up to 4 LED strips, not 4 LED strips (one of which getting 100% over-voltage) plus a buck converter (introducing unknown losses) that powers an Arduino. Which is why I list this as above option 2.
You could try to connect two parallel pairs of two LED strips in series. If my first guess is right, this should solve the issue. If it doesn't, it's probably option 2. Even for option 2, not over-volting the right LED strip may help to stabilize the power supply.
Alternatively, measure the voltage with a multimeter. Yes, the reading may be awkward, because you actually have drops/rises but most multimeter will read some value that is close to the average. No fancy oscilloscope needed, especially because a PWM of 255 is always on.
Comment: In the link, the strip has no voltage or current rating, but is supplied with 24v supply. Whats us still unclear is if the strip has been cut into 4 sections or there are 4 strips. But you are right, its overloading. And its never going to work correctly. The left is going to be dimmer than the right
Answer: You'r overloading the power supply.
It is "crowbar"-ing. I.e. shutting off to protect itself.
That's it. Mathematically calculate your current load based on LED strip specs and length, and make sure the power supply is up to snuff. My "general rule of thumb" is 20mA per cut section per channel, and you have 5 channels there: R, G, B, warm and cold white. But your strip may vary.
24W power supply seems awfully light for a 5m RGB strip let alone 10m RGBWW.   Check the labeling and instructions and make sure they even allow running it at full power.


Boost C++ regex - how to get multiple matches

Question: If I have a simple regex pattern like   "ab."  and I have a string that has multiple matches like  "abc abd".  If I do the following...
boost::match_flag_type flags = boost::match_default;
boost::cmatch mcMatch;
boost::regex_search("abc abd", mcMatch, "ab.", flags)

Then mcMatch contains just the first "abc" result.  How can I get all possible matches?
Answer: You can use the boost::sregex_token_iterator like in this short example:
#include <boost/regex.hpp>
#include <iostream>
#include <string>

int main() {
    std::string text("abc abd");
    boost::regex regex("ab.");

    boost::sregex_token_iterator iter(text.begin(), text.end(), regex, 0);
    boost::sregex_token_iterator end;

    for( ; iter != end; ++iter ) {
        std::cout<<*iter<<'\n';
    }

    return 0;
}

The output from this program is:
abc
abd

Comment: Thanks for the quick reply.  Question, what does *iter return, it doesn't appear to be a boost::cmatch in my quick test?  I just gave a very simple example.  In my regex I may have groups, so I need access to the group information for each match (as is available from cmatch)?
Comment: You could try out the regex_iterator instead, it returns a match_result when dereferenced, and should give you what you're looking for?


Seeking Proof for a Conclusion from Positive Definite Homogeneous Polynomials

Question: I am trying to find a proof for the following proposition from multivariate real analysis:

Suppose that $p$ on $\mathbb{R}^{n}$ is a homogeneous polynomial of degree $r$ in $x$ and $p\left(x\right) > 0$ for all $x \neq 0 \in \mathbb{R}^{n}$. Show that there is a $\rho > 0$ such that $p\left(x\right) \geq \rho\lVert x \rVert^{r}$ for all $x \in \mathbb{R}^{n}$.

A homogeneous polynomial of degree $r$ is of the following form:
\begin{equation}
\begin{aligned}
\forall x \in \mathbb{R}^{n},\ p\left(x\right) = \sum_{i_{1},i_{2},\dots,i_{r}=1}^{n}a_{i_{1},i_{2},\dots,i_{r}}{x_{i_1}}{x_{i_2}}\dots {x_{i_r}},
\end{aligned}
\end{equation}
where $x_{s}$ is the $s$-th element of the vector $x \in \mathbb{R}^{n}$.
P.S. This proposition serves as the basis for proving a theorem about local extreme points in multivariate real analysis. A hint is provided by the textbook: use the fact that $p$ assumes a minimum on the set $\left\{x \vert \lVert x \rVert = 1\right\}$. I am not sure how to construct the proposition from this starting point. Does anyone have an idea?
Comment: Consider $p(x/\|x\|)$.
Comment: @ShiveringSoldier Proof provided.
Answer: The homogeneous polynomial of order $r$ is of the following general form:
\begin{equation*}
\begin{aligned}
\forall x \in \mathbb{R}^{n},\ p\left(x\right) = \sum_{i_{1},i_{2},\dots,i_{r}=1}^{n}a_{i_{1},i_{2},\dots,i_{r}}{x_{i_1}}{x_{i_2}}\dots {x_{i_r}}.
\end{aligned}
\end{equation*}
As the set
\begin{equation*}
S = \left\{x \vert x \in \mathbb{R}^{n}, {\lVert x \rVert} = 1\right\}
\end{equation*}
is closed and bounded, and $p$ is continuous, there exists an $x_0 \in S$ ($\lVert x_{0}\rVert = 1$) such that
\begin{equation*}
\forall x \in S,\ p\left(x\right) \geq p\left(x_0\right)
\end{equation*}
Let $\rho = p\left(x_{0}\right)$. As $p$ is positive definite, we have $\rho > 0$. Then for all $x \neq 0$, we have
\begin{equation}
\begin{aligned}
p\left(\frac{x}{{\lVert x \rVert}}\right) &= \sum_{i_{1},i_{2},\dots,i_{r}=1}^{n}a_{i_{1},i_{2},\dots,i_{r}}{\frac{x_{i_1}}{{\lVert x \rVert}}}{\frac{x_{i_2}}{{\lVert x \rVert}}}\dots {\frac{x_{i_r}}{{\lVert x \rVert}}}\\
&= \frac{1}{{\lVert x \rVert}^{r}}\sum_{i_{1},i_{2},\dots,i_{r}=1}^{n}a_{i_{1},i_{2},\dots,i_{r}}{x_{i_1}}{x_{i_2}}\dots {x_{i_r}}\\
& = \frac{1}{{\lVert x \rVert}^{r}}p\left(x\right) \geq \rho,
\end{aligned}
\end{equation}
and considering the trivial case where ${\lVert x \rVert} = 0$, we have
\begin{equation*}
\forall x \in \mathbb{R}^{n}, p\left(x\right) \geq \rho {\lVert x \rVert}^{r}.
\end{equation*}
And the existential proof is constructed with such a $\rho$.


Installing Eclipse C/C++ Ubuntu 20.04

Question: looking to download the Eclipse CDT (IDE for C/C++)
but seems its currently unavailable for Ubuntu 20.04 in the apt package manager
looked for snaps and flatpaks , could not find any solutions there (they have only the Java IDE)
thinking about downloading the 'tar.gz' file but afraid that there would be dependencies issues, and the uninstallion would be hard
any help on how to go about this?
Answer: The Ubuntu repositories are lagging behind on Eclipse I'm afraid. I always use the .tar.gz file. Simply unpack it, and run the eclipse binary.
You'll need Java installed on your system: sudo apt install openjdk-11-jre. Other than Java, I don't think there are dependencies. And if there are, you will quickly run into them: Eclipse will not start. Just remove the directory of your unzipped Eclipse installation, and walk away

Installing Eclipse C/C++ Ubuntu 20.04


How to save each column of CSV file to separate .TXT files?

Question: As in title, i.e. I have spreadsheet with 4 columns, and I want to save each of them in separate .txt files. Spreadsheet won't have same amount of columns everytime.
Is that possible? Tried to do this with CSVhelper but I don't know how :c
Thanks for help!
Comment: Hi, what have you actually tried? In simplest form you could just read a line, use Split to separate the string using the comma that separates each column and place each into a text file. Hopefully the first line of your csv file will give you the column headers.
Answer: Please try something like the following after installing NPOI to your project:
<code>        public static void WriteColumnsToTextFile()
    {
        var readPath = @"C:\readLocation\testing.xlsx";

        using var stream = new FileStream(readPath, FileMode.Open);
        stream.Position = 0;

        XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream);
        //For encrypted spreadsheets use the above else use the below instead
        //HSSFWorkbook xssWorkbook = new HSSFWorkbook(stream);

        ISheet sheet = xssWorkbook.GetSheet("sheet1");
        var columnCount = sheet.GetRow(0).LastCellNum;
        var rowCount = sheet.LastRowNum;

        for (var colNum = 0; colNum < columnCount; colNum++)
        {
            StringBuilder text = new StringBuilder();
            for (var rowNum = 0; rowNum < sheet.LastRowNum; rowNum++)
            {
                text.Append(sheet.GetRow(rowNum).GetCell(colNum).ToString() + "\n");
            }
            File.WriteAllText("C:\\yourlocationhere\\testing_"+colNum+".txt", text.ToString());
        }

    }
</code>


Why would a recursive factorial function run faster than its equivalent iterative function when using BigInt in Firefox?

Question: While toying around with BigInt in the context of implementing a factorial function, I noticed some behavior that I was not expecting. When running in Firefox, it seems as if a recursive factorial function is more performant than its iterative counterpart. When running in Chrome, the performance was swapped (which is what I was expecting to see).
I created this GitHub Gist to show a performance comparison between multiple versions of the factorial function. Also here is an inline JavaScript snippet that is equivalent to the Gist. Note: I output the results with console.table which doesn't seem to show up when you run the snippet, you'll have to open the actual dev console in order to see the table.

function factorialIterBigInt(input) {
    let computedFactorial = 1n;
    for (let i = input; i >= 1n; i--) {
        computedFactorial *= i;
    }
    return computedFactorial;
}

function factorialForwardIterBigInt(input) {
    let computedFactorial = 1n;
    for (let i = 1n; i <= input; i++) {
        computedFactorial *= i;
    }
    return computedFactorial;
}

function factorialRecBigInt(input) {
    if (input === 0n) {
        return 1n;
    }
    else {
        return input * factorialRecBigInt(input - 1n);
    }
}

function factorialTailRecBigInt(input, accumulatedResult = 1n) {
    if (input === 0n) {
        return accumulatedResult;
    }
    else {
        return factorialTailRecBigInt(input - 1n, input * accumulatedResult);
    }
}

function factorialIterNumber(input) {
    let computedFactorial = 1;
    for (let i = input; i >= 1; i--) {
        computedFactorial *= i;
    }
    return computedFactorial;
}
function factorialForwardIterNumber(input) {
    let computedFactorial = 1;
    for (let i = 1; i <= input; i++) {
        computedFactorial *= i;
    }
    return computedFactorial;
}

function factorialRecNumber(input) {
    if (input === 0) {
        return 1;
    }
    else {
        return input * factorialRecNumber(input - 1);
    }
}

function factorialTailRecNumber(input, accumulatedResult = 1) {
    if (input === 0) {
        return accumulatedResult;
    }
    else {
        return factorialTailRecNumber(input - 1, input * accumulatedResult);
    }
}

function measurePerformanceOfFunction({ functionToMeasure, paramsToCallWith, timesToMeasure }) {
    timesToMeasure = timesToMeasure == null || timesToMeasure <= 0 ? 1 : timesToMeasure;
    let totalTime = 0;
    for (let i = 0; i < timesToMeasure; i++) {
        const start = performance.now();
        functionToMeasure.apply(null, paramsToCallWith);
        const end = performance.now();
        totalTime += end - start;
    }
    return totalTime / timesToMeasure;
}

const input = 5000;
const inputAsBigInt = BigInt(input);
const timesToMeasure = 100;

console.log(`Input: ${input}`);
console.log(`Measured: ${timesToMeasure} times`);

console.table({
    'Iterative Backward': {
        'BigInt': `${measurePerformanceOfFunction({ functionToMeasure: factorialIterBigInt, paramsToCallWith: [inputAsBigInt], timesToMeasure })}ms`,
        'Number': `${measurePerformanceOfFunction({ functionToMeasure: factorialIterNumber, paramsToCallWith: [input], timesToMeasure })}ms`
    },
    'Iterative Forward': {
        'BigInt': `${measurePerformanceOfFunction({ functionToMeasure: factorialForwardIterBigInt, paramsToCallWith: [inputAsBigInt], timesToMeasure })}ms`,
        'Number': `${measurePerformanceOfFunction({ functionToMeasure: factorialForwardIterNumber, paramsToCallWith: [input], timesToMeasure })}ms`
    },
    'Recursive': {
        'BigInt': `${measurePerformanceOfFunction({ functionToMeasure: factorialRecBigInt, paramsToCallWith: [inputAsBigInt], timesToMeasure })}ms`,
        'Number': `${measurePerformanceOfFunction({ functionToMeasure: factorialRecNumber, paramsToCallWith: [input], timesToMeasure })}ms`
    },
    'Tail Recursive': {
        'BigInt': `${measurePerformanceOfFunction({ functionToMeasure: factorialTailRecBigInt, paramsToCallWith: [inputAsBigInt], timesToMeasure })}ms`,
        'Number': `${measurePerformanceOfFunction({ functionToMeasure: factorialTailRecNumber, paramsToCallWith: [input], timesToMeasure })}ms`
    }
});

I'm just really curious if anyone would have any clue why the recursive version of the function is faster than its iterative counterpart in Firefox?
Comment: You should be asking only one question. I suggest to drop the last one. It could be a posted as a separate question though.
Comment: Thanks for the feedback @trincot, sure I can remove the second question and perhaps ask it in a separate thread.
Answer: One reason that the iterative version could be slower is that it is not performing the multiplications in the same order as the recursive version.
The recursive version is really performing a post-order process: first the recursion is made, and then -- while backtracking out of recursion -- the multiplications happen. This means that the smallest values are multiplied first.
The iterative version loops from high to low values, so there the multiplications happen in the opposite order. When I changed this, the iterative version became some 5-15% faster, making up much of the difference with the recursive version.
One reason for that speed-up, is the memory allocation footprint (for BigInt) during the whole process: when starting with the small numbers, the initial footprint is small, while in the opposite direction, the footprint gets bigger more quickly.
Here you can see both iterative versions run. In Firefox I get better performance for the forward version:

function factorialIterBigIntForward(input) {
    let computedFactorial = 1n;
    for (let i = 1n; i <= input; i++) {
        computedFactorial *= i;
    }
    return computedFactorial;
}

function factorialIterBigIntBackward(input) {
    let computedFactorial = 1n;
    for (let i = input; i >= 1n; i--) {
        computedFactorial *= i;
    }
    return computedFactorial;
}

let input = 20000n;
// Run both functions twice
let time1 = performance.now();
factorialIterBigIntBackward(input);
let time2 = performance.now();
factorialIterBigIntForward(input);
let time3 = performance.now();
factorialIterBigIntBackward(input);
let time4 = performance.now();
factorialIterBigIntForward(input);
let time5 = performance.now();

console.log("backward", time2 - time1 + time4 - time3);
console.log("forward", time3 - time2 + time5 - time4);
Comment: Thanks for your suggestion @trincot, that is at least a step in the correct direction. I've updated my post with a "forward" iterative version for additional comparison. I've also added a function to measure the performance of each of the factorial functions and provide the average performance so that results can hopefully be a bit more consistent (at the cost of more runtime :D).

Even with this speed improvement though, the recursive BigInt function still consistently running faster.


Disable button after click

Question: I want to disable my button after I click it. I want to see it but I don't want to click again after clicked. İn Windows Phone 8 how can I do this?
button1.isEnabled = false; //hide button.

I don't want to hide it and click it again.
Answer: UIElement.IsHitTestVisible Property

Gets or sets a value that declares whether this element can possibly
  be returned as a hit test

You can set your_btn.IsHitTestVisible = False at the beginning of your function and then reset it to True at the end
or
UIElement.IsEnabled Property

Gets or sets a value indicating whether this element is enabled in the
  user interface (UI)

Using IsEnabled (that set the background to transparent), you can create a style resource (going in XAML, right click on the view of your_btn->edit template->edit a copy..., then modifiy the VisualState x:Name="Disabled" field setting the Storyboard.TargetProperty="Background" Value="your_background". In this way you can also simulate a holding button...
The resource style is

And your button will have the Style="{StaticResource ButtonStyle1}" property
Answer: Have you tried to put in Click Event such a line?
myButton.IsHitTestVisible = false;

Answer: Unsubscribing from the click event should do the trick
try this -
private void button1_Click(object sender, RoutedEventArgs e)
{
    button1.Click -= button1_Click;

    //Then do what the button does.
}

So, after the first click, the Event Handler will unsubscribe from the Click Event. So, no further clicks will invoke the event handler.

Disable button after click


How to name the column being the day of the week

Question: I have this appointment, but I had to put the day of the week.
   select `a`.`aplicativo` AS `PROGRAMA`,
          sum((cast(`r`.`created_at` as date) = curdate())) AS `HOJE`,
          sum((cast(`r`.`created_at` as date) = (curdate() - 1))) AS `ONTEM`,
          sum((cast(`r`.`created_at` as date) = (curdate() - 2))) AS `2_DIAS`
   from (`registration` `r`
         join `aplicativos` `a` on ((`r`.`app_id` = `a`.`id`)))
   group by `r`.`app_id`

I have already tried with the following command gives error.
sum((cast(`r`.`created_at` as date) = (curdate() - 1))) AS DATE_FORMAT(curdate(),'%a %e')

I would like that in each column of sum, it appears
Sunday | Monday | Tuesday | Wednesday
65       54       99        100

It can not be fixed, because every day will change.
Today is Sunday and will appear the dates of Saturday, Friday ...
But tomorrow is Monday then it should appear: Sunday, Saturday ....
Tomorrow will be another result as below
Monday | Tuesday | Wednesday | Thursday
54       99        100         85

Comment: You cannot run functions on column aliases directly in query unless a stored proc. Consider also application code like PHP, Python, or R to dynamically create SQL statement with needed column alias.
Comment: Please edit your question and provide sample data and desired results.
Comment: Hi, @Gordon Linoff, can you help me with this too? I have already edited my question with the result that I need
Comment: @Parfait, I need to do this directly in the query because my report is straightforward in Mysql I do not use php, python etc ...
Comment: @William . . . A SQL result set has a set of columns with fixed names in a fixed order.  You can only do what you want using dynamic SQL.
Comment: @Gordon Linoff, Have an example with Dynamic SQL?
Comment: @William, dynamic SQL is run at application layer above database where a general purpose language (php, python, r, vb, c#, java, perl) builds a dynamic string SQL statement by conditional/logical criteria and sends it as a call to database. Your needs require a recreated query every day.
Comment: Thank you guys
I'll leave the name of the columns fixed.
Answer: SELECT a.aplicativo AS programa,
  SUM(CASE WHEN dayofweek(r.created_at)=1 THEN 1 ELSE 0 END) AS sunday,
  SUM(CASE WHEN dayofweek(r.created_at)=2 THEN 1 ELSE 0 END) AS monday,
  /* ... */
  SUM(CASE WHEN dayofweek(r.created_at)=7 THEN 1 ELSE 0 END) AS saturday
FROM registration r
  JOIN aplicativos a ON a.id=r.app_id
WHERE r.created_at>=(curdate()-6)
GROUP BY a.aplicativo

Comment: This way it would sum to the day of the week example: Sum all of the day of the week in the case Sunday.
That's not what I need! I need it to show All downloads for Today Sunday and the name of the Column = Sunday. Tomorrow will be Monday so the column should change to Monday
Comment: Look at WHERE clause: the query doesn't sums data for all sundays, all mondays etc. It sums data only for today and the 6 previous days. So it's exactly what you need EXCEPT the order of columns is fixed.
Comment: Again, @William, SQL is a special-purpose, declarative language where structural components like tables/columns once referenced are immutable though data can change. You need to recreate this query **every** day. Reconsider general purpose languages like aforementioned Python, PHP, R each with great APIs to MySQL.
Comment: The only other way is to build your query dinamically, as Gordon Linoff told already.
Comment: Thank you guys
I'll leave the name of the columns fixed.


Basic WebApp Questions

Question: I am currently thinking about coding my first webapp.
I would say i have beginner to intermediate coding skills in html,css,js,jquery node,sql and monogodb.
The problem is that i do not really know how to achieve my goal.
My goal is to built a responsive single page website, which gets the stock price from an api and display it on one card. Furthermore the user should be able to click on the plus button and add another card with an stock index he chose from a choosing form option.
Now what want to know is:

Is this an example for choosing a js framework like react, vue etc. and how can I accomplish my goal ?
I coded the api get request etc. in node and was able to print everything I want into the console log. How do I do the same thing but displaying it on my html page ?
How can I create these cards which are automatically getting added to the homepage ?
How can I save the data for each individual card? (especially without a login procedure...)?

I know these are quite easy questions but I really want to learn how to do it.
Please check the images below.
(check:

Comment: There are so many tutorials out there showing you how to do that. I still would use React over Vue because of ReactNative
Answer:
I would say try to use your existing skills to achieve your goals. When you run into problems you cannot solve or problems that could be solved by a specific framework such as react, try using them. It's better to understand what these frameworks are doing before you rely on them for every development.
You need to use an http framework like express to return your api values from node js to a web client.
Needs more info but as you're already talking about component based libraries, a good approach would be to keep the cards in a json array and render your page from that. If you are persisting the card data in a database you will also may want to render them server side as the page is loaded using a server side technology like node.
To keep things simple, you can store the info client side using something like localStorage or indexeddb. If you want to store something on the server side, you will need to introduce a way of identifying the user.

Basic WebApp Questions


Mounting errors in fstab while NAS is off

Question: (Xubuntu 20.04) I am having problems with fstab getting through the mounting process when the NAS is off. When the NAS is on and I turn on the pc, I have no problem with the mounting. The fstab lines look like below. In Xubuntu 18.04 I made a script for mounting which I could start manually after the NAS is turned on. It works on Xubuntu 20.04 too. Thank you.
ip_nas:/folder  /mnt/folder nfs defaults    0   0

Comment: I do not use nfs. But have seen this: use autofs for any storage that isn't connected directly to the system with SAS, SATA, eSATA, or Infiniband connections
https://wiki.archlinux.org/index.php/Autofs Some have issues that fstab is processed before network is up. Example autofs and _netdev
https://ubuntuforums.org/showthread.php?t=2450936
Answer: Try changing this in /etc/fstab:
ip_nas:/folder  /mnt/folder nfs defaults    0   0

To this (this assumes that ip_nas is in your /etc/hosts file, else use IP address):
//ip_nas/folder  /mnt/folder nfs defaults,nofail,x-systemd.device-timeout=30    0   0

or
//192.168.x.x/folder  /mnt/folder nfs defaults,nofail,x-systemd.device-timeout=30    0   0

And see if that helps. Report back.
Comment: It thought it worked, but I had '#' before the line in fstab. It seems that your solution is not working.
Comment: In dmesg I am getting a lot of these lines "NFS4: Couldn't follow remote path", "FS-Cache: Duplicate cookie detected", "FS-Cache: O-cookie c=blabla fl=222 nc=0 na=1]" and "FS-Cache: O-cookie c=blabla fl=2 nc=0 na=1]", etc. After maybe 5 minutes it continues to boot.
Comment: @mevrouwtje So the line in fstab was commented out? How did it ever mount the NAS then? Show me your script, and tell me when/how you use it. Can you mount the NAS manually, or with your script?
Comment: @mevrouwtje See edit in my answer.
Comment: I always use 192.168.x.x. First I used "defaults" instead of "defaults,nofail,..". It worked/works when my NAS is on, but when my nas is off booting takes approximately 4 minutes and there are lots of errors in the dmesg. That is when I put # in front of the code. After that I changed the code according to your solution, but forgot to delete the #. That is why I thought your solution worked. Of course I tested it only with the NAS off.
Comment: @mevrouwtje Then use the last example in my answer. Remove your original line, as it's clearly incorrect. Then `sudo mount -a` with NAS on to assure that the new fstab line works. Then `umount` the NAS. Then `sudo mount -a` with the NAS off. (`nfs` **might** need to be `smb` or `cifs`).
Comment: As I already wrote to you I am always using 192.168.x.x (your third solution right?). I also already wrote you I never had problems with the NAS on, also not with your solution I assume.
Comment: @mevrouwtje I'm getting mixed information here. Edit your question and show me `cat /etc/fstab` and your manual mounting script.
Comment: Hopefully the question on top is more clearly now. The script that I run manually after I have turned the NAS on is: sudo mount 'ip_nas:/folder' /mnt/folder


bufferGeometry and shadow react-three-fiber

Question: I am trying to make my own bufferGeometry work in react-three-fiber, and I am just not getting any shadows. I think I'm doing everything fine with the vertices, normals and even uvs of my bufferGeometry. I also tried to add indices to faces but for some reason that is messing up my geometry as well.
If I put a small test box in the scene, it cast shadows. Only my bufferGeometry doesn't seem to work.
Here is the code:
//MyGeometry.js -- it is stripe of quadrilaterals

import * as THREE from 'three'
import {useMemo} from 'react'

export default function MyGeometry({ position, L, W, res }) {

    const [vertices, faces, normals, uvs] = useMemo( () =>
    {
        const arr = [];
        const facesArr = [];
        const normsArr = [];
        const uvArr = []
        const triangle_pairs = Math.floor(L/res);
        const upper_left_corner = [
            position[0] - W/2,
            position[1] - L/2,
            position[2]
        ];

        for(let i=0; i<triangle_pairs; i++) {

            //v0
            const v0x = upper_left_corner[0] + Math.random()*(res/3);
            const v0y = upper_left_corner[1] + i*res + Math.random()*(res/3);
            const v0z = upper_left_corner[2] + Math.random()*(res/3);
            const v0 = new THREE.Vector3(v0x, v0y, v0z); //for computing normals
            //v1
            const v1x = upper_left_corner[0] + W + Math.random()*(res/3);
            const v1y = upper_left_corner[1] + i*res + Math.random()*(res/3);
            const v1z = upper_left_corner[2] + Math.random()*(res/3);
            const v1 = new THREE.Vector3(v1x, v1y, v1z); //for computing normals
            //v2
            const v2x = upper_left_corner[0] + Math.random()*(res/3);
            const v2y = upper_left_corner[1] + (i+1)*res + Math.random()*(res/3);
            const v2z = upper_left_corner[2] + Math.random()*(res/3);
            const v2 = new THREE.Vector3(v2x, v2y, v2z); //for computing normals
            //v3
            const v3x = upper_left_corner[0] + W + Math.random()*(res/3);
            const v3y = upper_left_corner[1] + (i+1)*res + Math.random()*(res/3);
            const v3z = upper_left_corner[2] + Math.random()*(res/3);
            const v3 = new THREE.Vector3(v3x, v3y, v3z); //for computing normals

            //UPPER triangle - 0,1,2

            //positions

            arr.push(v0x, v0y, v0z, v1x, v1y, v1z, v2x, v2y, v2z);

            //face, or indices

            facesArr.push(2*i, 2*i+1, 2*i+2);

            //normals

            const s21 = new THREE.Vector3();
            s21.copy(v2).sub(v1);
            const s01 = new THREE.Vector3();
            s01.copy(v0).sub(v1);
            const n1 = new THREE.Vector3();
            n1.copy(s21).cross(s01).normalize();
            normsArr.push(n1.x, n1.y, n1.z);
            normsArr.push(n1.x, n1.y, n1.z);
            normsArr.push(n1.x, n1.y, n1.z);

            //uvs
            uvArr.push(0,0, 1,0, 0,1)

            //LOWER triangle - 2,1,3

            //positions

            arr.push(v2x, v2y, v2z, v1x, v1y, v1z, v3x, v3y, v3z);

            //face, or indices

            facesArr.push(2*i+2, 2*i+1, 2*i+3);

            //normals

            const s31 = new THREE.Vector3();
            s31.copy(v3).sub(v1);
            const n2 = new THREE.Vector3();
            n2.copy(s31).cross(s21).normalize();
            normsArr.push(n2.x, n2.y, n2.z);
            normsArr.push(n2.x, n2.y, n2.z);
            normsArr.push(n2.x, n2.y, n2.z);

            //uvs
            uvArr.push(0,1, 1,0, 1,1);

        }

        const vertices = new Float32Array(arr);
        const faces = new Uint16Array(facesArr);
        const normals = new Float32Array(normsArr);
        const uvs = new Float32Array(uvs);

        return [vertices, faces, normals, uvs];

    }
    , []);

    return (
      <mesh castShadow={true} receiveShadow={true} position={position}>

        <bufferGeometry
            attach="geometry"
        >
            <bufferAttribute
                attachObject={["attributes", "position"]}
                count={vertices.length / 3}
                array={vertices}
                itemSize={3}
            />

            <bufferAttribute
                attachObject={["attributes", "normal"]}
                count={normals.length / 3}
                array={normals}
                itemSize={3}
            />

            <bufferAttribute
                attachObject={["attributes", "uv"]}
                count={uvs.length / 2}
                array={uvs}
                itemSize={2}
            />

            //faces - for some reason if i uncomment this my geometry gets messed up
            {/* <bufferAttribute
                attach="index"
                count={faces.length}
                array={faces}
                itemSize={1}
            /> */}

        </bufferGeometry>

        <meshPhongMaterial attach="material" color="blue" />

      </mesh>
    )
}

and then it gets rendered in here
//Main.js

import { useRef, useState, useEffect } from 'react'
import { Canvas, useFrame, useThree } from 'react-three-fiber'
import { Box } from '@react-three/drei'
import MyCamera from '../three/MyCamera'
import MyGeometry from '../three/MyGeometry'

export default function Main() {

  return (

    <Canvas
      linear = "true"
      frameloop="demand"
      shadows = "true"
      shadowMap
    >
      <MyCamera position={[0, 5, 30]} infLimit={-200} supLimit ={200} />
      <ambientLight intensity={1}/>
      <mesh receiveShadow castShadow position={[0,0,0]}>
        <planeBufferGeometry attach="geometry" args={[1000, 1000]} />
        <meshStandardMaterial attach="material" color="gray" />
      </mesh>
      <MyGeometry position={[0, 0, 0]} L={10} W={5} res={10} />
    </Canvas>

  )
}

Answer: TURNS out I resolved the issue:

I was really stupid when creating my mesh. I forgot in the Canvas object the y axis is flipped, so my normals were all messed up.
Theres a shadow camera property in lights witch has to contain the region the shadow will be rendered. I had no idea about that and also had to change things a bit:

I had a light in MyCamera object witch I deleted and instead create a light inside Main functional component and to access this shadow camera stuff I had to create it imperatively inside useMemo and render as a primitive inside Canvas:
export default function Main() {

  const dirLight = useMemo(()=>{

    const light = new THREE.DirectionalLight('white');
    light.castShadow=true;
    //Set up shadow properties for the light
    light.shadow.mapSize.width = 10240 // default
    light.shadow.mapSize.height = 10240 // default
    light.shadow.camera.near = 0.1 // default
    light.shadow.camera.far = 5000 // default
    light.shadow.camera.top = -100 // default
    light.shadow.camera.right = 100 // default
    light.shadow.camera.left = -100 // default
    light.shadow.camera.bottom = 100 // default
    return light

  },[])

  return (

    <Canvas
      linear = "true"
      frameloop="demand"
      shadows = "true"
      shadowMap
    >

      <MyCamera position={[0, 0, 30]} infLimit={-1000} supLimit ={0} />

      <ambientLight intensity={0.2}/>

      <primitive object={dirLight} position={[30, 0, 30]} />
      <primitive object={dirLight.target} position={[0, 0, 0]}  />

      <mesh receiveShadow position={[0,0,-2]}>
        <planeBufferGeometry attach="geometry" args={[1000, 1000]} />
        <meshStandardMaterial attach="material" color="gray" />
      </mesh>

      <MyGeometry position={[0, 0, 0]} L={400} W={5} res={4} />

    </Canvas>

  )
}

And then


how do I remove this old track light hanger from junction box?

Question: I need some guidance on how to remove this late 1980's vintage track light mounting strap or hanger (brace?) from the 4" round junction box? It appears to have the two small threaded rods, that the cover plate attached to, go all the way up through the two layers of the metal hanger. There are also two philips head screws holding the "top" of the strap into the j-box just above the lower metal strap. Both appear to be going into some of the plastic 'tabs' of the j-box.
Comment: link to photobucket for pictures: http://s747.photobucket.com/user/vthunter/library/Track%20Light%20bracket
Answer: If you can push the machine screws up, then you can just spin the bottom half of the bracket and get at the screws that are holding it.
If you can't push them up, grab them with locking pliers (ie, visegrips) and spin them out.
If that doesn't work, use brute force to bend the bottom half of the bracket to give you access to the screws holding the top half. Then you'll be in a better position to assess the hanging machine screws.
oh, and so I can sleep well at night, please put a cap on that black wire... you never know who'll flip a switch on you at the wrong time...
Comment: Aloysius, I was able to spin out the two threaded pins (screws) with vise-grips and rotate the bottom half of the bracket, without bending, easy as can be. Removed the two philips screws and ready to go. THANK YOU BOTH!!
Comment: Thank you for the quick feedback. I surely regret the impression left by my photo; rest assured, the pig-tails were removed and the wire nuts replaced on the ends. I have the power off at the switch and the breaker panel with a homemade lock-out/tag-out (really just a sticky note) on the brkr,.to warn anyone not to flip on. I really appreciate the advice. Thank you!!
Comment: http://i747.photobucket.com/albums/xx117/vthunter/Track%20Light%20bracket/1030161045-01_zpsu8gleg95.jpg

http://i747.photobucket.com/albums/xx117/vthunter/Track%20Light%20bracket/1030161044-00_zps6lgpam1z.jpg
Answer: Just follow the directions I added to the snip of your photo.
Comment: Thank you, Michael! Sound advice. I'm a bit worried on putting too much pressure on the box. Do you think the ends of the bracket will bend under vise-grips as you and Aloysius instruct? Thx again - no convo intended, just clarifying. Thanks again to both!!


Paypal SDK Payouts - cannot catch Exception and Receive http 400

Question: Hi I currently try to implement the following : someone is paying for something via paypal - a third person should receive like 50% of the price on their paypal account afterwards. So I always want to folow the steps : Person A pays 10€, I receive 10 €, I pay 5€ to Person C.
The first part is working via paypal sdk in php, the second part (transfering money to another person is not working well currently...)
This is my code for this
<code> $payouts = new \PayPal\Api\Payout();

 $senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();

 $senderBatchHeader->setSenderBatchId(uniqid())
     ->setEmailSubject("Test.");

 $senderItem1 = new \PayPal\Api\PayoutItem();

 $senderItem1->setRecipientType('Email')
            ->setNote('Test.')
            ->setReceiver('email@example.com')
            ->setSenderItemId('test ' . uniqid())
            ->setAmount(new \PayPal\Api\Currency('{
                    "value": "5.00",
                    "currency":"EUR"
                }'));

 $payouts->setSenderBatchHeader($senderBatchHeader)
   ->addItem($senderItem1);

 // For Sample Purposes Only.
 $request = clone $payouts;

// ### Create Payout
try {
    $output = $payouts->createSynchronous($this->_api_context);
} catch (PayPapl\Exception\PayPalConnectionException $ex) {
            //todo add exception handler
    dd('test');

    ResultPrinter::printError("Created Batch Payout", "Payout", null, $request, $ex);
    exit(1);
}

dd('test');
</code>
I cannot catch the error somehow. It says
PayPalConnectionException in PayPalHttpConnection.php line 174:
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payouts?sync_mode=true.
I'm implementing this using laravel 5.1
Any Ideas?
Answer: Put a '\' in front of your paypal error message. Worked for me. Its a namespace conflict.
<code>try {
    $output = $payouts->createSynchronous($this->_api_context);
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
    //todo add exception handler
    dd('test');
    ResultPrinter::printError("Created Batch Payout", "Payout", null, $request, $ex);
    exit(1);
}catch (\Exception $e){
    dd($e->getMessage( );
}
</code>
See this post
Answer: Based on your business model, REST API is not a good option to use.
Paypal has the adaptive payment API which enables you to send money in many different scenarios, from simple to complex.So in your case, you may refer the chained payment, the sender pays the primary receiver an amount, from which the primary receiver pays secondary receivers. The sender only knows about the primary receiver, not the secondary receivers. The secondary receivers only know about the primary receiver, not the sender. Adaptive payment demo download.


Appending the header of a txt document with ColdFusion

Question: Using ColdFusion I would like to append the header of the file each time that I add a row into the txt file
The format for the header is as follows:
E.g.
1234567890123456789012345678901234567890
BEEP BANK       1000009099810

The header's content is broken down into:
Element         Description                                        Pad char Pad side    Length
Bank name       First 16 characters of the Bank name as per file   [space]  right       16
                name, padded with spaces at the end if the name is
                less than 16 characters long. Convert to Uppercase
Record count    Number of data records in the file, depicted as a  0        left        3
                3 character, zero-left-padded string
Total value     Value (in cents) of all amounts in the file,       0        left        10
                depicted as a  10 character, zero-left-padded
                string
Total Header Record Length  29

At the moment I am running a loop and inside of the loop I would like to update the Record Count and the Total Value inside of the header while still keeping the same format
What I would like to know is how do I get the header of the txt file called test.txt and split the numeric value to get the individual values namely Record Count and Total Value to work with them and add my new dynamic values to them?
Thanks in advance
Comment: I've read this three times, and I still don't know what you're actually asking. Is it just me?
Comment: Hi Adam, I am quite confused myself but what I am trying to achieve in short: I would like to get the first row of the txt (the header) and update it. Does that make sense?
Answer: This will read the file and replace the first line, and write it back to the original file.
    <cffile action="read" variable="textDoc" file="#getDirectoryFromPath(getTemplatePath())#/test.txt" />
    <cfset textDoc = listSetAt(textDoc,1,"new header line","#chr(10)##chr(13)#")>
    <cffile action="write" file="#getDirectoryFromPath(getTemplatePath())#/test.txt" output="#textDoc#">

In this instance we are using new-line and carriage-return as the list delimiters.
Answer: You will have to parse the file. If you want to keep it human readable (as opposed to making it XML or similar) then you have to tell coldfusion how to find the characters to update.
I assume the header is always static, only the numbers recording the records change.
The best way is to include those records in the header by escape characters, for example {{125}}.
Then grab the file, and do a regexp looking for {{.?}}, update the number and replace. Then write the file.
OR just delete the whole header and rewrite with the update data everytime the file is saved. Whichever is easier in your case.