问:
fatal: The current branch master has no upstream branch
I'm trying to push one of my projects to github, and I keep getting this error:

```<code>peeplesoft@jane3:~/846156 (master) $ git push

fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

     git push --set-upstream origin master
</code>```

So I tried it and got this:

```<code>peeplesoft@jane3:~/846156 (master) $ git push --set-upstream origin master

fatal: Authentication failed
</code>```

Another stackoverflow thread suggested I try the following, with disappointing results.

```<code>peeplesoft@jane3:~/846156 (master) $ git push -u origin master

fatal: Authentication failed
</code>```

Then I tried this:

```<code>peeplesoft@jane3:~/846156 (master) $ git config remote.origin.push HEAD

peeplesoft@jane3:~/846156 (master) $ git push

fatal: Authentication failed
</code>```

Any hints?

答:
You need to configure the remote first, then push.

```<code>git remote add origin url-to-your-repo
</code>```

Actual Instructions

Body:
I'm trying to push one of my projects to github, and I keep getting this error:

peeplesoft@jane3:~/846156 (master) $ git push

fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

     git push --set-upstream origin master

So I tried it and got this:

peeplesoft@jane3:~/846156 (master) $ git push --set-upstream origin master

fatal: Authentication failed

Another stackoverflow thread suggested I try the following, with disappointing results.

peeplesoft@jane3:~/846156 (master) $ git push -u origin master

fatal: Authentication failed

Then I tried this:

peeplesoft@jane3:~/846156 (master) $ git config remote.origin.push HEAD

peeplesoft@jane3:~/846156 (master) $ git push

fatal: Authentication failed

Any hints?

Body:
You need to configure the remote first, then push.

git remote add origin url-to-your-repo

Actual Instructions


来源: stackexchange

问:
Being notified with key of sub-property changed?
Vue let you have watchers that monitor a given property (even nested):

```<code>// keypath
vm.$watch('a.b.c', function (newVal, oldVal) {
  // do something
})
</code>```

However, given a vue instance like this:

```<code>var vm = new Vue({
  data: {
    options: {
      a: 1,
      b: 2,
      c: 3
    }
  },
})
</code>```

Is there a way to watch options such that I'm notified when any child property is changed with the key as well as the value?

Note: I'm looking to also obtain what key the changed value related to.

Something that would respond back with something like: function(key, value) {}
Possibly even: function(key, value, oldValue) {}?

答:
By default Vue will watch all properties you define in data, so when you change options.a, options.b and options.c Vue will notice. But if you set something like

```<code>options.d = 'foo'
</code>```

Vue won't notice it. For vue to watch options.d, you need to use Vue.set: https://v2.vuejs.org/v2/api/#Vue-set

ContentLicense: CC BY-SA 3.0

Body:
Vue let you have watchers that monitor a given property (even nested):

// keypath
vm.$watch('a.b.c', function (newVal, oldVal) {
  // do something
})

However, given a vue instance like this:

var vm = new Vue({
  data: {
    options: {
      a: 1,
      b: 2,
      c: 3
    }
  },
})

Is there a way to watch options such that I'm notified when any child property is changed with the key as well as the value?

Note: I'm looking to also obtain what key the changed value related to.

Something that would respond back with something like: function(key, value) {}
Possibly even: function(key, value, oldValue) {}?

Body:
By default Vue will watch all properties you define in data, so when you change options.a, options.b and options.c Vue will notice. But if you set something like

options.d = 'foo'

Vue won't notice it. For vue to watch options.d, you need to use Vue.set: https://v2.vuejs.org/v2/api/#Vue-set

ContentLicense: CC BY-SA 4.0


问:
Does Static Methods give bad results if two threads having own objects accessing same?
Does Static non synchronized Methods give bad results if two threads accessing same?

```<code>public class MySubjectUtils {
   public static MyResponseClass createMyResponseClass(MyParameter record) {
   if (record == null) {
     return null;
   }
   MyResponseClass mRes = new MyResponseClass()
   mRes.setName(record.getName());
   mRes.setAddress(record.getAddress());
   return mRes;
}
</code>```

If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?

答:
If the object record refers to is immutable, you don't need any synchronization in that method, since that's the only potentially-shared resource that the method references. Everything else is local to the method.

But if the object record refers to isn't immutable and it may be used across threads, it could be modified by another thread between this method's calls to getName and getAddress, leading to an invalid response.

So the answer is: You may or may not need synchronization, and if you do, how you implement it will vary. In both cases, it depends on the definition of the MyParameter class and how the object result references is used by the calling code.

Body:
Does Static non synchronized Methods give bad results if two threads accessing same?

public class MySubjectUtils {
   public static MyResponseClass createMyResponseClass(MyParameter record) {
   if (record == null) {
     return null;
   }
   MyResponseClass mRes = new MyResponseClass()
   mRes.setName(record.getName());
   mRes.setAddress(record.getAddress());
   return mRes;
}

If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?


问:
Why does javax MimeType not implement equals?
The javax.activation.MimeType class does not compare intuitively (to me) due to a lack of an overridden equals-method. Consider the following snippet;

```<code>MimeType a = new MimeType("image/png");
MimeType b = new MimeType("image/png");

a.equals(b);                            // false

a.toString().equals(b.toString());      // true
a.getBaseType().equals(b.getBaseType());// true
a.getSubType().equals(b.getSubType());  // true
a.getParameters().size();               // 0
b.getParameters().size();               // 0
</code>```

It seems to me that a and b are equal in every aspect and that a.equals(b) should return true.

Is there a reason that this class does not implement an equals-method?

Update: There exists a match-method which does exactly what I want, but I only found out after posting this question which kind-of confirms the not-so-intuitiveness of this class.

答:
You could consider filing a bug; at a glance this seems like a class that should properly override .equals() and .hashCode(). Of course that won't help you for some time (not sure if this library is on the JDK's release cycle).

As a workaround you could create a subclass or wrapper class that properly implements .equals() and .hashCode(), e.g.:

```<code>public class ValueMimeType extends MimeType {
  // constructors

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof ValueMimeType) { // not MimeType, as that wouldn't be symetric
      return match((ValueMimeType) o);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return toString().hashCode();
  }
}
</code>```

And just always use ValueMimeType instead of MimeType. Obviously not ideal, but better than nothing.

Body:
The javax.activation.MimeType class does not compare intuitively (to me) due to a lack of an overridden equals-method. Consider the following snippet;

MimeType a = new MimeType("image/png");
MimeType b = new MimeType("image/png");

a.equals(b);                            // false

a.toString().equals(b.toString());      // true
a.getBaseType().equals(b.getBaseType());// true
a.getSubType().equals(b.getSubType());  // true
a.getParameters().size();               // 0
b.getParameters().size();               // 0

It seems to me that a and b are equal in every aspect and that a.equals(b) should return true.

Is there a reason that this class does not implement an equals-method?

Update: There exists a match-method which does exactly what I want, but I only found out after posting this question which kind-of confirms the not-so-intuitiveness of this class.

Body:
You could consider filing a bug; at a glance this seems like a class that should properly override .equals() and .hashCode(). Of course that won't help you for some time (not sure if this library is on the JDK's release cycle).

As a workaround you could create a subclass or wrapper class that properly implements .equals() and .hashCode(), e.g.:

public class ValueMimeType extends MimeType {
  // constructors

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof ValueMimeType) { // not MimeType, as that wouldn't be symetric
      return match((ValueMimeType) o);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return toString().hashCode();
  }
}

And just always use ValueMimeType instead of MimeType. Obviously not ideal, but better than nothing.


问:
express server returns errors on start
I'm having a hard time trying to figure out why my server returns errors when I start it. I'm not using webpack-dev-server because it doesn't compile JS files so I decided to make my own server. When I opened my browser, it displayed an error message that says:

server.js:

```<code>var webpack = require('webpack'),
    path = require('path'),
    express = require('express'),
    devMiddleware = require('webpack-dev-middleware'),
    hotMiddleware = require('webpack-hot-middleware'),
    config = require('./webpack.config'),
    app = express(),
    host = '127.0.0.1',
    port = 8000;

var middleware = devMiddleware(webpack({
  entry: path.join(__dirname, 'app/src/main.js'),
  output: {
    path: '/',
  }
}), {
  noInfo: true,
  publicPath: config.output.publicPath,
  index: path.join(__dirname, 'app/index.html'),
  stats: {
    colors: true
  }
});

app.use(middleware);

app.use(hotMiddleware(webpack(config)));

app.get('/', function(req, res) {
  res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'app/index.html')));
  res.end();
});

app.listen(port, host, function(err) {
  if (err) {
    console.error(err);
  }
  console.log('Listening on ' + host + ':' + port);
});
</code>```

project files and directories:

I don't understand why this is happening. Maybe I'm missing a lot of important plugins or dependencies to make it successful like react-hot-loader? Or it doesn't matter?

答:
From what I can see, you shouldn't be using middleware.fileSystem.readFileSync() to handle requests for index.html (which isn't part of your bundle).

Just use fs.readFileSync() or, preferably, res.sendFile():

```<code>app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'app/index.html'));
});
</code>```

Title: express server returns errors on start

Body:
I'm having a hard time trying to figure out why my server returns errors when I start it. I'm not using webpack-dev-server because it doesn't compile JS files so I decided to make my own server. When I opened my browser, it displayed an error message that says:

server.js:

var webpack = require('webpack'),
    path = require('path'),
    express = require('express'),
    devMiddleware = require('webpack-dev-middleware'),
    hotMiddleware = require('webpack-hot-middleware'),
    config = require('./webpack.config'),
    app = express(),
    host = '127.0.0.1',
    port = 8000;

var middleware = devMiddleware(webpack({
  entry: path.join(__dirname, 'app/src/main.js'),
  output: {
    path: '/',
  }
}), {
  noInfo: true,
  publicPath: config.output.publicPath,
  index: path.join(__dirname, 'app/index.html'),
  stats: {
    colors: true
  }
});

app.use(middleware);

app.use(hotMiddleware(webpack(config)));

app.get('/', function(req, res) {
  res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'app/index.html')));
  res.end();
});

app.listen(port, host, function(err) {
  if (err) {
    console.error(err);
  }
  console.log('Listening on ' + host + ':' + port);
});

project files and directories:

I don't understand why this is happening. Maybe I'm missing a lot of important plugins or dependencies to make it successful like react-hot-loader? Or it doesn't matter?

Body:
From what I can see, you shouldn't be using middleware.fileSystem.readFileSync() to handle requests for index.html (which isn't part of your bundle).

Just use fs.readFileSync() or, preferably, res.sendFile():

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'app/index.html'));
});


问:
I just started using methods. This is a template and I'm confused on how to do the methods. Can someone show me how to do what is being asked?
I'm not sure how to add the methods that is wanted as this is my first program not doing everything in a main. It's super confusing to me. I have no idea how to make a method and only vaguely what it entails or how to return. Could anyone help me out with this code?

Edit::
I did the code thanks to the provided tips. However, I can't seem to get the last two methods to work. I feel as though shift char is to be used withing String shift but i dont know how. What i have here compiles and runs but the last output is "String shifted by one letter is 'Nztizhzqtz'" when i input My Shy Gypsy which correctly shifts every letter forward 1 letter in the alphabet but takes the spaces away, why?

```<code>import java.util.Scanner;

public class StringMethods {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = input.nextLine();

        System.out.println("\nNumber of Spaces in the string = " + countSpaces(s) + "\n");
        System.out.println("Number of E's in the string = " + countChar(s, "E") + "\n");
        System.out.println("Number of Stars in the string = " + countChar(s, "*") + "\n");
        System.out.println("Does string contain vowels? " + anyVowels(s) + "\n");
        System.out.println("String reversed = " + reverse(s) + "\n");
        System.out.println("String shifted by one letter is " + shift(s)  + "\n");
    }

    // method to return the number of spaces in a String
    public static int countSpaces(String input) {
        int spaces = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == ' '){
                spaces++;
            }
        }
         return spaces;
    }

    // method to count the number of instances of
    // a particular character in a String
    // the method will return the total of upper and lower
    // case instances if it is a letter
    public static int countChar(String input,String findStr) {
        input = input.toLowerCase();
        findStr = findStr.toLowerCase();
        int num = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == findStr.charAt(0)){
                num++;
            }
        }
        return num;

    }

    // method to detect whether a String contains a vowel or not
    // must include call(s) to countChar
    // returns true or false
    public static boolean anyVowels(String input) {
        int num = 0;
        num = countChar(input, "a")+countChar(input, "e")+countChar(input, "i")+countChar(input, "o")+countChar(input, "u");
        if(num >  0) {
            return true;
        }
        return false;
    }

    // method to return the reverse of a String
    public static String reverse(String input) {
        String reverse = "";
        for (int i = 0;i<input.length();i++) {
            reverse = input.charAt(i) + reverse;
        }
        return reverse;
    }

    // method to return a character shifted one place in the alphaber
    // a becomes b, b become c etc. z becomes a
    // A becomes B, B becomes C etc. Z becomes A
    // all other characters are left unchanged
    public static char shift(char input) {

        char shiftedChar = 'a';
        shiftedChar++;
        //for (int i = 0; i < input.length();i++) {
        //    shiftedChar = input.charAt(i);
        //
        //}

        return shiftedChar;
    }

    // method to return a String with each letter shifted one place in the alphabet
    // method must include call(s) to previous method
    public static String shift(String input) {

        String shiftedString = "";
        for (int i = 0; i < input.length();i++) {
            char a = input.charAt(i);
            if (a != ' ') {
            a++;
            shiftedString = shiftedString + a;
            }
        }

        return shiftedString;
    }

}
</code>```

答:
I haven't provided all the method implementations. Some are left for the questioner to implement. However, below are some hints which can be useful - </p>

```<code>import java.util.Scanner;

public class StringMethods {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = input.nextLine();

        System.out.println("\nNumber of Spaces in the string = " + countSpaces(s) + "\n");
        System.out.println("Number of E's in the string = " + countChar(s, "E") + "\n");
        System.out.println("Number of Stars in the string = " + countChar(s, "*") + "\n");
        System.out.println("Does string contain vowels? " + anyVowels(s) + "\n");
        System.out.println("String reversed = " + reverse(s) + "\n");
        System.out.println("String shifted by one letter is " + shift(s)  + "\n");
    }

    // method to return the number of spaces in a String
    public static int countSpaces(String input) {
         return input.split(" ",-1).length-1;
    }

    // method to count the number of instances of
    // a particular character in a String
    // the method will return the total of upper and lower
    // case instances if it is a letter
    public static int countChar(String input, String findStr) {

    }

    // method to detect whether a String contains a vowel or not
    // must include call(s) to countChar
    // returns true or false
    public static boolean anyVowels(String input) {

    }

    // method to return the reverse of a String
    public static String reverse(String input) {
        StringBuffer sb = new StringBuffer(input);
        return sb.reverse().toString();
    }

    // method to return a character shifted one place in the alphaber
    // a becomes b, b become c etc. z becomes a
    // A becomes B, B becomes C etc. Z becomes A
    // all other characters are left unchanged
    public static char shift(char input) {

        char shiftedChar = '';
        // TODO - code to shift the char

        return shiftedChar;
    }

    // method to return a String with each letter shifted one place in the alphabet
    // method must include call(s) to previous method
    public static String shift(String input) {

        String shiftedString = null;

        //TODO shit the char for each char in a String

        return shiftedString;
    }

}
</code>```

Body:
I'm not sure how to add the methods that is wanted as this is my first program not doing everything in a main. It's super confusing to me. I have no idea how to make a method and only vaguely what it entails or how to return. Could anyone help me out with this code?

Edit::
I did the code thanks to the provided tips. However, I can't seem to get the last two methods to work. I feel as though shift char is to be used withing String shift but i dont know how. What i have here compiles and runs but the last output is "String shifted by one letter is 'Nztizhzqtz'" when i input My Shy Gypsy which correctly shifts every letter forward 1 letter in the alphabet but takes the spaces away, why?

import java.util.Scanner;

public class StringMethods {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = input.nextLine();

        System.out.println("\nNumber of Spaces in the string = " + countSpaces(s) + "\n");
        System.out.println("Number of E's in the string = " + countChar(s, "E") + "\n");
        System.out.println("Number of Stars in the string = " + countChar(s, "*") + "\n");
        System.out.println("Does string contain vowels? " + anyVowels(s) + "\n");
        System.out.println("String reversed = " + reverse(s) + "\n");
        System.out.println("String shifted by one letter is " + shift(s)  + "\n");
    }

    // method to return the number of spaces in a String
    public static int countSpaces(String input) {
        int spaces = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == ' '){
                spaces++;
            }
        }
         return spaces;
    }

    // method to count the number of instances of
    // a particular character in a String
    // the method will return the total of upper and lower
    // case instances if it is a letter
    public static int countChar(String input,String findStr) {
        input = input.toLowerCase();
        findStr = findStr.toLowerCase();
        int num = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == findStr.charAt(0)){
                num++;
            }
        }
        return num;

    }

    // method to detect whether a String contains a vowel or not
    // must include call(s) to countChar
    // returns true or false
    public static boolean anyVowels(String input) {
        int num = 0;
        num = countChar(input, "a")+countChar(input, "e")+countChar(input, "i")+countChar(input, "o")+countChar(input, "u");
        if(num >  0) {
            return true;
        }
        return false;
    }

    // method to return the reverse of a String
    public static String reverse(String input) {
        String reverse = "";
        for (int i = 0;i<input.length();i++) {
            reverse = input.charAt(i) + reverse;
        }
        return reverse;
    }

    // method to return a character shifted one place in the alphaber
    // a becomes b, b become c etc. z becomes a
    // A becomes B, B becomes C etc. Z becomes A
    // all other characters are left unchanged
    public static char shift(char input) {

        char shiftedChar = 'a';
        shiftedChar++;
        //for (int i = 0; i < input.length();i++) {
        //    shiftedChar = input.charAt(i);
        //
        //}

        return shiftedChar;
    }

    // method to return a String with each letter shifted one place in the alphabet
    // method must include call(s) to previous method
    public static String shift(String input) {

        String shiftedString = "";
        for (int i = 0; i < input.length();i++) {
            char a = input.charAt(i);
            if (a != ' ') {
            a++;
            shiftedString = shiftedString + a;
            }
        }

        return shiftedString;
    }

}

Body:
I haven't provided all the method implementations. Some are left for the questioner to implement. However, below are some hints which can be useful -

import java.util.Scanner;

public class StringMethods {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = input.nextLine();

        System.out.println("\nNumber of Spaces in the string = " + countSpaces(s) + "\n");
        System.out.println("Number of E's in the string = " + countChar(s, "E") + "\n");
        System.out.println("Number of Stars in the string = " + countChar(s, "*") + "\n");
        System.out.println("Does string contain vowels? " + anyVowels(s) + "\n");
        System.out.println("String reversed = " + reverse(s) + "\n");
        System.out.println("String shifted by one letter is " + shift(s)  + "\n");
    }

    // method to return the number of spaces in a String
    public static int countSpaces(String input) {
         return input.split(" ",-1).length-1;
    }

    // method to count the number of instances of
    // a particular character in a String
    // the method will return the total of upper and lower
    // case instances if it is a letter
    public static int countChar(String input, String findStr) {

    }

    // method to detect whether a String contains a vowel or not
    // must include call(s) to countChar
    // returns true or false
    public static boolean anyVowels(String input) {

    }

    // method to return the reverse of a String
    public static String reverse(String input) {
        StringBuffer sb = new StringBuffer(input);
        return sb.reverse().toString();
    }

    // method to return a character shifted one place in the alphaber
    // a becomes b, b become c etc. z becomes a
    // A becomes B, B becomes C etc. Z becomes A
    // all other characters are left unchanged
    public static char shift(char input) {

        char shiftedChar = '';
        // TODO - code to shift the char

        return shiftedChar;
    }

    // method to return a String with each letter shifted one place in the alphabet
    // method must include call(s) to previous method
    public static String shift(String input) {

        String shiftedString = null;

        //TODO shit the char for each char in a String

        return shiftedString;
    }

}


问:
Java Testing for Maps
I've created a List<Map<String, String>> for a source file.  I've succeeded in creating a Map with the header values as keys and the information below them as values.  I've tested and verified everything in that method works.

In my next method I've implemented an iterator that will grab the next mapping for processing in a different class.  I'm trying to test to make sure that it's doing what I think it's doing and to verify what I want it to do.

Here's the code of the method:

```<code>  public Map contact(List<Map<String, String>> list) {
return list.iterator().next();
}
</code>```

And here's my test code in the testing class:

```<code>  @Test
public void contact() throws Exception {

List<Map<String, String>> list = this.main.sourceToMap(source1.readLine());
Map nextContact = this.main.contact(list);

System.out.println(list.get(0));

Assert.assertEquals(nextContact,
    "zip=70116, address=6649 N Blue Gum St, city=New Orleans, " +
        "web=http://www.bentonjohnbjr.com, company_name=\"Benton, John B Jr\", " +
        "county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, " +
        "email=jbutt@gmail.com, phone1=504-621-8927");
}
</code>```

Finally, here's the error i'm getting:

java.lang.AssertionError: Expected :{zip=70116, address=6649 N Blue Gum St,city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927}

Actual :zip=70116, address=6649 N Blue Gum St, city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927

The expected and actual are exactly the same with one one difference.  A "{ }" is in front and behind the string.

I think it's because it's expecting a Map instead of a String but I can't figure out what to type in to make it a Map instead of a string.

This is an assignment but not THE assignment.  This is just one small test that i'm trying to prove before moving on.

Thanks!  :D

答:
If you would like to compare in that way (whole map contents against the String) - consider two things:

First argument in Assert.assertEquals(..) method is expected value. So, swap your arguments to match the contract

Add curly braces to the expected value:  Assert.assertEquals(
"{zip=70116, address=6649 N Blue Gum St, city=New Orleans, " +
    "web=http://www.bentonjohnbjr.com, company_name=\"Benton, John B Jr\", " +
    "county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, " +
    "email=jbutt@gmail.com, phone1=504-621-8927}", nextContact.toString());

Add toString() method call to the map object so that both objects would have the same type

Title: Java Testing for Maps

Body:
I've created a List<Map<String, String>> for a source file.  I've succeeded in creating a Map with the header values as keys and the information below them as values.  I've tested and verified everything in that method works.

In my next method I've implemented an iterator that will grab the next mapping for processing in a different class.  I'm trying to test to make sure that it's doing what I think it's doing and to verify what I want it to do.

Here's the code of the method:

  public Map contact(List<Map<String, String>> list) {
return list.iterator().next();
}

And here's my test code in the testing class:

  @Test
public void contact() throws Exception {

List<Map<String, String>> list = this.main.sourceToMap(source1.readLine());
Map nextContact = this.main.contact(list);

System.out.println(list.get(0));

Assert.assertEquals(nextContact,
    "zip=70116, address=6649 N Blue Gum St, city=New Orleans, " +
        "web=http://www.bentonjohnbjr.com, company_name=\"Benton, John B Jr\", " +
        "county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, " +
        "email=jbutt@gmail.com, phone1=504-621-8927");
}

Finally, here's the error i'm getting:

java.lang.AssertionError: Expected :{zip=70116, address=6649 N Blue Gum St,city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927}

Actual :zip=70116, address=6649 N Blue Gum St, city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927

The expected and actual are exactly the same with one one difference.  A "{ }" is in front and behind the string.

I think it's because it's expecting a Map instead of a String but I can't figure out what to type in to make it a Map instead of a string.

This is an assignment but not THE assignment.  This is just one small test that i'm trying to prove before moving on.

Thanks!  :D


问:
ASP.NET enable dot sign web.config
I need to redirect www.domain.com/.well-known/pki-validation/godaddy.html from my webpage to get SSL Certificate from godaddy. but when im given the file path from the web.config file to redirect to it suddenly my site not working. the reason is dot sign.

Please can you guys help me to figure this out.

Thanks

答:
```<code>Give proper url with http:\\

 protected void Page_Load(object sender, EventArgs e)
    {
       string url= WebConfigurationManager.AppSettings["url"].ToString();

       Response.Redirect(url);
    }

  <appSettings>
    <add key="url" value="your url""/>
    <add key="SiteName" value="New York Times"/>
  </appSettings>
</code>```

Title: ASP.NET enable dot sign web.config


问:
How to get next non child element
I honestly tried to do search before posting but couldn't find something specific.
So my task is to show hidden content in the blog, when user clicks on the link.
HTML looks like this:

```<code><div class="entry">
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is all the hidden content</p></div>
</div>
</code>```

Now jQuery I'm doing the following but it's not working:

```<code>$(".hidden_post").hide();
$(".a-toggle).click(function() {
$(this).next(".hidden_post").slideDown("slow"); });
</code>```

So to get next element I need to go to a parent element first and then proceed search from there.
Now it gets more complicated for me, because I'll actually going to have several hidden
contents in one "entry". Like this:

```<code><div class="entry">
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is hidden content #1</p></div>
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is hidden content #2</p></div>
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is hidden content #3</p></div>
</div>
</code>```

Now if I use $(this).parent().next(".hidden_post").slideDown("slow");
It will go up to "entry" div and then will find first "hidden_post" only. I guess
I still need another solution to go straight from class="a-toggle"> to
 that is next to it. Is there any solution?

答:
The quickest way in this case would be to do parent -> next</p>

```<code>$(".a-toggle").click(function(){
 $(this).parent().next(".hidden_post").slideDown("slow");
});
</code>```

Title: How to get next non child element

Body:
I honestly tried to do search before posting but couldn't find something specific.
So my task is to show hidden content in the blog, when user clicks on the link.
HTML looks like this:

Here is a visible content  Read More...

Here is all the hidden content

Now jQuery I'm doing the following but it's not working:

$(".hidden_post").hide();
$(".a-toggle).click(function() {
$(this).next(".hidden_post").slideDown("slow"); });

So to get next element I need to go to a parent element first and then proceed search from there.
Now it gets more complicated for me, because I'll actually going to have several hidden
contents in one "entry". Like this:

Here is a visible content  Read More...

Here is hidden content #1

Here is a visible content  Read More...

Here is hidden content #2

Here is a visible content  Read More...

Here is hidden content #3

Now if I use $(this).parent().next(".hidden_post").slideDown("slow");
It will go up to "entry" div and then will find first "hidden_post" only. I guess
I still need another solution to go straight from  to
 that is next to it. Is there any solution?

Body:
The quickest way in this case would be to do parent -> next

$(".a-toggle").click(function(){
 $(this).parent().next(".hidden_post").slideDown("slow");
});

ContentLicense: CC BY-SA 2.5


问:
Git master branch has no upstream branch
I'm trying to push one of my projects to github, and I keep getting this error:

```<code>fatal: The current branch master has no upstream branch.
</code>```

I've never seen this before. I re-initialized my git, re-added my origin, deleted and re-made the repo, and recreated my SSH key.

答:
You need to configure the remote first, then push.

git remote add origin url-to-your-repo

instructions

Body:
I'm trying to push one of my projects to github, and I keep getting this error:

fatal: The current branch master has no upstream branch.

I've never seen this before. I re-initialized my git, re-added my origin, deleted and re-made the repo, and recreated my SSH key.


问:
Results of calculating with Sum (expression) give a wrong number in SSRS
I have a column which should calculate some numbers and sometimes it gives me the correct sum and sometimes it doesn't. I don't know why! Can someone please point me in the right direction?

I used this expression:

```<code>=Sum(Fields!TotalEmployees.Value)
</code>```

When I don't choose something from filters on the top , it will give me the correct sum:

And when I choose something from the filters on the top, for example between 2 dates, it will give me wrong the sum:

Parameters & Body of report :

```<code>@EndDateFrom
@EndDateTo
</code>```

答:
i solved this issue with changing my query ,where all calculating (AVG , Sum &.. ) happens in query , instead reporting services do it for me .. after that i got the correct number: </p>

```<code>SELECT t1.Departments, count(t1.id), avg(t1.age),sum(t1.TotalEmployees)/count(t1.id)
    AS TotalEmpl FROM (<current_query>) AS t1 <br> GROUP BY t1.Departments
</code>```

Body:
I have a column which should calculate some numbers and sometimes it gives me the correct sum and sometimes it doesn't. I don't know why! Can someone please point me in the right direction?

I used this expression:

=Sum(Fields!TotalEmployees.Value)

When I don't choose something from filters on the top , it will give me the correct sum:

And when I choose something from the filters on the top, for example between 2 dates, it will give me wrong the sum:

Parameters & Body of report :

@EndDateFrom
@EndDateTo

Body:
i solved this issue with changing my query ,where all calculating (AVG , Sum &.. ) happens in query , instead reporting services do it for me .. after that i got the correct number:

SELECT t1.Departments, count(t1.id), avg(t1.age),sum(t1.TotalEmployees)/count(t1.id)
    AS TotalEmpl FROM (<current_query>) AS t1 <br> GROUP BY t1.Departments


问:
Magento Rebuild Catalog product fulltext search indexing locking tables
We have 4 stores,
catalog products 80000+
when I do indexing of "Rebuild Catalog product full-text search index" it runs for 30 min and then breaks due to lock of tables.

the site is also very slow.

cache is enabled.

How can I do full re-index in a faster method?
Any solution/suggestion welcomed

答:
This process is really slow and there is a good free extension with the explanation :

http://www.dnd.fr/2012/09/magento-patch-how-to-optimize-re-index-processing-time-for-url-rewrite/

else you can have a look at this one :

https://github.com/SchumacherFM/Magento-FastIndexer


问:
Android replace checkbox style with custom drawable selector
I have tried to make a xml selector with the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shuffleon" android:state_checked="true" />
    <item android:drawable="@drawable/shuffleoff" android:state_selected="false" />
</selector>
</code>```

and when I try to set the backgroundDrawable to the checkBox the checkbox doesn't replace the CheckBox style too:

```<code>  shuffle.setBackground(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.shuffle, null));
</code>```

Following this question: Change icons of checked and unchecked for Checkbox for Android I need to set the button drawable with my xml: android:button="@drawable/checkbox" but I can't do this because I'm creating the CheckBox programmatically.
Is there a way how to achieve this?

答:
Simple way

Create a new layout in drawable folder and  name it custom_checkbox (You can rename also)

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/Checked_image_name"android:state_checked="true"/>
<item android:drawable="@drawable/Unchecked_image_name" android:state_checked="false"/>
</selector>
</code>```

Use this in your layout activity

```<code><CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/custom_checkbox"/>
</code>```

Body:
I have tried to make a xml selector with the following:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shuffleon" android:state_checked="true" />
    <item android:drawable="@drawable/shuffleoff" android:state_selected="false" />
</selector>

and when I try to set the backgroundDrawable to the checkBox the checkbox doesn't replace the CheckBox style too:

  shuffle.setBackground(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.shuffle, null));

Following this question: Change icons of checked and unchecked for Checkbox for Android I need to set the button drawable with my xml: android:button="@drawable/checkbox" but I can't do this because I'm creating the CheckBox programmatically.
Is there a way how to achieve this?

Body:
Simple way

Create a new layout in drawable folder and  name it custom_checkbox (You can rename also)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/Checked_image_name"android:state_checked="true"/>
<item android:drawable="@drawable/Unchecked_image_name" android:state_checked="false"/>
</selector>

Use this in your layout activity

<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/custom_checkbox"/>


问:
Will Laravel 5.4 run on PHP 5.6.3?
I know that laravel 5.4 need to meets PHP >= 5.6.4. I try to find XAMPP with php 5.6.4 but i have nothing. I just have xampp with php 5.6.3 installed. Will laravel 5.4 run on php 5.6.3?</p>

答:
Server requirements for laravel 5.4:

PHP >= 5.6.4

OpenSSL PHP Extension

PDO PHP Extension

Mbstring PHP Extension

Tokenizer PHP Extension

XML PHP Extension

Laravel Installation Server Requirements

Title: Will Laravel 5.4 run on PHP 5.6.3?


问:
how to protect download link using html and javascript?
i have two download links.  after right click on this link it showing option link "open in new tab" "save link as" "copy link location" and so on. but i want to protect this link. there should not showing this option when right click on download link. please help

Thanks in advance

答:
You can't protect anything with client languages like javascript or html/css. If the browser can, an human can

You can create an unique download link in PHP, or create a password (unique too) to allow the user to get his file with expiration date for example.

Else, you can send the file in an e-mail as attachment.

They are many ways to do what you want, but only with a serverside language.


问:
Adding Events to Full Calendar using ASP.NET, C# and JSON
Ok, so I know this may be a bit of a duplicate of this question: fullCalendar events not showing even though correct JSON feed
But after trying the code to no avail I thought I would post another question to see if any body could help

Basically I'm trying to add events dynamically to the Full Calendar JQuery plugin with ASP.NET C# using data from an SQL Server Database.

Here is the code I have used in my web method in the code behind file

```<code>[WebMethod]
public static String TestOnWebService()
{

    String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
    SqlConnection myConnection = new SqlConnection(connectionString);

    myConnection.Open();

    String query = "SELECT * FROM timetable";

    SqlCommand cmd = new SqlCommand(query, myConnection);

    SqlDataReader reader = cmd.ExecuteReader();

    string myJsonString = "";
    List<object> myList = new List<object>();

    if (reader.HasRows)
    {
        var indexOfId = reader.GetOrdinal("id");
        var indexOfLecture = reader.GetOrdinal("lecture");
        var indexOfStartDate = reader.GetOrdinal("start_date");
        var indexOfEndDate = reader.GetOrdinal("end_date");
        var indexOfTimeStart = reader.GetOrdinal("start_time");
        var indexOfTimeEnd = reader.GetOrdinal("end_time");

        while (reader.Read())
        {

            var Id = reader.GetValue(indexOfId).ToString();
            var Lecture = reader.GetValue(indexOfLecture).ToString();
            var DateStart = reader.GetValue(indexOfStartDate).ToString();
            var DateEnd = reader.GetValue(indexOfEndDate).ToString();
            var StartTime = reader.GetValue(indexOfTimeStart);
            var EndTime = reader.GetValue(indexOfTimeEnd);

            //Convert Implicity typed var to Date Time
            DateTime RealStartDate = Convert.ToDateTime(DateStart);
            DateTime RealEndDate = Convert.ToDateTime(DateEnd);

            //Convert Date Time to ISO
            String SendStartDate = RealStartDate.ToString("s");
            String SendEndDate = RealEndDate.ToString("s");

            timeTable t_table = new timeTable(Id, Lecture, SendStartDate, SendEndDate);

            myList.Add(t_table);

        }
        myJsonString = (new JavaScriptSerializer()).Serialize(myList);

        myConnection.Close();
    }

    return myJsonString;

}
</code>```

}

and here is my AJAX call which I use to grab the JSON data via POST method:

```<code>$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function() {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);
                $(obj.event).each(function () {
                    events.push({
                        title: $(this).attr('title'),
                        start: $(this).attr('start'),
                        end: $(this).attr('end'),
                        id: $(this).attr('id')
                    });
                });
                //callback(events);
                callback && callback(events);
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})
</code>```

})

The AJAX call seems to succeed as I can alert out a success message and I can also alert out the JSON data, which looks like this:

I can also output the parsed object of the JSON Data in the console which looks like this:

I get no errors in the console when I do this but the events don't seem to add to the Full Calendar UI (which also appears fine on my page).

I think I might be going wrong somewhere with the following code but I can't seem to put my finger on it:

```<code>$(obj.event).each(function () {
  events.push({
  title: $(this).attr('title'),
  start: $(this).attr('start'),
  end: $(this).attr('end'),
  id: $(this).attr('id')
});
</code>```

Also I get an the error "Callback is not a function" when I use this code:

```<code>callback(events);
</code>```

But not when I use this:

```<code>callback && callback(events);
</code>```

I'm not sure if this has anything to do with the problems I'm experiencing but I thought I would add it in just in case.

Thanks in advance for any of your responses, they are much appreciated.

EDIT:

Apologies, I forgot to add the code for my timeTable class. It is as follows:

```<code>public class timeTable
{
public String id { get; set; }
public String title { get; set; }
public String start { get; set; }
public String end { get; set; }

public timeTable(String I, String t, String ds, String de)
{
    this.id = I;
    this.title = t;
    this.start = ds;
    this.end = de;
}

}
</code>```

My HTML is literally just one line:

```<code><div id="calendar"></div>
</code>```

Here is the javascript files I have linked in the head of my page

```<code>        <!-- Javascript -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src='js/moment.js'></script>
<script src='js/fullcalendar.js'></script>
<script src="js/script.js"></script>
</code>```

Update:

So another thing I've tried is looping through the object I have created using my JSON string and pushing it into the events array, however this doesn't seem to work either. See code below:

```<code>$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                      for (var p in d) { //Next we access the nested objects by using the p variable
                          if (p.hasOwnProperty) { //Check to make sure p has its own properties
                              //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                              events.push(p + ": " + d[p]);
                              }

                            }
                     }
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})
</code>```

})

It outputs the array to the console but still doesn't show any events on the Full Calendar UI :-(

Update 2

Here's my next code edit which doesn't seem to have worked either, I unsure why as it populates the events array fine with the values needed, I also added a addDay = "false" attribute as well but still no joy, Any body at all got any idea's, I'm stumped:

```<code>$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function () {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                //console.log(doc.d);
                var obj = $.parseJSON(doc.d);
                //console.log(obj);

                $.each(obj, function (index) {

                    $.each(obj[index], function (key, value) {

                        events.push(key + ": " + value)

                    });

                });

                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})
</code>```

})

答:
More correct:</p>

```<code><script>

    $(document).ready(function () {

        $.ajax({
            type: "POST",
            url: "../04_Entries/04_42_ReservationCalander.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {

                var events = [];
                var docd = doc.d;

                var obj = $.parseJSON(doc.d);
                console.log(obj);

               $('#calendar').fullCalendar({
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    eventClick: function () {

                    },

                    editable: false,

                    events: obj //Just pass obj to events
                })
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    });

</script>
</code>```

Body:
Ok, so I know this may be a bit of a duplicate of this question: fullCalendar events not showing even though correct JSON feed
But after trying the code to no avail I thought I would post another question to see if any body could help

Basically I'm trying to add events dynamically to the Full Calendar JQuery plugin with ASP.NET C# using data from an SQL Server Database.

Here is the code I have used in my web method in the code behind file

[WebMethod]
public static String TestOnWebService()
{

    String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
    SqlConnection myConnection = new SqlConnection(connectionString);

    myConnection.Open();

    String query = "SELECT * FROM timetable";

    SqlCommand cmd = new SqlCommand(query, myConnection);

    SqlDataReader reader = cmd.ExecuteReader();

    string myJsonString = "";
    List<object> myList = new List<object>();

    if (reader.HasRows)
    {
        var indexOfId = reader.GetOrdinal("id");
        var indexOfLecture = reader.GetOrdinal("lecture");
        var indexOfStartDate = reader.GetOrdinal("start_date");
        var indexOfEndDate = reader.GetOrdinal("end_date");
        var indexOfTimeStart = reader.GetOrdinal("start_time");
        var indexOfTimeEnd = reader.GetOrdinal("end_time");

        while (reader.Read())
        {

            var Id = reader.GetValue(indexOfId).ToString();
            var Lecture = reader.GetValue(indexOfLecture).ToString();
            var DateStart = reader.GetValue(indexOfStartDate).ToString();
            var DateEnd = reader.GetValue(indexOfEndDate).ToString();
            var StartTime = reader.GetValue(indexOfTimeStart);
            var EndTime = reader.GetValue(indexOfTimeEnd);

            //Convert Implicity typed var to Date Time
            DateTime RealStartDate = Convert.ToDateTime(DateStart);
            DateTime RealEndDate = Convert.ToDateTime(DateEnd);

            //Convert Date Time to ISO
            String SendStartDate = RealStartDate.ToString("s");
            String SendEndDate = RealEndDate.ToString("s");

            timeTable t_table = new timeTable(Id, Lecture, SendStartDate, SendEndDate);

            myList.Add(t_table);

        }
        myJsonString = (new JavaScriptSerializer()).Serialize(myList);

        myConnection.Close();
    }

    return myJsonString;

}

}

and here is my AJAX call which I use to grab the JSON data via POST method:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function() {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);
                $(obj.event).each(function () {
                    events.push({
                        title: $(this).attr('title'),
                        start: $(this).attr('start'),
                        end: $(this).attr('end'),
                        id: $(this).attr('id')
                    });
                });
                //callback(events);
                callback && callback(events);
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

The AJAX call seems to succeed as I can alert out a success message and I can also alert out the JSON data, which looks like this:

I can also output the parsed object of the JSON Data in the console which looks like this:

I get no errors in the console when I do this but the events don't seem to add to the Full Calendar UI (which also appears fine on my page).

I think I might be going wrong somewhere with the following code but I can't seem to put my finger on it:

$(obj.event).each(function () {
  events.push({
  title: $(this).attr('title'),
  start: $(this).attr('start'),
  end: $(this).attr('end'),
  id: $(this).attr('id')
});

Also I get an the error "Callback is not a function" when I use this code:

callback(events);

But not when I use this:

callback && callback(events);

I'm not sure if this has anything to do with the problems I'm experiencing but I thought I would add it in just in case.

Thanks in advance for any of your responses, they are much appreciated.

EDIT:

Apologies, I forgot to add the code for my timeTable class. It is as follows:

public class timeTable
{
public String id { get; set; }
public String title { get; set; }
public String start { get; set; }
public String end { get; set; }

public timeTable(String I, String t, String ds, String de)
{
    this.id = I;
    this.title = t;
    this.start = ds;
    this.end = de;
}

}

My HTML is literally just one line:

Here is the javascript files I have linked in the head of my page

Update:

So another thing I've tried is looping through the object I have created using my JSON string and pushing it into the events array, however this doesn't seem to work either. See code below:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                      for (var p in d) { //Next we access the nested objects by using the p variable
                          if (p.hasOwnProperty) { //Check to make sure p has its own properties
                              //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                              events.push(p + ": " + d[p]);
                              }

                            }
                     }
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

It outputs the array to the console but still doesn't show any events on the Full Calendar UI :-(

Update 2

Here's my next code edit which doesn't seem to have worked either, I unsure why as it populates the events array fine with the values needed, I also added a addDay = "false" attribute as well but still no joy, Any body at all got any idea's, I'm stumped:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function () {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                //console.log(doc.d);
                var obj = $.parseJSON(doc.d);
                //console.log(obj);

                $.each(obj, function (index) {

                    $.each(obj[index], function (key, value) {

                        events.push(key + ": " + value)

                    });

                });

                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

Body:
More correct:

<script>

    $(document).ready(function () {

        $.ajax({
            type: "POST",
            url: "../04_Entries/04_42_ReservationCalander.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {

                var events = [];
                var docd = doc.d;

                var obj = $.parseJSON(doc.d);
                console.log(obj);

               $('#calendar').fullCalendar({
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    eventClick: function () {

                    },

                    editable: false,

                    events: obj //Just pass obj to events
                })
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    });

</script>


问:
Validation of a Password - Python
So I have to create code that validate whether a password:

Is at least 8 characters long

Contains at least 1 number

Contains at least 1 capital letter

Here is the code:

```<code>def validate():
    while True:
        password = input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif not password.isdigit():
            print("Make sure your password has a number in it")
        elif not password.isupper():
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()
</code>```

I'm not sure what is wrong, but when I enter a password that has a number - it keeps telling me that I need a password with a number in it. Any solutions?

答:
```<code>r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')
</code>```

this code will validate your password with :

min length is 6 and max length is 20

at least include a digit number,

at least a upcase and a lowcase letter

at least a special characters

Title: Validation of a Password - Python

Body:
So I have to create code that validate whether a password:

Is at least 8 characters long

Contains at least 1 number

Contains at least 1 capital letter

Here is the code:

def validate():
    while True:
        password = input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif not password.isdigit():
            print("Make sure your password has a number in it")
        elif not password.isupper():
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

I'm not sure what is wrong, but when I enter a password that has a number - it keeps telling me that I need a password with a number in it. Any solutions?

Body:
r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')

this code will validate your password with :

min length is 6 and max length is 20

at least include a digit number,

at least a upcase and a lowcase letter

at least a special characters


问:
How to query roundable amount?
I have a column with 4 records as below

```<code>123.15
122.3
91273.77
1.12
</code>```

How to write a query that can return me rows with roundable nearest 5 cents? Which should return me row 3 and row 4?

row 1 and row 2 are not selected because they are already rounded, row 3 and row 4 are selected because they are not rounded yet

答:
You can do something like this. In WHERE clause just multiply the value with 100 and do modulo division with 10. If the reminder is 0 or 5, assume it has been already rounded. Select the rest.

Query

```<code>select [column_value]
from [your_table_name]
where cast(([column_value] * 100) % 10  as int) not in (0, 5);
</code>```

Find a demo here

Title: How to query roundable amount?

Body:
I have a column with 4 records as below

123.15
122.3
91273.77
1.12

How to write a query that can return me rows with roundable nearest 5 cents? Which should return me row 3 and row 4?

row 1 and row 2 are not selected because they are already rounded, row 3 and row 4 are selected because they are not rounded yet

Body:
You can do something like this. In WHERE clause just multiply the value with 100 and do modulo division with 10. If the reminder is 0 or 5, assume it has been already rounded. Select the rest.

Query

select [column_value]
from [your_table_name]
where cast(([column_value] * 100) % 10  as int) not in (0, 5);

Find a demo here


问:
How to supply password at runtime to a dataset?
I have a database with password.
If I allow the password to be saved with connectionstring it would be visible in .config file.

How can I set the same at runtime?

Checked :

Point ADO.Net DataSet to different databases at runtime?

Changing dataset connection string at runtime

But need some way to change the connectionstring in setting itself to avoid changes at many locations.

Update: This is windows forms application.

答:
Functional C# code, just tested (based on the brilliant answer by @Sachin Chavan). The override has to be placed in your Settings.cs file:</p>

```<code>public override object this[string propertyName]
{
    get
    {
        if (propertyName == "nameOfYourConnectionStringProperty")
        {
            return base[propertyName].ToString().Replace("******", "Y0uRpA$sW0rD");
        }
        return base[propertyName];
    }
    set { base[propertyName] = value; }
}
</code>```

Body:
Functional C# code, just tested (based on the brilliant answer by @Sachin Chavan). The override has to be placed in your Settings.cs file:

public override object this[string propertyName]
{
    get
    {
        if (propertyName == "nameOfYourConnectionStringProperty")
        {
            return base[propertyName].ToString().Replace("******", "Y0uRpA$sW0rD");
        }
        return base[propertyName];
    }
    set { base[propertyName] = value; }
}


问:
How can we render mathjax equation in web browser control?
We are using mathjax equations in our document but concern is to render these equations on server side instead of client side. For the rectification of this issue we want to render them in web browser controls. So how can we render mathjax equation in web browser control using c#?

It would be great for us if someone give us any idea about this.

答:
I have found a very good way to render mathjax equations on the server by using Latex. Latex makes images for the equations and allows you different image formats.

```<code>var val="your_equation_val";
</code>```

val = "http://latex.codecogs.com/gif.latex?" + val + "\"/>";

Now we have an HTML tag with mathjax equation image finally.

Body:
I have found a very good way to render mathjax equations on the server by using Latex. Latex makes images for the equations and allows you different image formats.

var val="your_equation_val";

val = "http://latex.codecogs.com/gif.latex?" + val + "\"/>";

Now we have an HTML tag with mathjax equation image finally.


问:
D3: Yet another "Cannot read property 'weight' of undefined"
I'm trying to create a force-directed graph with one twist: the node and link data comes from externally defined classes.    When I run it, I get the dreaded and familiar message:

```<code>Uncaught TypeError: Cannot read property 'weight' of undefined
</code>```

I've read d3: Cannot read property 'weight' of undefined in d3.force implementation and the excellent https://stackoverflow.com/a/15060978/558639.  But no joy.

I've created a JSFiddle in https://jsfiddle.net/3xcaqaLc/8/ which faithfully replicates the error.

what I've tried

The docs mentions a 'weights' property on the links, but it wasn't particularly clear if I needed to provide that.

I added a weight: 1.0 property to each link.  No joy.

I added a weight: 1.0 property to each node.  No joy.

what I've not tried

All the examples I found show the links constructed with zero-based indexes into the nodes array.  Instead, I'm constructing the links with references to the nodes themselves.  But according to the documentation for #force.nodes(), this should work (note the use of the word 'may'):

Note: the values of the source and target attributes may be initially
  specified as indexes into the nodes array; these will be replaced by
  references after the call to start.

Perhaps the documents are inaccurate, but solutions will be welcome!

答:
I had the same problem and commenting .node() and .links() as in accepted answer led to empty graph. So I made two things:

Downgraded d3 version to http://d3js.org/d3.v3.js cause v.4 seems to be fully incompatible with all this stuff, no scale, layout, etc.

changed start and end props of my links to source and target respectively

That's it, no need to add weight

Body:
I'm trying to create a force-directed graph with one twist: the node and link data comes from externally defined classes.    When I run it, I get the dreaded and familiar message:

Uncaught TypeError: Cannot read property 'weight' of undefined

I've read d3: Cannot read property 'weight' of undefined in d3.force implementation and the excellent https://stackoverflow.com/a/15060978/558639.  But no joy.

I've created a JSFiddle in https://jsfiddle.net/3xcaqaLc/8/ which faithfully replicates the error.

what I've tried

The docs mentions a 'weights' property on the links, but it wasn't particularly clear if I needed to provide that.

I added a weight: 1.0 property to each link.  No joy.

I added a weight: 1.0 property to each node.  No joy.

what I've not tried

All the examples I found show the links constructed with zero-based indexes into the nodes array.  Instead, I'm constructing the links with references to the nodes themselves.  But according to the documentation for #force.nodes(), this should work (note the use of the word 'may'):

Note: the values of the source and target attributes may be initially
  specified as indexes into the nodes array; these will be replaced by
  references after the call to start.

Perhaps the documents are inaccurate, but solutions will be welcome!


问:
where does python store inheritance information in a class?
python version 3.5.2

I tried to get parent class from a child class:

```<code>class A:
    pass
class B(A):
    pass
</code>```

after a little research, I got a solution from python doc: use __base__. (a special class attribute)
But I couldn't find this "__base__" in B.__dict__ or dir(B), which are my normal ways of getting attributes.

This is definitely class related information, if it's not in B.__dict__ where is it? (although I realized that "__base__" is returned by type(B).__dict__)

And why isn't dir() returning it? based on this stackoverflow question I read, dir() has some logics behind and it is supposed to return "a complete picture of all available attributes."

I initally thought this is hiding on purpose...but you can still easily manipulate a child's parent:

```<code>class C:
    pass
B.__bases__ = (C,) # voila, B got a new Dad
</code>```

答:
See the note on dir() (emphasis mine):

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

B is a class, its metaclass is type. So if you really want the full picture, you should also look as the metaclass’ dir():

```<code>>>> B.__class__ is type
True
>>> dir(type)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__',
 '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__',
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__',
 '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__',
 '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
 '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__',
 '__weakrefoffset__', 'mro']
</code>```

And there you have __base__ and __bases__, and also those other things that appeared in the list you linked, like mro and __subclasses__.

Body:
python version 3.5.2

I tried to get parent class from a child class:

class A:
    pass
class B(A):
    pass

after a little research, I got a solution from python doc: use __base__. (a special class attribute)
But I couldn't find this "__base__" in B.__dict__ or dir(B), which are my normal ways of getting attributes.

This is definitely class related information, if it's not in B.__dict__ where is it? (although I realized that "__base__" is returned by type(B).__dict__)

And why isn't dir() returning it? based on this stackoverflow question I read, dir() has some logics behind and it is supposed to return "a complete picture of all available attributes."

I initally thought this is hiding on purpose...but you can still easily manipulate a child's parent:

class C:
    pass
B.__bases__ = (C,) # voila, B got a new Dad

Body:
See the note on dir() (emphasis mine):

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

B is a class, its metaclass is type. So if you really want the full picture, you should also look as the metaclass’ dir():

>>> B.__class__ is type
True
>>> dir(type)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__',
 '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__',
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__',
 '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__',
 '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
 '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__',
 '__weakrefoffset__', 'mro']

And there you have __base__ and __bases__, and also those other things that appeared in the list you linked, like mro and __subclasses__.


问:
" Nothing to show " on android layout in android studio
I have problem with android studio which is i can't see source code folders on android layout as showen in screenshot below.

PS: i can see the folders on project layout.

答: Just delete the old android studio project folder(if any) under %USERS% of windows,refer to below image for more and re-sync the project, it will work smoothly


问:
How to split the given format into date and time in android
Given Format:
2017-03-08 13:27:00

I want to spilt it into 2 strings
1 for date and 1 for time
for

E.g.

08-03-2017

13:27:00

答:
try this

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2017-03-08 13:27:00";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Date :"+dt1.format(date));

          dt1 = new SimpleDateFormat("HH:mm:ss");
            System.out.println("Time :"+dt1.format(date));
    }

}
</code>```

It gives output like this

Date :2017-03-08  Time :13:27:00

Body:
try this

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2017-03-08 13:27:00";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Date :"+dt1.format(date));

          dt1 = new SimpleDateFormat("HH:mm:ss");
            System.out.println("Time :"+dt1.format(date));
    }

}

It gives output like this

Date :2017-03-08  Time :13:27:00


问:
Can you test the latest version of Firefox (52 as of now) using Webdriver.io?
I can see that Webdriver.io only supports Selenium 2, and the latest FF is using Selenium 3, so is there any work around to use Webdriver.io for the latest FF? Is Webdriver.io planning to support Selenium 3 anytime soon?</p>

答: I don't know about the support for selenium 3, but I am using latest version of ff, 52.0.1 - x64 & it is working fine with my tests. I am using selenium-server-standalone-3.0.1</p>


问:
How to use replaceFirst() to get a series of sequential strings in my case?
My input string uid contains 6 characters, and there are 0~6 '?' at random position like "00??00", "0?00?0", "0??00?". For example, if the input is "00?0?0", I want to replace two '?' with 0~9. So the results should be "000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"

Well, my following code can only get "000000","001010","002020"..."009090", I got to know that replace() will replace all '?', and using replaceFirst() might solve it. So how to use replaceFirst() to get the results I want?

```<code>List<Get> gets = new ArrayList<>();

for (int i =0; i<10; i++){
    get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());

    // get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());

    gets.add(get);
}
</code>```

答:
```<code>String patter = "00??00";
for (int i = 0; i < 100; i++) {
    System.out.println(patt.replace("??", ""+i));
}
</code>```

Body:
My input string uid contains 6 characters, and there are 0~6 '?' at random position like "00??00", "0?00?0", "0??00?". For example, if the input is "00?0?0", I want to replace two '?' with 0~9. So the results should be "000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"

Well, my following code can only get "000000","001010","002020"..."009090", I got to know that replace() will replace all '?', and using replaceFirst() might solve it. So how to use replaceFirst() to get the results I want?

List<Get> gets = new ArrayList<>();

for (int i =0; i<10; i++){
    get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());

    // get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());

    gets.add(get);
}


问:
python password rules validation
I'm practicing some Python and I'm having trouble understanding why this code won't take - function takes a string and if it's at least 10 characters in length, has at least 1 digit, 1 lowercase, and 1 uppercase letter, it should return True. Also, there's gotta be a more succinct way to write this than I did with all these nested conditionals. Thanks all!</p>

```<code>import string
alphalower = string.ascii_lowercase
alphaupper = string.ascii_uppercase
digs = string.digits

def checkio(data):
    if len(data) >= 10:
        if data.count(digs) >= 1:
            if data.count(alphaupper) >= 1:
                if data.count(alphalower) >= 1:
                    return True
    else:
        return False
</code>```

Title: python password rules validation

Body:
I'm practicing some Python and I'm having trouble understanding why this code won't take - function takes a string and if it's at least 10 characters in length, has at least 1 digit, 1 lowercase, and 1 uppercase letter, it should return True. Also, there's gotta be a more succinct way to write this than I did with all these nested conditionals. Thanks all!

import string
alphalower = string.ascii_lowercase
alphaupper = string.ascii_uppercase
digs = string.digits

def checkio(data):
    if len(data) >= 10:
        if data.count(digs) >= 1:
            if data.count(alphaupper) >= 1:
                if data.count(alphalower) >= 1:
                    return True
    else:
        return False


问:
Learning PowerShell. Create usernames no longer than 8 characters and check for collision
I'm learning powershell right now.

I need to import a CSV like this:
lastname,firstname
lastname,firstname
lastname,firstname
etc

Then create a list of usernames no longer then 8 characters and check for collisions.

I have found bits and pieces of scripting around but not sure how to tie it all together.

I use Import-Csv to import my file.csv:

```<code>$variablename = import-csv C:\path\to\file.csv
</code>```

but then I am not sure if I just import it into an array or not. I am not familiar with how for loops work in powershell exactly.

Any direction? Thanks.

答:
The script below should help you grasp a few concepts on how to work with csvs and manipulate data using PowerShell.

```<code># the code below uses a 'here string' to mimic the import of a csv.
$users = @'
smith,b
smith,bob
smith,bobby
smith,sonny
smithson,john
smithson,jane
smithers,rob
'@ -split "`r*`n"

$users |
  ConvertFrom-Csv -Header 'surname','firstname' |
  Select-Object @{Name='username'; Expression={"$($_.surname)$($_.firstname)        "}}, surname, firstname |
  Group-Object { $_.username.Substring(0,8).Trim() } |
  Select-Object @{Name='username'; Expression={$_.Name}}, Count |
  Format-Table -AutoSize
</code>```

The $users | line takes the list of $users and pipes into the next command.

The ConvertFrom-Csv -Header... line converts the string into a csv.

The Select-Object @{Name... line creates an expression alias, which concatenates surname+forename. You'll notice the extra 8 spaces we append to the end of the string so we know we will have at least 8 characters in the string.

The Group-Object {... line groups the username, using the first 8 characters, if available. The .Trim() gets rid of any trailing spaces.

The Select-Object @{Name='username'... line takes the Name field from the group-object and renames to username and also shows the count from the grouping operation.

The Format-Table -AutoSize line is purely for output formatting to the console and gives you an output like the one below.

```<code>username Count
-------- -----
smithb       1
smithbob     2
smithson     3
smithers     1
</code>```

An amended version of the above code, which you can use on your real csv. Change the surname, firstname column names to suit your csv.

```<code># you would use the code below, to import your list of names
# uncomment the `# -Header surname,firstname` bit if your csv has no headers
$users = Import-Csv -Path 'c:\path\to\names.csv' # -Header surname,firstname

$users |
  Select-Object @{Name='username'; Expression={"$($_.surname)$($_.firstname)        "}}, surname, firstname |
  Group-Object { $_.username.Substring(0,8).Trim() } |
  Select-Object @{Name='username'; Expression={$_.Name}}, Count
</code>```

Body:
I'm learning powershell right now.

I need to import a CSV like this:
lastname,firstname
lastname,firstname
lastname,firstname
etc

Then create a list of usernames no longer then 8 characters and check for collisions.

I have found bits and pieces of scripting around but not sure how to tie it all together.

I use Import-Csv to import my file.csv:

$variablename = import-csv C:\path\to\file.csv

but then I am not sure if I just import it into an array or not. I am not familiar with how for loops work in powershell exactly.

Any direction? Thanks.

Body:
The script below should help you grasp a few concepts on how to work with csvs and manipulate data using PowerShell.

# the code below uses a 'here string' to mimic the import of a csv.
$users = @'
smith,b
smith,bob
smith,bobby
smith,sonny
smithson,john
smithson,jane
smithers,rob
'@ -split "`r*`n"

$users |
  ConvertFrom-Csv -Header 'surname','firstname' |
  Select-Object @{Name='username'; Expression={"$($_.surname)$($_.firstname)        "}}, surname, firstname |
  Group-Object { $_.username.Substring(0,8).Trim() } |
  Select-Object @{Name='username'; Expression={$_.Name}}, Count |
  Format-Table -AutoSize

The $users | line takes the list of $users and pipes into the next command.

The ConvertFrom-Csv -Header... line converts the string into a csv.

The Select-Object @{Name... line creates an expression alias, which concatenates surname+forename. You'll notice the extra 8 spaces we append to the end of the string so we know we will have at least 8 characters in the string.

The Group-Object {... line groups the username, using the first 8 characters, if available. The .Trim() gets rid of any trailing spaces.

The Select-Object @{Name='username'... line takes the Name field from the group-object and renames to username and also shows the count from the grouping operation.

The Format-Table -AutoSize line is purely for output formatting to the console and gives you an output like the one below.

username Count
-------- -----
smithb       1
smithbob     2
smithson     3
smithers     1

An amended version of the above code, which you can use on your real csv. Change the surname, firstname column names to suit your csv.

# you would use the code below, to import your list of names
# uncomment the `# -Header surname,firstname` bit if your csv has no headers
$users = Import-Csv -Path 'c:\path\to\names.csv' # -Header surname,firstname

$users |
  Select-Object @{Name='username'; Expression={"$($_.surname)$($_.firstname)        "}}, surname, firstname |
  Group-Object { $_.username.Substring(0,8).Trim() } |
  Select-Object @{Name='username'; Expression={$_.Name}}, Count


问:
I have 2 text areas. On consecutive clicks of add description button the text of both the textareas will get merged into the first one
I am able to achieve this but I also need a time/date stamp along with each new entry.
Here's a fiddle link:

https://jsfiddle.net/Anupriya24/pstynje9/

Script:

```<code>    var count=0;
$('.addDescBtn').on('click', function() {
    count++;
    if(count<=1){
        if($("#description").val()==""){
            alert("Please add to existing description field.");
            $("#description").val("");
            $("#description").removeAttr("readonly");
            count=0;
        }
        else {
            $("#descriptionHolder").append('<div class="form-group col-md-12 pad0 mar-t20" id="newDesc"><label class="col-md-3 pad0 visible-none" for="description1">Description:</label><textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea> </div>');
        }
    }
    if($('#descriptionHolder').find('#newDesc').length){
        var text=$("#description").val().trim();
        var text1=$("#description1").val();
        var combinedText=text+"\n"+text1+"\n";
        $("#description").val(combinedText);
        $("#description").attr('readonly', 'readonly');
        $("#description1").val("");
    }

});
</code>```

Html

```<code>                        <div class="form-group col-md-12 pad0" id="descriptionHolder">
                            <label class="col-md-3 pad0" for="description">Description:</label>
                            <textarea rows="5" cols="50" class="form-control col-md-9" id="description" placeholder="Description" ></textarea>
                        </div>
                        <div class="form-group col-md-12 pad0">
                            <input type="button" class="addDescBtn orangeBtn btn fright" value="Add Description" id="addDescription"/>
                        </div>
</code>```

答:
Try this : </p>

```<code>   var count=0;
$('.addDescBtn').on('click', function() {
count++;
if(count<=1){
    if($("#description").val()==""){
        alert("Please add to existing description field.");
        $("#description").val("");
        $("#description").removeAttr("readonly");
        count=0;
    }
    else {
        $("#descriptionHolder").append('<div class="form-group col-md-12 pad0 mar-t20" id="newDesc"><label class="col-md-3 pad0 visible-none" for="description1">Description:</label><textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea> </div>');
    }
}
if($('#descriptionHolder').find('#newDesc').length){
    var text=$("#description").val().trim();
    //Just added new Date() with your string; It will give current timestamp.
    var text1=$("#description1").val() + new Date();
    var combinedText=text+"\n"+text1+"\n";
    $("#description").val(combinedText);
    $("#description").attr('readonly', 'readonly');
    $("#description1").val("");
}

});
</code>```

Body:
I am able to achieve this but I also need a time/date stamp along with each new entry.
Here's a fiddle link:

https://jsfiddle.net/Anupriya24/pstynje9/

Script:

    var count=0;
$('.addDescBtn').on('click', function() {
    count++;
    if(count<=1){
        if($("#description").val()==""){
            alert("Please add to existing description field.");
            $("#description").val("");
            $("#description").removeAttr("readonly");
            count=0;
        }
        else {
            $("#descriptionHolder").append('
Description:<textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea>
');
        }
    }
    if($('#descriptionHolder').find('#newDesc').length){
        var text=$("#description").val().trim();
        var text1=$("#description1").val();
        var combinedText=text+"\n"+text1+"\n";
        $("#description").val(combinedText);
        $("#description").attr('readonly', 'readonly');
        $("#description1").val("");
    }

});

Html

                            Description:
                            <textarea rows="5" cols="50" class="form-control col-md-9" id="description" placeholder="Description" ></textarea>

                            <input type="button" class="addDescBtn orangeBtn btn fright" value="Add Description" id="addDescription"/>

Body:
Try this :

   var count=0;
$('.addDescBtn').on('click', function() {
count++;
if(count<=1){
    if($("#description").val()==""){
        alert("Please add to existing description field.");
        $("#description").val("");
        $("#description").removeAttr("readonly");
        count=0;
    }
    else {
        $("#descriptionHolder").append('<div class="form-group col-md-12 pad0 mar-t20" id="newDesc"><label class="col-md-3 pad0 visible-none" for="description1">Description:</label><textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea> </div>');
    }
}
if($('#descriptionHolder').find('#newDesc').length){
    var text=$("#description").val().trim();
    //Just added new Date() with your string; It will give current timestamp.
    var text1=$("#description1").val() + new Date();
    var combinedText=text+"\n"+text1+"\n";
    $("#description").val(combinedText);
    $("#description").attr('readonly', 'readonly');
    $("#description1").val("");
}

});


问:
How to add "" double code in variable in bat file?
I have written bat file to get path from system variable using %JAVA_HOME% and assigned it into one variable, now how to use as set path, because in set path its asking me this path between " " code, which i am not able to add in.

Please help me to add it, how ?

答:
It is a big difference if an environment variable is defined with set variable="value" or with set "variable=value". Read the answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? for details.

It is strongly recommended to use set "variable=value", i.e. assign the string to the environment variable without double quotes and reference the value of the environment variable always enclosed in double quotes.

It looks like you use:

```<code>@ECHO OFF
set JAVA_CMD="C:\Program Files\Java\jdk1.8.0_92\jre\bin\java"
%JAVA_CMD% TransferArborDeereFiles
pause
</code>```

So to get path of java executable with having file extension .exe not specified and therefore Windows command interpreter needs to search for java.* with a file extension listed in local environment variable PATHEXT, the following batch code could be used:

```<code>@ECHO OFF
set JAVA_CMD="C:\Program Files\Java\jdk1.8.0_92\jre\bin\java"
rem %JAVA_CMD% TransferArborDeereFiles
for /F "delims=" %%I in (%JAVA_CMD%) do set "JAVA_CMD_PATH=%%~dpI"
set JAVA_CMD
pause
</code>```

This batch file just outputs the values of the environment variables JAVA_CMD and JAVA_CMD_PATH.

But much better would be:

```<code>@ECHO OFF
setlocal EnableExtensions DisableDelayedExpansion

set "JAVA_CMD=%ProgramFiles%\Java\jdk1.8.0_92\jre\bin\java.exe"
for /F "delims=" %%I in ("%JAVA_CMD%") do set "JAVA_CMD_PATH=%%~dpI"

rem Output all environment variables starting with JAVA_CMD.
set JAVA_CMD

rem "%JAVA_CMD%" TransferArborDeereFiles
rem "%JAVA_CMD_PATH%OtherScriptOrExe" "argument 1" "argument 2"

endlocal
</code>```

This batch file should be executed in a command prompt window and not with double clicking on the batch file. Debugging a batch file in development should be always done by running it from within a command prompt window to see possible error messages output by Windows command interpreter of errors resulting in exiting batch file execution.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

for /?

pause /?

rem /?

set /?

setlocal /?

Body:
It is a big difference if an environment variable is defined with set variable="value" or with set "variable=value". Read the answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? for details.

It is strongly recommended to use set "variable=value", i.e. assign the string to the environment variable without double quotes and reference the value of the environment variable always enclosed in double quotes.

It looks like you use:

@ECHO OFF
set JAVA_CMD="C:\Program Files\Java\jdk1.8.0_92\jre\bin\java"
%JAVA_CMD% TransferArborDeereFiles
pause

So to get path of java executable with having file extension .exe not specified and therefore Windows command interpreter needs to search for java.* with a file extension listed in local environment variable PATHEXT, the following batch code could be used:

@ECHO OFF
set JAVA_CMD="C:\Program Files\Java\jdk1.8.0_92\jre\bin\java"
rem %JAVA_CMD% TransferArborDeereFiles
for /F "delims=" %%I in (%JAVA_CMD%) do set "JAVA_CMD_PATH=%%~dpI"
set JAVA_CMD
pause

This batch file just outputs the values of the environment variables JAVA_CMD and JAVA_CMD_PATH.

But much better would be:

@ECHO OFF
setlocal EnableExtensions DisableDelayedExpansion

set "JAVA_CMD=%ProgramFiles%\Java\jdk1.8.0_92\jre\bin\java.exe"
for /F "delims=" %%I in ("%JAVA_CMD%") do set "JAVA_CMD_PATH=%%~dpI"

rem Output all environment variables starting with JAVA_CMD.
set JAVA_CMD

rem "%JAVA_CMD%" TransferArborDeereFiles
rem "%JAVA_CMD_PATH%OtherScriptOrExe" "argument 1" "argument 2"

endlocal

This batch file should be executed in a command prompt window and not with double clicking on the batch file. Debugging a batch file in development should be always done by running it from within a command prompt window to see possible error messages output by Windows command interpreter of errors resulting in exiting batch file execution.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

for /?

pause /?

rem /?

set /?

setlocal /?