How to measure the difficulty of a question

Question: This might be a more different question about difficulty than others, and might be a hard one to answer.
I am designing an educative application for tablets. The concept consists of a game where kids aged from about 10 to 12 years oldlearn the proces a certain product or service undergoes. Like the path from a cotton plant to the t-shirt they wear.
I have done my first UX test and had some useful responses. However I am not sure how to measure the difficulty of a question. Is it too hard or is it too easy? I made notes, did observation. Asking questions about this was too suggestive in my opinion.
Have you had this problem before?
Greetings,
Emnaon
Comment: It's more pedagogical field, still you could dig into Item-response theory, which claims among other "For a given ability level, the probability of a correct answer increases as item difficulty decreases." So applying some statistics to the collected data, you could infer the question difficultiness with some probability.
Comment: Can you collect how often the question is answered right vs wrong?
Comment: Perhaps [Cognitive Sciences](http://cogsci.stackexchange.com/) could help.
Comment: Item-response theory and test development are the place to find more information. In the U.S., ETS is a test development organization. [This is a link to a page on their site](http://www.ets.org/understanding_testing/test_development/) explaining test and test item development. Click on the Watch Now link (next to the big Q) for a video about evaluating questions in a test.
Answer: Difficulty of anything is subjective data and will vary from person to person. To identify difficulty of an application we have no other means but to undergo user-testing. To identify difficulty of a question, you would not just need to test it but test it with fairly large group of participants to be sure that what you calculated was difficulty of the question and not the efficiency of participants. For a class of students, performing bad on the question may mean they didn't learn the topic well instead of question being hard. So you will need to test same question with multiple groups of students who had their learning sessions different from the other and only then you can identify questions which are persistently hard and multiple groups were failing on the same.
Apart from this required user-testing, for text-book questions, we can have additional matrices which will help you estimate their difficulty to some level.

If a question requires understanding of multiple topics, you can presume it would be relatively hard to answer than the one which requires understanding of one topic only.
If a question has similar example given in the learning content, that question would be relatively easy solve than a completely new scenario.
Questions having multiple parts would be difficult than the single part question.
Questions in which result of a previous calculation is carried forward would be more difficult than the ones which have independent sections. It may not be called difficult but the percentage of candidates calculating correct result would decrease in such case.
Questions which require recalling of a number or formula would be more difficult.
In case of multiple choice, proximity of possible answers with each other makes the question hard. More closely related answers you have, the more difficult answer would be.


Could not find Java jdk in a directory that has been renamed

Question: I am trying to built a React Native app using Ubuntu 16.04. When I try to run npm run android in the terminal I get this error ERROR: JAVA_HOME is set to an invalid directory: /home/duong/git/Java/jdk1.8.0_144

The weird thing is that I have renamed my "git" folder to "admin" a while ago, and I also have deleted the Java directory in there also. How come npm sees the folder and not me? So now I don't know where the Java jdk is in my system. How can I retrieve the Java folder and set it to default location?
Comment: Presumably you originally set `JAVA_HOME` to `/home/duong/git/Java/jdk1.8.0_144` in one of your shell initialization files (such as `~/.bashrc`) and forgot to change it when you renamed the directory?
Comment: Yeah so I edited the bashrc file to a new path. When I run 'echo $JAVA_HOME' I get the output '/usr/lib/jvm/java-8-oracle'. But when I typed just '$JAVA_HOME' I get this error instead.. 'bash: /usr/lib/jvm/java-8-oracle: No such file or directory
'
Comment: Well `JAVA_HOME` won't be an executable file, it will be a directory - unfortunately I can't tell you where you installed it, you will need to figure that out yourself
Answer: Try ls /home/duong/git/Java/jdk1.8.0_144 Does that dir exist?
You say you renamed the "git" folder to "admin".
Try ls /home/duong/admin/Java/jdk1.8.0_144 Does that dir exist?
Do you have Java installed from a .deb package from the repository?
Try
foo@bar:$ which java
/usr/bin/java
foo@bar:$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 Oct 21  2016 /usr/bin/java -> /etc/alternatives/java
foo@bar:$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 43 Sep 15 19:03 /etc/alternatives/java -> /usr/lib/jvm/java-11-openjdk-amd64/bin/java
foo@bar:$

The system wide install creates the many symlinks seen above. Following these will show you the directory in which java is installed. In the example directly above this is /usr/lib/jvm/java-11-openjdk-amd64
When you find your java install directory, set that as JAVA_HOME
E.g.
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64

or
export JAVA_HOME=/home/duong/admin/Java/jdk1.8.0_144

or whatever directory in which your java is installed.
Then run your npm command.


Including header files in C

Question: I am working on a project in which If I could include a header file at runtime, it would save some programming effort. I google'd about it, but all in vain. My question is :
Can we include header files in a C program at runtime ?
If yes, how?
If not, why?
Comment: What actual problem are you trying to solve? A header file is an input to the compiler, and you don't have the compiler at runtime.
Answer: In C the source files are only read compile-time, so the answer to your question is not. Runtime there is only the executable binary, which has nothing to do with your source code headers.
Answer: Not really, no. Header files are brought in by the compiler to satisfy symbols needed during compilation.
If you simply want values unrelated to compilation, you can always put them in a configuration file which is read at runtime.
Other possible solutions are command line arguments or environment variables but, since you're discussing putting them into a file, the first option is probably the best.
Answer: No header files can't be added at run-time as,
The four stages for a C program to become an executable are the following:
1) Pre-processing
2) Compilation
3) Assembly
4) Linking

and Pre-processing is the very first stage through which a source code passes. In this stage the following tasks are done:
1) Macro substitution
2) Comments are stripped off
3) **Expansion of the included files**

and observation from intermediate file shows that we can get by passing argument to gcc as  gcc -Wall -save-temps hello.c -o hello :
1) All the macros are expanded in the preprocessing stage.
2) All the comments are stripped off.
3) The third observation is that beside the line '#include' is missing and instead of that we see whole lot of code in its place. So its safe to conclude that stdio.h and header files has been expanded and literally included in our source file.

and then compilation of code takes place ..
So including header files before compilation is needed.

Including header files in C


Sandbox with roof, but it floods and sump doesn't do it

Question: Built a roof covered sandbox for my kids, put a tarp at the bottom so groundwater wouldn't raise up, but the opposite problem keeps happening. My kids keep flooding it with water, and the and then becomes compact, hard, and also drains away. I have put the top of a 4L bucket (with 1" holes spaced about 5 inches apart) below the bottom of the sand, covered a sump pump with landscape fabric, filled the bucket with small rocks, covered the top of the sump with larger rocks, then some more landscape fabric, and then sand. Seems the groundwater problem is solved as when it rains, it no longer floods from groundwater, however, when my kids flood the sandbox, rather than the hose water having no effect on the sandbox, it fills up like a swimming pool and the sump fails to drain. Seems that the water is not making its way to the sump through the sand and landscape fabric. Anyone have any ideas on how to make a sandbox that will drain the water away so fast that the tykes cannot possibly flood it?
Thanks!
Comment: your chance to teach your kids about consequences ... tell them that if they flood the sandbox, then they cannot use it until it drains
Comment: You cut a hole through the tarp under the sand and the hole is located over the sump pump basin and the water does not flow into your 4L basin?
Comment: Sand filters in swimming pools work by allowing the water through without letting the sand , you need a fine enough mesh that will not plug up but still allow water flow it sounds like your landscape fabric may be two fine or multiple lay ears created a seal.
Comment: Definitely do **NOT** fix.  Until the kids learn that you aren't going to  repair everything they break, they'll keep on breaking it.   For that matter, why are you letting them anywhere near a water source?  There are far worse things they could think to flood.
Answer: You may have two issues with water not draining out of the sandbox.
1. The sand is becoming compact and hard.  Use clean sand, purchased from a big box store in bags.  It seems your sand is mixed with other material that makes it solidify.  Sand from a rock place may be acceptable, but I have no idea how clean it is.
2. As Ed stated, you have too much filtering on top of your sump basin.  Your screen filter only needs at most two layers of screen door mesh.


How to remove tags from react-native-render-html?

Question: How do I remove h2 tags that has only
 tag?

Comment: did my proposition solve your issue? If that is the case, please confirm the answer for the good of the community :-)
Answer: You can use alterChildren prop to delete some DOM nodes:
const html = `

Hello world

Lorem ipsum

`;

function hasOnlyBrChildren(node) {
  return node.children.every(
    (child) => child.type === 'tag' && child.name === 'br'
  );
}

function alterChildren(node) {
  return node.children.filter(
    (child) =>
      child.type !== 'tag' ||
      !(child.name === 'h2' && hasOnlyBrChildren(child))
  );
}

export default function App() {
  return (
    <ScrollView>

    </ScrollView>
  );
}

I made a snack here (I just replaced br with div to visually assess the effectiveness of the function): https://snack.expo.io/@jsamr/rnrhtml-alter-children


Inserting a line in text file through perl is failing

Question: I am trying to insert a new row on 2nd line of text file using perl . But it keeps failing.
I am using below command to achieve the same.
<code>  perl -ni -e "print; print \"permissibleCars = [ ${part[*]} ]\n\" if $. == 2" query/containerId_count.js
</code>
But I keep getting error :--
<code> root@vm-test-001:~/mongosearch# distinct_array=`sed ':a;N;$!ba;s/\n/ /g' output/ontainerId_distinct.txt`
 root@vm-test-001:~/mongosearch# declare -a arr=($distinct_array)
 root@vm-test-001:~/mongosearch# batchsize=1
 root@vm-test-001:~/mongosearch# IFS=,
 root@vm-test-001:~/mongosearch# part=( "${arr[@]:i:batchsize}" )
 root@vm-test-001:~/mongosearch# echo $part
 "C:00000092666270:53882159774"
 root@vm-test-001:~/mongosearch# perl -ni -e "print; print \"permissibleCars = [ ${part[*]} ]\n\" if $. == 2" query/containerId_count.js
 Bareword found where operator expected at -e line 1, near ""permissibleCars = [ "C"
    (Missing operator before C?)
String found where operator expected at -e line 1, near "53882159774" ]\n""
    (Missing operator before " ]\n"?)
syntax error at -e line 1, near ""permissibleCars = [ "C"
Illegal octal digit '9' at -e line 1, at end of line
Execution of -e aborted due to compilation errors.
</code>
Can you help me with same ?
Regards
Comment: Tried that but it didnt  work :-- Can't find string terminator '"' anywhere before EOF at -e line 1.
Comment: >> `perl -ni -e 'print; print "permissibleCars = [ \${part[*]} ]\n" if $. == 2'`
Comment: This wont give error but it will not copy the data stored in variable rather it copied permissibleCars = [ ${part[*]} ] as text.
Comment: So, add to the question what `${part[*]}` should return in your case.
Comment: that is already there :-- root@vm-test-001:~/mongosearch# echo $part
 "C:00000092666270:53882159774"
Comment: `${part[*]}` => `$ENV{part}`
Comment: This also didnt help
Comment: Look at $part. It's a string wrapped in quotes. And perl sees this `print "permissibleCars = [ "C:00000092666270:53882159774" ]\n"`.
Comment: @user2854333 You are in linux so use single quote to run the one liner.  `perl -ni -e 'print; print  "..." '`
Answer: Try this:
<code>export PARTS=${part[*]}
perl -lni -e 'print; print "permissibleCars = [".join(",",split/ /,$ENV{PARTS})."]" if $. == 2' query/containerId_count.js
</code>
And
In linux platform we should use single quote for one liner. From Perl black book see page number 19 and 20.
Comment: No, this seems to be having strange issue . It is randomly adding adding ] and triming the objects inside array .
Comment: @user2854333 Then what is the output you get with this command here? Looks like the issue is with how you construct `${part[*]}`.
Comment: It is a array which hold holds value as subset from array. It can be like "C:1000817:57160911940","C:1000817:57176485410","C:1000817:57205942228","C:1000817:57211484466","C:1000817:57215240125","C:1000817:57218809582","C:1000817:57221636702","C:1000817:57235388574","C:1000817:
57237335061","C:1000817:57239290315","C:1000817:57250543857","C:1000817:57250575736","C:1000817:57303722225","C:1000860:379598081","C:1000882:379598272","C:1000960:379598451"
Comment: Also, I was able to do using sed but  it is POSIX standard sed implementation, the byte length limit is 8192 bytes.
Comment: Ok, got it. And then in your perl script, do you need `part` as an array, or as a flat string?
Comment: when it inserts into a js file i want the second line as permissibleCars = [ "C:1156646:3445705296","C:1156646:54617499","C:1156666:54619560","C:1157183:54673215","C:1157748:1725390682"]
Comment: Note I just updated the answer. This should fix several issues.
Comment: Thank you. I think my initial issue is with Mongo itself where it is not taking complete list.
Comment: Did this perl command work for you? You can `echo $PARTS` to see if the list is complete.
Comment: Downvoting went a bit rude here. It was an obvious syntax problem right from the beginning. Nice day.


Add Numbers in ReactJS without button

Question: Seems like an easy task to add few number but I am not getting any
luck without usage of explicit button to add numbers.
  // Defining useState

  const [ totalCount, setTotalCount ] = useState(0)

  // User Can change count of fruits by increment or decrement operator

  const addNum = (apples,mango,orange) => {
    setTotalCount(parseInt(apples) + parseInt(mango) + parseInt(orange))
  }

  console.log("Total Number of Fruits", totalCount)

Desired Answer : Some number between 0 and 3
Answer getting : NaN
Comment: You have to show how you call `addNum`. Also, my guess is that if apples, mango, and orange are state (because user can change the count of fruits by an operator), then `totalCount` is not actually state
Answer: The component will track the quantities of individual items. The sum of the items is derived state and should NOT be saved as state of its own. Instead compute the sum on-the-fly -

function App({ items = [] }) {
  const [counts, setCounts] = React.useState(new Map)
  const update = (key, amount) => event =>
    setCounts(m => new Map(m).set(key, (m.get(key) || 0) + amount))
  return

    {items.map(item =>
      <Item key={item} item={item} count={counts.get(item) || 0} update={update} />
    )}
    total: {[...counts.values()].reduce((a,b) => a + b, 0)}

}

function Item({ item, update, count }) {
  return

    <button type="button" onClick={update(item, -1)} children="➖" />
    {item}: {count}
    <button type="button" onClick={update(item, 1)} children="➕" />

}

ReactDOM.render(<App items={["", "", ""]}/>, document.body)

Decomposition of a generic update and sum function allow you to keep the component logic simplified and allow these functions to be reused in other areas of your program -
function updateCount(map, key, amount) {
  return new Map(map).set(key, (map.get(key) || 0) + amount)
}

function sum(iter) {
  return [...iter].reduce((a,b) => a + b, 0)
}

function App({ items = [] }) {
  const [counts, setCounts] = React.useState(new Map)
  const update = React.useCallback((key, amount) => event =>
    setCounts(m => updateCount(m, key, amount)),
    []
  )
  return

    {items.map(item =>
      <Item key={item} item={item} count={counts.get(item) || 0} update={update} />
    )}
    total: {sum(count.values())}

}

Comment: @LonelySoul it would be against the react pattern to use `document.getElementById`. instead use a [controlled component](https://reactjs.org/docs/forms.html#controlled-components).
Comment: Thanks Mulan. Does it matter to use "documentByID" as search for these strings and convert to those in numbers and then add.

Add Numbers in ReactJS without button


Get orientation from video or thumb obtained with AVAssetImageGenerator

Question: In my application I create videos from single images. Everything works fine, videos are assembled correctly with right size and orientation. They are displayed correctly both in the Apple photo app, from MPMoviePlayer and from the sandbox directory where I save them.
The problem arise when I try to get a thumb from a movie. The orientation is not correct and I don't know how to fix, I've seen that there is a -preferredTransform property but the result is the the same for both landscape and portrait videos.  The url I'm using is the sandbox directory path.
Here is the snippet:
- (void) setVideoPath:(NSString *)videoPath {
    if (videoPath ==_videoPath) {
        return;
    }
    _videoPath = videoPath;
    AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:_videoPath]];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
    CMTime time = CMTimeMake(1, 1);
    CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
    UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    self.videoImageView.image = thumbnail;
}

Answer: Just use this, No need to write any methods
generator.appliesPreferredTrackTransform=true

Answer: SWIFT version
            // generate thumb from video and set it
        var err: NSError? = nil
        let asset = AVURLAsset(URL: NSURL(fileURLWithPath: videoPath! as String), options: nil)
        let imgGenerator = AVAssetImageGenerator(asset: asset)
        imgGenerator.appliesPreferredTrackTransform = true
        let cgImage: CGImage!
        do {
            cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(0, 60), actualTime: nil)
            let thumbnail = UIImage(CGImage: cgImage)
        } catch let error as NSError {
            err = error
            cgImage = nil
        }

Most important line for orientation:
imgGenerator.appliesPreferredTrackTransform = true

Answer: For the moment I've found a trick, find the video rotation and apply to the thumbnail. It seems to work but I'm pretty sure there is another way around.
The solution is taken from this gist, credits to Luca Bernardi.
{
//..
        NSArray *videoTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
        AVAssetTrack* videoTrack    = [videoTracks firstObject];
        CGAffineTransform txf       = [videoTrack preferredTransform];
        if (txf.a == 0 && txf.b == 1.0 && txf.c == -1.0 && txf.d == 0) {
            thumbOrientation = UIImageOrientationRight;
        }
        if (txf.a == 0 && txf.b == -1.0 && txf.c == 1.0 && txf.d == 0) {
            thumbOrientation =  UIImageOrientationLeft;
        }
        if (txf.a == 1.0 && txf.b == 0 && txf.c == 0 && txf.d == 1.0) {
            thumbOrientation =  UIImageOrientationUp;
        }
        if (txf.a == -1.0 && txf.b == 0 && txf.c == 0 && txf.d == -1.0) {
            thumbOrientation = UIImageOrientationDown;
        }
        UIImage *thumbnail = [UIImage imageWithCGImage:imageRef scale:[[UIScreen mainScreen]scale] orientation:thumbOrientation];
//..
}

Answer: -(UIImage *)generateThumbImage : (NSURL *)url
{
     AVAsset *asset = [AVAsset assetWithURL:url];
     AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
     imageGenerator.appliesPreferredTrackTransform = YES;
     CMTime time = [asset duration];
     time.value = 0;
     CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
     UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
     CGImageRelease(imageRef);  // CGImageRef won't be released by ARC
     return thumbnail;
}

Where url is video url.


Flexible functions R

Question: I have written some code to create my own descriptive statistics table since the default summary doesn't do what I want.
Now what I would like is to create a flexible / dynamic function that does this with varying number of variables.
My code looks like this:
N <- c( length(data1), length(data2), length(data3) )
mean<- c( mean(data1), mean(data2), mean(data3) )
sd <- c( sd(data1), sd(data2), sd(data3) )
min <- c( min(data1), min(data2), min(data3) )
max <- c( max(data1), max(data2), max(data3) )
print(q) <- data.frame(N, mean, sd, min, max)

So instead of editing this if i want descriptive of something else than 3 variables I would like a function that did something like this;
descriptive <- function(data1, ...) {
  N <- c( length(data1), length(...) )
  mean<- c( mean(data1), mean(...) )
  sd <- c( sd(data1), sd(...) )
  min <- c( min(data1), min(...) )
  max <- c( max(data1), max(...) )
  q <- data.frame(N, mean, sd, min, max)
  print(q)
}

I tried the above and hoped it would work, but it only works with two variables. As you might see, I am new to R. I have tried to search for a solution, but I've not been able to find one. But if R is as good as "they" say, I think something like this should be possible.
There's probably a function that already does this, but I would like to be able to do it my self. (: Hope someone can help me!
EDIT!!
Thank you all for your answers, they all seem to work. This shows there are multiple answers to the same question in R. I don't know if you get points for the accepted answer and if this is important, but I choose Arun answers since it comes closed to my aim of creating a descriptive table that is "good looking" and flexible.
If anyone in the future is interested I've add this to Arun answer that makes it fit my purpose perfect;
data <- list(var1, var2 ...)
names <- c"name1", "name2", "...")
descriptive(data)

This solution also seems to have the benefit of variables of different lengths vs data frames.
Answer: This would be a good opportunity to learn the apply family of functions, so that you can specify your intended output as a function and then apply that to a dataframe.
mydf <- data.frame(x=rnorm(100), y=rnorm(100)) # example data

descriptive <- function(x)
   c(length=length(x), mean=mean(x), sd=sd(x), min=min(x), max=max(x))

sapply(mydf, descriptive) # apply `descriptive` to the df

The output:
                   x             y             z
length  1.000000e+03 1000.00000000 1000.00000000
mean    3.846765e-03   -0.02009427    0.02001385
sd      9.818488e-01    0.97662850    1.01543571
min    -2.905149e+00   -3.25904432   -3.33017918
max     3.235993e+00    2.86892044    3.13183601

One caution with this is that unless you develop a more sophisticated descriptive function, it won't be able to handle NA values in your data and will cause you problems for variables of different classes in the dataframe (e.g., the mean of a character vector is NA).
This is also more efficient than building a function that internally applies to a list of vectors (as Arun suggests) and plyr (from Baptiste: ldply(mydf, each(length, mean, sd, min, max))):
mydf <- data.frame(x=rnorm(1e5),y=rnorm(1e5),z=rnorm(1e5))
microbenchmark(sapply(mydf,thomas), arun(mydf), baptiste(mydf))

Unit: milliseconds
                 expr       min        lq    median        uq      max neval
 sapply(mydf, thomas)  5.693252  6.039458  7.139658  7.953309 43.32675   100
           arun(mydf) 15.805778 18.522889 19.417559 22.016125 57.93630   100
       baptiste(mydf) 10.995073 11.597998 12.666252 13.861521 47.85533   100

Comment: `apply` and data frames don't go well together, since it turns its argument into a matrix. Use `lapply` instead.
Comment: with plyr, `ldply(mydf, each(length, mean, sd, min, max))`
Comment: @baptiste I like that syntax, it's very succinct.
Answer: If you really want to be able to use ...:
test <- list( seq(10), seq(5) )

descriptiveRow <- function(x) {
  res <- c(length(x), mean(x), sd(x), min(x), max(x))
  names(res) <- c("N","Mean","SD","Min","Max")
  res
}

descriptive <- function( ... ) {
  l <- list(...)
  res <- as.data.frame( lapply( l, descriptiveRow ) )
  colnames(res) <- seq(ncol(res))
  res
}

descriptive(test[[1]], test[[2]])

> descriptive(test[[1]], test[[2]])
            1        2
N    10.00000 5.000000
Mean  5.50000 3.000000
SD    3.02765 1.581139
Min   1.00000 1.000000
Max  10.00000 5.000000

Answer: You can provide a list as input to your function argument and then use sapply on each to get the statistic for each data.
descriptive <- function(ll) {
    N <- sapply(ll, length)
    mean <- sapply(ll, mean)
    sd <- sapply(ll, sd)
    min <- sapply(ll, min)
    max <- sapply(ll, max)
    print(out <- data.frame(N, mean, sd, min, max))
}

descriptive(list(1:5, 6:10))

  N mean       sd min max
1 5    3 1.581139   1   5
2 5    8 1.581139   6  10

Note: This'll work even if your input is a data.frame and you require statistics on all columns of your data.frame (as it's internally a list).
descriptive(data.frame(1:5, 6:10))
      N mean       sd min max
X1.5  5    3 1.581139   1   5
X6.10 5    8 1.581139   6  10

Comment: Or use `function(...) ll <- list(...)`

Flexible functions R


What's the effect of crouching in Alien Swarm?

Question: I saw that it is possible to crouch in Alien Swarm, but I didn't really understand its purpose.
Can someone explain it to me?
Answer: It's not possible to crouch, it's possible to walk (default binding is shift). When stationary and walking, the animation will show the marine crouched.
The purpose of walk is to be able to move slower when necessary (a rarity in my opinion), and also the minigun is constantly spinned when walking, just like if the alt fire is pressed. Oh, and it looks cool. That's about it.
All this is assuming you don't mean the defensive roll maneuver, which is something else completely, and allows you to evade projectiles (both enemy's and ally's).
EDIT: I've seen some posts in other forums that mention that "crouching" may improve accuracy (i.e. decrease the bullet spread). I've never noticed anything like this, and I browsed the game's source code and it seems that bullet spread does not depend on the stance.
Comment: And all this time I was *crouching* hoping to improve my aiming...
Comment: I was thinking the same as Juan. Oh god :) Thank you for the explanation
Comment: +1 for the tip about the minigun. Here I was thinking it was just extremely difficult to use!
Answer: Crouching is achieved by holding down the walk button (shift) and not moving. It doesn't improve your aim, but lowers your profile. Marines standing behind you will shoot over you without hitting you, pretty useful when you're in a crowded passage.
Edit: After @Oak pointed out it didn't work for him, I did some experimenting. It turns out that the effect is so small that it only works when shooting at targets on higher ground. So it's pretty useless, basically.
Comment: Are you sure? I just tested it and bullets from friendly marines definitely hit and damaged me when I was "crouching" (holding shift when stationary).
Comment: The effect is minimal, you'll only notice a difference if you're aiming upwards (e.g. if aliens are on higher ground). So it's mostly useless.


Using factor theorem on a multivariable function

Question: Q: Use the factor theorem to show that $a + b - c$ is a factor of $f(a, b, c) = (a+b+c)^3 - 6(a + b + c)(a^2 + b^2 + c^2) + 8(a^3 + b^3 + c^3)$ and hence factorise completely.
I know that the factor theorem states for $f(x)$ if $f(a) = 0$ then $x-a$ is a factor but when there are multiple variables how do you use factor theorem?
Comment: Write it as a polynomial in $c$ with  coefficients - polynomials in $a,b$. Then plug in $c=a+b$. You should get $0$, this will imply that $c-(a+b)$ is a factor, hence $(a+b-c)$ is a factor too.
Comment: are you sure there is no typo? Could it perhaps be $-6$ rather than $+6$?
Comment: @DavidQuinn my mistake yes, I'll edit it shortly
Comment: @markvs I can see if $c- (a+b) = 0$ that $a+ b - c=0$ but why would $a + b - c$ be a factor if $c - (a+b)$ is?
Comment: $a+b-c=-(c-(a+b))$
Answer: Hint...if you replace each $c$ term with $(a+b)$ and expand and simplify, the entire expression is zero, so $(a+b-c)$ is a factor.
Now write down two other similar looking factors, using the fact that the whole expression is symmetrical in $a,b$ and $c$ - i.e the letters are interchangeable.
All you need to do then is to decide what is the numerical factor which will complete the factorization by comparing coefficients...
Answer: Here is a compilation of my comments. Denote $c$ by $x$, write your polynomial as a cubic polynomial in $x$ whose coefficients are polynomials in $a,b$:
$$f(x)=f_0(a,b)x^3+f_1(a,b)x^2+f_2(a,b)x+f_3(a,b).$$
Plug in $x=a+b$, you get $f(a+b)=0$. So by the theorem, $x-(a+b)$ is a factor of $f(x)$: $f(x)=(x-(a+b))g(x)$. Then your original polynomial $f(c)=(c-a-b)g(c)=(a+b-c)(-g(c))$, so $a+b-c$ is a factor.
Answer: We are given that
$$ f(a,b,c) := (a+b+c)^3 - 6(a+b+c)(a^2+b^2+c^2) + 8(a^3+b^3+c^3).$$
Define three power sum polynomials
$$ p_1(a,b,c) := a+b+c, \quad p_2(a,b,c) := a^2+b^2+c^2, \quad p_3(a,b,c) := a^3+b^3+c^3. $$
Notice that
$$ p_1(a,b,a+b) = 2(a+b), \qquad p_3(a,b,a+b) = (a+b)(2a^2+ab+2b^2). $$
Define a one variable polynomial $\,P(x) := f(a,b,x)\,$
and rewrite  $\,P(a+b) = f(a,b,a+b)\,$ in terms of power sums to get
$$ P(a+b) = 8(a+b)^3 - 12(a+b)(a^2+b^2+(a+b)^2) + 8(a+b)(2a^2+ab+2b^2) $$
which factors further as
$$ P(a+b) = (a+b)\left( 8(a+b)^2 - 12(-2ab+2(a+b)^2) +
 8(-3ab+2(a+b)^2)\right) $$
and simplify to get
$$ P(a+b) = (a+b)\left( (8-24+16)(a+b)^2 + (24-24)ab \right) = 0. $$
Use the factor theorem to get that $\, P(x) \,$ is divisible
by $\,x-(a+b).\,$ In particular, this implies that $\,P(c) = f(a,b,c)\,$
is divisible by $\,c-(a+b) = -(a+b-c).\,$


PMF for total on a random number of dice?

Question: I am not sure how to do this, I know the PMF of rolling a dice is:
$$
P(x)=\begin{cases}
1/6 &x\in\{1,2,3,4,5,6\}\\
0& \text{Otherwise.}
\end{cases}
$$
Answer: Hint:
The mean can be found on base of:$$\mathbb E(Y)=\sum_{i=1}^6\mathbb E(Y\mid N=i)P(N=i)$$
Answer: You can use generating functions to see the pmf of the sum. The pmf, when you increase the number of addends, tends to be a normal shape, what is the content of the central limit theorem.
If you represent the sum $Y$ as a random variable composed of $N_i$ identical random variable and you apply the theorem about linearity of expectation
$$\Bbb E[Y]=\Bbb E(N_1 +N_2 + N_3+...)=\Bbb E[N_1]+\Bbb E[N_2]+\Bbb E[N_3]+...$$
Comment: what is the generating function ?do you mean the Probability generating Function (PGF) ?
Comment: @user315934 I mean that you can use a generating function to build a function to extract the coefficients, i.e., to create the PMF. See [here](http://math.stackexchange.com/questions/992125/rolling-dice-problem/993044#993044).
Answer: Comment:
This seems to 'a random sum of random numbers': $Y = \sum_{i=1}^N D_i,$
where $N$ is found by rolling a fair die and, independently the $D_i$ are also found by rolling fair dice. Then standard formulas are
$E(Y) = E(N)E(D)$ and $V(Y) = E(N)V(D) + V(N)[E(D)]^2,$ which can
be proved by conditioning methods as in another hint.
A simple simulation in R of 100,000 such sums gives the following
numerical and graphical results, which you can compare with
your analytic answer:
<code> m = 10^5;  y = numeric(m)
 for (i in 1:m) {
    n = sample(1:6, 1)
    y[i] = sum(sample(1:6, n, repl=T)) }
 mean(y);  var(y)
 ## 12.23903  # approx E(Y) = 3.5(3.5) = 12.25
 ## 46.13508  # approx V(Y)
</code>
The simulated PDF is 'lumpier' than I guessed, but several
runs of the simulation gave similar results.


Mockito @Before method is called after @PostConstruct

Question: This is my simplified code:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MockitoSpringBootTest {

    @MockBean
    private MyBean myBean;

    @Before
    private void before(){
        Mockito.when(myBean.getSomeString()).thenReturn("TEST"));
    }

}

@Service
private class TestClass {

    @Autowired
    private MyBean myBean;

    @PostConstruct
    public void initialize() {
        myBean.getSomeString(); //SmartNull - method is not stubbed yet
    }

}

My problem is that I need to stub MyBean methods, before any other class which has this object autowired will run @BeforeClass method. Right now @Before method is executed after @PostConstruct of any class which is autowiring this bean (there's more than one).
MyBean is autowired as a mock, but method is not stubbed, so I get: "SmartNull returned by this unstubbed method call on a mock:"
Is there any way to set priority of mocked bean in Spring container initialization ?
Comment: Which is as expected. The application context is initialized before the test method can be executed and hence it will construct all the beans. The `@Before` is called right before the test method gets executed and the context has already been initialized. There is nothing you can do to change this when using `@MockBean` like this. You could create a specialized configuration and manually mock the bean and directly register the behavior you want, that would be the only workaround.
Comment: This is not valid syntax. You can't annotate an initializer block. `@Before(){` You're missing a semicolon after `private MyBean myBean`. There's an extra parenthesis on the end of the `("TEST"))` line. Please run your code before you post it.
Comment: Has `myBean` already been autowired when the `@PostConstruct`-method is invoked, or is it still `null` then?
Comment: @isnot2bad yes - it's autowired as mock, but methods are not stubbed yet so smart null is returned
Comment: Does the initMocks() been invoked?
Comment: Yes, but it's inside @Before method, so it's  after PostConstruct method is called (to late)
Answer: Using @TestConfiguration rather than using the @MockBean might help to solve this problem.
@TestConfiguration
    static class Configuration {
        @Bean
        public BeanToMock name() {
            // return mock object
        }
    }

And annotating the test class with @ContextConfiguration:
@ContextConfiguration(classes = TestClassName.Configuration.class)

Answer: Maybe not the most elegant workaround, but you can mock the behavior within a static block. Code in static block is executed before both @Before and @PostConstruct. I don't think, that mocking using annotations (@MockBean) would work, but it can also be done programatically.


Some unicodes in Android EditText can not show correctly

Question: I just found that the following red marked unicodes can not be shown on Android EditText
Anyboday has met similar issue? And how can I resolve this issue?
Edit again:
I attached another picture to shown the unicode and the corresponding result in Android
Comment: There is only one Unicode, and it is a standard. Those marked things are not standards, so they are not obviously not "Unicodes".
Comment: No, They are all unicode, and you can find them in : http://en.wikibooks.org/wiki/Unicode/List_of_useful_symbols
Comment: That mentions "symbols" not "Unicodes".
Comment: No, they are unicode!
Answer: If you find that you are trying to use characters that are not in the standard android font then you might consider using a custom font like DejaVuSans.ttf (I use this one for Maths symbols). You display the character by entering its unicode symbol in the format \u...
Start searching for ttf files ... I think it is likely that you will find one that contains the characters you require.
Be aware that this will probably increase the size of your app by 1MB (based on DejaVuSans.ttf).
Information on how to use a custom font can be found here (you don't have to use a sub directory but you should put the file under assets):
Android - Using Custom Font


Why would bridging Neutral and Ground trip a GFCI breaker?

Question: I have a main breaker + GFCI combo breaker in my panel. I decided to do some work on an outlet and accidentally bridged ground and neutral, with the room breaker off and the live wire dead. The GFCI popped. The house had electricity except for the room. Is this supposed to happen? If so, why?
Thank you.
EDIT: The breaker is formally an RCCB. The house is single phase, Europe.
Comment: Did you double check that the power was off to that outlet.  Cables can use weird routes, just because an outlet is in a room, does not mean that room breaker powers it.
Comment: I had a device connected to the outlet. When I flipped the room breaker, the device turned off.
Comment: I also checked the wires with a wire tester(?) (a screwdriver with a lightbulb that you bridge with yourself)
Comment: Where in Europe is this? The electrical codes across Europe differ quite a bit
Comment: I live in Greece.
Answer: You created a ground fault.
So it worked exactly as it should have.
Rather than the current in the live and the current in the neutral being equal (or within 30 mA for most European RCCBs, 5 mA for most USA/Canada GFCIs) some of the current (more than 30 mA, evidently) traveled on ground, and wasn't showing up as equal on the neutral, so the RCCB said "we have a leak, shut it down!"
That's exactly what it's supposed to do.
If that happened on your "Whole house" RCCB when the room breaker was off, you may have incorrectly shared neutral wires. The RCCB is still doing its job correctly, but your house may have some improper wiring. Since all neutrals are normally connected, and don't get shut off with the breaker, the "whole house" nature of the RCCB means that a neutral-ground connection anywhere in the house will make a fault. [this is not the way USA/Canada folks (or I, anyway) normally think since we have single-circuit GFCIs for the most part, and there, if the circuit is off, the GFCI on the circuit is also off; so a GFCI trip elsewhere would mean an improperly shared neutral.] With a whole house RCCB, that's perfectly normal, as I think it through..
The returning current from a device/appliance whose breaker was still on found the short to ground through the house's neutrals to be the path of least resistance.
Comment: In Poland, and as far as I know in the whole European Union, a whole house GFCI is normal, and actually preferred, second only to having separate GFCI on all circuits, or "circuit blocks" (don't know the proper name, like all lights, all hardwired appliances, etc.). It is actually forbidden (exceptions apply) to make new installations with some circuits with GFCI and some without because this may cause false appearance of security. If any circuit in the panel requires it, all should have it so there is no chance someone will think circuit is protected against ground faults when it isn't.
Answer: Yes, typically a European house has a "whole house RCD" aka GFPE that serves at least several circuits at a time, if not the whole house.
I won't call it a GFCI because GFCIs are human safety rated with 5mA sensitivity (which is too sensitive for a whole house)... and RCD/GFPE are not (with 30mA sensitivity).
Current flows in loops.  Power comes out the live and back the neutral.  One easy way to spot trouble is to compare the two currents. They should be equal at all times.   If the currents are not equal, we know current is leaking out via a third path. It's not supposed to do that.   This is how GFCIs and RCDs work.
Note this method does not need to care about the ground wire, and indeed, they are not connected to ground at all.  (well GFCI receptacles are because they need ground for the socket, but the GFCI doesn't use it.)
Many normal branch circuits have circuit breakers that interrupt the live, but don't interrupt the neutral. Why bother, after all, since neutral current can't be more than live current unless it's crossed with another circuit.
When you shorted neutral to earth, you created a path around the RCD for ordinary neutral current in the house.  Some of it came out your branch circuit (since the breaker does not disconnect it), over to earth, and back to the system equipotential bond which is on the utility side of the RCD.  This path caused that neutral current to bypass the RCD.  Third path! Trip!
Comment: In France, in 40 year old installations you get a 500mA whole house RCD, and unipolar breakers/fuses. In ~20 year old installations, 30mA whole house RCD plus bipolar breakers. More recent installations, several 30mA RCDs, usually one per line of breakers on the panel, and bipolar breakers. Having several RCDs is nice to save your freezer contents.
Comment: This really depends on where in Europe you are. I have never seen a whole house GPFE, in NL there is a maximum of 4 16A circuits on one 30mA RCD.
Also, a normal ciruit breaker here would disconnect BOTH live and neutral, so there should be no way for current to flow from neutral to ground.
Comment: The (few) UK cases I've seen have RCDs for individual circuits _and_ a 'master' one for the whole house. Is that common?
Comment: @Pelle I see a lot of European and UK panels and yours is not the norm. "One RCD to rule them all" is common esp. on older or smaller homes, and neutral-switching is uncommon.  Nonetheless, I couched the language to be less absolute.
Comment: @gidds I suspect you are confusing MCBs with RCDs.


Hot to ground is 120v but hot to neutral is 90v

Question: See Diagram

I have a switch that controls a light as seen in this diagram. There is no neutral at the switch, instead, it picks that up from somewhere else. In the light receptacle it pigtails into the light and continues to the garage.
I measure 120v between the source hot and ground, and 120v when the switch is on between the hot lead and ground. In the light box, with the light disconnected I get 19v from neutral to ground. with or without the light, I get 90v between the hot to neutral.
In the garage, the outlets read out 120v and everything connected to them seem fine (work).
What is the right way to diagnose this? Any ideas why I'd be getting 20v in the neutral?
Comment: Can you post some photos of what's going on here?
Answer: Basically the neutral has current trying to return back the the transformer and is dropping voltage due to how a neutral is simply a series circuit.
When the source hot passes thru the light (as a parallel circuit), it continues out the neutral without dropping voltage.
The problem with this circuit is the neutral and hot do not originate in the same junction box and is very confusing not only DIY's but also electricians, not to mention a Code violation.
Comment: Thank you for this. Your comment about the neutral not originating in the same box got me thinking. I started tracing wires and discovered this neutral was connected to a 3way switch that was miswired. I also got to find another light that was used as a jbox and packed with cloth wiring... Ugh.


Using rvest to get the number of confirmed cases of coronavirus

Question: I am trying to create a scraper to get updates on the number of cases of coronavirus and I am using the page below.
When I give the xpath to the number of confirmed cases it shows "0" and not the real number that apears on the page when I inspect it Google Chrome's Dev Tools. Does anyone knows what is wrong here?
library(rvest)

response = read_html('https://news.qq.com/zt2020/page/feiyan.htm', encoding = 'GBK')

response %>%
  html_node(xpath = '//*[@id="charts"]/div[3]/div[1]')

{html_node}

[1]
0

[2]
全国确诊

Comment: The data is probably being dynamically loaded using Javascript. When I use dev tools to see which files are being download (the Network tab in Firefox's dev tools, not sure about Chrome), I see a JSON file with a name like `disease_h5` that seems to contain the numbers, you might be able to get that JSON data directly.
Answer: As mentioned by @Marius you can get the data from JSON file which is loaded. I got the url from the developer tools, read the html as text and get the number which is followed by "confirm".
url <- 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery34108850961227842673_1580448523488&_=1580448523489'

library(rvest)
url %>%
  read_html() %>%
  html_text() %>%
  stringr::str_match('confirm.*?(\\d+)') %>% .[,2] %>% as.integer()

#[1] 9731


Trying to remove indicator-KDEconnect

Question: Screenshot
Okay been trying remove this and it keeps giving me some trouble, tried many many commands and it usually has this error.
E: The repository 'http://ppa.launchpad.net/webupd8team/indicator-kdeconnect/ubuntu groovy Release' does not have a Release file.
Answer: The reason you get the error message is because the PPA maintainer has not updated the packages inside it for the release of Ubuntu you're running.
However the good news is, Martin Wimpress has a maintained PPA which does have an up to date KDE Connect Indicator package for Ubuntu 20.10.
https://launchpad.net/~flexiondotorg/+archive/ubuntu/indicator-kdeconnect
You can remove the .list file for the PPA you no longer need, which you will find in <code>/etc/apt/sources.list.d</code>.

Trying to remove indicator-KDEconnect


UIScrollView - Moving view to front, but below scroll indicators

Question: I am working with a custom view which inherits from UIScrollView. The problem I am having is adding a UILabel that should be displayed at the 'top', in front of the other views. It works, but unfortunately it also covers up the scroll indicators.

As you can see, the scroll indicator is being obscured. I don't want to disable scroll indicators.
I am adding the views directly to the UIScrollView:
UILabel *subsection = [[UILabel alloc] initWithFrame:CGRectMake(0, y * h,
    [self totalContentWidth], [tableViewDelegate rowHeight])];
[subsection setText:subsectionName];
[subsection setTextAlignment:NSTextAlignmentCenter];

[subSectionRows setValue:subsection forKey:key];

[self addSubview:subsection];

and then bringing them to the front, which
- (void) bringSubsectionsToFront {
    for (UIView* row in [self.subSectionRows allValues]) {
        [self bringSubviewToFront:row];
    }
}

This behavior is confusing to me. If I peek at UIView.layer.zPosition of all the UIScrollView's subviews, they are all the same.
If I adjust the bringSubsectionsToFront method to instead move the labels in front of the view that contains the grid lines, the behavior is the same.
Looking at some internal view classes whose behavior works, it looks as if they are being added to the scroll view with: [self insertSubview:cell atIndex:0];
What am I missing here?
Solution:
verec remarked that I could find the bars if I really wanted to. So I iterated over the subview list at a suitable point, and sure enough, there they were. The order of the objects was as follows:
CustomCell
...
UIImageView
UIImageView
CustomBorderView
UILabel
UILabel

Assuming this is the z ordering, no wonder my labels were always on top.
Solution becomes simple; add UILabel's after CustomCells. This solution only works because the custom table adds CustomCells at index 0, which I believe makes scroll indicators appear after the CustomCells. If this assumption holds, I can reorder the other views relative to the CustomCells, achieving the layering effect I want.
Answer: The simplest is to use and intermediate UIView, call it 'contentView' whose children are the views you want to bringToFront.
If that contentView is what is inside the scrollView, it will stay 'below' the scroll indicators whichever contentView child you bring to the front.
The alternative would be to scan into the scrollView looking for the scroll indicators (you will find them!) but that's a compatibility risk, as you never know if/when Apple may decide to remove/reshape/reposition them according to some new (flatter ...) design paradigm ...


What do the neutral and ground connectors in outlets connect to?

Question: I have reviewed the answers and explanations about switching from 4 prong to 3 prong connections on a clothes dryer and grounds and neutral wires and the old way and the safer new way and the 240 volt phase shift that makes it possible to use the old (3 prong) neutral connection as a ground or substitute ground for the green wire when changing from 4 prong to 3 prong. I have a two part question which if I know the answer I think it will help me get the full grasp of this.
A) On the older 3 prong dryer outlet (NEMA 10-30), what is the neutral or ground connected to under the house (water pipe? nothing?)
B) On the newer 4 prong dryer outlet (NEMA 14-30), what are the 2 neutral/ground connectors connected to? (same water pipe? different water pipe?)
Comment: Electric wiring is done differently in different places. You should state where you live.
Answer: Neutrals, grounds, NEMA 10, NEMA 14, and the First Rule of Electricity
The old way (3-wire) is called NEMA 10, and abuses the neutral as a protective chassis ground.  This works because the neutrals and grounds are bonded together in the main panel -- the purpose of a ground wire for an appliance is to send wayward current from the case back where it came i.e. the service entrance, while the neutral wire is going in the same direction, so to speak.  However, the NEMA 10 setup is problematic because if the combined neutral/ground breaks, the dryer's chassis will then float off to some shocking potential.
NEMA 14 (4-wire) eliminates this problem by separating the neutral and the ground, making them take two different paths back to that main panel bond.  That way, if the neutral wire to the dryer breaks or otherwise fails, the ground's still there to protect you from getting zapped.
When all else fails, remember the First Rule of Electricity: CURRENT FLOWS IN LOOPS!!! This means that electricity isn't ever trying to go to "ground", whatever-the-@$(!@$ that means, or to some random water pipe somewhere that really only is tangentially related to the entire electrical system.  It's always trying to get back to where it came from -- your electrical service from the utility or the battery in your car, for example.
Think of it like some district steam plant -- the utility is only loaning you the electrons or water molecules, as they are mere carriers of the energy you're getting sold.  Just like the steam utility would cut off someone who took all their valuable water and let it out into the atmosphere, the electric utility wants their electrons back just as much, if not more, and the same holds true for your car battery.
Answer: It is helpful to look at the wiring chart for common plugs to understand what is going on.

An electric drier is 240V, 30A, so it uses the NEMA 10-30 connector. As the chart shows, there are two hots and a neutral.
This is a Really Bad Thing. Much of the time, an appliance wired this way (electric ovens are similar) will just work fine. However, if there is a wiring fault (e.g. short circuit), the chassis of the appliance can be electrically charged. 240V with 30A of current will kill you.
You should always upgrade the wiring rather than downgrade the plug.
Anyway, on to your specific questions:

A) On the older 3 prong outlet what is the neutral or ground connected
  to under the house (water pipe? nothing?)

The neutral is connected to the neutral bus in the main panel, which has a wire to ground (grounding rod or cold water pipe) and is also connected to the neutral entering the panel from the electric company. NEMA 10-30 has no grounding connector.

B) on the newer 4 prong outlet what are the 2 neutral/ground
  connectors connected to? (same water pipe? different water pipe?)

Both the neutral and ground are connected to the neutral bus in the panel.
However, the wiring on the appliance side is different. The neutral is used as a return path for any single-phase needs in the appliance. For example, perhaps the heater coil uses both hots, while the motor does not (not saying this is the case, just an example). There must always be a return path to complete the circuit, so a 120V part of the appliance would need that neutral (the 240V components just use both hots).
The key difference here is that with a 3 prong cable, the chassis is not grounded, while with a 4 prong cable, it is. This is why the chassis can be "hot" in a wiring fault with a 3 prong cable: there is nowhere for the electricity to go until you touch it and provide a ground. With a 4 prong cable, a wiring fault will take that path back to ground, hopefully tripping the breaker before you or a loved one touches it and possibly dies.
Answer:
A) On the older 3 prong outlet what is the neutral or ground connected to under the house (water pipe? nothing?)
B) on the newer 4 prong outlet what are the 2 neutral/ground connectors connected to? (same water pipe? different water pipe?)

None of the wires in an outlet "connects to any pipes" (At least not physically directly.)
In your breaker box there are bus bars for ground and neutral.  If it's a main box they are the same and can be mixed.

The neutral (white) and earth ground (bare copper) wires both go to bars like this in your panel (box).  In a sub-panel they are separate, they both feed back to the master (main) panel.
In the master panel, the neutral/ground bus bars are connected to the same metal you would touch on the door of the panel for instance.
In the master panel, there's an incoming neutral from the power company, and there's one or more thick copper grounding wires that connect to buried grounding rods, or water pipes, or some other ground.
There may also be grounding wires that connect to other places including any large metal structures in your home, but that is not related to your question.
All of these connect to the same bus bars in the main panel.
So the ground and neutral of any outlet should conduct through to the panel (box) but it eventually winds up at a ground rod or metal water pipe pipe.   It does not run from each outlet to any old water pipe nearby! (unless it was put together by a drunken sailor)
Comment: that conveys a dangerously wrong message, you're talking like neutral and ground are the same thing and can be connected to the same places whatever   They are different things with different functions and it's intensely important they be bonded only at one place.
Comment: Nothing in it is wrong with the message.  It did not say that neutral and earth safety ground were "the same thing".
Comment: Not literally.  But my point stands, that your message does next to nothing to show why ground and neutral should be separate.  You use the confusing term "grounded conductor" and show a "grounded" bar with both grounds and neutrals on it. You don't make clear what happens in subpanels. Your last paragraph again talks as if grounds and neutrals go to the same place "through to a water pipe", see where that's confusing?  While you can justify each statement and an electrician will say "I see what you did there", it would confuse a novice badly. Hence my suggestion for some work.
Comment: The question was "where the wires go", not "how does safety grounding work and please also throw in a novel about subpanels".  I was tempted to joke that ground connects to the cold water supply from the city and the two hots connect to the two sides of the water heater but it sounded like he/she might actually believe that.  Sometimes less is more.  This is one of those times.
Comment: Good point, less is more. Yours is more fixable than mine, so here's an edit.
Answer: Neutral Is Not Ground!
Seriously.  They serve completely different functions, and should be isolated from each other entirely except in the one specific place they are bonded.
A lot of people have gotten into the bad habit of playing fast-and-loose with this.  They wire main panels and jumble up neutrals and grounds on the same bus.  They poach ground when they need neutral for a smart switch.  Doing those things is arguable, but the line of thinking which leads you to them is wrong, dangerous, and has a body count.
Like ThreePhaseEel says, electricity wants to get back to source.
Neutral is the normal everyday current path for current to return to source.
Ground is a protective shield.  It's used several ways, and the relevant one here is as a shield to protect humans from loose or misplaced "hot" wires.  It should never, ever flow current normally.  Any current moving on a ground is a fault condition.
Of course, current wants to get back to source, not to ground.  Why does it flow down ground during a fault condition?  Because as part of the design of this protection, we intentionally bond ground to source (neutral) inside the main service panel.   Because of this bond, it is not wrong (merely sloppy) to have neutrals and grounds use the same bus in the main service panel.  In ones way-of-thinking, they must be separated, and also in a sub-panel, they must be separated.
The history
In the beginning there was no ground, only neutral.   You'd wire a dryer  hot-neutral-hot and use a NEMA 10 connector.   However there were a lot of electrocutions, and they were searching for a way to slow those down.  In particular, equipment was mostly all-metal back then, and a fault between hot and chassis resulted in the equipment being energized at 120V.  So the idea of a safety shield came up, to connect all the chassis to what exactly?  Something that would safely take energy back to source, so they bonded neutral to ground at the supply, the transformer- or fairly near it, the main panel.  (Since the transformer was usually up on a pole, hard to inspect, and the ground jumper is hard to protect from damage).
They then wanted to roll out "grounding" to American homes.   They did this gradually, as renovations were done.  However, the dryer and stove industry pushed back politically - they didn't want their customers having to spend $1000 to replace wiring in order to buy a new stove - it would kill sales!   So they politicked to allow NEMA 10 to continue in service, on the logic that the plugs are rarely unplugged and dryers are rarely moved.   They said "just ground the chassis to the neutral".   Errmmmm...
How that fails with dryers and stoves
The problem is, if the neutral+ground wire has any kind of breakage, the hot wires will "pull up" the dryer's side of the broken wire up toward 120V.  If the dryer chassis is bonded to the dryer's side of the neutral, that means its chassis is now energized. Touching that with rubber soled shoes won't kill you, but touching that and anything else, like the washing machine next to it, or the oven... Will!
As you would expect, this situation has a body count.  It tends to be among the poor, so it's under-reported.
Grounding that dryer properly
I'm not going to trust my safety on a political compromise.
Obviously, hot-neutral-hot need to be connected in the usual way for the dryer to function.
A huge safety win is to put the hot-neutral-hot onto a GFCI breaker.  I would be confortable continuing a NEMA 10 in service in that situation.  It would protect from any sort of current leakage.
Otherwise I would properly retrofit a ground, which is now legal to do.  It can follow any viable route back to the same panel.  Then use a NEMA 14 receptacle (which the dryer probably comes with) so you are paying to replace the receptacle instead of the dryer cord.
Or I would hack the dryer to be 240V-only and not use neutral at all, by internally adding a small transformer to power whatever it has that is 120V.  (Probably the timer and controls, maybe a light bulb).  This isn't that weird; this is exactly what the manufacturer does when they sell the same dryer in 240V/60Hz territories like the Phillipines.  In fact I would just use OEM parts if available.   At that point I'd use a NEMA 6 connector (ground, no neutral) and (illegally) re-task the old "neutral" to be a "ground" by marking it with green tape and moving it to the ground bus.
Or if I was poor, I would hack in a proper ground any which way I could, i.e. To a nearby water pipe in an all-metal pipe system... not legal but better than nothing.
Comment: If the NEMA 10 circuit was installed with SE cable, then the neutral was bare to start with -- and retasking it to be a ground would be a compliance improvement, not a violation.  P.S. why in the world couldn't they make a 240VAC-only dryer back in the 1950s?
Answer: Under normal conditions neutral and ground should be at roughly the same potential. They should be connected to both the general mass of the earth through grounding rods and to the neutral point of the supply transformer.
Trouble is when trying to design a safe electrical system we don't just have to worry about normal conditions we also have to worry about what happens under fault conditions.
The ideal is for the neutral and Earth to meet at exactly one point. This is safe under "single fault" conditions. If the neutral breaks then things will stop working and some equipment may be fried by overvoltage but there is no real shock risk. If the Earth breaks then we have lost it's protection but we hopefully don't have an immediately dangerous scenario.
If the neutral and earth functions are combined in the same wire (or even with seperate wires the devices have a large earth leakage) then a disconnection of that wire makes the downstream devices live. This is a BAD thing.
Different countries at different times have had different ideas on to what extent it is appropriate to combine the two roles and what additional precautions should be taken when doing so.
AIUI current practice in the USA to combine the functions in utility wiring supplying houses and on the busbars of the customers main panel but after the main panel they must be seperated.
Older practice also combined the functions on distribution circuits to subpanels and on supplies to large 120/240V appliances like cookers.
Answer: I am an electrical contractor from the UK where residential power is 240v 50 hertz between neutral and hot. The ground (earth) is absolutely essential to carry any fault current back to the panel. When I arrived in the US some 40 years ago, I was amazed at the neutral/ground being tied together on the dryer and range situations. I tried to get the NEC to consider separating these for future installs. But with no success. I was also amazed at the disposal/dishwasher circuits being tied into two single breakers at the panel and not having a 2 pole breaker tying both circuits together off one handle. Turning off one single breaker on a shared 3 wire circuit leaves the other side hot in the box, (particularly on a disposal/dishwasher). I still think this is not good practice and really doesn't cost anymore to tie both circuits together (2 pole breaker). Just a view from an old electrician.
Answer: To answer your questions. Both a three and the four wire outlet. Do not hook up to the water pipe. They must go to the panel. And the dryer outlet. If it is the main panel.Both neutral and ground can go on same bar. If it goes to a sub-panel. Neutral goes to neutral bar. Ground goes to ground bar. On a four wire outlet. Without a lot of input. If you have three wire . Two hots and one white. If it is in emt could use emt as ground. Or add a ground wire if you want. Three wire in old work still code . If you can upgrade you should.
Answer: The 240v appliance sees both 120v taps from the transformer.
When only one of these taps is used for 120v appliances, computers, etc., the neutral serves as the return, and the ground protects against potential energizing of the appliance, computer, etc. in a fault condition.
When both 120v taps are used as hot for 240v appliances, the neutral (center tap) is not required at the wall socket/plug connection.
The earth ground connection to the chassis of the 240v appliance--via the panel--where both neutral and ground meet, eliminates a potential ground loop when the unnecessary neutral connection ends at the bus in the panel.
Comment: Hello, and welcome to Stack Exchange. While interesting, this doesn't really answer the original question.
Answer: I think simple on 3 wire outlets.  If a hot line touches the frame...you bet I want neutral as the frame ground...the alternative is my body to ground.  The flipside is the lower risk of becoming a better return path than neutral or a shock.  I think this is what NEMA  exception is, a lesser of two evils when 4 wire isn't there.
Wonder where this electricity wants to return to where it came from seminar is?  It's simple, path of least resistance to lowest potential.  It has no memory, it just naturally moves to a lower state. Lightning, Ground Conductors, Waterfalls, Your Fluke battery dying, LIFE etc..


typescript function to map through enum values searching for specific value

Question: I've made an API call that returns a string, for example "clear". I've made an enum SkyGradients to match this string:
export enum SkyGradients {
  Overcast = "linear-gradient(135deg, #808080, #404040)",
  Clear = "linear-gradient(135deg, #C0C0C0, #808080)",
}

as well as SkyColors:
export enum SkyColors {
  Overcast = "rgb(128, 128, 128)",
  Clear = "rgb(192, 192, 192)",
}

Now what I want to do is get the corresponding color and gradient using the string: "Clear"
I've tried this:
export function getGradients(text: string): string | undefined {
    for (const gradient in Gradients) {
        if (Gradients[gradient] === text) {
            return gradient;
        }
    }
}

But I'm getting this error:
'Gradients' only refers to a type, but is being used a value here.

as well as:
Element implicitly has an 'any' type because of type 'string' can't be used to index type 'typeof Gradients'. No index signature with a parameter of type 'string' was found on type 'typeof Gradients'

I understand the errors but unsure how to fix
Comment: Where does `Gradients` come from? Does just `SkyGradients['Clear']` not solve the problem?
Comment: I don't know the value of the string until I receive it from the API, that was just an example so I have to test it against each value in the enum
Answer: Unless there's some reason you really want an enum pattern, seems like a better solution would be
export type SkyFills = {
  Overcast: string,
  Clear: string,
  [key: string]: string | undefined // This lets you index with any string
}

export const skyGradients: SkyFills = {
  Overcast: "linear-gradient(135deg, #808080, #404040)",
  Clear: "linear-gradient(135deg, #C0C0C0, #808080)",
};

export const skyColors: SkyFills = {
  Overcast: "rgb(128, 128, 128)",
  Clear: "rgb(192, 192, 192)",
}

Then to access the value it's just
skyGradients.Overcast // "linear-gradient(135deg, #808080, #404040)"
skyGradients["Overcast"] // "linear-gradient(135deg, #808080, #404040)"
skyGradients["someString"] // undefined

TS Playground Example
See other solutions below.

Since you're ok with undefined being returned when the key does not exist, you can safely cast the enum to any.
export function getGradients(text: string): string | undefined {
    return (SkyGradients as any)[text];
}

TS Playground Example
Although you open yourself to runtime errors if you ever add values to the enum that aren't strings.

You can get more robust type safety if you declare objects instead of enums (enums are just compiled down to objects anyway). You can typecast the object to still infer the object's type, but also allow indexing with arbitrary strings. You can even create a type to act like an enum type.
This eliminates the need for a getter function while maintaining strict type safety and the same functionality as enums. Albeit it's not pretty to look at.
const _skyGradients = {
  Overcast: "linear-gradient(135deg, #808080, #404040)",
  Clear: "linear-gradient(135deg, #C0C0C0, #808080)",
} as const;

export type SkyGradients = typeof _skyGradients[keyof typeof _skyGradients];

export const skyGradients = _skyGradients as typeof _skyGradients & {[key: string]: SkyGradients | undefined}

Example usage:
const test1 = skyGradients.Overcast // type is "linear-gradient(135deg, #808080, #404040)"
const test2 = skyGradients.Clear // type is "linear-gradient(135deg, #C0C0C0, #808080)"
const test3 = skyGradients["someString"] // type is SkyGradients | undefined

function someFn(g: SkyGradients) {}

someFn(skyGradients.Overcast) // Ok
someFn("someString") // Not Ok

TS Playground Example


Error on UPDATE statement when saving

Question: I have textbox that has the data. Then if I click Update it will enable all of the textbox so I can edit them. If I click Update again it will save but
I keep getting an error that says
"syntax error in UPDATE statement"
<code>        myConnection.Open()
    Dim str As String = "UPDATE StudentDatabase set FName='" & FNameTextBox.Text & "',MName='" & MNameTextBox.Text & "',LName='" & LNameTextBox.Text & "' ,DOB='" & DOBDateTimePicker.Text & "',Gender='" & GenderTextBox.Text & "',Address='" & AddressTextBox.Text & "',Section='" & SectionTextBox.Text & "',FatherName='" & FatherNameTextBox.Text & "',FatherOccupation='" & FatherOccupationTextBox.Text & "',FatherContact='" & FatherContactTextBox.Text & "',MotherName='" & MotherNameTextBox.Text & "',MotherOccupation='" & MotherOccupationTextBox.Text & "',MotherContact='" & MotherContactTextBox.Text & "',Guardian='" & GuardianTextBox.Text & "',GuardianContact='" & GuardianContactTextBox.Text & "' where StudID='" & StudIDTextBox.Text & "'   "
    Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
    If (LNameTextBox.ReadOnly = True) Then
        FNameTextBox.ReadOnly = False
        LNameTextBox.ReadOnly = False
        MNameTextBox.ReadOnly = False
        GenderTextBox.ReadOnly = False
        AddressTextBox.ReadOnly = False
        SectionTextBox.ReadOnly = False
        FatherNameTextBox.ReadOnly = False
        FatherContactTextBox.ReadOnly = False
        FatherOccupationTextBox.ReadOnly = False
        MotherNameTextBox.ReadOnly = False
        MotherContactTextBox.ReadOnly = False
        MotherOccupationTextBox.ReadOnly = False
        GuardianContactTextBox.ReadOnly = False
        GuardianTextBox.ReadOnly = False
    ElseIf (LNameTextBox.ReadOnly = False) Then

        Try

            cmd.ExecuteNonQuery()

            FNameTextBox.ReadOnly = True
            LNameTextBox.ReadOnly = True
            MNameTextBox.ReadOnly = True
            GenderTextBox.ReadOnly = True
            AddressTextBox.ReadOnly = True
            SectionTextBox.ReadOnly = True
            FatherNameTextBox.ReadOnly = True
            FatherContactTextBox.ReadOnly = True
            FatherOccupationTextBox.ReadOnly = True
            MotherNameTextBox.ReadOnly = True
            MotherContactTextBox.ReadOnly = True
            MotherOccupationTextBox.ReadOnly = True
            GuardianContactTextBox.ReadOnly = True
            GuardianTextBox.ReadOnly = True
            myConnection.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End If
</code>
Comment: Do any of your textboxes have an apostrophe or a quote in it when running this update code? The way this is setup it is susceptible to SQL injection.
Comment: Use parameters... I could drop `StudentDatabse` with. `;DROP StudentDatabase` in the field `StudIDTextBox` just a suggestion...
Comment: Always use parameterized queries. That will solve your sytax error statement as well as protect you from sql injection attacks.
Your code should look like this:
`Dim str As String = "UPDATE StudentDatabase SET FName = @FName, MName = @MName, ..... "`

 `Cmd.Parameters.Add("@FName", SqlDBType.VarChar).Value = FNameTextBox.Text`
 `Cmd.Parameters.Add("@MName, SqlDBType.VarChar).Value = MNameTextBox`
 `...`
Answer: First off, as you've been cautioned, use parameterized queries. If the exception does not give you enough information, consider writing the complete query to the console so you can examine the syntax conveniently. What format does dobdatetimepicker.text return, and is that what your database expects (though, if I'm not mistaken, you would have received a different error message)? If none of those reveal the issue, start removing inputs from your query string till something different happens.

Error on UPDATE statement when saving


Creating shared vertex normals on GPU

Question: I've mostly succeeded at porting an implementation of Marching Cubes from CPU over to OpenGL compute shaders, but I haven't tackled normals yet and wondering the best way to go about it.
My implementation deals specifically with binary valued fields (I'm trying to model 3D fractal functions that don't have a distance estimator yet), so gradient and forward differences methods won't work. I have shared vertices working, and my CPU implementation uses Quilez's method described here to accumulate face normals onto each neighbouring vertex.
I could just port this implementation over to another shader, but the problem I see with this is the massive number of atomics needed. Since we can only use atomics on scalar integer types, and I cant think of a way to pack 3 signed ints into 1 in a summable way, that means 3 axes * 3 vertices = 9 atomic adds per shader invocation. They'll be spread throughout memory of course so it's not like hitting a single atomic counter 9 times, but it still seems like a hell of a lot.
The other alternative is to run a shader invocation per-polygon and build the face normal list (i could probably pack to x10y10z10 this way), then a shader per-vertex to accumulate all the normals of neighbouring faces. This would be an enormous memory hog though, the storage space of the face indices would need 12 int per vertex to deal with the worst case. There's also the problem of how to write into this storage without again resorting to atomics to work out how many faces have already been written to a particular vertex.
Anyone have any better ideas on how to do this?
Answer: For an nVidia only solution you can use floating point atomic add intrinsics (like NvInterlockedAddFp32) Unlocking GPU Intrinsics in HLSL | NVIDIA Developer
I tried this on 80.000 vertex mesh and it's quite fast (something like 1 or 2 ms on a GTX980M, if I remember correctly)
Just beware of compiling your shaders in release for the intrinsics to work (due to nvidia bug/limitation)
Also beware of vertex splits (due to UV discontinuities for example), you'll have to handle them or else you'll have unwanted hard edges at UV seams.
Comment: Because the question is old  I´ll ask you instead :-) For what I understand simply having adjencency information for each vertex was not good enough for russ?
Comment: This was for my thesis project last year, I ended up just going with the dumb  way and using integer atomic adds, scaled way up to maximize precision, then normalizing to float vectors. Couldn't figure out a way to list faces round each vertex without allocating worst-case space and using atomic counters to build the lists anyway. It's probably inefficient as hell but I still got a couple of orders of magnitude speedup from the CPU version and a first-class mark so I was happy enough with it :)
Comment: "Just beware of compiling your shaders in release for the intrinsics to work (due to nvidia bug/limitation)" you saved my day, thank you.

Creating shared vertex normals on GPU


Use Jmeter desktop application as web app

Question: As we know JMeter is desktop based application which will get launched in our OS and we can use it to do performance testing but what if I want to use it as web application rather than desktop application.
How can I use Jmeter desktop application as web app and expose this on some port ?
I tried following but none of them launched Jmeter as webapp.

Converting the jmeter desktop application to webapp using webswing, java web start but was not successful in that.
Running the jmeter jar directly in rest controller to launch it as webapp but it did not launch as webapp.
Also tried to run the jmeter docker image but that also did not help.

Can anyone please tell me ? do we have web app of jmeter or web version of jmeter so that I can use it as webapp and access it from web browser via some port ? like this localhost:8080/jmeter
Answer: Currently running JMeter as a "pure" web application is not possible, however if all you need to do is to make JMeter GUI available to yourself or someone else via a web interface/browser you can install JMeter into a Docker container and expose the virtual desktop via i.e. noVNC so you (or someone else) will be able to open specific hostname/port in the browser and see JMeter GUI and create, edit or debug a script.
Example Dockerfile:
FROM uphy/novnc-alpine
RUN \
    apk add --no-cache curl openjdk8-jre bash \
    && curl -L https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-5.4.1.tgz >  /tmp/jmeter.tgz \
    && mkdir -p /opt \
    && tar -xvf /tmp/jmeter.tgz -C /opt \
    && rm /tmp/jmeter.tgz \
    && cd /etc/supervisor/conf.d \
    && echo '[program:jmeter]' >> supervisord.conf \
    && echo 'command=/opt/apache-jmeter-5.4.1/bin/./jmeter' >> supervisord.conf \
    && echo 'autorestart=true' >> supervisord.conf

So given you follow next steps:

Build the image:
docker build -t jmeter .

Run the image as the container:
docker run -it --rm -p 8080:8080 jmeter

Open http://localhost:8080/vnc.html URL in your browser (must be Websocket-capable)

You will see a virtual desktop with JMeter

More information: Get Started With JMeter: Installation & Tests
Comment: Hi Dmitri,
Thanks for the great solution!
I have question, in this vnc.html page, can we remove followings

1. extra grey color space and black color space,
2. in the left hand side there is a noVNC button which has some settings,
3. in the down side of this page, there is a workspace 1,2,3,4,

it would be great if these above 3 extra things can be removed.

can you please help me in that ?
I want to see this vnc.html page just like you , is it possible?

Thanks in advance.
Comment: Hi Dmitri, this is the result that I am getting (screenshot)-> https://ibb.co/sRM63tM
Comment: This is not a code writing service, I didn't gave you the fish, I provided information regarding how to fish, you can either start JMeter in maximized mode or consider amending the dockerfile to expose JMeter in so called [kiosk mode](https://ubuntu.com/tutorials/secure-ubuntu-kiosk#1-overview)


Can not connect with Casbah but it works with ReactiveMongo

Question: I have an issue connecting to my mongo database with Casbah and it works fine with ReactiveMongo. Here is the code used with Casbah:
val client = MongoClient(MongoClientURI("my_uri")) and with ReactiveMongo: this.driver(actorSystem).connection(MongoConnection.parseURI("my_uri")). the error I get with with Casbah is: { "serverUsed" : "host:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18}. Any idea where this could come from ?
Comment: You're getting an "auth failed" message - how are you setting your mongodb credentials?
Comment: In both ways they're set in the mongo uri like this: `mongodb://login:password@host:port/database`
Comment: What version of MongoDB and what version of Casbah?
Comment: Mongodb version 2.6.8 and Casbah version 2.8.1
Comment: What does `db.getUser()` output? http://docs.mongodb.org/manual/reference/method/db.getUser/
Comment: Thanks Ross, I've found the issue the user does not exist in the database. If I try to login without login/password it works. But I don't understand why ReactiveMongo can login but Casbah can't.
Answer: You may need to explicitly set the authMechanism property if not using the default for the MongoDB Server.
Before MongoDB 3.0 the default authentication mechanism was MONGODB-CR, the "MongoDB Challenge-Response" protocol.  In MongoDB 3.0 the default was changed to SCRAM-SHA-1.
If no authMechanism is set then the underlying Java driver will pick the most secure mechanism available based on the sever version.
Try updating your Connection String to:
mongodb://login:password@host:port/database?authMechanism=MONGODB-CR


Ruby mediainfo find unique properites

Question: I'm trying to scan a large hard drive (think 17TBs) to find a storage estimate for video files within specific folders. In addition, I am trying to find specific unique properties of the video files. The purpose of this is to make a case for a digital asset management system that can support the video files that we have going back to 2009. I'm using mediainfo to inspect each video.
I have the file size/storage count working, but i'm having trouble adding the hashes of video properties to an array in my loop. My goal is for media info to look at the specific properties of each video, put them into a hash and add that hash to an array. Then, once I have collected all the hashes of video properties, I would call uniq! on the array so that it would show me the unique video properties.
The output of my code currently returns the video properties for the last video over and over again. I can't see what I'm doing wrong. Any advice?
require 'yaml'

#!/usr/bin/ruby

library_path = ARGV[0]

files_list = Dir.glob("#{library_path}/**/*")
total_capture_scatch_and_exports_size = 0

video_audit = Hash.new()
video_info = []
codecs = Hash.new()

files_list.each do |filepath|
filename = File.basename(filepath.to_s)
  filepath.chomp!
  puts filename
  folders_to_scan = ["/capture scratch/", "/capturescratch/", "/capture-scratch/", "/capture_scratch/", "exports", "export"]

  file_size = File.size(filepath)
  file_extension = File.extname(filepath)
  if
    folders_to_scan.any? { |folder| filepath.downcase.include? folder }

      if
        File.file?(filepath) && filename[0] != "." && file_extension != ".TIFF" && file_extension != ".TIF" && file_extension != ".tif" && file_extension != ".tiff" && file_extension != ".jpg" && file_extension != ".jpeg" && file_extension != ".JPG" && file_extension != ".JPEG"
            duration = %x[mediainfo --Inform="General;%Duration/String3%" '#{filepath}'].chomp!
            format = %x[mediainfo --Inform="General;%Format%" '#{filepath}'].chomp!
            commercial_name = %x[mediainfo --Inform="General;%Format_Commercial_IfAny%" '#{filepath}'].chomp!
            format_profile = %x[mediainfo --Inform="General;%Format_Profile%" '#{filepath}'].chomp!
            writing_library = %x[mediainfo --Inform="General;%Encoded_Library%" '#{filepath}'].chomp!

            video_audit[:filepath] = filepath
            video_audit[:filename] = filename
            video_audit[:duration] = duration
            video_audit[:file_size] = file_size
            video_audit[:format] = format
            video_audit[:commercial_name] = commercial_name
            video_audit[:format_profile] = format_profile
            video_audit[:writing_library] = writing_library
            video_audit[:file_extension] = file_extension

            codecs[:filename] = filename
            codecs[:format] = format
            codecs[:commercial_name] = commercial_name
            codecs[:format_profile] = format_profile
            codecs[:writing_library] = writing_library
            codecs[:file_extension] = file_extension
      end

  end
  puts video_audit.to_yaml
  puts codecs
  video_info << codecs
  total_capture_scatch_and_exports_size += file_size

end
puts "THE VIDEO INFO IS=======>>>> #{video_info}"
puts "THE UNIQUE CODECS ARE: #{video_info.uniq!}"
#1000**3 is for gigabytes (this is how finder on OSX calculates storage on the Drobo Harddrives)use 1024**3 ofr gibibytes
puts "The total filesize is : #{total_capture_scatch_and_exports_size/(1000**3).to_f} GB"

Answer: I figured it out. I was creating new hashes outside of the loop. A new hash needed to be created for each iteration so that it could then be added to the video_info array. Then I needed to remove the bang operator when I called uniq on video_info at the end of the script. Here's my final code:
require 'json'

#developed by Maile Thiesen
#!/usr/bin/ruby

library_path = ARGV[0]

files_list = Dir.glob("#{library_path}/**/*")
total_capture_scatch_and_exports_size = 0
counter = 0

video_info = []

files_list.each do |filepath|
filename = File.basename(filepath.to_s)
  codecs = {}
  filepath.chomp!
  folders_to_scan = ["/capture scratch/", "/capturescratch/", "/capture-scratch/", "/capture_scratch/", "exports", "export"]

  file_size = File.size(filepath)
  file_extension = File.extname(filepath)
  if
      folders_to_scan.any? { |folder| filepath.downcase.include? folder }

      if
          File.file?(filepath) && filename[0] != "." && file_extension != ".TIFF" && file_extension != ".TIF" && file_extension != ".tif" && file_extension != ".tiff" && file_extension != ".jpg" && file_extension != ".jpeg" && file_extension != ".JPG" && file_extension != ".JPEG"
              duration = %x[mediainfo --Inform="General;%Duration/String3%" '#{filepath}'].chomp!
              format = %x[mediainfo --Inform="General;%Format%" '#{filepath}'].chomp!
              commercial_name = %x[mediainfo --Inform="General;%Format_Commercial_IfAny%" '#{filepath}'].chomp!
              format_profile = %x[mediainfo --Inform="General;%Format_Profile%" '#{filepath}'].chomp!
              writing_library = %x[mediainfo --Inform="General;%Encoded_Library%" '#{filepath}'].chomp!

              codecs[:format] = format
              codecs[:commercial_name] = commercial_name
              codecs[:format_profile] = format_profile
              codecs[:writing_library] = writing_library
            codecs[:file_extension] = file_extension
            total_capture_scatch_and_exports_size += file_size

            counter += 1
            video_info << codecs
      end

  end

end
puts "THE UNIQUE CODECS ARE: #{JSON.pretty_generate(video_info.uniq)}"
puts "THE TOTAL FILESIZE IS : #{total_capture_scatch_and_exports_size/(1000**3).to_f} GB"

Ruby mediainfo find unique properites


How to play APE (Monkey's audio) files?

Question: How can I play APE (Monkey's audio) files in Ubuntu 11.10?
Thanks in advance!

Solution:
I finally installed ffmpeg as duffydack suggested, using the instructions from here: http://ubuntuforums.org/showthread.php?t=786095
Then i converted the ape file to flac format:
ffmpeg -i inputaudio.ape outputaudio.flac

Answer: Audacious and Banshee play APE files fine.  I have the ubuntu-restricted-extras package installed if that makes a difference.
Comment: Thanks, I installed ubuntu-restricted-extras and I'm using Audacious, but still no luck. I get "No decoder found for file ..."
Comment: really?  strange.  Try enabling the medibuntu repository and update the restricted packages  run this in terminal,  `sudo wget --output-document=/etc/apt/sources.list.d/medibuntu.list http://www.medibuntu.org/sources.list.d/$(lsb_release -cs).list &&
sudo apt-get --quiet update && sudo apt-get --yes --quiet --allow-unauthenticated install medibuntu-keyring && sudo apt-get --quiet update` and do a `sudo apt-get dist-upgrade`
Comment: a last alternative is to just convert them with ffmpeg.  compile it from source, its quite simple with this guide.  http://ubuntuforums.org/showthread.php?t=786095  , then you would use it in terminal something like `ffmpeg -i file.ape -ab 256k -f mp3 output.mp3`

How to play APE (Monkey's audio) files?


Is there an efficient way to collect items using Thaumcraft Golems?

Question: I was wondering if there was a way to automatically collect the items harvested by Straw Golems in the Thaumcraft mod for Minecraft, or do you need to always pick up after them?
Answer: You can simply use Wood Golems.(Also from Thaumcraft) Place them on a chest you want them to put the stuff in and they will collect for you.
Comment: @Aaron128l that depends on which mod version they're running. One of the older ones had different material golems for different jobs.
Comment: You have to use the Gather Golem Core and use it on any Golem. You might also need to use the golemnacers bell.


Adding data to "multipart/data-form" object

Question: I have a "multipart/form-data" form in a JSP/servlet application. This application is loaded on Apache tomcat 6.31.
What I want to know is can we add new data to the form object received in servlet? If yes then how?
Something like:

JSP page has a form where a file has to be uploaded.
Once the form is submitted and the data received in servlet we need to add say userid and password to it which we cannot expose in UI layer. Then resubmit that form to another JSP / Servlet with the new data
Answer: I would do it as follows:

Servlet 1 will received the multipart request.
I would decorate the HTTPServletRequest using HttpServletRequestWrapper received in servlet one and return the user and password when the "getParameter" is called on the request. (See this to see a sample decorator of HttpServletRequest using HttpServletRequestWrapper).
RequestDispatcher.forward(decoratedRequest, response) to that JSP/Servlet that would process the data.

What I want to know is can we add new data to the form object received in servlet?

To answer this question, you can generally have other form controls like textbox, radio, checkbox etc, along with a FILE control in a multipart/form-data type of form, just in case you are already not aware of this.
Answer: If I understand your requirement properly,
you want to add few more parameters to the request object after it reaches to servlet.
you can do this like,
request.setAttribute("userId", "xyz");
request.setAttribute("password", "abc");
request.getRequestDispatcher("Path where you want to forward").forward(request, response);

You can access the same attribute at the result page.


Calculus - improper integrals

Question: I have a few questions from my h.w, I hope someone can help me.
the question is:
$f:[a,\infty) \rightarrow \mathbb{R}$ is a continuous and periodic function, with period of $T>0$ .
$g:[a,\infty) \rightarrow \mathbb{R}$ is a monotonic function and $\lim \limits_{x\rightarrow\infty} g(x) = 0$
Assume that $\displaystyle \int_{a}^{a+T} f(x) dx = 0$, and that $g$ is differentiable and its derivative is continuous. Prove that $\displaystyle\int_{a}^{\infty} f(x)g(x) dx$ converges.
I hope the question is clear. Thank you
Comment: There're directions in the FAQ section how to properly write mathematics in this site with LaTeX...
Answer: Hint: (many details need to be added)
$$
F(x)=\int_a^xf(x)\,\mathrm{d}x\tag{1}
$$
Show that $F$ is periodic with period $T$. Furthermore, since $g$ is monotonic,
$$
\begin{align}
\int_a^\infty|g'(x)|\,\mathrm{d}x
&=\left|\int_a^\infty g'(x)\,\mathrm{d}x\right|\\[6pt]
&=|g(a)|\tag{2}
\end{align}
$$
Finally,
$$
\begin{align}
\int_a^bf(x)g(x)\,\mathrm{d}x
&=\int_a^bg(x)\,\mathrm{d}F(x)\\
&=g(b)F(b)-g(a)F(a)-\int_a^bF(x)g'(x)\,\mathrm{d}x\\
&=g(b)F(b)-\int_a^b F(x)g'(x)\,\mathrm{d}x\tag{3}
\end{align}
$$
Show that $(3)$ has a limit as $b\to\infty$.
Comment: I think there is a problem. Did you use $\lim_{x\to\infty}g'(x)=0$ in your proof? This condition is not given.
Comment: @xpaul: nope. But we do know that $\int_a^\infty|g'(x)|\,\mathrm{d}x=|g(a)|$ and $F(x)$ is bounded.

Calculus - improper integrals


Shower temperature not regulating

Question: I have a single handle Koehler shower faucet. Recently the temperature regulation has started to malfunction. The shower is ice cold until you turn the knob to the very hottest setting. Once there the water turns to extreme hot. If you turn down the knob it remains the same hot temperature until it gets to the lowest level before turning off the flow of water. At that point the water goes back to ice cold and to get any heat in it you need to turn it all the way back to the top. I can get extreme cold and extreme hot but nothing in between.
The rest of the faucets in the condo behave normally so I think something has failed in this faucet directly. I am not sure if this is something I can fix myself or if I need a plumber to look into.
Comment: Try calling Kohler they could be under warranty.
Answer: You will need to change out the cartridge in your unit. They can be purchased form the manufacturer, online or some times at one of the big box stores.

Shower temperature not regulating


GroupBy with list of keys -- Scala

Question: I'm micro-optimising some code as a challenge.
I have a list of objects with a list of keys in each of them.
What's the most efficient way of grouping them by key, with each object being in every group of which it has a key.
This is what I have, but I have a feeling it can be improved.
I have many objects (100k+), each has ~2 keys, and there's less than 50 possible keys.
I've tried parallelising the list with listOfObjs.par, but there doesn't seem to be much of an improvement overall.
case class Obj(value: Option[Int], key: Option[List[String]])

listOfObjs
  .filter(x => x.key.isDefined && x.value.isDefined)
  .flatMap(x => x.key.get.map((_, x.value.get)))
  .groupBy(_._1)

Comment: Your result is `Map[String,List[(String, Int)]]` where `String` represents duplicate data, i.e. the `Map` key is always the same as the 1st element of the tuple. Is this duplication necessary? Why not `Map[String,List[Int]]`?
Comment: what about `listOfObjs.collect{ case Obj(Some(v), Some(k)) => k.map((_, v)) }.flatten.groupBy(_._1)`
Comment: @jwvh that's exactly what I'm trying to achieve with the groupBy
Answer: If you have that many object, the logical next step would be to distribute the work by using a MapReduce framework. At the end of the day you still need to go over every single object to determine the group it belongs in and your worst case will be bottlenecked by that.
The best you can do here is to replace these 3 operations by a fold so you only iterate through the collection once.
Edit: Updated the order based on Luis' recommendation in the comments
listOfObj.foldLeft(Map.empty[String, List[Int]]){ (acc, obj) =>
  (obj.key, obj.value) match {
    case (Some(k), Some(v)) =>
      k.foldLeft(acc)((a, ky) => a + (ky -> {v +: a.getOrElse(ky, List.empty)}))))
    case _ => acc
  }
}

Comment: Thank you @LuisMiguelMejíaSuárez Def. haven't looked into the benchmarks that close. Updated based on your recommendations
Comment: It would be better to prepend to the `List` and then reverse at the end. - Also, it is usually recommended to call the `empty` factory methods instead of an empty `apply`
Answer: I got the impression you are looking for a fast alternative; thus a little bit of encapsulated mutability can help.
So, what about something like this:
def groupObjectsByKey(objects: List[Obj]): Map[String, List[Int]] = {
  val iter =
    objects.iterator.flatMap {
      case Obj(Some(value), Some(keys)) =>
        keys.iterator.map(key => key -> value)

      case _ =>
        Iterator.empty[(String, Int)]
    }

  val m =
    mutable
      .Map
      .empty[String, mutable.Builder[Int, List[Int]]

  iter.foreach {
    case (k, v) =>
      m.get(key = k) match {
        case Some(builder) =>
          builder.addOne(v)

        case None =>
          m.update(key = k, value = List.newBuilder[Int].addOne(v))
      }
  }

  immutable
    .Map
    .mapFactory[String, List[Int]]
    .fromSpecific(m.view.mapValues(_.result()))
}

Or if you don't care about the order of the elements of each group we can simplify and speed up the code a lot:
def groupObjectsByKey(objects: List[Obj]): Map[String, List[Int]] = {
  val iter = objects.iterator.flatMap {
    case Obj(Some(value), Some(keys)) =>
      keys.iterator.map(key => key -> value)

    case _ =>
      Iterator.empty[(String, Int)]
  }

  val m = mutable.Map.empty[String, List[Int]]

  iter.foreach {
    case (k, v) =>
      m.updateWith(key = k) match {
        case Some(list) =>
          Some(v :: list)

        case None =>
          Some(v :: Nil)
      }
  }

  m.to(immutable.Map)
}

GroupBy with list of keys -- Scala


Hiding a div and all of its content on page load without flicker

Question: Is the only way to completely hide an element and its contents on page to add the following style to it?
display: none;

I noticed with any other technique during page load you see a slight flicker of the div's content. I have tried using jQuery show and hide functions but these do not seem to be good for page load.
Is there any other way besides this css style and just using css in general?
Comment: Yes, `display:none` hides completely the element. What you need? A monosylabic answer? Please, read this before ask: http://stackoverflow.com/help/how-to-ask
Comment: @BlakeRivell : Why on earth do you want a JS solution for something that can be done with just a single line of CSS code? Also, if you can choose between CSS and JavaScript / jQuery to do the same thing, you should ALWAYS go for CSS!!
Comment: Can you please provide a fiddle?
Comment: I feel bad adding this as an inline style to any element that I want completely hidden on page load. I was wondering if there were better ways using jQuery or JavaScript besides adding the same style to an element using .css().
Comment: @BlakeRivell you can add that to your stylesheet, there is no need for an inline style.
Comment: I must have worded my question incorrectly. I am aware of how to use css and inline styles. I was just wondering if there were any JavaScript/jQuery alternatives to fully hide an element.
Answer: You could set whatever div you want to hide the following properties:
div {
  height:0px;
  overflow:hidden;
}

Comment: Thank you for the alternative css solution, but I am wondering if there are ways besides using css or is display: none; basically what everyone uses?
Comment: I mean, you can use jQuery to move the dev thousands of pixels of the page, but other than that, I just use `display:none;`, May I ask what you need an alternative for?
Comment: No reason, I regret even asking this question at this point. StackOverflow probably wasn't the right place. I simply just wanted to know what alternatives are out there besides using display: none; to make sure there was nothing I was missing.
Answer: In your CSS create a class and add this in your div or whatever you want to hide it will hide without flashing.
.divonpageload {
                    height: 0px;
                    overflow: hidden;
                    display: none;
                }

SHOW
    `

and create a jquery function: