Rectangle 27 15

Every async function returns a Promise object

await
Promise
resolve
reject

So no, you can't do console.log on the result of an async function directly, even if you use await. Using await will make your function wait and then return a Promise which resolves immediately, but it won't unwrap the Promise for you. You still need to unwrap the Promise returned by the async function, either using await or using .then().

When you use .then() instead of console.logging directly, the .then() method makes the result of the Promise available to you. But you can't get the result of the Promise from outside the Promise. That's part of the model of working with Promises.

I thought the whole point of async/await was so that you could write async Promise functions using synchronous code. Are you saying that you always have to follow up an async function with .then()? If so, then how is that different than just using a Promise by itself?

The point is that within the async function, you can write async code as if it were synchronous. However, from outside the async function, you need to treat the asynchronous result of that function as usual. Which is usually not a problem, since you should be only getting asynchronous results in your UI logic anyway.

In summary: You write your async logic as if it were synchronous, however when you call your async logic from code that is actually synchronous, you need to differentiate between actually-synchronous and actually-asynchronous.

javascript - async/await always returns promise - Stack Overflow

javascript asynchronous promise async-await ecmascript-2017
Rectangle 27 1

tl;dr: The promise yielded by the generator has to move the generator forward.

If you look at first examples in http://davidwalsh.name/async-generators, you will notice that the async function actually moves the iterator forward:

function request(url) {
    // this is where we're hiding the asynchronicity,
    // away from the main code of our generator
    // `it.next(..)` is the generator's iterator-resume
    // call
    makeAjaxCall( url, function(response){
        it.next( response );               // <--- this is where the magic happens
    } );
    // Note: nothing returned here!
}

But since you are working with promises, we can improve on that, a little bit. y.next().value returns a promise, and you'd have to listen to that promise. So instead of writing console.log(y.next()), you'd write:

var promise = y.next().value;
promise.then(y.next.bind(y)); // or promise.then(function(v) { y.next(v); });

Of course this not very practical, because now you cannot access the next yielded value and you don't know when the generator will be done. However, you could write a recursive function which takes care of that. That's what runGenerator introduced later in this article takes care of.

javascript - ECMA6 generators: yield promise - Stack Overflow

javascript node.js ecmascript-6
Rectangle 27 13

Text area not working when the moon is full

I'd like the display of the questions in the list to change based on the list. If you are viewing a list sorted by recent activity, I'd like to see what that activity is:

I don't need to see "votes", "answers", "views", or "tags" for this list. They just clutter it up and a are distracting.

If you a viewing a popular list, "views", "votes", and the question title are about all that matter.

Since "sorted by recent activity" is the default front-page view I'd say that votes, answers and tags are definitely relevant there. (And view count is probably as relevant there as it is anywhere else, too).

In particular, tags are relevant in every list of questions, since many SE sites encourage askers not to include context information in question titles when it can also be deduced from the tags. So if the question title is just "How does one blargle a whatsit?" one will often need to look at the tags to find out whether it's about Greek whatsits or the entirely different concept of plumbing whatsits.

Recent activity doesn't make much sense on the front page to me unless you are a moderator or acting as a moderator. Hot site questions would be better for new users and "things to answer" would be better for somewhat experienced users. Ideally, the front page would be customizable. I'd like to see some of each there, actually. Different sections, maybe in columns.

discussion design navigation homepage new-nav
Rectangle 27 27

1. Test if it is working before the changes

Detailed answer for those of us willing to make local config changes that includes backing up the config file:

If you don't have a test program already, you can use my java SSLPing ping program which tests the TLS handshake (will work with any SSL/TLS port, not just HTTPS). I'll use the prebuilt SSLPing.jar, but reading the code and building it yourself is a quick and easy task:

$ git clone https://github.com/dimalinux/SSLPing.git
Cloning into 'SSLPing'...
[... output snipped ...]

Since my Java version is earlier than 1.8.0_101 (not released at the time of this writing), a Let's Encrypt certificate will not verify by default. Let's see what failure looks like before applying the fix:

I'm on Mac OS X with the JAVA_HOME environment variable set. Later commands will assume this variable is set for the java installation you are modifying:

$ echo $JAVA_HOME 
/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home/

Make a backup of the cacerts file we will be modifying so you can back out any change without reinstalling the JDK:

$ sudo cp -a $JAVA_HOME/jre/lib/security/cacerts $JAVA_HOME/jre/lib/security/cacerts.orig
$ wget https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.der
$ sudo keytool -trustcacerts -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -noprompt -importcert -alias lets-encrypt-x3-cross-signed -file lets-encrypt-x3-cross-signed.der 
Certificate was added to keystore

Verify that Java is now happy connecting to the SSL port:

$ java -jar SSLPing/dist/SSLPing.jar helloworld.letsencrypt.org 443
About to connect to 'helloworld.letsencrypt.org' on port 443
Successfully connected

ssl - Does Java support Let's Encrypt certificates? - Stack Overflow

java ssl keystore lets-encrypt ca
Rectangle 27 19

See the working code here

The problem was Autocomplete couldn't render the source for its functioning.

You need to set the source of the autocomplete based on the JSON data present using ,

source: function (request, response) {
           //data :: JSON list defined
           response($.map(data, function (value, key) {
                return {
                    label: value.first_name,
                    value: value.id
                }
            }));

    },

And, I also removed the .data callback from the code.

Wonderful. An explanation with working code. +10

This doesn't actually seem to filter the data list though, if I type 'em' I get both values.

javascript - jQuery UI autocomplete with objects - Stack Overflow

javascript jquery jquery-ui jquery-ui-autocomplete
Rectangle 27 18

Tested and working!

package com.example.dto;

import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonProperty;

@XmlRootElement
public class Location {

    private String room;
    private String building;
    private String computers;
    @JsonProperty("string")
    private String str;

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }

    public String getBuilding() {
        return building;
    }

    public void setBuilding(String building) {
        this.building = building;
    }

    public String getComputers() {
        return computers;
    }

    public void setComputers(String computers) {
        this.computers = computers;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

}
package com.example.main;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.example.dto.Computer;

public class JSONParse {

    public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException {

        /* JSON provider */
        URL url = new URL("http://api.engin.umich.edu/hostinfo/v1/computers.json?building=PIERPONT&room=B505");

        ObjectMapper mapper = new ObjectMapper();

        /*
         * This allows the ObjectMapper to accept single values for a collection.
         * For example: "location" property in the returned JSON is a collection that 
         * can accept multiple objects but, in deserialization process, this property just 
         * have one object and causes an Exception.
         */
        mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

        /* 
         * If some JSON property is not present, avoid exceptions setting
         * FAIL_ON_UNKNOWN_PROPERTIES to false 
         */
        mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        /* Get all computers */
        List<Computer> computers = mapper.readValue(url, new TypeReference<List<Computer>>(){});

        /* Print each computer (previously overriding "toString()" method) */
        for(Computer computer : computers) {
            System.out.println(computer.toString());
        }

    }

}
class
=================================
Hostname: pierb505p13.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9608460
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.23
Last_Access: 
Last_Report: 1383202078

=================================
Hostname: pierb505p22.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9609244
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.32
Last_Access: 
Last_Report: 1383201987

=================================
Hostname: pierb505p06.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9606464
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.16
Last_Access: 
Last_Report: 1383201982

=================================
Hostname: pierb505p17.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9606820
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.27
Last_Access: 
Last_Report: 1383202064

=================================
Hostname: pierb505p15.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9609052
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.25
Last_Access: 
Last_Report: 1383202052

=================================
Hostname: pierb505p12.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9607136
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.22
Last_Access: 
Last_Report: 1383202037

=================================
Hostname: pierb505p03.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9603132
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.13
Last_Access: 
Last_Report: 1383201964

=================================
Hostname: pierb505p14.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9599592
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.24
Last_Access: 
Last_Report: 1383201996

=================================
Hostname: pierb505p07.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9608176
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.17
Last_Access: 
Last_Report: 1383202127

=================================
Hostname: pierb505p23.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9600968
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.33
Last_Access: 
Last_Report: 1383202013

=================================
Hostname: pierb505p11.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9607224
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.21
Last_Access: 
Last_Report: 1383202098

=================================
Hostname: pierb505p21.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9595136
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.31
Last_Access: 
Last_Report: 1383202035

=================================
Hostname: pierb505p16.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9601212
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.26
Last_Access: 
Last_Report: 1383202106

=================================
Hostname: pierb505p04.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9603220
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.14
Last_Access: 
Last_Report: 1383202135

=================================
Hostname: pierb505p08.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 16024588
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.18
Last_Access: 
Last_Report: 1383202133

=================================
Hostname: pierb505p25.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 10299356
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.35
Last_Access: 
Last_Report: 1383202100

=================================
Hostname: pierb505p26.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 11303888
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.36
Last_Access: 
Last_Report: 1383202027

=================================
Hostname: pierb505p19.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 15914176
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.29
Last_Access: 
Last_Report: 1383202081

=================================
Hostname: pierb505p09.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 29956064
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.19
Last_Access: 
Last_Report: 1383201997

=================================
Hostname: pierb505p10.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 19663960
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.20
Last_Access: 
Last_Report: 1383202003

=================================
Hostname: pierb505p24.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 19197988
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.34
Last_Access: 
Last_Report: 1383202038

=================================
Hostname: pierb505p20.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 9585536
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.30
Last_Access: 
Last_Report: 1383201994

java - Simple Spring code to parse JSON - Stack Overflow

java json spring
Rectangle 27 18

Tested and working!

package com.example.dto;

import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonProperty;

@XmlRootElement
public class Location {

    private String room;
    private String building;
    private String computers;
    @JsonProperty("string")
    private String str;

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }

    public String getBuilding() {
        return building;
    }

    public void setBuilding(String building) {
        this.building = building;
    }

    public String getComputers() {
        return computers;
    }

    public void setComputers(String computers) {
        this.computers = computers;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

}
package com.example.main;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.example.dto.Computer;

public class JSONParse {

    public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException {

        /* JSON provider */
        URL url = new URL("http://api.engin.umich.edu/hostinfo/v1/computers.json?building=PIERPONT&room=B505");

        ObjectMapper mapper = new ObjectMapper();

        /*
         * This allows the ObjectMapper to accept single values for a collection.
         * For example: "location" property in the returned JSON is a collection that 
         * can accept multiple objects but, in deserialization process, this property just 
         * have one object and causes an Exception.
         */
        mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

        /* 
         * If some JSON property is not present, avoid exceptions setting
         * FAIL_ON_UNKNOWN_PROPERTIES to false 
         */
        mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        /* Get all computers */
        List<Computer> computers = mapper.readValue(url, new TypeReference<List<Computer>>(){});

        /* Print each computer (previously overriding "toString()" method) */
        for(Computer computer : computers) {
            System.out.println(computer.toString());
        }

    }

}
class
=================================
Hostname: pierb505p13.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9608460
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.23
Last_Access: 
Last_Report: 1383202078

=================================
Hostname: pierb505p22.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9609244
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.32
Last_Access: 
Last_Report: 1383201987

=================================
Hostname: pierb505p06.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9606464
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.16
Last_Access: 
Last_Report: 1383201982

=================================
Hostname: pierb505p17.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9606820
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.27
Last_Access: 
Last_Report: 1383202064

=================================
Hostname: pierb505p15.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9609052
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.25
Last_Access: 
Last_Report: 1383202052

=================================
Hostname: pierb505p12.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9607136
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.22
Last_Access: 
Last_Report: 1383202037

=================================
Hostname: pierb505p03.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9603132
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.13
Last_Access: 
Last_Report: 1383201964

=================================
Hostname: pierb505p14.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9599592
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.24
Last_Access: 
Last_Report: 1383201996

=================================
Hostname: pierb505p07.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 0
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9608176
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.17
Last_Access: 
Last_Report: 1383202127

=================================
Hostname: pierb505p23.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9600968
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.33
Last_Access: 
Last_Report: 1383202013

=================================
Hostname: pierb505p11.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9607224
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.21
Last_Access: 
Last_Report: 1383202098

=================================
Hostname: pierb505p21.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9595136
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.31
Last_Access: 
Last_Report: 1383202035

=================================
Hostname: pierb505p16.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9601212
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.26
Last_Access: 
Last_Report: 1383202106

=================================
Hostname: pierb505p04.engin.umich.edu
Vendor: Linux
Model: Dell 980
Swap: 8126456
Memory: 7797
Sess_Count: 0
Load: 
  One: 1
  Five: 0
  Fifteen: 0
In_Use: false
Free_In_Tmp: 9603220
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.14
Last_Access: 
Last_Report: 1383202135

=================================
Hostname: pierb505p08.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 16024588
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.18
Last_Access: 
Last_Report: 1383202133

=================================
Hostname: pierb505p25.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 10299356
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.35
Last_Access: 
Last_Report: 1383202100

=================================
Hostname: pierb505p26.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 11303888
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.36
Last_Access: 
Last_Report: 1383202027

=================================
Hostname: pierb505p19.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 15914176
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.29
Last_Access: 
Last_Report: 1383202081

=================================
Hostname: pierb505p09.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 29956064
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.19
Last_Access: 
Last_Report: 1383201997

=================================
Hostname: pierb505p10.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 19663960
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.20
Last_Access: 
Last_Report: 1383202003

=================================
Hostname: pierb505p24.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 19197988
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.34
Last_Access: 
Last_Report: 1383202038

=================================
Hostname: pierb505p20.engin.umich.edu
Vendor: Windows
Model: OptiPlex 980
Swap: 0
Memory: 0
Sess_Count: 0
Load: 
  One: 1
  Five: 5
  Fifteen: 15
In_Use: false
Free_In_Tmp: 9585536
Class: L
Location: 
  Building: PIERPONT
  Computers: 26
  Room: B505
  String: B505 PIERPONT
Ip: 141.213.54.30
Last_Access: 
Last_Report: 1383201994

java - Simple Spring code to parse JSON - Stack Overflow

java json spring
Rectangle 27 208

Creating a Working Internet Explorer 8 Addon

Man... this has been a lot of work! I was so curious about how to do this, that I did it myself.

First of all... credit is not all mine. This is a compilation of what I found, on these sites:

  • 15seconds, but it was not 15 seconds, it took about 7 hours;
  • Microsoft tutorial, helped me adding the command button.
  • And this social.msdn topic, that helped me figure out that the assembly must be in the GAC.
  • many other sites, in the discovery process...
  • a button that shows a window (in my case to setup)

I will describe it step by step, how I managed to do it working with Internet Explorer 8, in Windows 7 x64... note that I could not test in other configurations. Hope you understand =)

I am using Visual Studio 2010, C# 4, .Net Framework 4, so some of these steps might be slightly different for you.

<Reference Include="Interop.SHDocVw, Version=1.1.0.0, Culture=neutral, PublicKeyToken=90ba9c70f846762e, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <EmbedInteropTypes>True</EmbedInteropTypes>
  <HintPath>C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\Interop.SHDocVw.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.mshtml, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />

Create the following files:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;
using mshtml;
using SHDocVw;

namespace InternetExplorerExtension
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("D40C654D-7C51-4EB3-95B2-1E23905C2A2D")]
    [ProgId("MyBHO.WordHighlighter")]
    public class WordHighlighterBHO : IObjectWithSite, IOleCommandTarget
    {
        const string DefaultTextToHighlight = "browser";

        IWebBrowser2 browser;
        private object site;

        #region Highlight Text
        void OnDocumentComplete(object pDisp, ref object URL)
        {
            try
            {
                // @Eric Stob: Thanks for this hint!
                // This will prevent this method being executed more than once.
                if (pDisp != this.site)
                    return;

                var document2 = browser.Document as IHTMLDocument2;
                var document3 = browser.Document as IHTMLDocument3;

                var window = document2.parentWindow;
                window.execScript(@"function FncAddedByAddon() { alert('Message added by addon.'); }");

                Queue<IHTMLDOMNode> queue = new Queue<IHTMLDOMNode>();
                foreach (IHTMLDOMNode eachChild in document3.childNodes)
                    queue.Enqueue(eachChild);

                while (queue.Count > 0)
                {
                    // replacing desired text with a highlighted version of it
                    var domNode = queue.Dequeue();

                    var textNode = domNode as IHTMLDOMTextNode;
                    if (textNode != null)
                    {
                        if (textNode.data.Contains(TextToHighlight))
                        {
                            var newText = textNode.data.Replace(TextToHighlight, "<span style='background-color: yellow; cursor: hand;' onclick='javascript:FncAddedByAddon()' title='Click to open script based alert window.'>" + TextToHighlight + "</span>");
                            var newNode = document2.createElement("span");
                            newNode.innerHTML = newText;
                            domNode.replaceNode((IHTMLDOMNode)newNode);
                        }
                    }
                    else
                    {
                        // adding children to collection
                        var x = (IHTMLDOMChildrenCollection)(domNode.childNodes);
                        foreach (IHTMLDOMNode eachChild in x)
                        {
                            if (eachChild is mshtml.IHTMLScriptElement)
                                continue;
                            if (eachChild is mshtml.IHTMLStyleElement)
                                continue;

                            queue.Enqueue(eachChild);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        #region Load and Save Data
        static string TextToHighlight = DefaultTextToHighlight;
        public static string RegData = "Software\\MyIEExtension";

        [DllImport("ieframe.dll")]
        public static extern int IEGetWriteableHKCU(ref IntPtr phKey);

        private static void SaveOptions()
        {
            // In IE 7,8,9,(desktop)10 tabs run in Protected Mode
            // which prohibits writes to HKLM, HKCU.
            // Must ask IE for "Writable" registry section pointer
            // which will be something like HKU/S-1-7***/Software/AppDataLow/
            // In "metro" IE 10 mode, tabs run in "Enhanced Protected Mode"
            // where BHOs are not allowed to run, except in edge cases.
            // see http://blogs.msdn.com/b/ieinternals/archive/2012/03/23/understanding-ie10-enhanced-protected-mode-network-security-addons-cookies-metro-desktop.aspx
            IntPtr phKey = new IntPtr();
            var answer = IEGetWriteableHKCU(ref phKey);
            RegistryKey writeable_registry = RegistryKey.FromHandle(
                new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)
            );
            RegistryKey registryKey = writeable_registry.OpenSubKey(RegData, true);

            if (registryKey == null)
                registryKey = writeable_registry.CreateSubKey(RegData);
            registryKey.SetValue("Data", TextToHighlight);

            writeable_registry.Close();
        }
        private static void LoadOptions()
        {
            // In IE 7,8,9,(desktop)10 tabs run in Protected Mode
            // which prohibits writes to HKLM, HKCU.
            // Must ask IE for "Writable" registry section pointer
            // which will be something like HKU/S-1-7***/Software/AppDataLow/
            // In "metro" IE 10 mode, tabs run in "Enhanced Protected Mode"
            // where BHOs are not allowed to run, except in edge cases.
            // see http://blogs.msdn.com/b/ieinternals/archive/2012/03/23/understanding-ie10-enhanced-protected-mode-network-security-addons-cookies-metro-desktop.aspx
            IntPtr phKey = new IntPtr();
            var answer = IEGetWriteableHKCU(ref phKey);
            RegistryKey writeable_registry = RegistryKey.FromHandle(
                new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)
            );
            RegistryKey registryKey = writeable_registry.OpenSubKey(RegData, true);

            if (registryKey == null)
                registryKey = writeable_registry.CreateSubKey(RegData);
            registryKey.SetValue("Data", TextToHighlight);

            if (registryKey == null)
            {
                TextToHighlight = DefaultTextToHighlight;
            }
            else
            {
                TextToHighlight = (string)registryKey.GetValue("Data");
            }
            writeable_registry.Close();
        }
        #endregion

        [Guid("6D5140C1-7436-11CE-8034-00AA006009FA")]
        [InterfaceType(1)]
        public interface IServiceProvider
        {
            int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject);
        }

        #region Implementation of IObjectWithSite
        int IObjectWithSite.SetSite(object site)
        {
            this.site = site;

            if (site != null)
            {
                LoadOptions();

                var serviceProv = (IServiceProvider)this.site;
                var guidIWebBrowserApp = Marshal.GenerateGuidForType(typeof(IWebBrowserApp)); // new Guid("0002DF05-0000-0000-C000-000000000046");
                var guidIWebBrowser2 = Marshal.GenerateGuidForType(typeof(IWebBrowser2)); // new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
                IntPtr intPtr;
                serviceProv.QueryService(ref guidIWebBrowserApp, ref guidIWebBrowser2, out intPtr);

                browser = (IWebBrowser2)Marshal.GetObjectForIUnknown(intPtr);

                ((DWebBrowserEvents2_Event)browser).DocumentComplete +=
                    new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
            }
            else
            {
                ((DWebBrowserEvents2_Event)browser).DocumentComplete -=
                    new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
                browser = null;
            }
            return 0;
        }
        int IObjectWithSite.GetSite(ref Guid guid, out IntPtr ppvSite)
        {
            IntPtr punk = Marshal.GetIUnknownForObject(browser);
            int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
            Marshal.Release(punk);
            return hr;
        }
        #endregion
        #region Implementation of IOleCommandTarget
        int IOleCommandTarget.QueryStatus(IntPtr pguidCmdGroup, uint cCmds, ref OLECMD prgCmds, IntPtr pCmdText)
        {
            return 0;
        }
        int IOleCommandTarget.Exec(IntPtr pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                // Accessing the document from the command-bar.
                var document = browser.Document as IHTMLDocument2;
                var window = document.parentWindow;
                var result = window.execScript(@"alert('You will now be allowed to configure the text to highlight...');");

                var form = new HighlighterOptionsForm();
                form.InputText = TextToHighlight;
                if (form.ShowDialog() != DialogResult.Cancel)
                {
                    TextToHighlight = form.InputText;
                    SaveOptions();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return 0;
        }
        #endregion

        #region Registering with regasm
        public static string RegBHO = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";
        public static string RegCmd = "Software\\Microsoft\\Internet Explorer\\Extensions";

        [ComRegisterFunction]
        public static void RegisterBHO(Type type)
        {
            string guid = type.GUID.ToString("B");

            // BHO
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(RegBHO, true);
                if (registryKey == null)
                    registryKey = Registry.LocalMachine.CreateSubKey(RegBHO);
                RegistryKey key = registryKey.OpenSubKey(guid);
                if (key == null)
                    key = registryKey.CreateSubKey(guid);
                key.SetValue("Alright", 1);
                registryKey.Close();
                key.Close();
            }

            // Command
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(RegCmd, true);
                if (registryKey == null)
                    registryKey = Registry.LocalMachine.CreateSubKey(RegCmd);
                RegistryKey key = registryKey.OpenSubKey(guid);
                if (key == null)
                    key = registryKey.CreateSubKey(guid);
                key.SetValue("ButtonText", "Highlighter options");
                key.SetValue("CLSID", "{1FBA04EE-3024-11d2-8F1F-0000F87ABD16}");
                key.SetValue("ClsidExtension", guid);
                key.SetValue("Icon", "");
                key.SetValue("HotIcon", "");
                key.SetValue("Default Visible", "Yes");
                key.SetValue("MenuText", "&Highlighter options");
                key.SetValue("ToolTip", "Highlighter options");
                //key.SetValue("KeyPath", "no");
                registryKey.Close();
                key.Close();
            }
        }

        [ComUnregisterFunction]
        public static void UnregisterBHO(Type type)
        {
            string guid = type.GUID.ToString("B");
            // BHO
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(RegBHO, true);
                if (registryKey != null)
                    registryKey.DeleteSubKey(guid, false);
            }
            // Command
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(RegCmd, true);
                if (registryKey != null)
                    registryKey.DeleteSubKey(guid, false);
            }
        }
        #endregion
    }
}
using System;
using System.Runtime.InteropServices;
namespace InternetExplorerExtension
{
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]
    public interface IObjectWithSite
    {
        [PreserveSig]
        int SetSite([MarshalAs(UnmanagedType.IUnknown)]object site);
        [PreserveSig]
        int GetSite(ref Guid guid, [MarshalAs(UnmanagedType.IUnknown)]out IntPtr ppvSite);
    }


    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct OLECMDTEXT
    {
        public uint cmdtextf;
        public uint cwActual;
        public uint cwBuf;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
        public char rgwz;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct OLECMD
    {
        public uint cmdID;
        public uint cmdf;
    }

    [ComImport(), ComVisible(true),
    Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"),
    InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IOleCommandTarget
    {

        [return: MarshalAs(UnmanagedType.I4)]
        [PreserveSig]
        int QueryStatus(
            [In] IntPtr pguidCmdGroup,
            [In, MarshalAs(UnmanagedType.U4)] uint cCmds,
            [In, Out, MarshalAs(UnmanagedType.Struct)] ref OLECMD prgCmds,
            //This parameter must be IntPtr, as it can be null
            [In, Out] IntPtr pCmdText);

        [return: MarshalAs(UnmanagedType.I4)]
        [PreserveSig]
        int Exec(
            //[In] ref Guid pguidCmdGroup,
            //have to be IntPtr, since null values are unacceptable
            //and null is used as default group!
            [In] IntPtr pguidCmdGroup,
            [In, MarshalAs(UnmanagedType.U4)] uint nCmdID,
            [In, MarshalAs(UnmanagedType.U4)] uint nCmdexecopt,
            [In] IntPtr pvaIn,
            [In, Out] IntPtr pvaOut);
    }
}

and finally a form, that we will use to configure the options. In this form place a TextBox and an Ok Button. Set the DialogResult of the button to Ok. Place this code in the form code:

using System.Windows.Forms;
namespace InternetExplorerExtension
{
    public partial class HighlighterOptionsForm : Form
    {
        public HighlighterOptionsForm()
        {
            InitializeComponent();
        }

        public string InputText
        {
            get { return this.textBox1.Text; }
            set { this.textBox1.Text = value; }
        }
    }
}

In the project properties, do the following:

  • Sign the assembly with a strong-key;
C:\Program Files (x86)\Internet Explorer\iexplore.exe
http://msdn.microsoft.com/en-us/library/ms976373.aspx#bho_getintouch

Attention: as my computer is x64, there is a specific x64 inside the path of gacutil executable on my machine that may be different on yours.

64bit IE Needs 64bit-compiled and 64bit-registered BHO. Use 64bit RegAsm.exe (usually lives in C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe)

It traverses all DOM tree, replacing the text, configured using the button, by itself with a yellow background. If you click on the yellowed texts, it calls a javascript function that was inserted on the page dynamically. The default word is 'browser', so that it matches a lot of them! EDIT: after changing the string to be highlighted, you must click the URL box and press Enter... F5 will not work, I think that it is because F5 is considered as 'navigation', and it would require to listen to navigate event (maybe). I'll try to fix that later.

Now, it is time to go. I am very tired. Feel free to ask questions... may be I will not be abled to answer since I am going on a trip... in 3 days I'm back, but I'll try to come here in the meantime.

I tried to do this on IE9 and: 1. If your project path has spaces: instead of $(TargetDir)$(TargetFileName) use "$(TargetDir)$(TargetFileName)" 2. If you use Visual Studio 2010 Express you probably (I do) don't see the Start External Program option in Debug tab - I simply run IE and navigate to the provided URL 3. It seems not to work on IE9 - I can open the form (Highlighter options) but I don't know how to make it highlight the text

For the Interop.SHDocVw reference - instead you should add a COM reference to "Microsoft Internet Controls" and then "using SHDocVw;"

"IE10 on x64 Windows 8 will not load your add-on when starting unless you will build with "Any CPU" architecture and register using both 32 and 64 bit RegAsm.exe." was an edit by someone that got rejected.

c# - How to get started with developing Internet Explorer extensions? ...

c# c++ internet-explorer atl browser-extension
Rectangle 27 6

If you are working on a Windows-generated file

Ctrl+M minimizes my window, but Ctrl+Enter actually inserts a ^M character. I also had to be sure not to lift off the Ctrl key between presses.

So the solution for me was:

:%s/<Ctrl-V><Ctrl-Enter>/\r/g
<Ctrl-V><Ctrl-Enter>

press and hold

and then release

The above solution will add an additional line between existing lines, because there is already an invisible \r after the ^M.

To prevent this, you want to delete the ^M characters without replacing them.

:%s/<Ctrl-V><Ctrl-Enter>//g

Where % means "in this buffer," s means "substitute," / means "(find) the following pattern," <Ctrl-V><Ctrl-Enter> refers to the keys to press to get the ^M character (see above), // means "with nothing" (or, "with the pattern between these two slashes, which is empty"), and g is a flag meaning "globally," as opposed to the first occurrence in a line.

line breaks - How to convert the ^M linebreak to 'normal' linebreak in...

vim line-breaks
Rectangle 27 6

If you are working on a Windows-generated file

Ctrl+M minimizes my window, but Ctrl+Enter actually inserts a ^M character. I also had to be sure not to lift off the Ctrl key between presses.

So the solution for me was:

:%s/<Ctrl-V><Ctrl-Enter>/\r/g
<Ctrl-V><Ctrl-Enter>

press and hold

and then release

The above solution will add an additional line between existing lines, because there is already an invisible \r after the ^M.

To prevent this, you want to delete the ^M characters without replacing them.

:%s/<Ctrl-V><Ctrl-Enter>//g

Where % means "in this buffer," s means "substitute," / means "(find) the following pattern," <Ctrl-V><Ctrl-Enter> refers to the keys to press to get the ^M character (see above), // means "with nothing" (or, "with the pattern between these two slashes, which is empty"), and g is a flag meaning "globally," as opposed to the first occurrence in a line.

line breaks - How to convert the ^M linebreak to 'normal' linebreak in...

vim line-breaks
Rectangle 27 12

Original CSS not working

The CSS I pasted in here was wrong, I was editing the wrong file DOH!

background-image: linear-gradient(top, rgba(255,255,255,0) 0%, #fff 5%, #fff 100%);
background-image: -o-linear-gradient(top, rgba(255,255,255,0) 0%, #fff 5%, #fff 100%);
background-image: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, #fff 5%, #fff 100%);
background-image: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%, #fff 5%, #fff 100%);
background-image: -ms-linear-gradient(top, rgba(255,255,255,0) 0%, #fff 5%, #fff 100%);

Problem being transparent isn't a colour, it is black with 0 alpha, setting to specifically white with 0 alpha fixes the issue. (thanks @carisenda)

This still points on inconsistencies with how browser vendors are dealing with alpha transparency in CSS3 gradients.

CSS3 gradient rendering issues from transparent to white - Stack Overf...

css3 gradients
Rectangle 27 4

Working with returned values:

The traditional way to solve this is to add the promises to an array, then evaluate them all together using $.when.apply

As you want to keep the values, you can then access them using the arguments array:

var promise = [];
for (var i = 0; i < 6; i++){
    promise.push(delay(6-i, $('#' + i)));
}
$.when.apply($, promise).done(function(){
    $('body').append("All done!");
    for (var i = 0; i < arguments.length; i++){
        $('body').append(arguments[i]).append("<br/>");
    }
});

The following example uses a simple function that returns a promise, using a timer, to simulate ajax calls. It clearly shows the suggestion working even though the promises complete in "random" order (just to demonstrate):

  • The values are returned in the order the calls were made, not the completion order.

Little trick I found: You can chain promises in parallel with $.when without having to use an array of promises:

var promise;   // Undefined also means a resolved promise to $.when
for(...){//we don't know the number of ajax calls
   promise = $.when(promise, $.ajax({...}));
}
promise.done(function(){
   alert("All done");
});
  • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
  • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested recursively inside additional objects). If you do not require the parameters, it is short and simple.

You will note in the following fiddle that the results are nested and in the reverse order you want them. Again this technique is only useful if you do not want the results of the promises (which is quite often for parallel operations).

Summary: The $.when technique is only useful if you do not care about the result values.

So your solution is to run the ajax calls sequentially?

Oh, I misread the $.when as $.then - my mistake (thought $.then was some more jQuery bastardisation of the promise spec) - the question asks how can I use the results of ajax calls - seems your solution throws all the results away

@JaromandaX: Have added answer that includes processing a variable number of results.

arr= arguments[0];
arr= arguments;
promise = $.when(promise, undefined);

javascript - How can I use the results of ajax calls, made inside a lo...

javascript jquery ajax promise deferred
Rectangle 27 4

Working with returned values:

The traditional way to solve this is to add the promises to an array, then evaluate them all together using $.when.apply

As you want to keep the values, you can then access them using the arguments array:

var promise = [];
for (var i = 0; i < 6; i++){
    promise.push(delay(6-i, $('#' + i)));
}
$.when.apply($, promise).done(function(){
    $('body').append("All done!");
    for (var i = 0; i < arguments.length; i++){
        $('body').append(arguments[i]).append("<br/>");
    }
});

The following example uses a simple function that returns a promise, using a timer, to simulate ajax calls. It clearly shows the suggestion working even though the promises complete in "random" order (just to demonstrate):

  • The values are returned in the order the calls were made, not the completion order.

Little trick I found: You can chain promises in parallel with $.when without having to use an array of promises:

var promise;   // Undefined also means a resolved promise to $.when
for(...){//we don't know the number of ajax calls
   promise = $.when(promise, $.ajax({...}));
}
promise.done(function(){
   alert("All done");
});
  • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
  • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested recursively inside additional objects). If you do not require the parameters, it is short and simple.

You will note in the following fiddle that the results are nested and in the reverse order you want them. Again this technique is only useful if you do not want the results of the promises (which is quite often for parallel operations).

Summary: The $.when technique is only useful if you do not care about the result values.

So your solution is to run the ajax calls sequentially?

Oh, I misread the $.when as $.then - my mistake (thought $.then was some more jQuery bastardisation of the promise spec) - the question asks how can I use the results of ajax calls - seems your solution throws all the results away

@JaromandaX: Have added answer that includes processing a variable number of results.

arr= arguments[0];
arr= arguments;
promise = $.when(promise, undefined);

javascript - How can I use the results of ajax calls, made inside a lo...

javascript jquery ajax promise deferred
Rectangle 27 10

Tested and working!

$(function() {

    var extraDays = 0;
    var combobox = $('#select1');
    var txtStartDate = $('#startdate');
    var txtEndDate = $('#enddate');
    var inputs = txtStartDate.add(txtEndDate);

    combobox.on('change', function() {

        inputs.val('');

        var val = $(this).val();
        if(val == 1) extraDays = 5;
        if(val == 2) extraDays = 7;

        txtStartDate.datepicker({
            showButtonPanel: true,
            closeText: 'Close',
            dateFormat: 'mm/dd/yy',
            beforeShowDay: function(date) {

                /* Check for the first day */
                if (date.getDate() == 1) { return [true, '']; } 
                else { return [false, '', 'Unavailable']; }
            },
            onSelect: function(selected) {

                /* Add extra days to the date according to 'combobox' selection */
                var endDate = new Date(selected);
                endDate.setDate(endDate.getDate() + extraDays);

                var m = pad(endDate.getMonth() + 1, 2);
                var d = pad(endDate.getDate(), 2);
                var y = endDate.getFullYear();
                var endDateStr = [m, d, y].join('/');

                txtEndDate.val(endDateStr);
            }
        });

    });

});

/* This function just adds a zero to get this format: "01, 02, etc" in a number less than 10 */
function pad(number, length) {
    var str = '' + number;
    while (str.length < length) { str = '0' + str; }
    return str;
};

Jquery datepicker make only 1 day selectable and copy date +x days in ...

jquery jquery-ui datepicker
Rectangle 27 10

Tested and working!

$(function() {

    var extraDays = 0;
    var combobox = $('#select1');
    var txtStartDate = $('#startdate');
    var txtEndDate = $('#enddate');
    var inputs = txtStartDate.add(txtEndDate);

    combobox.on('change', function() {

        inputs.val('');

        var val = $(this).val();
        if(val == 1) extraDays = 5;
        if(val == 2) extraDays = 7;

        txtStartDate.datepicker({
            showButtonPanel: true,
            closeText: 'Close',
            dateFormat: 'mm/dd/yy',
            beforeShowDay: function(date) {

                /* Check for the first day */
                if (date.getDate() == 1) { return [true, '']; } 
                else { return [false, '', 'Unavailable']; }
            },
            onSelect: function(selected) {

                /* Add extra days to the date according to 'combobox' selection */
                var endDate = new Date(selected);
                endDate.setDate(endDate.getDate() + extraDays);

                var m = pad(endDate.getMonth() + 1, 2);
                var d = pad(endDate.getDate(), 2);
                var y = endDate.getFullYear();
                var endDateStr = [m, d, y].join('/');

                txtEndDate.val(endDateStr);
            }
        });

    });

});

/* This function just adds a zero to get this format: "01, 02, etc" in a number less than 10 */
function pad(number, length) {
    var str = '' + number;
    while (str.length < length) { str = '0' + str; }
    return str;
};

Jquery datepicker make only 1 day selectable and copy date +x days in ...

jquery jquery-ui datepicker
Rectangle 27 14

See a working example http://jsbin.com/owuyiq/

just change the order of your code, i.e.,

ctx.rotate(...);

ctx.drawImage(...);
$(function () {
    var canvas = document.getElementById('logobg1');
    var ctx = canvas.getContext('2d');
    var img = new Image();

    var ang = 0; //angle
    var fps = 1000 / 25; //number of frames per sec
    img.onload = function () { //on image load do the following stuff
        canvas.width = this.width << 1; //double the canvas width
        canvas.height = this.height << 1; //double the canvas height
        var cache = this; //cache the local copy of image element for future reference
        setInterval(function () {
            ctx.save(); //saves the state of canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
            ctx.translate(cache.width, cache.height); //let's translate
            ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image 
            ctx.drawImage(img, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image ;)
            ctx.restore(); //restore the state of canvas
        }, fps);
    };

    img.src = 'http://i.stack.imgur.com/Z97wf.jpg?s=128'; //img
});

you need to vary the rotation angle.., i.e, ctx.rotate(Math.PI /180 * angle). for every loop(setInterval) increment the angle value...

ok it rotates but it doesn't rotate around the center rather than the top left.

You need to add two additional parameters to rotate which are the X and Y of the coordinates to rotate around on. In this case you will have to use the center X and center Y coordinates of your object.

Modified the example above to work when your canvas has a fixed size (not based on your image size): jsbin.com/suwovibove/. I will add it as answer in case that link vanishes.

javascript - Rotate an image around its center in canvas - Stack Overf...

javascript image animation canvas rotation
Rectangle 27 10

PowerShell ignores the working directory by design

For this answer, assume that the directory C:\Users\iain.CORP\SqlcmdQuestion exists and that executing dir at that location produces the following output, as implied by the question:

Directory: C:\Users\iain.Corp\SqlcmdQuestion


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        26/09/2012     15:30         27 ExampleQuery.sql
-a---        26/09/2012     15:30         61 ExecQuery.cmd
-a---        26/09/2012     15:34        172 ExecQuery.ps1

My question has a false premise:

How do I make Invoke-Sqlcmd use the current working directory instead of the default working directory?

The cmdlet does use the current working directory. The problem is that I didn't change the working directory at all in my PowerShell session.

In PowerShell, cd is an alias for the Set-Location cmdlet. You can prove this using the Get-Alias cmdlet:

Get-Alias cd
CommandType     Name                                                Definition
-----------     ----                                                ----------
Alias           cd                                                  Set-Location

[A]lthough PowerShell's location is analogous to the working directory, the location is not the same thing as the working directory. In fact, PowerShell doesn't touch the working directory.

Set-Location does not set the working directory. It sets the working location, which is a similar but distinct concept in PowerShell.

You can prove this by inspecting the working directory using the .NET property Environment.CurrentDirectory after setting the working location using cd as in the question:

cd C:\Users\iain.CORP\SqlcmdQuestion
Environment::CurrentDirectory
Z:\

I would guess this design decision was made to be consistent. The working directory would be undefined when, for example, the working location were set to a registry hive.

Invoke-Sqlcmd violates PowerShell's general design principle to use the working location rather than the working directory. Most cmdlets use the working location to resolve relative paths, but Invoke-Sqlcmd is an exception.

Using the ILSpy disassembler and a little intuition to inspect the containing assembly Microsoft.SqlServer.Management.PSSnapins, I believe I have found the reason for the error.

I believe that the cmdlet's parameter -InputFile is implemented by the method IncludeFileName. ILSpy's disassembly of the method looks like this:

// Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor
public ParserAction IncludeFileName(string fileName, ref IBatchSource pIBatchSource)
{
    if (!File.Exists(fileName))
    {
        ExecutionProcessor.sqlCmdCmdLet.TerminateCmdLet(new FileNotFoundException(PowerShellStrings.CannotFindPath(fileName), fileName), "ExecutionFailureException", ErrorCategory.ParserError);
        return ParserAction.Abort;
    }
    BatchSourceFile batchSourceFile = new BatchSourceFile(fileName);
    pIBatchSource = batchSourceFile;
    return ParserAction.Continue;
}

Invoke-Sqlcmd uses the .NET method File.Exists to check whether the specified input file exists. The method's documentation remarks that relative paths are resolved using the working directory:

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

This suggests that File.Exists would return false in this case, which would cause the error message seen in the question. You can prove this by executing the method directly from the prompt:

cd C:\Users\iain.CORP\SqlcmdQuestion
[IO.File]::Exists('ExecQuery.sql')
False

The method returns false, so the cmdlet terminates with a 'file not found' error.

There are two workarounds for Invoke-Sqlcmd using the working directory instead of the working location to resolve relative paths:

  • Always use an absolute path as the value of the -InputFile parameter. CandiedCode's answer shows how to do this.
  • Set the working directory and use a relative path.

I solved the problem without side-effects by modifying ExecQuery.ps1 like this:

Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100

$RestoreValue = [Environment]::CurrentDirectory
[Environment]::CurrentDirectory = Get-Location
Invoke-Sqlcmd -InputFile 'ExampleQuery.sql' -Variable "ComputerName = $Env:COMPUTERNAME"
[Environment]::CurrentDirectory = $RestoreValue
Column1
-------
SKYPC0083

The new script sets the working directory to match the working location before executing Invoke-Sqlcmd. To avoid unintended side-effects of changing the working directory, the scrtipt restores the working directory value before completing.

Setting the current directory is described in this Channel 9 thread. The example there uses the Directory.SetCurrentDirectory method, but I find it simpler to set the property directly.

+1 for a beautifully crafted and comprehensive answer!

sql server - How to convert this sqlcmd script to an Invoke-Sqlcmd scr...

sql-server tsql powershell cmd sqlcmd
Rectangle 27 37

Note : This has been tested and working 100% percent

override func viewWillDisappear(animated: Bool){
    super.viewWillDisappear(animated)

    if self.isBeingDismissed()  //presented view controller
    {
        // remove observer here
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

In iOS 6.0 > version , its better to remove observer in viewWillDisappear as viewDidUnload method is deprecated.

[[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];

There is many times its better to remove observer when the view has been removed from the navigation stack or hierarchy.

- (void)viewWillDisappear:(BOOL)animated{
 if (![[self.navigationController viewControllers] containsObject: self]) //any other hierarchy compare if it contains self or not
    {
        // the view has been removed from the navigation stack or hierarchy, back is probably the cause
        // this will be slow with a large stack however.

        [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    if ([self isBeingDismissed] == YES) ///presented view controller
    {
        // remove observer here
        [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
    }
}

Except a controller may still want notifications when its view is not showing (e.g. to reload a tableView).

@wcochran automatically reload/refresh in viewWillAppear:

@Prince can you explain why viewWillDisapper better then dealloc? so we have add observer to self, so when the self will be dropped from memory it will call dealloc and then all observers will be deleted, is this not a good logic.

removeObserver:self
UIViewController

Putting the removeObserver calls in viewWillDisappear as indicated is definitely the right way to go if the controller is being presented via pushViewController. If you put them in dealloc instead then dealloc will never be called -- in my experience at least...

ios - Objective C: Where to remove observer for NSNotification? - Stac...

objective-c ios nsnotifications
Rectangle 27 1

Here is another approach which is working for me.

My scenario: I want to hide the collapsible when I click anywhere outside of a form which contains a dropdownlist.

$(document).ready(function(){
      //check if collapsible is shown
      $(".collapse").on('shown.bs.collapse', function(){
        //then check if there was a click
        $(document).click(function(event) {
          //exclude the click was on the form 
          if (!$(event.target).hasClass("input-default")) {
              //then hide it
              $(".collapse").collapse('hide');
          }
        });
      });
  });

javascript - How to hide my collapse bootstrap 3 navbar with click on ...

javascript jquery html css twitter-bootstrap
Rectangle 27 3

Note:- You can only share text or image, both sharing together in what...

/*
    //Share text
    NSString *textToShare = @"Enter your text to be shared";
    NSArray *objectsToShare = @[textToShare];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
     */

    //Share Image
    UIImage * image = [UIImage imageNamed:@"images"];
    NSArray *objectsToShare = @[image];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];

iphone - Share image/text through WhatsApp in an iOS app - Stack Overf...

iphone ios