Hadoop - Result of WordCount is not writing on output file

Question: I'm trying to run a program to count the number of words with their frequency by following the steps given in this link: http://developer.yahoo.com/hadoop/tutorial/module3.html
I've loaded one directory named input which includes three text files.
I was able to configure everything correctly. Now while the running the WordCount.java, I don't see anything in part-00000 file inside output directory.
The java code for Mapper is:
import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

public class WordCountMapper extends MapReduceBase
implements Mapper<LongWritable, Text, Text, IntWritable> {

private final IntWritable one = new IntWritable(1);
private Text word = new Text();

public void map(WritableComparable key, Writable value,
  OutputCollector output, Reporter reporter) throws IOException {

String line = value.toString();
StringTokenizer itr = new StringTokenizer(line.toLowerCase());
while(itr.hasMoreTokens()) {
  word.set(itr.nextToken());
  output.collect(word, one);
}
}

@Override
public void map(LongWritable arg0, Text arg1,
    OutputCollector<Text, IntWritable> arg2, Reporter arg3)
     throws IOException {
// TODO Auto-generated method stub

 }

}

The reduce code is:
public class WordCountReducer extends MapReduceBase
implements Reducer<Text, IntWritable, Text, IntWritable> {

public void reduce(Text key, Iterator values,
  OutputCollector output, Reporter reporter) throws IOException {

int sum = 0;
while (values.hasNext()) {
    //System.out.println(values.next());
  IntWritable value = (IntWritable) values.next();
  sum += value.get(); // process value
}

output.collect(key, new IntWritable(sum));
 }
 }

The code for Word counter is:
public class Counter {

public static void main(String[] args) {
    JobClient client = new JobClient();
    JobConf conf = new JobConf(com.example.Counter.class);

    // TODO: specify output types
    conf.setOutputKeyClass(Text.class);
    conf.setOutputValueClass(IntWritable.class);

    // TODO: specify input and output DIRECTORIES (not files)
    conf.setInputPath(new Path("src"));
    conf.setOutputPath(new Path("out"));

    // TODO: specify a mapper
    conf.setMapperClass(org.apache.hadoop.mapred.lib.IdentityMapper.class);

    // TODO: specify a reducer
    conf
                   .setReducerClass(org.apache.hadoop.mapred.lib.IdentityReducer.class);

    client.setConf(conf);
    try {
        JobClient.runJob(conf);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

In console I get these logs:
13/09/10 10:09:20 WARN mapred.JobClient: Use GenericOptionsParser for parsing the       arguments. Applications should implement Tool for the same.
13/09/10 10:09:20 INFO mapred.FileInputFormat: Total input paths to process : 3
13/09/10 10:09:20 INFO mapred.FileInputFormat: Total input paths to process : 3
13/09/10 10:09:20 INFO mapred.JobClient: Running job: job_201309100855_0012
13/09/10 10:09:21 INFO mapred.JobClient:  map 0% reduce 0%
13/09/10 10:09:25 INFO mapred.JobClient:  map 25% reduce 0%
13/09/10 10:09:26 INFO mapred.JobClient:  map 75% reduce 0%
13/09/10 10:09:27 INFO mapred.JobClient:  map 100% reduce 0%
13/09/10 10:09:35 INFO mapred.JobClient: Job complete: job_201309100855_0012
13/09/10 10:09:35 INFO mapred.JobClient: Counters: 15
13/09/10 10:09:35 INFO mapred.JobClient:   File Systems
13/09/10 10:09:35 INFO mapred.JobClient:     HDFS bytes read=54049
13/09/10 10:09:35 INFO mapred.JobClient:     Local bytes read=14
13/09/10 10:09:35 INFO mapred.JobClient:     Local bytes written=214
13/09/10 10:09:35 INFO mapred.JobClient:   Job Counters
13/09/10 10:09:35 INFO mapred.JobClient:     Launched reduce tasks=1
13/09/10 10:09:35 INFO mapred.JobClient:     Launched map tasks=4
13/09/10 10:09:35 INFO mapred.JobClient:     Data-local map tasks=4
13/09/10 10:09:35 INFO mapred.JobClient:   Map-Reduce Framework
13/09/10 10:09:35 INFO mapred.JobClient:     Reduce input groups=0
13/09/10 10:09:35 INFO mapred.JobClient:     Combine output records=0
13/09/10 10:09:35 INFO mapred.JobClient:     Map input records=326
13/09/10 10:09:35 INFO mapred.JobClient:     Reduce output records=0
13/09/10 10:09:35 INFO mapred.JobClient:     Map output bytes=0
13/09/10 10:09:35 INFO mapred.JobClient:     Map input bytes=50752
13/09/10 10:09:35 INFO mapred.JobClient:     Combine input records=0
13/09/10 10:09:35 INFO mapred.JobClient:     Map output records=0
13/09/10 10:09:35 INFO mapred.JobClient:     Reduce input records=0

I'm pretty new in Hadoop.
Kindly reply with appropriate answer.
Thanks.
Comment: Delete the second **map()** and re-run your job. I would also suggest you to use the new API.
Comment: Could you please show me your code?Your job is reading the input but it is not emitting anything.
Comment: @Tariq I've edited the question. Please have a look.
Answer: You have two map methods in your Mapper class. The one with the @Override annotation is the method which is actually getting overridden, and that method does not do anything. So nothing comes out of your mapper, and nothing goes into the reducer, and consequently there is no output.
Delete the map method marked with the @Override annotation and mark the first map method with @Override. Then fix any method signature issues, and it should work.
Comment: I was supposed to get each word and its frequency, but part-00000 just shows some numbers and it's frequency. Most of the times 1 as frequency.
Answer: I faced the same problem. I resolved it by deleting the overrided map method and changing signature of map method with first argument to be of LongWritable. Update the map method signature as below:
@Override
public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter)
    throws IOException {


Skip first line while reading CSV file in Java

Question: I am writing a parser code to read a .csv file and parse it to XML. This is the code I have and it works, except I would like it to skip the first line in the file. So I decided to set up a HashMap but it doesn't seem to work:
for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (file.isFile() && file.getName().endsWith(".csv")){

            System.out.println("File Found: " + file.getName());//Prints the name of the csv file found

            String filePath = sourcepath + "\\" + file.getName();

            BufferedReader br = new BufferedReader(new FileReader(file));

String line;
int n = 1;
Map<Integer,String> lineMap = new HashMap<Integer,String>();
int k=2;
while ((line = br.readLine()) != null) {
    System.out.println(n + " iteration(s) of 1st While Loop");

                    lineMap.put(k, line);

    fw.write("          <ASSET action=\"AddChange\">\n");
    fw.write("              <HOSTNAME>\n");
    hostName=line.substring(0, line.indexOf(","));
    fw.append(hostName);
    fw.write("</HOSTNAME>\n");
    fw.write("              <HOSTID>\n");
    hostID=line.substring(line.indexOf(",")+1, nthOccurrence(line, ',', 1));
    fw.append(hostID);
    fw.write("</HOSTID>\n");
    fw.write("              <MACMODEL>\n");
    machineModel=line.substring(nthOccurrence(line, ',', 1)+1, nthOccurrence(line, ',', 2));
    fw.append(machineModel);
    fw.write("</MACMODEL>\n");
    fw.write("              <PROMODEL>\n");
    processorModel=line.substring(nthOccurrence(line, ',', 2)+1, nthOccurrence(line, ',', 3));
    fw.append(processorModel);
    fw.write("</PROMODEL>\n");
    fw.write("              <CORE>\n");
    core=line.substring(nthOccurrence(line, ',', 3)+1, nthOccurrence(line, ',', 4));
    fw.append(core);
    fw.write("</CORE>\n");
    fw.write("              <PROC>\n");
    proc=line.substring(nthOccurrence(line, ',', 4)+1, nthOccurrence(line, ',', 5));
    fw.append(proc);
    fw.write("</PROC>\n");
    fw.write("              <TIER>\n");
    tier=line.substring(nthOccurrence(line, ',', 5)+1, nthOccurrence(line, ',', 6));
    fw.append(tier);
    fw.write("</TIER>\n");
    fw.write("              <PRODNAME>\n");
    productName=line.substring(nthOccurrence(line, ',', 6)+1, nthOccurrence(line, ',', 7));
    fw.append(productName);
    fw.write("</PRODNAME>\n");
    fw.write("              <VERSION>\n");
    version=line.substring(nthOccurrence(line, ',', 7)+1, nthOccurrence(line, ',', 8));
    fw.append(version);
    fw.write("</VERSION>\n");
    fw.write("              \n");

  fw.write("            </ASSET>\n");
  k++;
}n++;

This is a snippet of the main part of the code. Any Ideas or Solutions???
Comment: Not your down-voter, but clarify your `"it does seem to work"`, please.
Comment: sorry typo....it doesn't seem to work
Comment: We know that, but in the future, tell more about how it doesn't work. The more useful information you give, the easier it will be to answer your questions.
Answer: You might consider placing headerLine = br.readLine() before your while loop so you consume the header separately from the rest of the file. Also you might consider using opencsv for csv parsing as it may simplify your logic.
Answer: I feel compelled to add a java 8 flavored answer.
List<String> xmlLines = new BufferedReader(new FileReader(csvFile))
    .lines()
    .skip(1) //Skips the first n lines, in this case 1
    .map(s -> {
        //csv line parsing and xml logic here
        //...
        return xmlString;
    })
    .collect(Collectors.toList());

Answer: Create a variable interation and initialize with 0. Check it as very first thing in while loop.
String line;
int iteration = 0;
while ((line = br.readLine()) != null) {
    if(iteration == 0) {
        iteration++;
        continue;
    }
    ...
    ...
}

Comment: @KalaJ: Do ``if(iteration == 0 || iteration == 1)`` instead or even better ``if(iteration < 2)``. Got it?
Comment: What if I wanted to skip the first two lines? one line with text and the next line is an empty row/whitespace?
Answer: I am rather confused by your code, your have the lineMap and you also have fw (whatever that is). Which one are you using?  You say you want to skip the first line, but you don't
if (firstLine == true) {
   firstLine = false;
   continue;
}

I would also suggest using a library like CSVReader which I belive even has a property ignoreFirstLine
http://opencsv.sourceforge.net/apidocs/au/com/bytecode/opencsv/CSVReader.html
Answer: why don't you just use the for loop
for(int i=1; (line = br.readLine()) != null; i++)
{
    //Your code
}

Comment: How initializing i=1 will read from second line, there is no control on a variable i, using i is obsolete here.
Answer: An easy technique, declare a variable and assign it a value (e.g. int k = 0;), and increment the variable value right after you enter into the loop. The code is given below.
BufferedReader csvReader = new BufferedReader(new FileReader("mycsv.csv"));
        // declare a variable
        int k=0;
        while ((row = csvReader.readLine()) != null) {
            if(k == 0){
                k++;
                continue;
            }
         //rest of your code
         // inside while loop
        }

Answer: Use buffer reader two times, like this:
while ((line = br.readLine()) != null) {
  while ((line = br.readLine()) != null) {
    //your code
  }
}

Answer: boolean isRecord = false;
for (CSVRecord record : records) {
    if(isRecord){
        //process records here.
    }else{
        isRecord = true;
    }
}

Instead of adding counter adding flag will not hit the performance.
Answer: A simple solution, read the first line outside of the loop
        String[] nextLine;
        String[] headerLineInCSVFile = csvReader.readNext();
        while ((nextLine = csvReader.readNext()) != null) {
            String columnOne = nextLine[0];
        }

Answer: For skipping first line(which normally contains header of the columns) take a variable and  increase this variable in while loop at first place, and continue;
int lineNumber = 0;

and then in while loop

while ((line = br.readLine()) != null) {
                        if(lineNumber == 0) {
                            lineNumber++;
                            continue;
                        }
                        lineNumber++;

                       //do waterver u have to do with the tokens in this line(second line)

            }

Comment: The same basic answer was posted more than a year ago.


AppDelegate not showing Storyboard buttons

Question: I am setting up a MainViewController holding multiple ViewControllers the following way:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let pageController = UIPageViewController(
            transitionStyle: UIPageViewControllerTransitionStyle.scroll,
            navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal,
            options: nil
        )

        let navigationController = MainViewController(rootViewController: pageController)
        navigationController.view.backgroundColor = UIColor.white

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let leftView = storyboard.instantiateViewController(withIdentifier: "VC1")
        let middleView = storyboard.instantiateViewController(withIdentifier: "VC2")
        let rightView = storyboard.instantiateViewController(withIdentifier: "VC3")

        navigationController.viewControllerArray = [leftView, middleView, rightView]

        self.window!.rootViewController = navigationController
        self.window!.makeKeyAndVisible()

        return true
    }
}

My MainViewController also has what is supposed to be a floating button. I have aded this in the storyboard (see picture below). The problem is that the button is not showing. How do i make it show?
I know that somehow this problem is related to the fact that I adding MainViewController in the AppDelegate, but I am not sure how that is hiding the buttons.
Answer: You aren't creating your MainViewController instance from the storyboard, you are just creating it with a call to its initialiser.  This means that none of your storyboard elements will be loaded
You need something like:
let navigationController = storyboard.instantiateViewController(withIdentifier: "Main")
navigationController.viewControllers = [pageController]

Comment: you are correct, I had the feeling this was the case. But the problem is not, how to set up the rootViewController? In other words how do I replace this part '(rootViewController: pageController)'
Comment: Add your `pageController` to the storyboard.  You can then get a reference to it in the `prepareForSegue` function in your navigation controller


reverse auth token from server side with Twitter4j

Question: I saw that Twitter4j has interface to oauth
Does it have an interface for reverse auth token as described here?
This would require adding, among others:
 x_auth_mode reverse_auth

Answer: See:
twitter4j.auth.OAuthSupport
RequestToken getOAuthRequestToken(java.lang.String callbackURL,
                                java.lang.String xAuthAccessType,
                                java.lang.String xAuthMode)
                                  throws TwitterException
Retrieves a request token
Parameters:
    callbackURL - callback URL
    xAuthAccessType - Overrides the access level an application requests to a users account. Supported values are read or write. This parameter is intended to allow a developer to register a read/write application but also request read only access when appropriate.
    xAuthMode - Set to reverse_auth to obtain a special request token to be used in the reverse auth process.
Returns:
    generated request token
Since:
    Twitter4J 2.2.3


SQl 2000 Reporting Services and SQL 2005 Reporting Services side by side?

Question: Does anyone know if it is possible to install SQL 2000 Reporting Services Server side by side with SQL 2005 Reporting Services Server?
The Reports and ReportServer virual directories are both virtual directories in the default website and they use different .net frameworks. Is this even allowed? Do I need to create a new website to support one of the two engines?
Thanks!
Answer: The answer is YES.  You must keep the SQL Server 2000 version as the default instance, and the SQL Server 2005 version as a named instance.  Also,

The virtual directories must be unique
  for each report server and Report
  Manager instance.
You can use the same Web site for all
  virtual directories. However, you
  should create a separate application
  pool for the SQL Server 2005 report
  server and Report Manager
  applications.

Source


How to change the order of fill aesthetic in faceted ggplot?

Question: I have a faceted ggplot that is all but done. I cannot seem to get the fill aesthetic to be descending for each group in the dodged plot and across facets. The idea is to look at the plot and quickly recognise the top three categories within each group on the y-axis - and that the colors will be order different for each group. Here is some code to get a representative graph.
library(tidyverse)
set.seed(123)

#using crossing from purrr

df <- crossing(
  mean = 1:8,
  cats = sample(letters[1:3], 8, T),
  gender = c('Male', 'Female')) %>%
  mutate(vary_x = sample(seq(1,3,.1),nrow(.), T))

df %>%
  ggplot(aes(mean, vary_x, fill = cats))+
  geom_bar(stat = 'identity',
           position = 'dodge') +
  facet_grid(.~gender) +
  coord_flip()

Answer: Something like this maybe:
df %>%
  ggplot(aes(mean, reorder(vary_x,mean), fill = cats))+
  geom_bar(stat = 'identity',
           position = 'dodge') +
  facet_grid(.~gender) +
  coord_flip()


Fractals - exact and self similarity

Question: Can someone explain me what is the difference between strictly and exactly  self-similar fractals? What is the stronger possession and what are the examples for both types? Thanks in advance.
Comment: Can you give a reference or two to where you've encountered the terms "strictly" and "exactly" used in regard to self similarity?
Comment: The book is: "Fractals and Chaos: An Illustrated Course", Paul S. Addison.
Answer: As near as I can tell from a brief look at the book the OP cites, "strict" self similarity means you see similarity no matter where you look -- Addison gives the Sierpinski triangle as an example of strict self similarity and a spiral as an example that's self similar only at the center of the spiral but nowhere else -- while "exact" means you see an exact copy of the fractal at each point of self similarity, as opposed to something that merely has the same general appearance, which Addison calls "statistical" self similarity.  All this is explained in the first few pages of the book, where the terms appear in boldface.  Nothing there, though, is given with any mathematical rigor; whether rigorous definitions are given later, I can't say. (I was looking on googlebooks, which limits what's shown.)
Comment: Thanks, just one question about strict self similarity: do these copies inside of fractal have to be exact copies or they can be in some way deformed like in Mandelbrot set? Does that mean that  exact self similarity implies strict self similarity?
Comment: @user121, again, Addison doesn't seem to give rigorous definitions, so I can't say exactly what "exactly" means. But I think that the example of the spiral shows exact self similarity at its center, so I am inclined to say that exact self similarity does *not* imply strict self similarity. However, Addison does say that his book is mainly (if not exclusively) interested in fractals that are strictly self similar.

Fractals - exact and self similarity


execute bash if else command in php ( bash vs php )

Question: What i want to achieve
I want to execute some script it it's process in not started on the server. so for that i am preparing the command in shell script and executing it in single line.
Command with php variable
$cmd = "if [[ `ps auxww | grep -v grep | grep ".$process_file." | grep '".$find."'`  == '' ]] ; then ".$cmd2."  fi";

echo $cmd."\n";

Executed command, once variables are replaced (what will actually run on bash):
if [[ `ps auxww | grep -v grep | grep /home/new_jig.php | grep 'test_51 1714052'`  == '' ]] ; then  php /home/new_jig.php test_51 1714052 & fi;

executing command
exec($cmd,$out,$res);

Please note that, I have also split the problem in to two statement and execute those.  But it is time consuming.  It is causing problems when I have more than 2000 in list, and the command is executed for all.  This takes about 1 or more than 1 minute to reach to the last number.
I want to achieve this within 10 seconds. Please help me to reach optimum output.
Thanks
Jignesh
Comment: @MagnusEriksson: indeed, I removed my comment, rewrite follows.
Comment: _"I want to achieve this within 10 seconds"_ - Any specific reason for that magic number? You might also want to explain what the script actually does? You also seem to be executing some PHP code in your bash script. What does that script do?
Comment: we have one daemon process with runs every 3 seconds which trigger multiple php processes ( 2000+). to do some data fetching from third party websites. Currently problem is, it is taking more than a minutes to reach till end if i use followings...  $cmd = "ps auxww | grep -v grep | grep ".$process_file." | grep ".$find." > /dev/null 2>&1";   exec($cmd,$out,$res); and based on the result i execute  something like ... php /home/new_jig.php test_51 1714052
Comment: @Nic3500 - Isn't that package making shell commands as well? So basically, it would simply just move the call from one place to another? And regarding `grep`, `if then else`, I doubt that it will make any performance difference if those are in PHP vs CLI.
Comment: @MagnusEriksson; indeed, it could be, I did not dig in the code.  CLI has to start a shell to run every command, processing text (or arrays here) is much faster in PHP, than starting a bunch of shells.  I sometimes rewrite long bash scripts into Perl (or other), and the difference is crazy!  Hence my suggestion to do as little in bash as possible when speed is a concern.
Comment: @Nic3500 - I totally agree with using some other language for managing processes. PHP isn't really optimized for that. Just wanted to point out that the package you recommended also does CLI-calls, so there aren't much to gain by using that instead :-)
Comment: To cut processing time, you need to do as much as you can in PHP, and reduce the number of shell commands.  But why use PHP at all to manage processes? If speed is critical, look at building or finding something in C.
Comment: my application is php and shall script base. so i thought to reduce php function and start combining functionality on shall to see how it sounds.
Comment: I also come across.... but it is not working as expected, ps auxww | grep -v grep | grep /home/new_jig.php && php /home/new_jig.php test_51 1714052  . Here with && if first command executes then only the next command executes. i don't want output, but i want conditional execution, if from first command ( process is not running on server then only)  execute the next command.
Answer: somehow I am able to make it execute with the following command
$process_file = phpfile which executing some functionality
$cmd2 = " php ".$process_file." 1212 >/dev/null 2>/dev/null & ";
$cmd11 ="if ps -auxw | grep -v grep | grep '".$process_file."' | grep '".$find."' &> /dev/null ; then echo 1;".$cmd2."; fi";
shell_exec($cmd11." >/dev/null 2>/dev/null &");
Before this: for 1100 request the process was taking about 60+ seconds
After this: it is getting completed between 20 to 30 seconds


How to make a UEFI compatble ISO with grub-mkrescue?

Question: I have been following this guide to produce a customized version of Ubuntu.
As of now, the structure of the CD is complete. I just have to generate a bootable ISO image with the command:

sudo grub-mkrescue -o live_cd.iso /path/to/cd/root

I got a perfectly working iso image which boots well in VirtualBox, under UEFI mde.
The problem is when I copy the iso to my USB flash drive (using dd command)  it does not boot in my real machine under UEFI mode. I get this:

However, I can boot the flash drive fine in legacy bios mode.
I have installed grub-efi package as well.
Can anyone tell me what I'm doing wrong?
Thanks!
Comment: cross: http://unix.stackexchange.com/questions/223453/how-to-make-a-uefi-bootable-iso-image-with-grub-mkrescue
Answer:
mount Stick
sudo mount -t vfat /dev/sdX /mnt
Install another Grub2 to USB:
sudo grub-install --no-floppy --force --root-directory=/mnt /dev/sdX
Copy iso to stick
cp -v ~/live-cd.iso /mnt
Add following to /mnt/boot/grub/grub.cfg
set default="0"
set timeout=10

insmod fat
set iso_path=/live-cd.iso
loopback loop (${usb})${iso_path}
set root=(loop)
set bootopts="boot=casper iso-scan/filename=${iso_path} noprompt"

menuentry "Boot ISO from HDD/USB" {
linux (loop)/casper/vmlinuz $bootopts
initrd (loop)/casper/initrd.img
}

Source: https://help.ubuntu.com/community/MakeALiveCD/DVD/BootableFlashFromHarddiskInstall#Appendix_2._How_to_Make_bootable_USB_flash
It may solve your problem
Comment: Thanks, but it isn't the optimal solution I'm seeking.
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Mardi-Gras combinatorics

Question: A group of $8$ people decides to go to a masquerade in a $6-$floor palace. The people are masked in such way that they are indistinguishable one from another. Not knowing at which floor the party is, each person decides where to look for the party. In how many different ways can this happen?
Combinatorically speaking, this problem is giving me issues. I suppose that I should fix the number of floors which will be occupied and find in how many different ways people can distribute in this number of floors. This lead me to think that the formula should be something like $\sum_{i=1}^6 {6\choose{i}}*f(i)$, but I can't figure out how to work out a general expression for $f(i)$. Working it by cases did not really help much. Am I completely offroad?
I found the solution of the problem computationally with Python. This can be easily done noticing that the problem is equivalent to search for the cardinality of the solution set to the equation
$$x_1+x_2+\ldots+x_6=8 $$ with $x_i \in \mathbb N$ and $0\leq x_i\leq 8$
The answer should be $1287$. What path should I choose to look for $f(i)$? Is there an easier approach to the problem which I am not considering?
Comment: Basically, you're putting 8 unlabelled balls into 6 labelled boxes?
Comment: So what they were saying about Ash Wednesday was true. Yes, indeed, the two problems are exactly the same!
Answer: your problem is equivalent to this one:
Consider 8 unlabelled balls and 5 sticks, you're looking for all the way you can dispose that elements in a line. Pay attention that with 5 sticks you can create 6 groups of balls (eventually empty).
You have 8+6-1 elements in total and 6 boxes to form, so your relation is: (8+6-1)!/((5)!(8)!)
Speaking in general, if you have k unlabelled balls and n boxes, you have the following relation (n+k-1)!/(k!(n-1)!)
Comment: I don't understand what you mean by disposing sticks and unlabeled balls in a line. What do you mean by "with 5 sticks you can create 6 grousp of balls"?
Comment: Say 2 people look on floor 1, nobody looks on floors 2 or 3, 2 people look on floor 4, 3 people look on floor 5, and 1 on floor 6.  You can represent this with the picture oo|||oo|ooo|o  where the o's represent masked (indistinguishable) people and the sticks separate the floors.
Comment: I got it. Your help was really appreciated, thank you!

Mardi-Gras combinatorics


How do I build a search with the number of results for each category?

Question: I need to show the number of results for a given category, and hide any categories that give no results.
Example: This Yahoo!Jobs page shows the number of results in categories like City, Job Category, Experience etc.
I work in C#/Asp.Net, and fear that our server will choke without some serious caching and sql optimization.
How would you go forward creating a solution like this?
Comment: What type of database are you using? Oracle, MySQL, etc.
Comment: See my comment to George Mauer's answer below.
Answer: Relational databases are not suited for that kind of stuff. It's just the wrong tool for the job. Instead, take a look at Lucene, Solr, Sphinx, etc.
I personally recommend Solr, it's very easy to get started and with SolrNet you can write a faceted ASP.NET app in a few lines of code.
Disclaimer: I'm the author of said library.
Answer: I think you will have to go into a heck of a lot more detail about your set-up.  Are you using an ORM?  Is the data already in memory?  How is the request coming in?  What specifically is your concern?  Have you done any profiling to determine this is indeed a problem?  I cannot stress that last one enough.  Ensure that what you're afraid of is an actual problem before you try to find ways around it.
To attempt an answer however, if you do something like this
<code>_categoryRepository
  .Where(category=>category.Matches(query))
  .Select(category.Items.Count())
</code>
Count() will only be executed for categories where category.Matches(query) returns true.
Comment: @comichael - Where there's few options there's few solutions.  If the ONLY thing you are willing to work with is SQL then the ONLY solution available is caching.  At the very least build a category repository class which hides the raw SQL - it will be easier to cache at that level.  Also, you should profile even if the site is slow - are you certain that the database is the bottleneck?  In asp.net applications its usually something else.
Comment: I'm bulding on a 7 year old solution with no ORM, no objects, just plain old datasets. The total number of rows is large (10K), so it's not an option to keep all the data in-memory. Refactoring/rebuilding to use DDD / linq would be great, but there's no time for it. So.. as far as I'm concerned, I need to add a query for each category item in each cateogory (select count(*) where city =='[city]'). And there will literally be hundreds of those "count-queryies" for each main query - that's my big worry. The site is slow enough today, so even if no profiling is done, I can guess the outcome.
Answer: The typical way these counts are done is via caching. The model is to have a trigger on insert into the relevant tables, then update a calculated field with 'CurrentCount'.
You can add further levels of caching into the app itself, so that counts only get incremented every few hours, or similar.
It is significantly better than actually counting all the rows each time, but it does mean you need to know in-advance what sorts of data you will be counting, so you can pre-calculate it.


how to know the location of ubuntu installed in vmware in windows 10?

Question: I installed ubuntu in vmware, in windows 10. i want to copy some stuff from windows10 to ubuntu, to use it inside ubuntu. But i am not getting location of ubuntu installed in vmware.
so how can i know location of myfiles in ubuntu installed on windows10 ?
i Searched inside Vmware folder in programfiles but had not got ubuntu folder and files
Answer: The files of your vmware guest are not directly accessible from your host.
You have to set up file sharing or use a shared folder.
See: Sharing Files Between Guest and Host Operating Systems


I am getting net error ERR_CONNECTION_RESET when calling an API method using ajax

Question: We have a IIS 8 web server on which Web API is deployed. We have a front end application written in extJS. When the application accessed, it makes sever API calls to the server and many of these calls return success except one specific API call. Chrome says request status as cancelled (ERR_CONNECTION_RESET), and I am not able to figure out how to troubleshoot and fix this error. I have checked many places online but I could not get much help.
Please help.
Answer: Are you using Entity Framework Core? If so, you may have an object graph loop in your many-to-many relationships as EFCore does not support lazy loading at this time.
If so, you can configure your serializer to not follow graph loops.
In your Startup.cs file, replace the services.AddMvc() line with this:
services.AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);


On which regions can Green's theorem NOT be applied?

Question: In my calculus book (Stewart), the theorem is proved for a simple region (I understand that this is being enclosed by a simple curve). But then it is specified that the theorem can be extended for a finite union of simple regions that do not overlap, and even for regions that are not simply connected (that is, with holes).
So it doesn't occur to me about what kind of region the theorem might not apply to.
Answer: Green's theorem works only for the case where C is a simple closed curve. If C is an open curve, please don't even think about using Green's theorem.
So what is a simple curve? A curve that does not cross itself. So if the region is a finite union of simple regions that overlaps, the curves that enclose the region will not be simple as they will cross each other. So Green's theorem is not applicable there.
Now comes the question. When can we use Green's theorem?

i)  When the curve is simple closed curve (failing any one of the conditions can make damage).
ii)Green's theorem can be used only for vector fields in two dimensions,i.e in $ F(x,y)$ form. It cannot be used for vector fields in three dimensions. So, don't bother with Green's theorem if you are given an integral like
  $ \int_C Adx+Bdy−Cdz\;$
  even if $ C$ is a closed path.


Parse PHP using simplexml for field values

Question: Trying to parse the following xml:
<?xml version="1.0"?>
<devices>
<device name="TEMP" index="0" available="1" type="" id="xxx">
<field type="2" max="50" min="-20" niceName="Temperature (C)" value="24.75" key="TempC"/>
<field type="2" max="122" min="-4" niceName="Temperature (F)" value="76.55" key="TempF"/>

and pull the TempF value of 76.55.
This is the code I was trying, but I'm not doing something isn't right:
$xml = simplexml_load_file('c:\data.xml') or die("Error: Cannot create object");
echo '
Server Temperature
';
$list = $xml->devices;
for ($i = 0; $i < count($list); $i++) {
    echo 'Temp: ' .$list[$i]->TempF[value] . '
';

Answer: You can loop $devices->device instead without instead of using a for loop
echo '
Server Temperature
';
foreach ($xml->device as $device) {
    foreach ($device->field as $field) {
        $att = $field->attributes();
        if ((string)$att->key === "TempF") {
            echo 'Temp: ' . $field->attributes()->value . "
";
        }
    }
}

Output

Server Temperature
Temp: 76.55

See a Php demo
Or if you want to loop all the values of field, you can use xpath:
echo '
Server Temperature
';
foreach ($xml->xpath('/devices/device/field[@key="TempF"]/@value') as $value) {
    echo 'Temp: ' . $value . "
";
}

Output

Server Temperature
Temp: 76.55

See another Php demo
Comment: got it, Thanks!!
Comment: Thanks! But that code still doesn't appear to be showing the data, just getting the h2 text.
Comment: @jackstrum See `Temp: 76.55` where `76.55` comes from the xml
Comment: @jackstrum See https://3v4l.org/FmOWG I have added 2 demo's to the answer.


How to write a new row in an existing csv file without appending it in the last line?

Question: I want to add a new row to an existing .csv file in python.
I tried by the following by appending a line to the csv file in spyder IDE in windows.
def write_to_file():

file = open('E:/Python/Sample//Dataset.csv','a')
file.write(",".join([str(newID),request.form['username'],request.form['age']]))

file.close()

I expect the new values in a new row. But it is appending the new values in the last row.
If i add name "Erick" and Age "60", the output looks like the below image.
But I expect something like the below.
Comment: Why can't you write a newline before the row?
Comment: @cricket_007 sorry. I want to add the row in order.
Comment: Possible duplicate of [append new row to old csv file python](https://stackoverflow.com/questions/2363731/append-new-row-to-old-csv-file-python)
Answer: What you're doing is correct, but you're assuming that the file already ends with a new line character
You need to put file.write("\n") before and/or after you've written each line
Comment: Careful that if your file already ends with a newline, then you shouldn't write another one. Otherwise, you would then have empty lines... In such cases, using CSV as a "database replacement" is not a good idea
Answer: A simpler version would be:
import csv

row =['Eric', '60']

with open('people.csv','a') as csvFile:   #a to append to existing csv file
    writer = csv.writer(csvFile)
    csvFile.write("\n")    #write your data to new line
    writer.writerow(row)
csvFile.close()

Output (assuming your csv Doesn't end on new line):

Please be warned (If your csv ends on a newline) the output will have additional space:
Comment: I checked it. It's working fine and it's not adding additional space.
Comment: Notice how prior "Before" image has 3 lines, whereas the later "before" text has 4 lines. If your csv ends on newline it will add space


How to update response xml using groovy and print it

Question: I am completely new to Groovy and SOAPUI.
Scenario : Compare two xml response.(Both belong to different project)
Method Tried : capture the response and write the response to a file, compare both the files.
Issue faced : Timestamp mismatch as both request are run at different times
Due to the above issue I tried to get the Node value of time stamp and change it to * for both the responses.
But I am unable to write the changed response value.
Groovy script :
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
log.info( groovyUtils.projectPath );
def holder = groovyUtils.getXmlHolder( "loginRequest#Response" )
holder.setNodeValue( "//ns3:loginUserResponse[1]/ns3:loginUserResponse/userModel/auditModel/timestamp", "1" );

Initially def holder holds the response xml, but after getting the xml in holder, I am updating the node value. I am not sure how to proceed further. I need to write the updated xml to a file.
Comment: What is the error that you see? Stacktrace please?
Comment: You did not define namespaces in the your XPath! Try `holder.setNodeValue( "//*:loginUserResponse[1]/*:loginUserResponse/*:userModel/*:auditModel/*:timestamp", "1" )`.
Comment: use //*:elementName convention  for the xpath  and then use the groovy code  "holder.updateProperty()" and then write it to a file
Comment: @Rao I do not see any error, I am not sure how to proceed further after getting the XML into the holder
Comment: I understand that, and provided an answer using a random xml since you did not have any xml in the question. Please try it.
Comment: In my case I am getting the XML from the response in holder object. So If I need to use your code I need to convert it into string and check right ?
Comment: @RageshKr, updated my answer covering what you needed to change for dynamic response instead of fixed one, find the details in comments. All you need to do is remove the fixed xml statement and uncomment the currently commented line and replace value for your test step name in place of `TEST_STEP_NAME`. Hope that useful/
Answer: Here is a sample groovy script which uses an arbitrary xml and updates an element value based on certain condition. Then it writes back the updated data to a file as requested. Please follow the in-line comments of the script.
And I believe that this will help your understanding and you will be able to apply it to your actual xml.
What this script actually does?
This xml has incorrect value for madeBy when car name is i30. And like to update xml with Hyundai and write it to the specified file.
/**
* below is the groovy script which read and parses xml
* and updates its value and then writes back to file
**/
import groovy.xml.*
//Sample xml string
def xml = '''<?xml version="1.0" encoding="utf-8"?>
<cars>
  <car>
    <name>Jetta</name>
    <madeBy>Volkswagen</madeBy>
  </car>
  <car>
    <name>Polo GT</name>
    <madeBy>Volkswagen</madeBy>
  </car>
  <car>
    <name>i30</name>
    <madeBy>Typo</madeBy>
  </car>
</cars>'''
//if you want to pass the dynamic response instead of above fixed xml, then
//use below statements by uncommenting below one and replace value for TEST_STEP_NAME and
//comment above xml statement
/**
def xml = context.expand('${TEST_STEP_NAME#Response}')
**/
//parse the xml string and create object
def cars = new XmlSlurper().parseText(xml)
//find the car whose name is i30 and update its madeBy element value to Hyundai
cars.'**'.find { if (it.name == 'i30') it.madeBy = 'Hyundai'}
//print changed cars object
println XmlUtil.serialize(cars)
//Serializes and Writes cars object into given file
new File('c:/Temp/test1.xml').write(XmlUtil.serialize(cars))

If you open your xml file, the output should be as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<cars>
  <car>
    <name>Jetta</name>
    <madeBy>Volkswagen</madeBy>
  </car>
  <car>
    <name>Polo GT</name>
    <madeBy>Volkswagen</madeBy>
  </car>
  <car>
    <name>i30</name>
    <madeBy>Hyundai</madeBy>
  </car>
</cars>

You may also find this example useful which illustrates to create a new xml altogether.


JavaScript replacing /r with  is not working

Question: Now before some one marks this as a duplicate question, I have looked at the other posts with this problem and they have not solved my problem.
so I have a string that has some \r in it that need to be converted into

But nothing is working
output = output.replace("\\r", "
");

is the closest thing that I got working was when my string has /r/r it will replace the first r with
every thing else I have tried literally has done nothing including
replace("\r", "
");
replace(/\\r/g, "
")
replace(/\r/g, "
")
replace(/\n/g, "
")

and a few others that I can not remember.
All those I found on other posts on stack over flow did not work. They did not even replace \r.
Here is an example of one of the strings Year 9 students to meet in their core subject groups at the following places at 8.30 am\r\r9A - OUTSIDE ESOL BLOCK\r9B - TECHNOLOGY COMPUTER ROOM\r9C - ESOL ROOM.\r\rPLEASE WEAR TRACKSUIT.\r its in an loop theres a bunch of different strings –
since people bleave it should be working here is a more brod view of the code

Comment: Are you quite sure the string contains the characters you're trying to replace? At least one of the last three you list having tried should work.
Comment: On three occasions you mention your string contains `/r`(slash r). But in all your attempts your try to replace `\r`(*back*slash r).
Comment: Show us what `output` contains. E.g., we need a [mcve]. Also, if those last four were really `output = output.replace(...)`, show that, don't make people assume you did it based on the first one.
Comment: Maybe your *new-line* is `` tag?
Comment: @SkylineGodzilla: To improve the question, use the "edit" link, not comments.
Comment: If you use one of the things you say you tried on the string in that comment, it works just fine: https://jsfiddle.net/7fupv7Lu/
Comment: Works fine: https://jsfiddle.net/Lh40udds/
Comment: im telling you it dose not work in my code.
ill post my full code
Comment: *"ill post my full code"* No, again, post a *[mcve]*, ideally using Stack Snippets (the `[<>]` toolbar button) so we can see it run live on-site.
Answer: Ok I managed to fix it by creating an function
function nl2br (str)
                {
                    //returns an string that replaces all the \r with new lines
                    return (str + '').replace(/\\r/g,'
');
                }

and then used it to process my output
output = (JSON.stringify(worksheet[z].h)).toString();
output = nl2br (output);
output = output.replace(/"/g,"");

this was a very weird issue and i am glad to of finally solved it.


Google Iframes issue

Question: After hosting google frames html page. I'm getting an error like this:

cb=gapi.loaded_0:154 GET
  https://play.google.com/work/apps?usegapi=1&usegapi=1&origin=https://192.168.0.223&gsrc=3p&jsh=m;//scs/apps-static//js/k%3Doz.gapi.en.tZDXb_qbHrc.O/m%3D__features__/am%3DAQ/rt%3Dj/d%3D1/rs%3DAGLTcCOgQjGru3ruZo70XwAerRmnfOfOeA&etok=WAFX9RHuN55VaiZM_AlanMAxabxxu_V-Vzq7m3MqLK5mLxxvqsRgx_y177_7U6-3bkpjufdZVThjtMQcn-PCI1cJLkS9VwQlHYY7YNETKncL2Z0ykKzA0ifnhd8eLy7vnoVfJt-eTB90k
  500 ();enter image description here
Comment: The error message says you got a 500 Internal Server Error. If I click the link, it shows an internal server error. Why would you expect a different result for that URL under any other condition?
Comment: actually i m trying to create play store in my website using google api before 7 to 8 days ago it will work fine. but now it will shows error like this 500 error. u have any idea how can i make google play store in my website.
Answer: If you press F12 in your browser and go to console. You will see this error.
It says No 'Access-Control-Allow-Origin' when it is trying to go to stathat.com...It could be a CORS issue. Here is a video about it: https://www.codeschool.com/discuss/t/how-to-solve-no-access-control-allow-origin-header-is-present-on-the-requested-resource-origin-null-is-therefore-not-allowed-access-in-angular-js/28989/2
Comment: after accessing html page and after inspect that page i will get likethis.

Google Iframes issue


Store existing buttons in a array in c#

Question: so far I Have this code.
Button[] buttons = this.Controls
  .OfType<Button>()
  .ToArray();

for (int i = 0; i < 25; i++) {
    buttons[i].FlatStyle = FlatStyle.Flat;
    buttons[i].ForeColor = Color.Red;
}

and it gives me a IndexOutOfRangeException. I have 25 buttons.
Comment: What is `this`?  Is it a form?  Also, are any of your buttons inside other containers like a `Panel` or `GroupBox`?
Comment: Why not `i < buttons.Length` in case you change the number of buttons?
Comment: Have you used a debugger to check the size of the button array?
Comment: @Ed Plunkett Thanks for the tip, I have been manually clicking with the mouse each time I needed a break point.  <3
Comment: Are you sure? why don't you do this: `for (int i = 0; i < buttons.Length; i++)`?
Comment: You should use `foreach` to safely loop through them or `button.Length`.
And learn debugging skills)
Comment: My favorite button is `F9`. Use it to set a breakpoint in your code, so you can hover the mouse over `buttons`  and `i` and see what the problem is.
Comment: @ChrisDunaway it's inside a group box
Comment: Then you should be doing something like :`Button[] buttons = this.groupbox1.Controls.OfType().ToArray();`
Comment: You need a recursive function to run through all the controls in the form, returning your arrary of buttons. All container controls have its own Controls collection.
Answer: Do not use magic numbers (25):
Button[] buttons = this.Controls
  .OfType<Button>()
  .ToArray();

foreach (var button in buttons) {
  button.FlatStyle = FlatStyle.Flat;
  button.ForeColor = Color.Red;
}

If you insist on for loop (please, notice buttons.Length - actual array's length):
for (int i = 0; i < buttons.Length; i++) {
  buttons[i].FlatStyle = FlatStyle.Flat;
  buttons[i].ForeColor = Color.Red;
}

Comment: I'm using a groupbox container.. having a large difference?
Comment: @Frank gagui: no, probably you'll want to change the *Linq* a bit (say, get not all the buttons but within the groupbox only)
Answer: Using the Length of the array in the for loop statement should prevent the out of range exception.
  Button[] buttons = this.Controls.OfType<Button>().ToArray();
  for (int i = 0; i < buttons.Length; i++)
  {
     buttons[i].FlatStyle = FlatStyle.Flat;
     buttons[i].ForeColor = Color.Red;
  }

Store existing buttons in a array in c#


Watch a prop change from parent to child

Question: I was trying to implement watcher like in the following solution:
How to listen for 'props' changes
and I have an attribute called "selectedItem" which I'm trying to pass on to a child and watch over the value that comes so I can make some manipulations on it over the handler, but the watch isn't being triggered for some reason.
here are the parent and child code:
parent (Products component):
<template>

    <Popup item="selectedItem" />

      <template #cell(Edit)="data">

          Edit

      </template>

</template>

child (popup component)
<template>

</template>

I know I've asked a question which runs a lot here, but haven't figured what I did wrong.
Comment: `` - Are you really using this or is it a typo?
Answer: Your Popup component is declaring it receives prop with the name selectedItem. But you are using the Popup like <Popup item="selectedItem" /> which means that you are trying to pass a string "selectedItem" into a prop called item
This is what you want:
<Popup :selectedItem="selectedItem" />

Comment: Thanks friend. I forgot about the string template, and didnt realize that I've used different names for the prop. silly me.


Why network button not working when I clicked it

Question: Sometimes I clicked this network button:
http://www.divshare.com/download/15716721-6fa
Why it doesn't work (just like I haven't clicked it)?
When it failed, only when I reboot,it works again.
Sometimes it failed again.
What could I do?
I use ubuntu 11.04 64 bits.
Answer: Try this when it doesn't work - sudo service network-manager restart . That will restart the network-manager applet.
Answer: If the above does not work then you can try this:
sudo modprobe -rfv ath9k
sudo rfkill unblock all
sudo modprobe -v ath9k

which a temporary solution. It will work until you reboot. For more details and a permanent solution:
http://ubuntuforums.org/showthread.php?t=1895671
Comment: can you please provide details of the "permanent solution"?


How do I check if something was 4 days ago in PHP?

Question: I am trying to write a function which checks if a "Finished Lesson" was four days ago. How do I check if said lesson was in that time range, for example. If it was finished yesterday, 2 days ago, 3 days ago, 4 days ago, it would be true since it is in the time range of "4 days ago".
How do I check this?
So far I've done:
$time = time();

$fourDays = 345600;
$threeDays = 259200;
$lastLesson = $ml->getLesson($cid, $time, true);

$lastLessonDate = $lastLesson['deadline'];
$displayLastLesson = false;
if ($lastLessonDate  + $fourDays < $time)
{
    $displayLastLesson = true;
    //We print lesson that was finished less than 4 days ago
}
else
{
    //We print lesson that is in the next 3 days

}

Right now, the if statement keeps hitting true which is not what I want since I have a lesson that was finished on the 3rd May. It should be true for a lesson that was finished on the 7th May I guess?
Comment: What datatype is $finishedLesson['deadline'], is it a unix timestamp?
Comment: When you say 4 days ago, do you mean between exactly 4 days ago and 5 days ago (ie between 1:27pm on the 6:th and 1:27pm on the 7:th) or do you mean anytime during the day on the 6:th?
Answer: $time = time();
$fourDays = strtotime('-4 days');
$lastLesson = $ml->getLesson($cid, $time, true);

$lastLessonDate = $finishedLesson['deadline'];
$displayLastLesson = false;
if ($lastLessonDate >= $fourDays && $lastLessonDate <= $time)
{
    $displayLastLesson = true;
    //We print lesson that was finished less than 4 days ago
}
else
{
    //We print lesson that is in the next 3 days

}

Comment: Hey, your answer is correct and makes more sense than mine but what is the difference between this:

$lastLessonDate + $fourDays > $time and your if statement ?
Comment: Actually...I found $lastLessonDate + $fourDays > $time to work !
Answer: All calculations should be calculated relative to today at 12am, not time() which gives you the current time now (e.g. 6pm)  This is an issue because when you do this, 1 day ago (now - 24hours) means time that is between yesterday 6pm and today 6pm. Instead, yesterday should mean a time between yesterday 12am and today 12am.
Below is a simplified calculation to illustrate the idea:
$lastLessonDate = strtotime($lastLessonDate);
$today = strtotime(date('Y-m-d')); // 12:00am today , you can use strtotime('today') too
$day = 24* 60 * 60;
if($lastLessonDate > $today) // last lesson is more than 12:00am today, meaning today
 echo 'today';
else if($lastLessonDate > ($today - (1 * $day))
 echo 'yesterday';
else if($lastLessonDate > ($today - (2 * $day))
 echo '2 days ago';
else if($lastLessonDate > ($today - (3 * $day))
 echo '3 days ago';
else if($lastLessonDate > ($today - (4 * $day))
 echo '4 days ago';
else
 echo 'more than 4 days ago';


Want to cover up nail points in attic ceiling

Question: I'm in the attic every so often to store empty boxes and I'm planning to do some wiring (non electrical) so I'm afraid that I might stand up and have nails through my head.
My plan isn't to cover the whole attic ceiling, just a small section of the attic ceiling. Any ideas on what I can do to cover the nail points?
I tried using a hammer to try to bend it but the nails are way too strong to do that.
Answer: Leave a hardhat or bump helmet (lighter version of a hardhat) by the attic hatch. Put it on when you enter; take it off when you leave.
Comment: Yea I was thinking hard hat too
Answer: I stick a wine cork on each nail.
Answer: You can try using a tool called "end cutting nippers" like this one at
http://www.zoro.com/knipex-end-cutting-nippers-8-in-68-01-200/i/G4782504/?gclid=CjwKEAiAwZO0BRDvxs_1w-qFnhkSJABo10ggFX-miYd0y3GpEsBdvsvujCS5ESnbOYiu6hZYLmz5oBoChZnw_wcB&gclsrc=aw.ds
Cut the ends of the nails off close to the inside of the roof.
Comment: No, it will not cause the shingles to "take flight". A roofing job properly done means **no shiners**. The roofer was too lazy/cheap to procure the proper length nails.
Answer: I found a simple way to cover the nail points.  Use small pieces of plastic tubing over each nail point.  Depending on the size of nails, you may need one or two different tubing sizes.  I used  "Micro-Fuel Line" from Home Depot in two sizes: 1/4" OD/7/64" ID, and 3/16" OD/3/32" ID because I had two different nail sizes in my attic.  A 10' length of each costs only $4.76.  Cut the tubing into pieces about 3/8" to 1/2" long depending on length of exposed nails in your attic, then push a piece of tubing onto each nail point.  No more nails in the head!
Answer: Thin (1/4") plywood or OSB across the bottom of the rafters would work well. Make sure that you don't prevent air from passing under the back of the roof. As long as you leave 2 feet open at the top and bottom of the plywood, and you don't fill the roofing cavity, you should be fine.
Answer: I have the same issue in my garage. I had the attic truss setup for storage with just enough head room to bend over and walk. Nails showing everywhere.  I think I will by some cheap long rolls of chicken wire to staple on the bottom of the roof rafters. This will keep me from causing injury to my head but will still allow air to flow under shingles
Answer: My plan for this is to stick lattice (vinyl or Cedar) panels between the rafters. This would provide clearance over the nails, would keep airflow going, and not leave spaces for critters to hide as partial OSB coverage would. The next step up would be to cover it all with OSB with vent opening (as one would do with closed soffits) but that is probably an overkill for a storage space.
Answer: If only a few rogues and you can get at them with Junior hacksaw then saw just under half way through near to board as possible.  Bend over with pliers or mole grips for better grip.
Add a blob of 2 part epoxy if it is still sharpish at the bend or a bit of blue tack for quickness. This is only suitable for small area as tiles now pinned tight and make them harder to remove if needed.  Best suited to a shed or a few rogues in loft.


Connect C# client to C++ server

Question: I just can't get it to work, I'm frustrated.
My C++ code ( _details is addrinfo* and _socket is SOCKET):
struct addrinfo hints;
_socket = socket(AF_INET, SOCK_STREAM, 0);
if (_socket < 0)
    throw "Invalid socket";
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

if (getaddrinfo(NULL, Port.c_str(), &hints, &_details) != 0)
{
    throw "GetAddrInfo failed";
}

if ((bind(_socket, _details->ai_addr, this->_details->ai_addrlen)) != 0)
{
    throw "Bind Unsuccessful";
}

freeaddrinfo(this->_details);
if (listen(this->_socket, SOMAXCONN) != 0)
        throw "Listen Unsuccessful";
client = accept(this->_socket, (struct sockaddr*)&client_addr, &addrlen);

A simple C++ server. C++ and Python clients work perfectly with the above server, and doing everything as expected.
Then comes the client:
        Socket s;

        IPAddress ip = Dns.GetHostEntry("127.0.0.1").AddressList[0];
        int port = 7777;
        IPEndPoint remoteEP = new IPEndPoint(ip, port);

        s = new Socket(AddressFamily.InterNetworkV6,
            SocketType.Stream, ProtocolType.Tcp);

        bool isConnected = false;
        while (!isConnected)
        {
            try
            {
                s.Connect(remoteEP);
                isConnected = true;
            }
            catch (Exception e1)
            {
                System.Threading.Thread.Sleep(2000);
            }
        }

The C# client works perfectly with a C# server.
Each of these work, together - they just don't. I try to connect to the server but the client always ends up throwing System.Net.Sockets SocketException with the error code of 10061, claiming that the C++ server rejects it.
One thread on SO asked a similar question, receiving the answer that he should sleep after every connection request and then try again (as you can see, done already).
Another thread, on another site, claimed that the problem is in the server and that he converted the C++ server parameters from host byte order to network byte order:
listenSocketAddress.sin_port = htons((u_short)port);
listenSocketAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

but I use addrinfo which doesn't contain the same variables as sockaddr_in.
How can I connect those two?
Comment: Well, I'm not an C++ socket expert... but isn't your C++ side using IPv4, while the C# side is using IPv6? The `AddressFamily.InterNetworkV6` seems to be a dead giveaway...
Comment: @Luaan I cannot believe my error was so foolish, I didn't even notice it. I should probably have the server IPv6 instead :D Thank you very much.
Answer: As far as I can tell, your C++ side is using IPv4 (AF_INET), while your C# side is using IPv6 (AddressFamily.InterNetworkV6). Either change the server to use IPv6, or change the client to use IPv4. Or ideally, let them use whichever works best, and use hostnames instead of IP addresses.
Comment: Thanks a lot, unbelievable I made so much effort and I didn't spot the `V6` part.

Connect C# client to C++ server


Area under the curve and manual calculation

Question: Imagine a situation where each additional item is sold with a higher price.
First Item costs 1 dollar, second item costs 2 dollars, third 3 dollars etc.
This image show the example graph:

If you want to buy 3 items, you would have to pay $\$1 + \$2 + \$3 = \$6$.
The area under the curve is the area of the triangle:
$$\frac12  bh = 4.5.$$
Shouldn't the area under the graph curve equal $6$ dollars instead of $4.5$ dollars?
Clearly I'm not getting something right here.
Please point me to the right direction.
Comment: The area under the graph from $0$ to $1$ is $1/2$, which is $1/2$ dollar short.  The area under the graph from $1$ to $2$ is $3/2$, which is $1/2$ dollar short.  The area under the graph from $2$ to $3$ is $5/2$, which is $1/2$ dollar short.  Apparently you need the line to be shifted up a bit if you want its areas over these unit intervals to equal each of the three item costs...  (... or add $1/2$ dollars per item to make up for this shortfall ...)
Comment: So basically I'm looking for a formula to help me calculate how much the customer has to pay for requested number of items with constant increasing price.. I thought integration solves this problem, or in this case geometric formula since the graph is linear. I still don't get why is it short for 1/2 dollar ...
Comment: Look at your graph between $0$ and $1$.  The area for one itsm's cost is the $1 \times 1$ square in your graph, the lower-right half of which is the blue triangle your integral is giving you.  So you have graphed why the integral is $1/2$ dollar short on $[0,1]$.  On $[1,2]$ you want an area that is the same as two $1 \times 1$ blocks stacked on top of each other, but your function has cut off the upper-left half of the upper block...
Answer: For easier reading, I shall refer to the items as pens.

Consider labelling the axes better: the vertical axis "cost" is very
ambiguous (total cost? average cost? etc.?) and can be renamed "cost
of the $n$th pen", while the horizontal axis should be "pen
number/index" instead of "number of pens".
The area under a graph gives the sum of the 'vertical' quantity as
the function varies over an interval of the 'horizontal' quantity.
On the other hand, the pens' total cost is a sum of discretely
many items, rather than a sum over an interval. This is why they aren't
equal.
The sum that you require is just an arithmetic series, so does have
a formula: $$\text{total cost of $n$ pens}=\frac{n(n+1)}2.$$
Reverse-engineering this formula: $$\text{total cost of $n$ pens}\\=\text{the area under the $\left(x+\frac12\right)$-versus-$x$ graph between $0$ and $n$}.$$


Desire2Learn Valence API for library sections

Question: Is there a Valence API call that can be used to check whether or not a given question library section name exists?
Answer: There are no APIs related to question libraries or quizzes in Valence currently.


PWA Manifest Icons failing to fetch

Question: I am wondering what the path and issue is for this error from Lighthouse Audit:
Web app manifest does not meet the installability requirements
Failures: Manifest icon failed to be fetched.
I have all of my images icons from 72x72 to 512x512 so I am wondering what the problem is?
in the public folder i have a folder: assets/icons/(all the icons)
This is the manifest.json
<code>{
  "name": "Chronowell",
  "short_name": "Chronowell",
  "theme_color": "#000099",
  "background_color": "#000099",
  "display": "fullscreen",
  "Scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "splash_pages": null
}
</code>
Comment: @MichaelPaccione I am facing the same issue. Were you able to fix it?
Comment: Have you run Lighthouse in Chrome to check for errors?
Comment: Yes, that was the error I copy pasted from Lighthouse.
Comment: Oh you know what I think I see it now it looks like the array keyname got replaced during a word search and replace!
Comment: Updating the question because it still gives a failed to fetch
Comment: Ah yes I believe the one of the images was not actually the correct size as it was labeled... and it produced a generic error.
Answer: Make sure that the icons are accessible. You can find the URL that chrome is trying to access under "Application" tab under "manifest", they will be shown there if there is a problem.
One problem I had was that the icons and the manifest are requested without sending cookies. My server would return "Unauthorized" in that case.
The manifest can be adjusted to send cookies like this:
<code><link rel="manifest" href="/app/manifest.json" crossorigin="use-credentials">
</code>
For the icons I'm not sure if there is a option to send them with credentials. I resolved the issue by putting them in a publicly accessible folder and updating the manifest to contain absolute URL's.
Answer: You are not able to fetch your icons because you're setting the URL in the wrong way. Your URL should be: "/assets/icons/icon-72x72.png" in this case. First of all, make sure you're passing the right URL, and test if your icons are accessible first. Hope this answer helps you.

PWA Manifest Icons failing to fetch


Can a Truth window operator arm be *repaired* (not replaced)?

Question: Good Afternoon,
In the picture you are looking at "left orientated" Truth window operator arm:

https://ibb.co/8sBW6Sp
For those of you who are more experienced handymen, will notice that the round plastic bit broke off at the end of the operator arm, resulting in coming out of the rails.
My question is:  Do I have to now go and spend $30 to replace the entire arm?  is there no way I can just replace the white plastic bit?
Thank you for your time.
Comment: Unfortunately it is probably simpler and cheaper these days to replace the arm.  If you know the shape and size of plastic piece, might be able to have it made by a 3D printer, or might find something at a store/online that might be able to replaced it with.  Depends if the brass looking knob can be removed.
Comment: Edited for you, to put picture in post.
Comment: @crip659 I had not thought about a 3D printer, I know HP made some metal filled setups and they printed us some 6" crescent wrenches that was 10 years ago and I still have mine somewhere it has been used a few times so printing may work but replacement is probably a better path. +
Comment: As someone with a lathe, I'd sure give it a go to turn a replacement out of brass, and forgo the plastic piece completely.   Sure it'll cost $60 in brass and 12 hours, but still a cheaper hobby than smoking :)
Answer: Those arms are not really meant to be repaired. The axle is riveted onto the arm so your only real chance of repairing it it to pop the riveted area on the bottom of the arm and pry the piece off. Then look for a nylon washer at your home store that's close to the size of the broken piece, reassemble and Press fit or hammer the riveted part of the axle back into the arm.
You could also try to replace that axle with a bolt, nylon washer and nut on the bottom.
Honestly though, having tried all of the above, I would buy the new part if it's available.
Comment: They may be able to tap a short shoulder bolt but I agree it may be able to be done but probably not worth the effort.
Comment: THANKS FOR ALL THE COMMENTS


Getting attribute value using XElement

Question: I have an xml file like this
<Program xmlns="CBOpenIFSchema3_0">
    <Variables/>
    <CodeBlocks>
        <CodeBlock Name="Code1">

                Sample code 1

        </CodeBlock>
        <CodeBlock Name="Code2">

                Sample code 2

        </CodeBlock>
        <CodeBlock Name="Code3">

                Sample code 3

        </CodeBlock>
    </CodeBlocks>
</Program>

From this xml I need to get the name of each codeblock and the code corresponding to it. How can this be done using XElement? I tried using the following.
XElement xDoc = XElement.Load("test.xml");
IEnumerable<XElement> codeBlocks = xDoc.Descendants("CodeBlocks").Elements();
foreach (var c in codeBlocks)
    Console.WriteLine(c.Attribute("Name").Value);

codeBlocks is showing "Enumeration yielded no results".
Edit: xmlns="CBOpenIFSchema3_0" gives the problem.
Comment: is this your read XML in `test.xml`? your code working fine for me
Comment: @Sreeja try again. it seems ok. Just check the test.xml file that your programm is suppose to use. and also check your projects output directory.
Comment: Sorry an error while copy-pasting the xml. Edited it.
Answer: Your document uses default XML namespace, so you have to use one within your query:
var xDoc = XDocument.Load("source.txt");
var ns = XNamespace.Get("CBOpenIFSchema3_0");

var codeBlocks = xDoc.Root.Element(ns + "CodeBlocks").Elements(ns + "CodeBlock");
foreach (var c in codeBlocks)
    Console.WriteLine((string)c.Attribute("Name"));

I've also made some changes to your code:

use XDocument to load XML document
use XAttribute Explicit Conversion (XAttribute to String) instead of XAttribute.Value property
don't use Descendants method unless your XML contains tree-like structure
Comment: Can you please tell me why do you suggest XDocument when both XElement and XDocument works fine? Is it the best practice?
Comment: Is your XML a document? So use class that is designed to deal with document. There is additional XML validation when you're using `XDocument`.
Comment: An XDocument is rarely needed, an XElement as root works fine in most cases.
Comment: And you could have used `var ns = xDoc.GetDefaultNameSapce();`

Getting attribute value using XElement


Mapkit with annotations and IBAction to Load New View on Pin

Question: I have recently attended an introductory course in using the iPhone SDK and the Objective-C programming language. The course didn't really go into great detail on using Mapkit and the likes of annotations etc..
I am required to create an application which uses the inbuilt Framework MapKit, I need to be able to generate a map based on user input from the super view which then queries an external NSURL and reads either jSON or XML data type output from that URL to populate the Map's Pins (annotations).
These Pins need to have an IBAction or IBOutlet to load another sub view based on what the user has tapped to reveal more information on that particular entry - which needs to be stored in memory until viewDidUnload or loading a particular sub or parent view.
So as you can imagine this seems terribly daunting in order to find out, I have trolled Google and this site for answers and I can't seem to find what I am looking for - hence this post.
If anyone could assist or point me in the right direction that would be deeply appreciated!
I hope this post makes sense?
Thanks!
Answer: You could take a look at iTunes U -> CS193P - Fall 2010 -> Lecture 14. Core Location and Mapkit
Link
Hope this helps you going in the right direction


Typo3: Add

Question: Im currently working on some content within a typo3 page I only have editor rights on.
I'd like to add some styling to a table. To do so, I wanted to add the following:

Typo3 seems to remove the tags when I save, rendering me unable to add the styles.
Is there a way to accomplish this in my situation?
Answer: I guess you tried to add the styles in the RTE editor, but style or script tags will be removed on save, this is normal.
The main problem is, that you are not an admin. The only way to add some styles is adding a "Plain HTML" content element to the page and add your styles there, but it can be possible, that the admin deactivates that element for you.
Answer: Thanks for your help, this function is indeed (as expected) deactivated. But you've helped me clear out the situation. I now know what I have to ask the admin for.

Typo3: Add


Global variables or equivalent in C#

Question: I need to read XML file and store all the info inside variables/class  when the software starts, and make the variables/classes be accessible every class.
With C++, I could use global variables or classes, even though it's not a good practice to have a global variables.

If the variables/classes are read only data, what methods can I use for my purpose with C#?
What if the variables/classes are read/write?
Answer: You could use a public static class, and make everything available from there. You could populate it with data at creation time. It won't technically be at global scope, but would make the data easily available, and you wouldn't explicitly have to instantiate anything.
Answer: a static class with a static readonly variable
Answer: static class with static public variables
read/write can be done this way:
<code>private int _someInt;
public int SomeNumber{
  public get {return _someInt;}
  private set {_someInt = value;}
}
</code>

Global variables or equivalent in C#


What is the practicality of using PhoneGap?

Question: I am currently doing some research in using PhoneGap instead of write different code for all platforms. In my mind, right off the bat, one con to this is, in fact, you aren't writing your applications natively. I ask myself, what does this mean?

Will there be a performance hit?
Does PhoneGap offer wrappers for all native functionality? Is the documentation enough to get by?
What kind of UI's would you want or need(i.e. JQuery) and do they have proper documentation? Do these frameworks work seamlessly across different platforms?
Since Adobe is now in the mix will PhoneGap eventually become obsolete and in the long term it just doesn't really matter?

I would like to hear any feedback/advice/suggestions for those that have tried PhoneGap. Also if there is a list of functionality PhoneGap doesn't provide could someone provide a link?
**EDIT: I should point out that I realize that a big motivation of using PhoneGap is so that one doesn't have learn multiple programming languages. I already know Objective-C and Java and I am just exploring the potential use of PhoneGap - so I am coming at this from a slightly different angle. I mentioned this in one of my comments below.
Comment: If you want to check out some html app examples check out: http://m.chromeexperiments.com/ This is not phonegap, but you could make all this using PhoneGap aswell. Just to let you know some possibilities.
Answer: Short, objective answer: It depends.
Specifically, whether PhoneGap/Cordova is appropriate for your project depends on your needs. There are a lot of PhoneGap-based projects out there, so it's obviously useful for some developers; only you can say whether you're likely to be in that group.
More details:

Will there be a performance hit?

Yes. Whether that matters depends on your application.

Does PhoneGap offer wrappers for all native functionality? Is the
  documentation enough to get by?

No on the first question, but it's extensible, so you can always add your own native code if you need to. Only you can say whether the documentation is sufficient, but you can always look at the code if you need/want to.

What kind of UI's would you want or need(i.e. JQuery) and do they have
  proper documentation? Do these frameworks work seamlessly across
  different platforms?

That would seem to depend on what you're doing and on what you already know. PhoneGap doesn't make much difference one way or the other here.

Since Adobe is now in the mix will PhoneGap eventually become obsolete
  and in the long term it just doesn't really matter?

Whether Cordova (the open-source software formerly known as "PhoneGap") survives and thrives depends on many factors:

Are people using it?
Do the people who use it contribute to it?
What will Adobe decide to do with PhoneGap (the proprietary version)? Will they kill it? Enhance it? Add features so compelling that most people choose it over Cordova?

If Cordova makes sense for your application, by all means use it. Contribute to it, if you can, and it will become even more useful to you and to the rest of the world.
Comment: as I had mentioned below to Yusufs post one of the main capabilities that I am going to be looking for is Core Graphics and/or the Android equivalent. Web services is another issue. Can PG take information from a webservice using JSON and export the data as need by the native app(s)? I am sure there are other libraries that I need to mention but those are the two that I can think of now.
Comment: PhoneGap lets you write your app using JavaScript & HTML, and it lets you make calls to the native app for additional functionality. You could implement certain features in native code using Core Graphics and then drive those features from JavaScript, but if yours is a graphics-intensive app then PhoneGap may not be the right solution. You'd do well to simply start using it for a simple project to learn more about it so that you can make a choice informed by your own experience.
Answer: For simple apps, PG will not be a performance hit.
PG has many but not all native functions. You can always write a plugin, but really who wants to?
PG may go away eventually, but probably not until after your app does.
Comment: The only reason to write a plugin is if you already have a lot of HTML5 code from some other project and lack only one native function to complete your awesome app.
Comment: One of the native functions that I am really going to be interested in is the Core Graphics methods for iOS. On the PhoneGap website it does state that it supports "Media" but to me that sounds more like Movies and Pictures rather than custom drawing with core graphics. Also i see "Network" but that doesn't really scream web services(JSON?)
Comment: @cspam, If you have heavy graphics requirements maybe you could get away with new capabilities in HTML5 but I'm not sure how those features are adopted in mobile device browsers. Since you are making an app with html/javascript, you can call web services with ajax requests. If there is something you need natively, you can write a plugin but keep in mind that you would need one plugin per mobile platform that you're wanting to build/distribute.
Comment: @jlafay. Thanks for bringing the plugins piece of this. If you need to write a plugin because PG doesnt offer a functionality that you need and like you said, you need to write the plugin for each device that you are targeting...then haven't defeated the purpose of not having to write separate pieces of code natively for each platform? What if you end up having to write 3 or 4 plugins? then thats a possible 8 different pieces of code that you would have to write. At some point it would have just been easier to start off native.
Comment: @YusufX, yes it definitely depends on what you want to do and it's something to keep in mind when considering PG. Since the question is very open and high level, it's hard to say what would need to be used.
Comment: @YusufX - I am going to assume, at the moment, that PG doesnt support wrappers for Core Graphics. We are talking about a lot of missing native functionality here that you would need to write plugins for. I am not familiar with how writing a plugin works(still working through that) but if i end up needing to write multiple plugins(as I pointed out from jlafays response) then thats a lot of extra work. The reason a lot of people want to use PhoneGap is that they dont want to learn multiple programming languages. I already know ObjC and Java so I am coming from the other angle here.


how to add elements dict to dataframe using python?

Question: i want to add a data from dict to dataframe and display on table is possible ??
import pandas as pd
names = ['alan','jack','martin','loki','edward','sakes']
old = [18,17,20,21,22,19]

data = {'names':names,'old':old}
print(data)

after excute :
{'names': ['alan', 'jack', 'martin', 'loki', 'edward', 'sakes'], 'old': [18, 17, 20, 21, 22, 19]}

any solution possible ??

plz help me i need for us
Comment: Is `data = pd.DataFrame({'names': names, 'old': old})` what you are looking for?
Answer: I can't really tell whether you want column-oriented or row-oriented.
timr@tims-gram:~/src$ cat x.py
import pandas as pd
names = ['alan','jack','martin','loki','edward','sakes']
old = [18,17,20,21,22,19]
print( pd.DataFrame( [old], columns=names ) )
print( pd.DataFrame( {'names': names, 'old':old } ) )

Output:
timr@tims-gram:~/src$ python x.py
   alan  jack  martin  loki  edward  sakes
0    18    17      20    21      22     19
    names  old
0    alan   18
1    jack   17
2  martin   20
3    loki   21
4  edward   22
5   sakes   19

Answer: It is actually quite simple:
pd.DataFrame([data])

That should do the trick


Determine whether $\sum_{n=2}^\infty \frac{1}{n(n - 1)}$

Question: I am trying to determine whether the series $\sum_{n=2}^\infty \frac{1}{n(n-1)}$ converges or not.
I first broke the sequence up into partial fractions to obtain
$$\sum_{n=2}^\infty -\frac{1}{n} + \frac{1}{n-1}$$
$$=  \sum_{n=2}^\infty -\frac{1}{n} + \sum_{n=2}^\infty \frac{1}{n-1} $$
The first series is a harmonic series and so it diverges. The second series is bigger than an ordinary harmonic series $\sum_{n=2}^\infty \frac{1}{n}$ and so by direct comparison if the harmonic series diverges so must $\sum_{n=2}^\infty \frac{1}{n-1}$. Both series diverge and it is known that the sum of two divergent series could be either divergent or convergent. I am not sure how to determine if this series converges - any help would be appreciated.
Comment: By method of difference, it likely will converge. I'll double check again.
Comment: It does converge and the sum is 1. I'm just not sure how to get to this result.
Answer: $$
\lim_{k\to \infty}\sum_{n=2}^k\left(\frac{1}{n-1}-\frac{1}{n}\right)=\lim_{k\to \infty} \left(1-\frac{1}{2}+\frac{1}{2}-\frac{1}{3}+\cdots-\frac{1}{k}\right)=\lim_{k\to \infty}1-\frac{1}{k}=1.
$$
Answer: \begin{align}
\sum_{n=2}^\infty \frac{1}{n(n-1)}=&\lim_{N \to \infty}\sum_{n=2}^N \frac{1}{n-1}-\frac{1}{n}\\
&=\lim_{N \to \infty} \bigg(\frac{1}{1}-\frac{1}{2}\\
&+\frac{1}{2}-\frac{1}{3}\\
&+\frac{1}{3}-\frac{1}{4}\\
&\vdots\\
&+\frac{1}{N-1}-\frac{1}{N} \bigg)\\
&=\lim_{N \to \infty} \left(1-\frac{1}{N}\right)\\
&=1
\end{align}
Clearly the series converges.
Answer: use that $$\sum_{n=2}^m\frac{1}{n(n-1)}=1-\frac{1}{m}$$
Answer: Use the limit comparison test
$$
\frac{1}{n(n-1)}\bigg/n^{-2}\to1
$$
as $n\to\infty$. Since $\sum n^{-2}$ converges, your series converges as well.


How can you control cities in Sid Meier's Pirates?

Question: On the PC version of the game the box says that you could take control of cities and rule them yourself. How can you do that and can you get settlements too?
Comment: Which Pirates? The new one or the original one?
Comment: I didn't know there was more than 1 type. I bought mine in 2007.
Comment: @YoungGuilo Well, the original Sid Meier's Pirates! came out for the C64, that is where I played it :D. Probably my most played game from age of 13 and I still play it with the VICE Emulator sometimes. And since then a big Sid Meier's Fan hehe. Sorry for offtopic.
Comment: You make them part of your nation. Reading some game reviews (i.e., doing some research) can help you avoid asking really basic questions here.
Answer: You can't, except in two meta-ways:

The most common is when you successfully pillage a city after destroying a significant amount of its defending garrison. The Governor will run for the hills and you get to decide which of the four nations to invite to send a replacement. Needless to say, the nation that gets a shiny new (well, slightly used) town out of it will be very happy with this.
If you complete all the quests, get all the loot and max out your rank and wealth, the highest position you can earn as you retire is "Governor". Of course, at that point the game is over, so that may or may not count either...


Is it possible to install Ubuntu on my iMac OSX 10.8.5?

Question: it's possible to  install Ubuntu on my  iMac OSX 10.8.5....
Do You guys have any tutorial on  because I am a dummy... or somewhere where I can learn.
Comment: Possible Duplicate of: [How to install Ubuntu 12.04 on Mac OS X?](http://askubuntu.com/q/151371/107450) or see here: [How to install Ubuntu on MacBook using USB Stick](https://help.ubuntu.com/community/How%20to%20install%20Ubuntu%20on%20MacBook%20using%20USB%20Stick)
Answer: Yes, it is very much possible, download ubuntu from the Ubuntu Downloads Page and then either Create a bootable flash disk or Burn it onto DVD and then restart your machine with the either the disc inside the machine or the flash disk attached to the usb port.
I beleive noboy is a dummy, but if you really are not getting it, Click this link to see detailed information and procedures on the installation process.


Why request latency increases when adding more async requests, resulting in ridiculous load time?

Question: I have MVC app that is basically 1 main view and multiple partial views.
I have this tiny script on a min page that loads partials views asynchronously:

When I comment them all, I get this (very fast loading):

Now I uncomment just the "Bookmarks" request (just reads small JSON file from local drive), I get this (Bookmarks takes 9ms):

Now I uncomment the "Calendar" request (Google Calendar API), I get this (why Bookmarks latency jumps from 9ms to 1.04s if the requests are async?):

Now I uncomment the "Gmail" request (Google Gmail API), I get this (Bookmarks latency jumps again from  from 1.04s to 1.53s?):

Now I uncomment the rest ("Gmail", "Weather" and "News" requests), I get these insane increased latencies all over, the Bookmarks request takes now 5s to execute, instead of 9ms - why?):

You can see the increase in latency for each operation - it looks like these ajax requests are not asynchronous at all :( How is that possible, when AJAX is supposed to be async by default?
I am sure I am missing something here, may jQuery load function is not async, but it's on javascript size, and the delay is on server-side. I am now confused.
Update: obviously jQuery call are async, all load functions are executed at the same time. It's easy. The problem is on the server side. After having dome some tests, it's clear that IIS executes these request synchronously, sequentially one after another in the order it received them from the browser. I have done some additional reading on IIS, and by default IIS apppool has only 1 worker process that is being used, that can fire multiple threads for processing all these requests. But for some reason, the requests are being processed sequentially and not in parallel. I haven't found yet why (if a AppPool worker process can start many threads for simultaneous processing) the requests are still executed sequentially, and  how to make these requests to be processed in parallel, and if it's even possible. If someone has any idea how to make thing work properly I would really like to hear. Thanks.
Update After some more reading, found that requests are processed sequentially if Session is enabled. The session object is a single threaded object. The session object cannot be shared by two threads simultaneously. Hence when there are two requests for the same session one is queued while the session object is in use by the other. This sucks :( Any suggestions, IIS experts? :)
Solved
Yes, Session State was the problem! I disabled session state in web.config  and removed one line that used Session object to avoid runtime error. Now everything works perfect. The true problem was indeed - that Session state is bound to a single thread, therefore on the server side my app behaved like an old STA fart :)

http://msdn.microsoft.com/en-us/library/ms178581.aspx
Concurrent Requests and Session State
Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.
Answer:
After some more reading, found that requests are processed
  sequentially if Session is enabled. The session object is a single
  threaded object. The session object cannot be shared by two threads
  simultaneously. Hence when there are two requests for the same session
  one is queued while the session object is in use by the other. This
  sucks :( Any suggestions, IIS experts? :)

Don't use Session. I rarely find cases that justify use of Session, and it's often easy to find storage alternatives that don't have the scalability limitations that you run into with it.
Comment: Yes, that was the problem! I disabled session state in web.config  and removed that one line that used Session object to avoid runtime error. Now everything works perfect. The true problem was indeed - that Session state is bound to a single thread, therefore on the server side my app behaved like an old STA fart :) Thanks man!


The first derivative of inverse hyperbolic sin

Question: If I know $ sinh^{-1}(x) $  = $ ln(x+ (1 + x^{2} ) ^ { \frac{1}{2} } )  $
I know a way to evaluate that derivative, it is : $\frac {1}{(1 + x^{2} )^{\frac{1}{2}} }$ but is it acceptable to take $ \frac{d}{dx} $ both sides above and work it out?
I have attempted it anyhow on RHS and here are the steps so far :
$ \frac{d}{dx}  ln(x+ (1 + x^{2} ) ^ { \frac{1}{2} } ) = \frac { f'(x) } { f(x) }
 [ $ where $ f (x) = (x+ (1 + x^{2} ) ^ { \frac{1}{2} } ) $ ]
$ = \frac { 1+ \frac{(x^{2} +1)^{\frac{-3}{2}}}{2} }{x+ (x^{2}+1)^{\frac{1}{2}}} $
and this is where I stopped.
Edit :
the reason was a simple mistake in differentation in the last step where it should be $ \frac {-1}{2} $ instead of $ \frac {-3}{2} $ which lead to problems with the simplification. Mark's answer is complete.
Comment: I hope you know the much simpler way of getting the derivative, i.e. implicit differentiation.
Comment: shouldn't it be -1/2 for the exponent on top
Comment: no it's just a normal square root.. here's how http://wwwf.imperial.ac.uk/metric/metric_public/functions_and_graphs/hyperbolic_functions/inverses.html
Comment: @Deepak , i think i have an intuition on it since it's how the implicit function is defined ( i guess ) but i haven't tried to drive with it. i will try and update .
Comment: If you've ever seen the derivation using implicit derivatives for the inverse trig functions, the development is basically identical
Answer: We have the following:
$$f(x)=sinh^{-1}(x)=log(x+(x^2+1)^{1/2})$$
So, taking the derivative of both sides yields:
$$\frac {dy}{dx}=\frac {1+\frac {x}{(x^2+1)^{1/2}}}{x+(1+x^2)^{1/2}}$$
This is simply via the chain rule, noting $\frac {d}{dx}log(x)=\frac 1x$, so $\frac {d}{dx}log(g(x))=\frac {g'(x)}{g(x)}$
So, combine the two fractions in the numerator into a single fraction:
$$\frac {dy}{dx}=\frac {(x^2+1)^{1/2}+x}{(x^2+1)^{1/2}}\cdot \frac {1}{(1+x^2)^{1/2}+x}=\frac {1}{(x^2+1)^{1/2}}$$


Ubuntu on a Fresh Lenovo G400

Question: I downloaded 12.04 using OS X, transferred the ISO to USB, then set the Lenovo G400 to boot from USB. However, it just goes back to FreeDOS and nothing happens. What else should I do?
Thanks
Comment: How did you transfer the iso to USB? You do not have to simply copy the file but create a bootable disc.
Answer: I think your USB is not bootable. If you search on the web you will find many source to know how to do so.
If you must do it in OS X, this is the official guide be ubuntu: How to create a bootable USB stick on OS X

Ubuntu on a Fresh Lenovo G400


Hide and Show elements across multiple pages

Question: Is there a way to save the state of an element across multiple pages? Maybe using session or local storage perhaps?
Functionality like this is what I want to achieve. But I want it to remember what is shown and hidden upon exiting and returning to the page.
<button onclick="myFunction()">Try it</button>

This is my DIV element.

Comment: yes, use localStorage.setItem('display', 'block') and use localStorage.getItem('display')
Comment: Doing this: `localStorage.setItem('display', x.style.display )` saves the state and it updates when I select the button again, however on return to the page, although the key is saved, there is no style defined in the html.
Comment: instead of saving x.style.display,var dis;  if (x.style.display === "none") {
        x.style.display = "block"; dis = 'block'
    } else {
        x.style.display = "none"; dis ='none'
    }
Comment: use variable and assign value in if else ,  setItem and getItem to see the last stored value
Comment: I am able to see the last stored value in storage and it is updating when I press the button. In the html it is changing the style to display block and display none. However on return to the page there is no style assigned to the html element, and so it is displayed again by default, even though session storage has a value assigned to the display key.
Comment: then create onload function on body tag and localStorage.getItem('display') and add x.style.display = localStorage.getItem('display')
Answer: To achieve expected result, use below option localStorage and onload function

Use locaStorage.setItem and localStorage.getItem to set and fetch values from localstorage
Use onload function on body to set display from the localstorage

function myFunction() {
    var x = document.getElementById("myDIV");
  console.log(x.style.display)
    if (x.style.display === "none") {
      localStorage.setItem('display','block')
        x.style.display = "block";
    } else {
        localStorage.setItem('display','none')
        x.style.display = "none";
    }
  console.log(localStorage)
}

function checkDisplay(){
      var x = document.getElementById("myDIV");
      x.style.display = localStorage.getItem('display');
}

<button onclick="myFunction()">Try it</button>

This is my DIV element.

code sample - https://codepen.io/nagasai/pen/BxabBz
Comment: I realise following your last comment I was not using a further function to check and it was defaulting to display none. This answer works perfectly for me. Thank you.


Change settings of a running process

Question: I noticed that when a process starts for the first time, it statically reads some system parameter info only once and keeps it until terminated
which means,
that if there is some modification to the system parameters already read by the process, they wouldn'y reflect until the process is restarted.
e.g. Launch Notepad and type ';' key on the keyboard. Now change the input language from the langauge toolbar to Spanish. Now again hit the key ';'. Though the Input langauge has been changed to Spanish, the keys are still English (as seen by pressing ';' key).
Ideally on pressing ';' afer the input language is changed to Spanish, we should have noticed 'ñ'.
When we restart Notepad, we notice that ';' results in 'ñ' which means that the Notepad process needed to be restarted to take effect.
Is there some way where the process is not needed to be restarted to reflect the change in the Input method?
Thanks
Answer: If a process cares to, it can listen for notifications of changes to various system-wide settings. The wm_SettingChange message comes to mind.
It's a fool's errand to try to make some other process honor setting changes if it hasn't been written to do so. If a program isn't already listening for change notifications and acting upon them, you can't make it act differently.
Notepad probably isn't a good example; it's a pretty simple program, so it doesn't necessarily cover all the details that a good Windows program should.
The "answer" you gave, to refine your question, talks about changing the system's default input language with SystemParametersInfo. When you call that function, it will broadcast the wm_SettingChange message. To be notified of the change, other programs need to listen for that message; do that the same way you listen for any other window messages in your programming environment.
When you receive that message, the wParam parameter will be either spi_GetDefaultInputLang or spi_SetDefaultInputLang; I don't know which. That's you cue to call SystemParametersInfo to find out the new value of the setting. Based on what I've just read in "Languages, Locales, and Keyboard Layouts", you should call ActivateKeyboardLayout using the HKL value you get from SystemParametersInfo.
The process that changes the default input language cannot force other processes to use it. Until they choose for themselves to change their input languages, they will continue using whatever was the language when they started running. That's the distinction between the default setting and the current setting.
Comment: What Rob said. You can't make a program that was not designed to update when setting change start updating when settings change. That is a design choice the authors of Notepad decided not to code for.

Change settings of a running process