text:
Q: How to encourage junior developers to participate in code review? I'm currently working as a senior dev with 3 juniors below me and have introduced a code review process to help manage the quality of code going into production.
I feel its very beneficial for all of us to review each others work, however after about 5 weeks of the process I am the only one to make any comments in the tool (BitBucket).
I think there are part cultural issues at work, and perhaps a natural reluctance in case their comments are wrong, but is there any way that I can help the juniors feel more comfortable critiquing mine and each others work?

A: Have code review meetings in person at set time every week. I sold this to my teammate like this (we're actually both senior devs, but whatever):
"The code review is partially there for me to get to know your code a bit better and know what's going on in your side of things in case you get hit by a truck someday and I'm ordered to finish your sprint. But mainly it's there for you to explain your code to someone else, because when you do that, it engages a different part of your brain, and often times your explanation to them, and/or their questions or comments, might cause you to remember something you forgot to do in the code, or might cause you to realize a better way to make it more readable or architect it better. That leads to more beautiful code."
I like to think of it as a show-and-tell. People get to show off their work to their peers. It's not about your peers finding things wrong in your work, which nobody likes the feeling of. It's about impressing your peers with your awesome code, which everybody likes the feeling of.
However I think using code review tools where there's no human interaction, no meeting in a room, no whiteboard.. it becomes just another annoying "thing" to do. It's not that there shouldn't be such tools, but they should be something you resort to if, during the code review meeting, it's realized that a more in-depth review of a certain section of code might be necessary. Then you could assign one of the junior devs to review the other one's code on a certain area.

A: To me, the question here is "what are you looking for your junior developers to get out of the code reviews?". To me, potentially the most important thing is for the junior developers to learn by looking at what is hopefully good code; if they happen to find issues in your code as well, that's a bonus.
If you are looking for your junior staff to learn from the code reviews, the most important thing you have to do is to create an environment where learning is valued, and not viewed as a waste of time. This means a number of things:

*

*There is no such thing as a stupid question. If someone doesn't understand a bit of code, why you've used a certain pattern or whatever, they need to feel free to ask, without ever being made to feel that they're wasting either your time or that of the other developers.

*Time spent learning is time well spent. You want your junior developers to spend time looking at code and learning from it, because it's going to make them better, more productive staff in the future. Unless it's a critical fix which needs to be reviewed now, encourage them to spend more, rather than less, time on the code reviews.

*Senior staff are not always right. Just because you've been doing this for longer doesn't mean you're right. If they think they've found a bug, they're probably right. If they think another design pattern would be appropriate for this bit of code, then they need to feel free to say so without getting negative feedback.

A: You can help by setting a good example. You can't get defensive when someone points out your mistakes. Do a code review on your own code and note areas of improvement. Share this with the team. Eventually, they will learn that this is encouraged and no one is going to get a beating for having a bug in their code.
Having a job means taking responsibility and pride in your work. If code review is a part of that, then participation in code review should be included in evaluations. I've taken online classes where participation in online discussions is a part of the grade. Comments need to be elaborated on. "I agree" is not acceptable.
Code review should improve code. Depending on your situation it could be measured by sales numbers, user complaints, or some other rating if you writing code for internal use. The reality is your code serves some purpose and your team should be measured by how well they serve that purpose. Those you determine contribute to the success, get to share proportionately in the rewards.
Focus on releasing quality code. The goal isn't for everyone to feel good about themselves by shying away from bugs. I write bad code; I have to fix the bad code. That is work and life. I hate fixing bugs, so I try to avoid them. I take pride in my work, so it bothers me when my code doesn't work. I feel bad for the users or anyone else who has to take their time to point these things out and it motivates me to want to fix it.
As a side note, if you have an environment where no one can give or accept constructive criticism, you have a problem.

A: The process: Someone wants to commit his changes. Someone is assigned as the reviewer and reviews the changes. Then the reviewed and fixed changes go to testing.
If testing finds bugs introduced in the change, then author and reviewer are equally to blame.
So doing a review without any comments will get you into trouble unless the code was perfect.


text:
Q: How do I test for a empty string/null, using JavaScript? How do I test for a input[text] field that has nothing in?
This is what I have so far:
    if ($('#StartingPrice').length == ""){
        alert("ERROR!");
    }

Any help would be greatly appreciated, Thanks

A: $('#StartingPrice').length returns an integer so it will never equal "".
Try using the val() method:
if($('#StartingPrice').val() == "")
{
    alert("ERROR!");
}

.length

The number of elements in the jQuery object.

.val()

Get the current value of the first element in the set of matched elements.

.value

No Such jQuery Method Exists

A: try this:
if ($('#StartingPrice')[0].value.length == 0){
    alert("ERROR!");
}

A: Just as an alternative to the already provided solutions... you could also use a Regex to test that it actually contains something other than whitespace.
!!$('#StartingPrice').val().match(/\S/)

This will test for the existing of a non-whitespace character and using the Not-Not will convert it to a Boolean value for you. True if it contains non-whitespace. False if blank or only whitespace.

A: if ($('#StartingPrice').val() === ""){
    alert("ERROR!");
}

A: if ($('#StartingPrice').val() == ""){
    alert("ERROR!");
}

If the value of your text input is any empty string then it's empty.

A: I think you want this:
if ($('#StartingPrice').val() == false) {
    alert("Error!");
}

Use the .val() method to get the value and then pass that into the if. If the string is empty or white space it will evaluate to false.

A: Try:
if(myStr){
   // Your code here
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show the co-countable topology is a topology? I am trying to show the co-countable topology $\tau$ is a topology on a set $X$.
The first point to show $\emptyset,X\in\tau$ is not difficult.
Now let $S_i\in\tau$. From the definition of co-countable, $S_i=\emptyset$ or $X\backslash S_i$ is countable.
I struggle to prove the second point $\cup S_i\in\tau$:
If $S_i=\emptyset$, then $\cup S_i=\cup\emptyset=\emptyset\in\tau$. The part I got stuck is what if $S_i\neq\emptyset$? So far I have not used $X\backslash S$?
The thing that troubles me a lot is that we are not told beforehand whether $X$ is countable or uncountable. Is it necesary to know?
How are we going to work on the condition being countable?
The third point $\cap S_i\in\tau$ should be similar but I am also not very sure about how can we make use of $X\backslash S_i$?
Thanks for any help on this matter.

A: Suppose $S_{i} \in \tau$. First prove that
$$ X \setminus (\bigcup S_{i}) = \bigcap (X \setminus S_{i})$$
Now there are two cases. Either all of the $S_{i}$ are the empty set, or at least one is not the empty set. The first case is straightforward. For the second case, ask yourself what the intersection of two countable sets looks like.


text:
Q: Impossible Cpu time for process / thread with rusage I am calculating the delta between the cpu time a process / thread is using, between the calling of a certain function.
I am getting impossible value for the process cpu time, some time's the next call is returning smaller cpu time, which is impossible.
this is the code i am using to calculate the cpu time:
  u64 CpuTime::calculateCpuTime(bool a_thread)
  {
    struct rusage l_rusage;
    int retVal;
    if(a_thread)
    {
      retVal = getrusage(1, &l_rusage); //1 = RUSAGE_THREAD
    }
    else
    {
      retVal = getrusage(0, &l_rusage); //0 = RUSAGE_SELF
    }
    ASSERT(retVal==0);

    u64 userUSeconds = (static_cast<u64>(l_rusage.ru_utime.tv_sec)*1000000)+
      (static_cast<u64>(l_rusage.ru_utime.tv_usec));

    u64 systemUSeconds = (static_cast<u64>(l_rusage.ru_stime.tv_sec)*1000000)+
      (static_cast<u64>(l_rusage.ru_stime.tv_usec));

    if(a_thread)
    {
      return userUSeconds + systemUSeconds;
    }
    return (userUSeconds + systemUSeconds) / ACE_OS::num_processors_online();
  }

Also the function calculating retrieving this is async, no more then 1 thread can access it at a time.
this is an example of the impossible output (process):

2016/03/23 13:39:05.187 - #2 - 15471/15055 -
  ThreadDeltaCpuTime = 6000  ThreadCpuTime = 46756013 ProcessCpuTime = 39820759  deltaProcessCpuTime= 250
2016/03/23 13:39:05.386 - #2 - 15470/15055 -
  ThreadDeltaCpuTime = 5000  ThreadCpuTime = 46663013 ProcessCpuTime = 39699759  deltaProcessCpuTime = 18446744073709430616

The delta calculation is a simple newValue - oldValue, with a unsigned int, it leads to those numbers.
Example for a thread impossible output:

2016/03/23 13:38:59.183 - #2 - 15472/15055 - ThreadDeltaCpuTime =
  6000 ThreadCpuTime = 47541012 ProcessCpuTime = 39658134
  deltaProcessCpuTime = 5250
2016/03/23 13:38:59.382 - #2 - 15472/15055 - ThreadDeltaCpuTime =
  1844
  6744073708557617 ThreadCpuTime = 46547013 ProcessCpuTime = 39663009 deltaProcessCpuTime = 4625

i have bolded the thread id, also you can see the function has been executed 200ms after the first 1.
I am looking for a clue for why this is happening, i have tried using the ACE_OS rusage as well, with same results (make sense), i could solve this by ignoring "bad" values, but i am wondering why this is happening.
EDIT:
This is where i do the actual printing:
  u64 computeCpuTime()
  {
    u64 deltaCpuTime= CpuTime::getThreadDeltaCpuTime();
    u64 CpuTime= getThreadCpuTime();
    u64 ProcessCpuTime= getProcessCpuTime();
    u64 deltaProcessCpuTime= CpuTime::getProcessDeltaCpuTime();
    Log<<value(deltaCpuTime)<<value(CpuTime)<<value(ProcessCpuTime)<<value(deltaProcessCpuTime)<<endlog;
    return deltaCpuTime;
  }

And the rest of the functions used in this calculation:
  u64 CpuTime::getThreadDeltaCpuTime()
  {
    pid_t thisThread = (pid_t) syscall (SYS_gettid);
    u64& val = m_threadsCpuMap[thisThread];
    u64 oldValue =val;
    val = calculateCpuTime(true);
    return val - oldValue;
  }

  u64 CpuTime::getProcessDeltaCpuTime()
  {
    u64 oldValue = m_processCpu;
    m_processCpu = calculateCpuTime(false);

    return m_processCpu - oldValue;
  }

  u64 getThreadCpuTime()
  {
    return CpuTime::calculateCpuTime(true);
  }

  u64 getProcessCpuTime()
  {
    return CpuTime::calculateCpuTime(false);
  }

The object doing the system call ("m_cpuTime") is a singleton, protected with a mutex, only 1 thread can access it at a time.
it holds the map of the threads cpu usage, m_threadsCpuMap (used for the delta), and also the last process cpu usage, m_processCpu.
ANOTHER EDIT:
I have simplified it with a simple test, working with a single thread, removed the division by active cpu's, and am only checking the Process Cpu time, still with impossible results.
Here is the updated functions:
Test:
for(int i = 0; i < 100000 ; i++)
{
  for(int k = 0; k < 1000000; k++)
    m = k % i;
    cpuTime = CpuTime::instance()->getProcessDeltaCpuTime();
}

Functions used in test:
  u64 CpuTime::getProcessDeltaCpuTime()
  {
    u64 oldValue = m_processCpu;
    m_processCpu = calculateCpuTime(eThisProcess);
   Log<<value(oldValue)<<value(m_processCpu)<value( m_processCpu - oldValue)<<endlog;
    return m_processCpu - oldValue;
  }

  u64 CpuTime::calculateCpuTime(int a_type)
  {
    struct rusage l_rusage;
    int retVal;
    if(a_type == eThisThread)
    {
      retVal = /*ACE_OS::*/getrusage(1, &l_rusage);
    }
    else
    {
      retVal = /*ACE_OS::*/getrusage(0, &l_rusage);
    }

    u64 userUSeconds = (static_cast<u64>(l_rusage.ru_utime.tv_sec)*1000000)+
      (static_cast<u64>(l_rusage.ru_utime.tv_usec));

    u64 systemUSeconds = (static_cast<u64>(l_rusage.ru_stime.tv_sec)*100000)+
      (static_cast<u64>(l_rusage.ru_stime.tv_usec));

    if(a_type == eThisThread)
    {
      return userUSeconds + systemUSeconds;
    }
    return (userUSeconds + systemUSeconds)/* / ACE_OS::num_processors_online()*/;

This is an example of the logs, i have removed all the times the delta was ~0

2016/03/29 08:07:05.198 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime:  oldValue = 14797750 m_processCpu =
  14798749 m_process Cpu - oldValue = 999
2016/03/29 08:07:05.199 - #2 -
  24011/24011 - CpuTime::getProcessDeltaCpuTime:  oldValue = 14798749
  m_processCpu = 14799749 m_process Cpu - oldValue = 1000
2016/03/29
  08:07:05.200 - #2 - 24011/24011 - CpuTime::getProcessDeltaCpuTime:
  oldValue = 14799749 m_processCpu = 14800749 m_process Cpu - oldValue =
  1000
2016/03/29 08:07:05.201 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime:  oldValue = 14800749 m_processCpu =
  14801749 m_process Cpu - oldValue = 1000
2016/03/29 08:07:05.202 - #2
  - 24011/24011 - CpuTime::getProcessDeltaCpuTime:  oldValue = 14801749 m_processCpu = 14802749 m_process Cpu - oldValue = 1000
2016/03/29 08:07:05.203 - #2 - 24011/24011 - CpuTime::getProcessDeltaCpuTime:
  oldValue = 14802749 m_processCpu = 13903748 m_process Cpu - oldValue =
  18446744073708652615
2016/03/29 08:07:05.204 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime:  oldValue = 13903748 m_processCpu =
  13904748 m_process Cpu - oldValue = 1000
2016/03/29 08:07:05.205 - #2
  - 24011/24011 - CpuTime::getProcessDeltaCpuTime:  oldValue = 13904748 m_processCpu = 13905748 m_process Cpu - oldValue = 1000

This time there was only 1 time of bad values, out of 100000 iterations.
And after it all the following calculation were also smaller, e.g. it went like this:
1 2 3 4 5 6 7 8 9 10 bad value, 6 7 8 9 10...
As if the process lost count, went back, and then continued normally.
YET ANOUTHER EDIT:
I have separated the code, completely, compiled it as simple as possible. and the problem did not occur, it could be a matter of probability (it was 1/100000 before).
this is the code:
int main()
{
  long int n = 0;
  long int oldValue = 0;
  long int newValue = 0;
  unsigned long int deltaValue = 0;

  for(int i = 0; i < 1000000; i++)
  {
    for(long int m = 0; m <10000; m++)
      n = m + i;
    struct rusage l_rusage;
    int retVal;
    retVal = getrusage(0, &l_rusage);
    if(retVal != 0) return 0;

    long int userUSeconds = l_rusage.ru_utime.tv_sec*1000000 + l_rusage.ru_utime.tv_usec;

    long int systemUSeconds = l_rusage.ru_stime.tv_sec*100000 + l_rusage.ru_stime.tv_usec;
    oldValue = newValue;
    newValue = userUSeconds + systemUSeconds;
    deltaValue = newValue - oldValue;
    if(deltaValue != 0)
      std::cout<<"Old value: "<< oldValue <<" New Value: "<< newValue <<" Delta value: "<<deltaValue<<"\n";

  }
  std::cout<<n;
  return 0;
}

And from further investigating the earlier test, (which use our unittest framework), the problem occurs always at around the same CPU time.
Which mean this is happening for a reason, i just cant figure out what happens at that exact time which could cause some thing like this.
Or how some thing like this could be caused.
I am not familiar enough with linux kernel to understand how this calculation is made.
Another insight - when using clock() to get the process. it does not happen, even more - it seems like until that moment the values were around the same, after this point they are not:

2016/03/29 12:36:19.158 - #2 - 20544/20544 -
  CpuTime::getProcessDeltaCpuTime:  oldValue = 14598780
  m_processCpu = 14598780 m_processCpu - oldValue = 0 oldClockTime =
  14580000 m_clockTime = 14580000 m_clockTime - oldClockTime = 0
2016/03/29 12:36:19.158 - #2 - 20544/20544 -
  CpuTime::getProcessDeltaCpuTime:  oldValue = 14598780
  m_processCpu = 13699779 m_processCpu - oldValue = 18446744073708652615
  oldClockTime = 14580000 m_clockTime = 14590000 m_clockTime - oldClockTime = 10000
2016/03/29 12:36:19.158 - #2 - 20544/20544 -
  CpuTime::getProcessDeltaCpuTime:  oldValue = 13699779
  m_processCpu = 13699779 m_processCpu - oldValue = 0 oldClockTime = 14590000 m_clockTime = 14590000 m_clockTime - oldClockTime = 0

Which leads me to a different question, how is rusage calculated, and how is clock()? what could lead to the difference between them?
I have worked around the problem, measuring it using clock_gettime, here is the code if any 1 is interested:
  u64 CpuMeasure::calculateCpuTime(int a_type)
  {
    struct timespec ts;

    if(a_type == eThisThread)
    {
      if (ACE_OS::clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0)
      {
         return (u64)ts.tv_sec * 1000000 + (u64)ts.tv_nsec / 1000; //From nano to mili seconds
      }
    }
    else
    {
      if (ACE_OS::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == 0)
      {
         return (u64)ts.tv_sec * 1000000 + (u64)ts.tv_nsec / 1000;
      }
    }
    ASSERT(false); //we cant be here, unless some thing bad happened
    return 0;
}

I am using ACE_OS for portability, but it works with the default functions from sys/time.h
Yet, i am still in question about rusage strange behavior , what could cause it to give those values.

A: Check carefully these lines: you are multiplying the system time seconds by 100 thousand instead of 1 million:
u64 userUSeconds = (static_cast<u64>(l_rusage.ru_utime.tv_sec)*1000000)+
  (static_cast<u64>(l_rusage.ru_utime.tv_usec));

u64 systemUSeconds = (static_cast<u64>(l_rusage.ru_stime.tv_sec)*100000)+
  (static_cast<u64>(l_rusage.ru_stime.tv_usec));

They are there in two of three examples you have shown (not in the first one).
However this would explain the odd sequence:

2016/03/29 08:07:05.201 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime: oldValue = 14800749 m_processCpu =
  14801749 m_process Cpu - oldValue = 1000
2016/03/29 08:07:05.202 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime: oldValue = 14801749 m_processCpu =
  14802749 m_process Cpu - oldValue = 1000
2016/03/29 08:07:05.203 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime: oldValue = 14802749 m_processCpu =
  13903748 m_process Cpu - oldValue = 18446744073708652615
2016/03/29 08:07:05.204 - #2 - 24011/24011 -
  CpuTime::getProcessDeltaCpuTime: oldValue = 13903748 m_processCpu =
  13904748 m_process Cpu - oldValue = 1000

at every iteration it adds 1000 us. But I guess that as soon as the system time surpass one second, only 1/10 of second is added, resulting in -0.9 seconds shift that is exactly 14.8 -> 13.9 seconds.
in fact:
 18446744073708652615 - 2^64 + 1 = -899000

that is -900000 (0.9 seconds) + 1000 us


text:
Q: How much are you willing to pay for this treasure chest game? I was given an interesting problem that comes in two parts.

In front of you is a treasure chest containing \$1000 with a 6-digit
  combination lock. You have to pay a constant amount for each time you
  change a digit. What is the maximum amount you are willing to pay per turn?

Not sure if my approach here is correct: if the expected value of the game is $E$ and the amount I pay per turn is $x$, then
$$E=\frac{1}{10^6}(1000-x)+\frac{10^6-1}{10^6}(E-x)$$
$$=E\left(1-\frac{1}{10^6}\right)+\frac{1000}{10^6}-x.$$
$$\Rightarrow E=1000-10^6x.$$
For positive payoff, we require $x<1000/10^6$, i.e. we want to pay less than \$0.001.
My main issue is with the next subproblem.

When two or less digits are correct, an LED on the chest glows red.
  When three or more (but not six) digits are correct, the LED glows
  yellow. When all digits are correct, the LED glows green and the chest
  opens. Is there an optimal strategy? How much are you willing to pay
  per turn now?

How exactly do we form a strategy? I'm unsure of the most efficient way to keep track of the correct digits, and how to get back on track if a yellow LED switches to red. I am also unsure of how this affects the equation for the expectation. Could someone guide me on this please? Thank you!

A: *

*$\bf{\color{red}{\text{RED}}}$ is $0, 1, 2$ right digits

*$\bf{\color{orange}{\text{YELLOW}}}$ is for $3, 4, 5$ right digits

*$\bf{\color{green}{\text{GREEN}}}$ for the number itself

*$n = \overline{d_6d_5d_4d_3d_2d_1}$
Since nothing a priori is known, any first guess will work in the same way, we guess

$0-0-0-0-0-0$

Few cases are possible (we don't know what is the case, except for color),

*

*$3$ to $5$ digits were guessed right. Then for every digit $d_1, \ldots, d_6$ try it(the digit) from $1$ to $9$, e.g. for $d_1$

$0-0-0-0-0-1$ to $0-0-0-0-0-9$ are tried

if color changed (on the first try) to RED, we've initially guessed $3$ right digits, incl. $d_1=0$
if color change to GREEN (during those 9 trials), we are done
otherwise, inconclusive. Then proceed in the same way with other locations $d_2$ till $d_6$. If there were $3$ or $5$ correct digits initially, this will be established on those trials. We will need at worst all $54$ trials in case of $5$ (but we will learn the number), for $3$ after at most $28$ trials we will know it is $3$ and which digits are right (once you know it is $3$ - $1$ trial is enough to check every digit if it is right or not, still inside $28$).
after $1 + 54$ trials, we established, there are $4$ right digits in $0-0-0-0-0-0$ guess. Now, pick a pair of digits, e.g. $d_1$ and $d_2$, and change them to $1-1$ (if color changed to RED - those were right digits, if to GREEN - done). In $3$ trials you find $2$ right zeros, in other $3$ the other right pair. In $18$ trials you can find the right value of two missing digits (you turn off two right, and run from $1$ to $9$ independently)
in the same spirit you can establish in $27$ trials, all the digits, in case of $3$.
check out, that initial testing could be done the triplets of digits [did not think this case for optimality].

*The more difficult is the case of RED light on $0-0-0-0-0-0$ trial.
in $1000$ trials, trying all the triplets of $d_1, d_2, d_3$,  we can establish their true value, and from that point proceed like above [more $27$] - this is the upper bound on the number of trials
The coverage idea
is to try numbers, like in the kids game [have no idea of its English name]. Each number you try and get RED - you basically drop numbers, that would otherwise give you YELLOW or GREEN.
Example:
After we have tried $0-0-0-0-0-0$, we know that $n$ could not be $0, 1, 2, 10, 11, 999$, etc. In fact, any first try will eliminate $15850$ possibilities. Interestingly, guessing next $1-1-1-1-1-1$ will eliminate $15830$, etc. While, I'm yet to establish there are at most $100$ guesses, which eventually result in a YELLOW light.
UPDATE [31/07/2019]:
(After I have optimized code enough, so it will be solvable in the short - order of hours amount of time)
As I have stated previously, $1,000$ consecutive trials of $3$ right-most digits will hit every possible number with $\bf{\color{orange}{\text{YELLOW}}}$ light eventually.
Therefore we are interested in anything that is faster. I have applied a greedy algorithm, that traverses all the numbers and picks the number, that covers (i.e. turns light yellow) the most yet uncovered numbers. It is not the optimal (i.e. probably the list could be made short, by choosing some other numbers, or just by changing the order of numbers in coverage could lead to over better numbers to pick).
In the abstract land, build a graph on $1000000$ vertices. Define edges between two vertices $v$ and $u$, if the Hamming distance between their decimal representation is at least $3$. We want to find a dominating set in this graph. Such that, if we complete the dominating set, so we can move from one vertex in it to another (weights are just a Hamming distance), some Hamiltonian path through it has a minimal weight.
Unfortunately, I'm not that good in complexity, so I suppose both DS and HPP are hard problems.
In my attempt I have found a $292$ big dominating set. And finally iterated few times through it to find some Hamiltonian path with eventual weight of $949$ (i.e. $949$ digit changes, before you deterministically hit $\bf{\color{orange}{\text{YELLOW}}}$ light on any possible number, but without paying for the first attempt). Recall that after the yellow light was produced, it still could require another $54$ attempts to establish which digits are right (and the value of which were guessed wrong).
Overall, this strategy requires $949$ digit changes to hit yellow light, then $54$ (plus maybe $6$ to set the guessed digit to the wrong state and back in the final attempt). This is $1007$ attempts instead of at most $1026 = 999 + 27$ in the trivial strategy approach
Let call it $2 \text{%}$-better strategy.
Therefore, slightly less than $1\$$ is a safe point.
Dump of the coverage (i.e. combinations should be tried in this order):

231750
139790
159430
279637
257639
207536
923536
327580
370540
350948
351989
315189
815185
875104
951304
658394
738393
794593
595793
513593
413592
493997
491507
497605
293625
983655
981607
481403
441633
540634
520544
592542
256542
258112
554192
550722
91222
11762
13661
702661
302666
666666
626612
706319
806368
405328
55928
935920
845020
575080
215084
219046
209743
273443
663423
847423
857063
853253
103254
168154
148138
697138
617208
636203
349003
379906
272908
973418
912818
112806
112029
132098
178498
178649
78241
48521
388621
318652
218359
888379
843377
893747
890716
460386
970381
790281
395271
309275
304195
104110
605810
800
0
3008
69758
69370
69402
709102
725192
720693
120604
121325
107821
967824
147974
167987
987
54687
854517
862509
62589
23189
283188
888888
888565
180575
286574
886501
456701
426051
150051
870052
430852
464872
452870
472150
410137
230167
241107
241859
240898
910853
110913
582913
502483
922481
722088
751078
321076
341396
145796
945648
995663
175563
674523
671029
786029
786095
228091
236491
262591
662694
162711
111111
291311
194302
994709
999999
829399
429914
439518
336514
346785
749285
948282
946172
956476
952266
928760
124768
594678
534777
508737
501836
31835
34055
964015
904094
904931
714901
734956
24946
444444
408344
408265
468425
560465
566169
640169
680968
600778
600479
105459
187259
186247
537217
571297
861290
867450
687451
689031
685046
625366
625847
225875
227405
538805
597004
752014
642017
932077
832427
316427
320927
360228
764238
765432
742332
987312
87992
377932
379862
99867
91464
30234
35679
839671
884680
284360
383490
344458
526358
97356
692955
606155
659345
12345
16930
876935
801942
818446
728419
363819
333333
365307
755857
555555
909557
806684
814264
514239
437249
337141
737748
777777
773724
783844
796540
798120
753106
523200
222222
274216
774836
76896
196883
477883
499184
419626
589126
519374
613770
917795
71715
85213
22173
268973
648906
638586
631782
133062
563041
543961
547610
473675
485769
382734
824831
654891
711568
961143
498037

A: This answer is limited to the first part of the problem, because there seems to be an error in the OP's approach there.
The OP's answer, $x\lt1000/10^6$ is correct only if there is a single attempt at unlocking the chest, or if by "willing to pay" what's meant is "willing to pay with no risk whatsoever of losing money."  If "willing to pay" has its more typical meaning of "willing to risk in order to get a positive expected return," and if you have unlimited attempts (and if you can keep track of the all those attempts, so you don't try the same combination twice), then the correct answer is $x\lt2000/10^6$ (or $1000/500{,}000$).
That is, if you systematically explore all $10^6=1{,}000{,}000$ different combinations without ever repeating yourself (which is possible to do while changing just one digit at a time), it'll take, on average, $500{,}000$ attempts to find the combination that unlocks the chest, so the expected return is $E=1000-500{,}000x$, and this is positive if $x\lt1000/500{,}000=\$0.002$ (i.e., two-tenths of a penny per attempt).

A: (Only second part of the question. The first part seems trivial)
Short summary: it seems that a naive approach can find the combination in 200 tries (on average).
This problem can be thought of as a variant as the classic "bulls and cows" game, with the added restriction that a guess can differ by only one digit from the previous guess.
The optimal strategy is not obvious, but here is an observation and results from computer simulations.
Observation 1: after the LED turns yellow for the first time, you know one position for certain (the last one changed), and you can get the other two by turning the other five positions once or twice. If, after changing a digit, the LED stays yellow you keep the change. If it goes red you know the number for that position and you change it back. After determining those 3 change one of them to turn the led to red, and using at most 30 tries you can determine the values of the other 3.
Every time you make a change and the LED stays red you gain some information.  For example, if you try 1,2,3,4,5,6 and get red, 1,2,3,X,X,X is not possible, 1,2,X,4,X,X not possible, etc. At most you eliminate $15850 = 20 \cdot 9^3 + 15 \cdot 9^2 + 6 \cdot 9 + 1$ (first try, for instance), but in general some combinations might be rules out already, and in practice you eliminate 4,000 to 6,000 combinations in the first 50 moves or so.
I wrote some code which picks a guess by keeping track of all valid remaining combinations, picks a position in one valid combination which is different than the guess and changes the guess to match this value. This is obviously not optimal but can give an idea about the upper limits. It seems that this method can fine the combination in around 200 moves (on average).
The code is not fast, so I run only 20-30 times, but I think somewhere between 150 and 250 (for the average) is reasonable.
Finding a better strategy seems interesting but not trivial.


text:
Q: can't start mysqld on centos because I cant find mysql.sock Hello when I try to start up my mysqld I get this error:
[root@localhost /]# service mysqld restart
Stopping mysqld:                                           [  OK  ]
MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]

the main reason is that my.cnf file can't find my mysql.sock file.
[root@localhost /]# mysqladmin -u root -p status

mysqladmin: connect to server at 'localhost' failed

error: 'Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/var/lib/mysql/mysql.sock' exists!

When I try to search it with :
sudo find / -type s | grep mysqld.sock

I'll get
find: '/proc/3253/task/3253/fd/5': Bestand of map bestaat niet
find: '/proc/3253/task/3253/fdinfo/5': Bestand of map bestaat niet
find: '/proc/3253/fd/5': Bestand of map bestaat niet
find: '/proc/3253/fdinfo/5': Bestand of map bestaat niet

"Bestand of map bestaat niet" == "File or directory don't exists"

I'm new at this so can anyone help me please?

A:
"the main reason is that my.cnf file can't find my mysql.sock file."

Nope. "THE MAIN REASON" is mysqld has not started, so there is no mysql.sock and any client cannot establish connection.
Currently "why mysqld failds" is broad question.  MySQL Error log has the reason 'Why MySQL fails'. If you know where mysql error log is, just open it, and post error message into you question.
But probably I guess you don't know where mysql error log is....
Identify where mysql error log is
So, we need to identify where it is. we could guess somewhere... but the exact approach is using strace
$ strace -f > strace.log 2>&1 service mysqld start

now strace.log has all system call related to MySQL Deamon. open strace.log with any editor and search 'err"'. in my case
[pid 26976] open("/XXX/hostname.err", O_WRONLY|O_CREAT|O_APPEND, 0666) = 3

when open() fails
It could happen open() fails, common error is

*

*'2' for 'no such file or directory' means 'there is no /XXX directory.

*'3' for 'permission denied' means you (or user in my.cnf) don't have write permission on 'XXX'

so you can find why mysqld fails to start in '/XXX/hostname.err'. we highly appreciate if you post error message.
p.s.
I have test strace with
$ strace -f > strace.log 2>&1 mysql.server start

Not sure working with service mysqld, but no reason not to work
UPDATE

"I don't get anything in return with: $ strace -f > strace.log 2>&1 service mysqld start "

Actually service mysqld start invokes /etc/rc.d/init.d/mysqld start (assuming CentOS or Fedora). so, you could try.
$ strace -f > strace.log 2>&1 /etc/rc.d/init.d/mysqld start

If my.cnf which you referenced is right file for mysqld, open it and search [mysqld] section. It looks like as follows
[mysqld]
user    = username
port    = 1111
basedir = /path/
datadir = /path/data

MySQL error log is in /path/data

A: What a pain! I stumbled upon same problem (on RedHat) and this helped me:
service mysqld stop
rm -rf /var/lib/mysql/*
service mysqld start
mysql_secure_installation

Hope that helps. Good luck!

A: Am not an expert in mysql but the question is:
Is mysql listening on a socket, on a tcp port or both?
check the my.cnf configuration file which usually is in /etc or /etc/mysql and you will see this. Also, if it is already running as a socket, you will see the path to the socket.
Hope it helps.
Regards

A: From your post, it seems mysqld failed to start MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED].
Check if mysqld is running service mysqld status.
The config file my.cnf is looking for mysql.sock and you were looking for mysqld.sock. Two different names.

A: Thanks Barmaley,  for the awesome answer. I checked my mysqld.log file.
It show all the reasons why my mysql service not starting. In my case the user mysql has no write permission to "/var/run/mysqld". I gave permission to mysql user from root user and it worked for me.
Thanks again! Barmaley

A: Tech Set up:
Vagrant (Centos 6.6, MySQL 6.6) on top of MacOS Captain

Every time when I try to run mysql on Centos, I see this problem, I am not sure If this problem is only specific to OS and MySQL version.
If you open the log files and check you will see something like this

/usr/sbin/mysqld: File '/var/log/mysql-bin.index' not found (Errcode:
  13 - Permission denied)

That Permission Denied is because by default we don't have permissions to write into /var/log files, so we should change permissions for the user. MySQL is trying to write something into bin-log or relay-logs located in /var/log/mysql.
Before we change permissions, we need to realize that there is no mysql directory in /var/log so, we need to create that first and then change permissions.
So, I did this:
mkdir mysql
chown mysql: mysql

mysqld should start working now!


text:
Q: Unite several polygons that share boundaries in QGIS My study zone is in the middle of two geologic maps with two different shp files.
Is it possible to remove the boundaries of the polygons between these two maps that are created at the union of these in order to have only one polygon (per geologic unit)?.
In other words: to obtain an "unpartitioned" map (in QGIS).

A: Use Dissolve tool from Vector -> Geoprocessing -> Dissolve and choose the field that has the geologic name or id, the one you are using to style the polygons.

*

*Input layer: Select the polygon layer

*Dissolve field(s): Select the field that represents the geologic data

*Dissolve: Save the output final file into your hard drive

If the line did not disappear, zoom in into the line and check if there is a gap between the polygons.

A: If you want more control over the attributes of the merged feature than the Dissolve tool allows, use the Merge Selected Features tool in the Advanced Digitizing toolbar.

Manually select the features you want to merge into one feature. Click the Merge Selected Features button. Now you get a popup window, that allows you to set the attributes of the merged feature. For every attribute table field, you can choose from these options:

*

*Feature 1/2/3 etc (take the attribute from one feature, and discard the others)

*mathematical calculations for numerical fields: Count, Sum, Mean, Median, Standard deviation (pop or sample), Minimum, Maximum, Range, Minority, Majority, Variety, Q1, Q3, IQR

*concatenation for text fields

*Skip attribute (replace with NULL)

*Manual value (type whatever you want)

Obviously the downside of this tool is that you have to do each set of features separately, so it can be time-consuming if you have a lot of features. You can achieve a similar level of control over the attributes by first Dissolving, then running join attributes by location (summary).


text:
Q: Why does Medium use H3 tags in their articles while the Editor shows H1 when formatting? Considering Medium is a highly specialised publishing platform, Im a bit curious to learn about their formatting choices. For starters, they seem to use H3 tags for first level heading in the markup when the editor presents the user with choices for H1 and H2. It is also interesting that they let users define multiple H1 headings within the same "section" (which is actually multiple h3's in practice). What is the thought process behind this? While I love the fact that they let users publish articles even without forcing for a heading in the presentation layout, what are the SEO implications for this product decision?

A: I don`t think there is any rule in google book which states that you can only use one H1 per page. take a look below:

I always only use one H1 Element on any page. Google has recommended
  this in the past. Many argue that having more than one H1 per page is
  sensible in some instances (and HTML5 certainly allows for this). In
  the end – it will depend entirely on the site you want to make and the
  audience it serves. I think it is important to KEEP IMPLEMENTATION
  CONSISTENT across your entire site to maximise usability.

http://www.hobo-web.co.uk/headers/
In short Medium could get a slight seo boost if they followed the seo recommendations but they perhaps follow what suits their users best.


text:
Q: команда USE Sercver в запросе Господа, прошу объяснить не мыслимое
Есть простой запрос, который у меня работает, и в C# и в МС студии
//c#
string slim_sqlquery = "SELECT * FROM sys.Tables";
//Ms SQL Server Management Studio
SELECT * FROM sys.Tables

Но на некоторых серверах таблички не находятся, в студии делаю по другому
//Ms SQL Server Management Studio
Use MyServerName
GO
SELECT * FROM sys.Tables

А как это же самое реализовать на c# ?
//p.s.
string slim_sqlquery = "Use MyServerName GO SELECT * FROM sys.Tables";
SqlCommand cmd = new SqlCommand(slim_sqlquery, conn_my_servak);
SqlDataReader reader = cmd.ExecuteReader();//вот тут лезут ошибки, что SQL запрос надо в 1 строку

A: SqlClient не понимает GO так, как это делает SSMS.
Либо используйте three-part naming:
SqlCommand cmd = new SqlCommand("SELECT * FROM MyServerName.sys.Tables", conn_my_servak);
SqlDataReader reader = cmd.ExecuteReader();

Либо вынесите смену контекста в отдельную команду:
conn_my_servak.ChangeDatabase("MyServerName");

SqlCommand cmd = new SqlCommand("SELECT * FROM sys.Tables", conn_my_servak);
SqlDataReader reader = cmd.ExecuteReader();

A: В Запросе Use MyServerName GO убери.
   using (var connection = new SqlConnection(conn_my_servak))
   {
          connection.Open();
          using (var command = connection.CreateCommand())
          {
                command.CommandText("SELECT * FROM sys.Tables")
                using (var reader = command.ExecuteReader())
                {
                      while(reader.Read())
                      {
                            SomeId = (int)reader["id"];
                            SomeString = reader["someStr"].ToString();
                            .....
                      }
                }
          }

    }


text:
Q: Complete and Generate number for a array in JS In javascript I'm looking to complete one numbers, you can help me generate a array of please.
The first 4 digits start by "23 29 xx xx xx", the xx remains to be completed with a range from 0 to 99. Ex. 23 29 01 02 03
let firstDigit = "2329";
let numberOfRandomDigit = "6";
let firstRange = "01";
let maxRange = "99";
let arrayOfNumbers = ["2329010203, 2329xxxxxx", ...];

I don't know to do this with a loop for complete array

A: as I see it's a 10 digit number, and you know 4 digits initial, so rest 6 digits you can generate randomly like this :
from random import randint

def random_num(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

rest_digit = random_num(6)

Now you can simply append these 6 digit to the 4 digits that you have.

A: In JavaScript:
let firstDigit = "2329";
let firstRange = "00";
let maxRange = "99";

var random_string = function(digits) {
    var num = Math.floor(Math.random() * (maxRange-firstRange+1)+firstRange).toString();
    while (num.length < digits)
        {
            num = "0" + num;
        }
    return num;
}

var arrayOfNumbers = [];
for (i=0;i<10;i++)
{
    six_digit_string = random_string(2)+random_string(2)+random_string(2);
    arrayOfNumbers.push(firstDigit+six_digit_string);
}

In Python:
import random

def random_two_digit_numbers():
    return str(random.randint(0,99)).zfill(2)

generated_string = '23 29 {} {} {}'.format(random_two_digit_numbers,random_two_digit_numbers,random_two_digit_numbers)


text:
Q: how to set an gcc on arm board so that it can compile for itself i want a compiler on board so that it has the ability to compile for itself. As you known, self compile is a key ability for a "PC". There is ubuntu running on arm board, so if there is a way to setup a gcc on board, then i can use arm board to develop simple program.
Is there a project doing this?
Is there a way port gcc on board?
Any clue can help

A: Certainly, making a self-hosted compiler is possible. The most straightforward way is just to build GCC using the same cross-compiler toolchain you use to compiler "normal" apps for the board. However, it's not a trivial process.
Here are a couple of projects that produce a toolchain that runs on the target itself:
Bootstrap-Linux: https://github.com/pikhq/bootstrap-linux
Aboriginal Linux: http://landley.net/code/aboriginal/ (includes prebuilt binaries)

A: If you have fully functional Ubuntu, just do:
sudo apt-get update
sudo apt-get install build-essential

If you don't have enough memory or apt is missing, you have to manually download packages for ARM architecture and your Ubuntu version from internet to your board, and do
dpkg -i <package_name.deb>

At this stage you can get a lot of unsatisfied depencies, so you have to download and install them too.


text:
Q: Need guidance with aspects of strcpy in C This code is from strcpy in string.c
I am trying to understand a few of the features here:
 char *(strcpy)(char *restrict s1, const char *restrict s2)
 {
     char *dst = s1;
     const char *src = s2;
     while ((*dst++ = *src++) != '\0')
         ;
     return s1;
 }

What is going on in this while loop?
(*dst++ = *src++)
Thanks.

A: (*dst++ = *src++)
There is a lot going on here.
The first thing to note is that this is assigning the value of *src++ to *dst++.
The asterisk dereferences both dst++ and src++, so this is an assignment of one char to another. Note that the ++ operator has higher precedence than the * (dereference) operator. See https://en.cppreference.com/w/c/language/operator_precedence.
The second important detail is that the increments are postfix; ++ is to the right of the variables dst and src. So dst and src are only incremented after the check inside the while is complete. Effectively, this sets the first character in dst to be the first character in src.
So, dst and src increment by one each time the first character of src is not the zero character \0.
For your second question, see What do the parentheses around a function name mean?.
src is declared a const char * because the character(s) it points to are not being modified and this is generally good practice. There are lots of discussions on this on the internet; e.g. https://dev.to/fenbf/please-declare-your-variables-as-const. Note that src itself (the pointer) is clearly modified in the while loop.


text:
Q: System.OutOfMemory exception when trying to read large files public static byte[] ReadMemoryMappedFile(string fileName)
    {
        long length = new FileInfo(fileName).Length;
        using (var stream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
        {
            using (var mmf = MemoryMappedFile.CreateFromFile(stream, null, length, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false))
            {
                using (var viewStream = mmf.CreateViewStream(0, length, MemoryMappedFileAccess.Read))
                {
                    using (BinaryReader binReader = new BinaryReader(viewStream))
                    {
                        var result = binReader.ReadBytes((int)length);
                        return result;
                    }
                }
            }
        }
    }

OpenFileDialog openfile = new OpenFileDialog();
        openfile.Filter = "All Files (*.*)|*.*";
        openfile.ShowDialog();
        byte[] buff = ReadMemoryMappedFile(openfile.FileName);
        texteditor.Text = BitConverter.ToString(buff).Replace("-"," "); <----A first chance exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll

I get a System.OutOfMemory exception when trying to read large files.
I've read a lot for 4 weeks in all the web... and tried a lot!!! But still, I can't seem to find a good solution to my problem.
Please help me..
Update
public byte[] FileToByteArray(string fileName)
    {
        byte[] buff = null;
        FileStream fs = new FileStream(fileName,
                                       FileMode.Open,
                                       FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        long numBytes = new FileInfo(fileName).Length;
        buff = br.ReadBytes((int)numBytes);
        //return buff;
        return File.ReadAllBytes(fileName);
    }

OR
public static byte[] FileToByteArray(FileStream stream, int initialLength)
    {
        // If we've been passed an unhelpful initial length, just
        // use 32K.
        if (initialLength < 1)
        {
            initialLength = 32768;
        }
        BinaryReader br = new BinaryReader(stream);
        byte[] buffer = new byte[initialLength];
        int read = 0;

        int chunk;
        while ((chunk = br.Read(buffer, read, buffer.Length - read)) > 0)
        {
            read += chunk;

            // If we've reached the end of our buffer, check to see if there's
            // any more information
            if (read == buffer.Length)
            {
                int nextByte = br.ReadByte();

                // End of stream? If so, we're done
                if (nextByte == -1)
                {
                    return buffer;
                }

                // Nope. Resize the buffer, put in the byte we've just
                // read, and continue
                byte[] newBuffer = new byte[buffer.Length * 2];
                Array.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (byte)nextByte;
                buffer = newBuffer;
                read++;
            }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
    }

I still get a System.OutOfMemory exception when trying to read large files.

A: You need to read the file in chunks, keep track of where you are in the file, page the contents on screen and use seek and position to move up and down in the file stream.

A: If your file is 4GB, then BitConverter will turn each byte into XX- string, each char in string is 2 bytes * 3 chars per byte * 4 294 967 295 bytes = 25 769 803 770. You need +25Gb of free memory to fit entire string, plus you already have your file in memory as byte array.
Besides, no single object in a .Net program may be over 2GB. Theoretical limit for a string length would be 1,073,741,823 chars, but you also need to have a 64-bit process.
So solution in your case - open FileStream. Read first 16384 bytes (or how much can fit on your screen), convert to hex and display, and remember file offset. When user wants to navigate to next or previous page - seek to that position in file on disk, read and display again, etc.

A: You will not be able to display 4Gb file reading all of it in memory first by any approach.
The approach is to virtualize the data, reading only the visible lines when user scrolls. If you need to do a read-only text viewer then you can use WPF ItemsControl with virtulizing stack panel and bind to custom IList collection which will lazily fetch lines from the file calculating file offset by for the line index.


text:
Q: mySql search using LIKE operator and partial search I have the following code:
$search_str= "I want to be a programmer.";

And I have the following data in mysql database.
I want to be.

I have used: LIKE %$search_str%
But it return no data.
If I search with only " I want" then getting the result.
I want to get the data if any part OR full part is matched.

A: You will need to do the like the other way around and say where your input is like the column.
SELECT *
FROM <TABLE>
WHERE <input> LIKE CONCAT('%', <TABLENAME>.<COLUMNNAME>, '%')

A: To get the results according to your criteria you can add additional like clause in reverse way to match column against your string
select *
from table
where search_column like '%I want to be a programmer.%'
or 'I want to be a programmer.' like concat('%',search_column ,'%')