问:
Jquery acting different on mobile compared to PC, with the same code
The problem is in the website I am developing

http://balticpremier.sem.lv/en/

(https://www.virustotal.com/#/url/e2f05f0f4d6fde378f3f784c8c331849caef1e556fb1b173e4ac2f5ba521405c/detection)

Scroll to the bottom and see the Our delivered products section. It is supposed to expand on hover and click, which it does without problem on PC. However, when it is visited through phone, on click, it does the fade effect and doesn't have the correct logic.

This is the only JS that affects this part is here:

```<code>$('.deliveredCategory').on('click mouseenter mouseleave', function () {
    $(this).find(".expandableClient").toggle();
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
    $(this).find('.dotHide').toggle();
});
</code>```

Help appreciated!!

EDIT: Forgot to say that fade effect is not a part of the code, and only happens on mobile. Is this how toggle(); is interpreted on mobile? Either way, on mobile I also can't close it after it has been expanded. Really weird.

答:
Apparently, the site I am working on has Cloudflare connected and it cached a part of my JS code before, which explains the problems I am having. I contacted the host manager, they flushed the cache and it works again.

Thank you all for answers.

Body:
The problem is in the website I am developing

http://balticpremier.sem.lv/en/

(https://www.virustotal.com/#/url/e2f05f0f4d6fde378f3f784c8c331849caef1e556fb1b173e4ac2f5ba521405c/detection)

Scroll to the bottom and see the Our delivered products section. It is supposed to expand on hover and click, which it does without problem on PC. However, when it is visited through phone, on click, it does the fade effect and doesn't have the correct logic.

This is the only JS that affects this part is here:

$('.deliveredCategory').on('click mouseenter mouseleave', function () {
    $(this).find(".expandableClient").toggle();
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
    $(this).find('.dotHide').toggle();
});

Help appreciated!!

EDIT: Forgot to say that fade effect is not a part of the code, and only happens on mobile. Is this how toggle(); is interpreted on mobile? Either way, on mobile I also can't close it after it has been expanded. Really weird.


来源: stackexchange

问:
How to check if a generic parameter is not null without boxing
I want to write a method that accepts a single IBar and call its Baz method.

This throws when obj is null:

```<code>void Foo<T>(T obj)
    where T : IBar
    => obj.Baz();
</code>```

This boxes obj when it is a value type:

```<code>void Foo<T>(T obj)
    where T : IBar
    => obj?.Baz();
</code>```

This doesn't call Baz if obj is zero:

```<code>void Foo<T>(T obj)
    where T : IBar
{
    if (!EqualityComparer<T>.Default.Equals(obj, default(T)))
        obj.Baz();
}
</code>```

And here, Foo(new Bar()) always picks the generic method no matter if Bar is a class or struct:

```<code>void Foo<T>(T obj)
    where T : struct, IBar
    => obj.Baz();

void Foo(IBar obj)
    => obj?.Baz();
</code>```

This makes my eyes bleed:

```<code>void FooVal<T>(T obj)
    where T : struct, IBar
    => obj.Baz();

void FooRef(IBar obj)
    => obj?.Baz();
</code>```

So is there a best practice for this? I'm open to all suggestions.

Edit:

The question is marked as duplicate with Generic constraints, where T : struct and where T : class and with the old title, it was. So I've updated the title to convey my problem better. What I'm asking is that how can I call a generic method and use the argument only if it is not null, without boxing.

Some workarounds explained for the linked question may be used to answer this one but I still believe this is a fundamentally different question.

答:
I came up with this helper:

```<code>public static class Null
{
    public static bool IsNull<T>(T obj) => !Data<T>.HasValue(obj);

    private static class Data<T>
    {
        public static readonly Func<T, bool> HasValue = InitHasValue();

        private static Func<T, bool> InitHasValue()
        {
            var type = typeof(T);
            if (!type.IsValueType)
                return obj => obj != null;

            if (type.IsGenericType &&
                type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                var value = Expression.Parameter(type, "value");
                var getter = type.GetProperty("HasValue").GetMethod;
                var call = Expression.Call(value, getter);
                var lambda = Expression.Lambda<Func<T, bool>>(call, value);
                return lambda.Compile();
            }

            return obj => true;
        }
    }
}
</code>```

So I can do this:

```<code>void Foo<T>(T obj)
    where T : IBar
{
    if (!Null.IsNull(obj)) // Does not box.
        obj.Baz();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to write a method that accepts a single IBar and call its Baz method.

This throws when obj is null:

void Foo<T>(T obj)
    where T : IBar
    => obj.Baz();

This boxes obj when it is a value type:

void Foo<T>(T obj)
    where T : IBar
    => obj?.Baz();

This doesn't call Baz if obj is zero:

void Foo<T>(T obj)
    where T : IBar
{
    if (!EqualityComparer<T>.Default.Equals(obj, default(T)))
        obj.Baz();
}

And here, Foo(new Bar()) always picks the generic method no matter if Bar is a class or struct:

void Foo<T>(T obj)
    where T : struct, IBar
    => obj.Baz();

void Foo(IBar obj)
    => obj?.Baz();

This makes my eyes bleed:

void FooVal<T>(T obj)
    where T : struct, IBar
    => obj.Baz();

void FooRef(IBar obj)
    => obj?.Baz();

So is there a best practice for this? I'm open to all suggestions.

Edit:

The question is marked as duplicate with Generic constraints, where T : struct and where T : class and with the old title, it was. So I've updated the title to convey my problem better. What I'm asking is that how can I call a generic method and use the argument only if it is not null, without boxing.

Some workarounds explained for the linked question may be used to answer this one but I still believe this is a fundamentally different question.

Body:
I came up with this helper:

public static class Null
{
    public static bool IsNull<T>(T obj) => !Data<T>.HasValue(obj);

    private static class Data<T>
    {
        public static readonly Func<T, bool> HasValue = InitHasValue();

        private static Func<T, bool> InitHasValue()
        {
            var type = typeof(T);
            if (!type.IsValueType)
                return obj => obj != null;

            if (type.IsGenericType &&
                type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                var value = Expression.Parameter(type, "value");
                var getter = type.GetProperty("HasValue").GetMethod;
                var call = Expression.Call(value, getter);
                var lambda = Expression.Lambda<Func<T, bool>>(call, value);
                return lambda.Compile();
            }

            return obj => true;
        }
    }
}

So I can do this:

void Foo<T>(T obj)
    where T : IBar
{
    if (!Null.IsNull(obj)) // Does not box.
        obj.Baz();
}


问:
Is it possible to rewrite strings in unknown json structure?
I have a requirement to parse arbitrary json, encode/rewrite any string key or value longer than 85 characters(think of a kind of short URL service) and marshal it back to raw json.
 e.g. a document like this {"Name": "Ed", "Text": "long characters....85 chars"} should become something like this {"Name": "Ed", "Text": "short://ID=3403"}. This example is simple but I have to deal with complex structures with nested objects and arrays and basically unknown  structures.

My question is: Is it possible to do this using a known library or even the standard encoding/json package?
 What I actually need is the equivalent of an implementation of Marshaler interface on type  string but we know that's not possible so I'm wondering what other options I have (beside forking the standard encoding/json package)

答:
Here is a an approach (tested) which uses json.Decoder's Token() method, and avoids deserializing the whole data structure into memory. It's mostly done for fun and for the sake illustrating how you can use that method, but it could possibly be of some use if your JSON documents are very large and you would like to avoid the memory overhead.

```<code>// For example
r, w := os.Stdin, os.Stdout

dec := json.NewDecoder(r)
// Avoids any round-trip loss by leaving numbers un-parsed
dec.UseNumber()

// Current state (in an object or in an array; following the open
// delim, or a key, or a value). The decoder has its own stack pretty
// like this one, but it's private, so keep our own.
const (
    jsonArrayStart = iota
    jsonArrayVal
    jsonObjectStart
    jsonObjectKey
    jsonObjectVal
)
stack := []byte{}

for {
    t, err := dec.Token()
    if err == io.EOF {
        break
    } else if err != nil {
        log.Fatal(err)
    }

    switch val := t.(type) {
    case json.Delim:
        // Copy delimiters out, and push/pop the state stack as appropriate
        w.WriteString(string([]rune{rune(val)}))
        switch val {
        case '[':
            stack = append(stack, jsonArrayStart)
        case '{':
            stack = append(stack, jsonObjectStart)
        case ']', '}':
            stack = stack[:len(stack)-1]
        }
        // The rest of the cases just copy values out
    case nil:
        w.WriteString("null")
    case json.Number:
        w.WriteString(string(val))
    case bool:
        if val {
            w.WriteString("true")
        } else {
            w.WriteString("false")
        }
    case string:
        // Modify strings if called for (shortenString needs to be provided)
        if len(val) >= 85 {
            val = shortenString(val)
        }
        encoded, err := json.Marshal(val)
        if err != nil {
            log.Fatal(err)
        }
        w.Write(encoded)
    }

    if dec.More() {
        // If there's more in the current array/object, write a colon or comma
        // (if we just wrote a key/value), and set the next state.
        // Arrays start with a value, and follow with more values.
        // Objects start with a key and alternate between key and value.
        switch stack[len(stack)-1] {
        case jsonArrayStart:
            stack[len(stack)-1] = jsonArrayVal
        case jsonArrayVal:
            w.WriteString(",")
            // State remains jsonArrayVal
        case jsonObjectStart:
            stack[len(stack)-1] = jsonObjectKey
        case jsonObjectKey:
            w.WriteString(":")
            stack[len(stack)-1] = jsonObjectVal
        case jsonObjectVal:
            w.WriteString(",")
            stack[len(stack)-1] = jsonObjectKey
        }
    } else {
        if len(stack) == 0 {
            // End after the first complete value (array/object) in the stream
            break
        }
        if stack[len(stack)-1] == jsonObjectKey {
            // Should never happen
            log.Fatal("Object key without a value?")
        }
    }
}
</code>```

Body:
Here is a an approach (tested) which uses json.Decoder's Token() method, and avoids deserializing the whole data structure into memory. It's mostly done for fun and for the sake illustrating how you can use that method, but it could possibly be of some use if your JSON documents are very large and you would like to avoid the memory overhead.

// For example
r, w := os.Stdin, os.Stdout

dec := json.NewDecoder(r)
// Avoids any round-trip loss by leaving numbers un-parsed
dec.UseNumber()

// Current state (in an object or in an array; following the open
// delim, or a key, or a value). The decoder has its own stack pretty
// like this one, but it's private, so keep our own.
const (
    jsonArrayStart = iota
    jsonArrayVal
    jsonObjectStart
    jsonObjectKey
    jsonObjectVal
)
stack := []byte{}

for {
    t, err := dec.Token()
    if err == io.EOF {
        break
    } else if err != nil {
        log.Fatal(err)
    }

    switch val := t.(type) {
    case json.Delim:
        // Copy delimiters out, and push/pop the state stack as appropriate
        w.WriteString(string([]rune{rune(val)}))
        switch val {
        case '[':
            stack = append(stack, jsonArrayStart)
        case '{':
            stack = append(stack, jsonObjectStart)
        case ']', '}':
            stack = stack[:len(stack)-1]
        }
        // The rest of the cases just copy values out
    case nil:
        w.WriteString("null")
    case json.Number:
        w.WriteString(string(val))
    case bool:
        if val {
            w.WriteString("true")
        } else {
            w.WriteString("false")
        }
    case string:
        // Modify strings if called for (shortenString needs to be provided)
        if len(val) >= 85 {
            val = shortenString(val)
        }
        encoded, err := json.Marshal(val)
        if err != nil {
            log.Fatal(err)
        }
        w.Write(encoded)
    }

    if dec.More() {
        // If there's more in the current array/object, write a colon or comma
        // (if we just wrote a key/value), and set the next state.
        // Arrays start with a value, and follow with more values.
        // Objects start with a key and alternate between key and value.
        switch stack[len(stack)-1] {
        case jsonArrayStart:
            stack[len(stack)-1] = jsonArrayVal
        case jsonArrayVal:
            w.WriteString(",")
            // State remains jsonArrayVal
        case jsonObjectStart:
            stack[len(stack)-1] = jsonObjectKey
        case jsonObjectKey:
            w.WriteString(":")
            stack[len(stack)-1] = jsonObjectVal
        case jsonObjectVal:
            w.WriteString(",")
            stack[len(stack)-1] = jsonObjectKey
        }
    } else {
        if len(stack) == 0 {
            // End after the first complete value (array/object) in the stream
            break
        }
        if stack[len(stack)-1] == jsonObjectKey {
            // Should never happen
            log.Fatal("Object key without a value?")
        }
    }
}


问:
Pasting xml to console
I  need to get data SHILS_V from XML file. I read .xml

XML code for example:

```<code><SVED_PR_GS>
          <ZGLV>
            <VERSION>99</VERSION>
            <DATA>9999</DATA>
            <FILENAME>1234</FILENAME>
            <FIRSTNAME>1234</FIRSTNAME>
          </ZGLV>
          <SVD>
            <CODE></CODE>
            <YEAR></YEAR>
            <MONTH></MONTH>
          </SVD>
          <SV_PR_GS>
            <OBSV>
              <N_ZAP>1</N_ZAP>
              <MO_SV_V>12345</MO_SV_V>
              <SNILS_V>123456789</SNILS_V>
            </OBSV>
          </SV_PR_GS>
</SVED_PR_GS>
</code>```

My code to read xml:

```<code>XmlDocument xml = new XmlDocument();
xml.Load(filename);
Console.WriteLine("this");
XmlNodeList nodes = xml.GetElementsByTagName("SVED_PR_GS/SV_PR_GS");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    XmlNode snils_v = n["OBSV/SNILS_V"];
    Console.WriteLine("Snils V: " + snils_v);
}
</code>```

Where is the problem?
How to get the information from SNILS_V?

答:
GetElementsByTagName expects a tagname, not an XPath expression, "SV_PR_GS" will work there. And the same goes for the indexer of your XmlNode instance called n, this XPath will not work n["OBSV/SNILS_V"], use a tagname there as well but you have to handle the extra OBSV child there.

Here is your adapted code that produces output for me:

```<code>XmlNodeList nodes = xml.GetElementsByTagName("SV_PR_GS");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    // first get the OBSV element
    XmlNode obsv = n["OBSV"];
    // now we can reach the other childs
    XmlNode snils_v = obsv["SNILS_V"];
    // Value will be null for XmlElement types, use InnerText instead
    Console.WriteLine("Snils V: {0}" , snils_v.InnerText);
}
</code>```

Notice that the Value property will return null for XmlNode that are of type XmlElement. In the XmlNode.Value documentation it is stated:

null. You can use the XmlElement.InnerText or XmlElement.InnerXml properties to access the value of the element node.

As your SNILS_V element seem to contain just a value InnerText is appropriate here.

Title: Pasting xml to console

Body:
I  need to get data SHILS_V from XML file. I read .xml

XML code for example:

<SVED_PR_GS>
          <ZGLV>
            <VERSION>99</VERSION>
            <DATA>9999</DATA>
            <FILENAME>1234</FILENAME>
            <FIRSTNAME>1234</FIRSTNAME>
          </ZGLV>
          <SVD>

            <YEAR></YEAR>
            <MONTH></MONTH>
          </SVD>
          <SV_PR_GS>
            <OBSV>
              <N_ZAP>1</N_ZAP>
              <MO_SV_V>12345</MO_SV_V>
              <SNILS_V>123456789</SNILS_V>
            </OBSV>
          </SV_PR_GS>
</SVED_PR_GS>

My code to read xml:

XmlDocument xml = new XmlDocument();
xml.Load(filename);
Console.WriteLine("this");
XmlNodeList nodes = xml.GetElementsByTagName("SVED_PR_GS/SV_PR_GS");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    XmlNode snils_v = n["OBSV/SNILS_V"];
    Console.WriteLine("Snils V: " + snils_v);
}

Where is the problem?
How to get the information from SNILS_V?

Body:
GetElementsByTagName expects a tagname, not an XPath expression, "SV_PR_GS" will work there. And the same goes for the indexer of your XmlNode instance called n, this XPath will not work n["OBSV/SNILS_V"], use a tagname there as well but you have to handle the extra OBSV child there.

Here is your adapted code that produces output for me:

XmlNodeList nodes = xml.GetElementsByTagName("SV_PR_GS");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    // first get the OBSV element
    XmlNode obsv = n["OBSV"];
    // now we can reach the other childs
    XmlNode snils_v = obsv["SNILS_V"];
    // Value will be null for XmlElement types, use InnerText instead
    Console.WriteLine("Snils V: {0}" , snils_v.InnerText);
}

Notice that the Value property will return null for XmlNode that are of type XmlElement. In the XmlNode.Value documentation it is stated:

null. You can use the XmlElement.InnerText or XmlElement.InnerXml properties to access the value of the element node.

As your SNILS_V element seem to contain just a value InnerText is appropriate here.


答:
You should be able to get the value as follows:</p>

```<code>XmlDocument xml = new XmlDocument();
xml.Load(filename);
Console.WriteLine("this");
XmlNodeList nodes = xml.GetElementsByTagName("OBSV");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    XmlNode snils_v = n.SelectSingleNode("SNILS_V");
    Console.WriteLine("Snils V: " + snils_v.InnerText);
}
</code>```

Title: Pasting xml to console

Body:
You should be able to get the value as follows:

XmlDocument xml = new XmlDocument();
xml.Load(filename);
Console.WriteLine("this");
XmlNodeList nodes = xml.GetElementsByTagName("OBSV");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    XmlNode snils_v = n.SelectSingleNode("SNILS_V");
    Console.WriteLine("Snils V: " + snils_v.InnerText);
}


问:
devtools::install_github fails with CA cert error
When I try to call install_github, I get the following error (not just for this package, but for all github packages):

```<code>> install_github('ramnathv/slidify')
Downloading github repo ramnathv/slidify@master
Error in curl::curl_fetch_memory(url, handle = handle) :
Problem with the SSL CA cert (path? access rights?)
</code>```

But if I use RCurl directly to access github with ssl, I don't get any problem:

```<code>>  x <- getBinaryURL(
          url='https://github.com/ramnathv/slidify/archive/master.zip',
          followlocation=1L
          )
</code>```

works with no errors, so RCurl can verify the SSL certificate properly and download the archive file.

```<code>> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 8 (jessie)

locale:
 [1] LC_CTYPE=en_US.utf8       LC_NUMERIC=C
 [3] LC_TIME=en_US.utf8        LC_COLLATE=en_US.utf8
 [5] LC_MONETARY=en_US.utf8    LC_MESSAGES=en_US.utf8
 [7] LC_PAPER=en_US.utf8       LC_NAME=C
 [9] LC_ADDRESS=C              LC_TELEPHONE=C
 [11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.95-4.7 bitops_1.0-6   devtools_1.8.0

loaded via a namespace (and not attached):
 [1] httr_1.0.0      R6_2.1.0        magrittr_1.5    rversions_1.0.2
 [5] tools_3.2.1     curl_0.9.1      Rcpp_0.12.0     memoise_0.2.1
 [9] xml2_0.1.1      stringi_0.5-5   git2r_0.10.1    stringr_1.0.0
 [13] digest_0.6.8
</code>```

And

```<code>> curlVersion()

$age
[1] 3

$version
[1] "7.38.0"

$vesion_num
[1] 468480

$host
[1] "x86_64-pc-linux-gnu"

$features
   ipv6         ssl        libz        ntlm   asynchdns      spnego
      1           4           8          16         128         256
   largefile         idn tlsauth_srp     ntlm_wb
    512        1024       16384       32768

$ssl_version
[1] "OpenSSL/1.0.1k"

$ssl_version_num
[1] 0

$libz_version
[1] "1.2.8"

$protocols
[1] "dict"   "file"   "ftp"    "ftps"   "gopher" "http"   "https"  "imap"
[9] "imaps"  "ldap"   "ldaps"  "pop3"   "pop3s"  "rtmp"   "rtsp"   "scp"
[17] "sftp"   "smtp"   "smtps"  "telnet" "tftp"

$ares
[1] ""

$ares_num
[1] 0

$libidn
[1] "1.29"
</code>```

If I use httr::set_config( httr::config( ssl_verifypeer = 0L ) ) then I can successfully run install_github but I would prefer to actually check ssl certificates.

Can anyone offer a solution?

答: Make sure, the current version of R has the package curl installed: install.packages('curl')

Body:
When I try to call install_github, I get the following error (not just for this package, but for all github packages):

> install_github('ramnathv/slidify')
Downloading github repo ramnathv/slidify@master
Error in curl::curl_fetch_memory(url, handle = handle) :
Problem with the SSL CA cert (path? access rights?)

But if I use RCurl directly to access github with ssl, I don't get any problem:

>  x <- getBinaryURL(
          url='https://github.com/ramnathv/slidify/archive/master.zip',
          followlocation=1L
          )

works with no errors, so RCurl can verify the SSL certificate properly and download the archive file.

> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 8 (jessie)

locale:
 [1] LC_CTYPE=en_US.utf8       LC_NUMERIC=C
 [3] LC_TIME=en_US.utf8        LC_COLLATE=en_US.utf8
 [5] LC_MONETARY=en_US.utf8    LC_MESSAGES=en_US.utf8
 [7] LC_PAPER=en_US.utf8       LC_NAME=C
 [9] LC_ADDRESS=C              LC_TELEPHONE=C
 [11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.95-4.7 bitops_1.0-6   devtools_1.8.0

loaded via a namespace (and not attached):
 [1] httr_1.0.0      R6_2.1.0        magrittr_1.5    rversions_1.0.2
 [5] tools_3.2.1     curl_0.9.1      Rcpp_0.12.0     memoise_0.2.1
 [9] xml2_0.1.1      stringi_0.5-5   git2r_0.10.1    stringr_1.0.0
 [13] digest_0.6.8

And

> curlVersion()

$age
[1] 3

$version
[1] "7.38.0"

$vesion_num
[1] 468480

$host
[1] "x86_64-pc-linux-gnu"

$features
   ipv6         ssl        libz        ntlm   asynchdns      spnego
      1           4           8          16         128         256
   largefile         idn tlsauth_srp     ntlm_wb
    512        1024       16384       32768

$ssl_version
[1] "OpenSSL/1.0.1k"

$ssl_version_num
[1] 0

$libz_version
[1] "1.2.8"

$protocols
[1] "dict"   "file"   "ftp"    "ftps"   "gopher" "http"   "https"  "imap"
[9] "imaps"  "ldap"   "ldaps"  "pop3"   "pop3s"  "rtmp"   "rtsp"   "scp"
[17] "sftp"   "smtp"   "smtps"  "telnet" "tftp"

$ares
[1] ""

$ares_num
[1] 0

$libidn
[1] "1.29"

If I use httr::set_config( httr::config( ssl_verifypeer = 0L ) ) then I can successfully run install_github but I would prefer to actually check ssl certificates.

Can anyone offer a solution?


问:
Timer can not be repeated on android How to fix?
I want Timer execute repeat.
so I try this source

```<code>public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}
</code>```

init() called when record button click.

why recordWork() only one execute?
this timer not execute repeat.

How to fix this problem?

thanks.

答:
Use the function timer.scheduleAtFixedRate() to execute the timer every X seconds.

For example timer.scheduleAtFixedRate(timerTask, new Date(), 2000) to start the timer now and execute every 2 seconds.

Body:
I want Timer execute repeat.
so I try this source

public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}

init() called when record button click.

why recordWork() only one execute?
this timer not execute repeat.

How to fix this problem?

thanks.


问:
psql: FATAL: database "<user>" does not exist
I'm using the PostgreSql app for mac (http://postgresapp.com/). I've used it in the past on other machines but it's giving me some trouble when installing on my macbook. I've installed the application and I ran:

```<code>psql -h localhost
</code>```

It returns:

```<code>psql: FATAL:  database "<user>" does not exist
</code>```

It seems I can't even run the console to create the database that it's attempting to find. The same thing happens when I just run:

```<code>psql
</code>```

or if I launch psql from the application drop down menu:

Machine stats:

OSX 10.8.4

psql (PostgreSQL) 9.2.4

Any help is appreciated.

I've also attempted to install PostgreSql via homebrew and I'm getting the same issue. I've also read the applications documentation page that states:

When Postgres.app first starts up, it creates the $USER database,
  which is the default database for psql when none is specified. The
  default user is $USER, with no password.

So it would seem the application is not creating $USER however I've installed->uninstalled-reinstalled several times now so it must be something with my machine.

I found the answer but I'm not sure exactly how it works as the user who answered on this thread -> Getting Postgresql Running In Mac: Database "postgres" does not exist didn't follow up. I used the following command to get psql to open:

```<code>psql -d template1
</code>```

I'll leave this one unanswered until someone can provide an explanation for why this works.

答: Had the same problem, a simple psql -d postgres did it (Type the command in the terminal)

Body:
I'm using the PostgreSql app for mac (http://postgresapp.com/). I've used it in the past on other machines but it's giving me some trouble when installing on my macbook. I've installed the application and I ran:

psql -h localhost

It returns:

psql: FATAL:  database "<user>" does not exist

It seems I can't even run the console to create the database that it's attempting to find. The same thing happens when I just run:

psql

or if I launch psql from the application drop down menu:

Machine stats:

OSX 10.8.4

psql (PostgreSQL) 9.2.4

Any help is appreciated.

I've also attempted to install PostgreSql via homebrew and I'm getting the same issue. I've also read the applications documentation page that states:

When Postgres.app first starts up, it creates the $USER database,
  which is the default database for psql when none is specified. The
  default user is $USER, with no password.

So it would seem the application is not creating $USER however I've installed->uninstalled-reinstalled several times now so it must be something with my machine.

I found the answer but I'm not sure exactly how it works as the user who answered on this thread -> Getting Postgresql Running In Mac: Database "postgres" does not exist didn't follow up. I used the following command to get psql to open:

psql -d template1

I'll leave this one unanswered until someone can provide an explanation for why this works.


问:
undefined method `source_url' for #<Chef::Cookbook::Metadata:0x000000006f1378>
I'm learning docker using book docker in practice.

I am working on technique 47 in chapter 5.

This recipe is about using chef for managing docker configurations.
The github link is here.

When I build the docker image from the container, I encounter below error.

```<code>$ docker build -t chef-example .
Sending build context to Docker daemon  9.728kB
Step 1/12 : FROM ubuntu:latest
 ---> ccc7a11d65b1
Step 2/12 : RUN apt-get update && apt-get install -yy git curl
 ---> Using cache
 ---> ef956c61c59f
Step 3/12 : RUN curl -L https://opscode-omnibus-packages.s3.amazonaws.com/ubuntu/12.04/x86_64/chefdk_0.3.5-1_amd64.deb -o chef.deb
 ---> Using cache
 ---> 1260301dbe67
Step 4/12 : RUN dpkg -i chef.deb && rm chef.deb
 ---> Using cache
 ---> 8c1aeaf84423
Step 5/12 : COPY . /chef
 ---> 18986195e732
Removing intermediate container 758dfce43670
Step 6/12 : WORKDIR /chef/cookbooks
 ---> fbdd9c386801
Removing intermediate container 936393187cb4
Step 7/12 : RUN knife cookbook site download apache2
 ---> Running in 2ba7d0765ae2
 WARNING: No knife configuration file found
 Downloading apache2 from the cookbooks site at version 5.0.1 to /chef/cookbooks/apache2-5.0.1.tar.gz
Cookbook saved: /chef/cookbooks/apache2-5.0.1.tar.gz
 ---> 8b3fa14f4416
Removing intermediate container 2ba7d0765ae2
Step 8/12 : RUN knife cookbook site download iptables
 ---> Running in 94275acfdb44
WARNING: No knife configuration file found
Downloading iptables from the cookbooks site at version 4.3.1 to /chef/cookbooks/iptables-4.3.1.tar.gz
Cookbook saved: /chef/cookbooks/iptables-4.3.1.tar.gz
 ---> c8a4c6d17253
Removing intermediate container 94275acfdb44
Step 9/12 : RUN knife cookbook site download logrotate
 ---> Running in 27b5f736d6cf
WARNING: No knife configuration file found
Downloading logrotate from the cookbooks site at version 2.2.0 to /chef/cookbooks/logrotate-2.2.0.tar.gz
Cookbook saved: /chef/cookbooks/logrotate-2.2.0.tar.gz
 ---> 1b4b4460bdc9
Removing intermediate container 27b5f736d6cf
Step 10/12 : RUN /bin/bash -c 'for f in $(ls *gz); do tar -zxf $f; rm $f; done'
 ---> Running in 7e6b912d910e
 ---> d5e77acc14f1
Removing intermediate container 7e6b912d910e
Step 11/12 : RUN chef-solo -c /chef/config.rb -j /chef/attributes.json
 ---> Running in a0c7f7f7a00a
[2017-12-05T08:01:08+00:00] INFO: Forking chef instance to converge...
[2017-12-05T08:01:08+00:00] INFO: *** Chef 11.18.0.rc.1 ***
[2017-12-05T08:01:08+00:00] INFO: Chef-client pid: 9
[2017-12-05T08:01:09+00:00] INFO: Setting the run_list to
["recipe[apache2::default]", "recipe[mysite::default]"] from CLI options
[2017-12-05T08:01:09+00:00] INFO: Run List is
[recipe[apache2::default], recipe[mysite::default]]
[2017-12-05T08:01:09+00:00] INFO: Run List expands to [apache2::default, mysite::default]
[2017-12-05T08:01:09+00:00] INFO: Starting Chef Run for 8089fe031125
[2017-12-05T08:01:09+00:00] INFO: Running start handlers
[2017-12-05T08:01:09+00:00] INFO: Start handlers complete.
[2017-12-05T08:01:09+00:00] ERROR: Running exception handlers
[2017-12-05T08:01:09+00:00] ERROR: Exception handlers complete
[2017-12-05T08:01:09+00:00] FATAL: Stacktrace dumped to /chef/cache/chef-stacktrace.out
[2017-12-05T08:01:09+00:00] ERROR: undefined method `source_url' for #<Chef::Cookbook::Metadata:0x000000006f1378>
[2017-12-05T08:01:09+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
The command '/bin/sh -c chef-solo -c /chef/config.rb -j /chef/attributes.json' returned a non-zero code: 1
</code>```

I'm new to chef. Not sure why I'm getting this error.

答:
Your cookbook doesn't have a metadata.rb which is probably breaking things, but you're also using Chef 11.18 which is entirely out of support at this point. Current Chef is 13.6.4.

Also we don't really recommend using Chef to build container images in most cases. It can definitely work, but overall Chef was built to manage servers so this will result in server-like fat images in most cases.

Body:
I'm learning docker using book docker in practice.

I am working on technique 47 in chapter 5.

This recipe is about using chef for managing docker configurations.
The github link is here.

When I build the docker image from the container, I encounter below error.

$ docker build -t chef-example .
Sending build context to Docker daemon  9.728kB
Step 1/12 : FROM ubuntu:latest
 ---> ccc7a11d65b1
Step 2/12 : RUN apt-get update && apt-get install -yy git curl
 ---> Using cache
 ---> ef956c61c59f
Step 3/12 : RUN curl -L https://opscode-omnibus-packages.s3.amazonaws.com/ubuntu/12.04/x86_64/chefdk_0.3.5-1_amd64.deb -o chef.deb
 ---> Using cache
 ---> 1260301dbe67
Step 4/12 : RUN dpkg -i chef.deb && rm chef.deb
 ---> Using cache
 ---> 8c1aeaf84423
Step 5/12 : COPY . /chef
 ---> 18986195e732
Removing intermediate container 758dfce43670
Step 6/12 : WORKDIR /chef/cookbooks
 ---> fbdd9c386801
Removing intermediate container 936393187cb4
Step 7/12 : RUN knife cookbook site download apache2
 ---> Running in 2ba7d0765ae2
 WARNING: No knife configuration file found
 Downloading apache2 from the cookbooks site at version 5.0.1 to /chef/cookbooks/apache2-5.0.1.tar.gz
Cookbook saved: /chef/cookbooks/apache2-5.0.1.tar.gz
 ---> 8b3fa14f4416
Removing intermediate container 2ba7d0765ae2
Step 8/12 : RUN knife cookbook site download iptables
 ---> Running in 94275acfdb44
WARNING: No knife configuration file found
Downloading iptables from the cookbooks site at version 4.3.1 to /chef/cookbooks/iptables-4.3.1.tar.gz
Cookbook saved: /chef/cookbooks/iptables-4.3.1.tar.gz
 ---> c8a4c6d17253
Removing intermediate container 94275acfdb44
Step 9/12 : RUN knife cookbook site download logrotate
 ---> Running in 27b5f736d6cf
WARNING: No knife configuration file found
Downloading logrotate from the cookbooks site at version 2.2.0 to /chef/cookbooks/logrotate-2.2.0.tar.gz
Cookbook saved: /chef/cookbooks/logrotate-2.2.0.tar.gz
 ---> 1b4b4460bdc9
Removing intermediate container 27b5f736d6cf
Step 10/12 : RUN /bin/bash -c 'for f in $(ls *gz); do tar -zxf $f; rm $f; done'
 ---> Running in 7e6b912d910e
 ---> d5e77acc14f1
Removing intermediate container 7e6b912d910e
Step 11/12 : RUN chef-solo -c /chef/config.rb -j /chef/attributes.json
 ---> Running in a0c7f7f7a00a
[2017-12-05T08:01:08+00:00] INFO: Forking chef instance to converge...
[2017-12-05T08:01:08+00:00] INFO: *** Chef 11.18.0.rc.1 ***
[2017-12-05T08:01:08+00:00] INFO: Chef-client pid: 9
[2017-12-05T08:01:09+00:00] INFO: Setting the run_list to
["recipe[apache2::default]", "recipe[mysite::default]"] from CLI options
[2017-12-05T08:01:09+00:00] INFO: Run List is
[recipe[apache2::default], recipe[mysite::default]]
[2017-12-05T08:01:09+00:00] INFO: Run List expands to [apache2::default, mysite::default]
[2017-12-05T08:01:09+00:00] INFO: Starting Chef Run for 8089fe031125
[2017-12-05T08:01:09+00:00] INFO: Running start handlers
[2017-12-05T08:01:09+00:00] INFO: Start handlers complete.
[2017-12-05T08:01:09+00:00] ERROR: Running exception handlers
[2017-12-05T08:01:09+00:00] ERROR: Exception handlers complete
[2017-12-05T08:01:09+00:00] FATAL: Stacktrace dumped to /chef/cache/chef-stacktrace.out
[2017-12-05T08:01:09+00:00] ERROR: undefined method `source_url' for #<Chef::Cookbook::Metadata:0x000000006f1378>
[2017-12-05T08:01:09+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
The command '/bin/sh -c chef-solo -c /chef/config.rb -j /chef/attributes.json' returned a non-zero code: 1

I'm new to chef. Not sure why I'm getting this error.


问:
Excel insert rows without conditional formatting
I am working on a macro to insert a specific number of rows. I'm struggling with clearing the format of the inserted cells because the inserted rows currently use the conditional formatting of the row above.

```<code>Sub RijInsert()
'
' RijInsert Macro
'
' Sneltoets: Ctrl+Shift+R
'
Dim Rng As Integer
Dim k As Integer
Dim rRange As Range

Set rRange = Selection

Rng = InputBox("Aantal in te voegen rijen?")
For k = 1 To Rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
          CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub
</code>```

How can I insert rows without using the conditional formatting from the preceding rows?

答:
Try this:

Rows(rRange.Row).Offset(-1, 0).ClearFormats

It's similar to the other solutions ;)

Here is the full code:

```<code>Sub RijInsert()

Dim Rng As Integer
Dim k As Integer
Dim rRange As Range

Set rRange = Selection

Rng = InputBox("Aantal in te voegen rijen?")
For k = 1 To Rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
          CopyOrigin:=xlFormatFromLeftOrAbove
    Rows(rRange.Row).Offset(-1, 0).ClearFormats
Next
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a macro to insert a specific number of rows. I'm struggling with clearing the format of the inserted cells because the inserted rows currently use the conditional formatting of the row above.

Sub RijInsert()
'
' RijInsert Macro
'
' Sneltoets: Ctrl+Shift+R
'
Dim Rng As Integer
Dim k As Integer
Dim rRange As Range

Set rRange = Selection

Rng = InputBox("Aantal in te voegen rijen?")
For k = 1 To Rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
          CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub

How can I insert rows without using the conditional formatting from the preceding rows?

Body:
Try this:

Rows(rRange.Row).Offset(-1, 0).ClearFormats

It's similar to the other solutions ;)

Here is the full code:

Sub RijInsert()

Dim Rng As Integer
Dim k As Integer
Dim rRange As Range

Set rRange = Selection

Rng = InputBox("Aantal in te voegen rijen?")
For k = 1 To Rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
          CopyOrigin:=xlFormatFromLeftOrAbove
    Rows(rRange.Row).Offset(-1, 0).ClearFormats
Next
End Sub


问:
Styling an input type="file" button
How do you style an input type="file" button?

<input type="file" />```

答:
Here we use a span to trigger input of type file and we simply customized that span, so we can add any styling using this way.

Note that we use input tag with visibility:hidden option and trigger it in the span.

.attachFileSpan{
color:#2b6dad;
cursor:pointer;
}
.attachFileSpan:hover{
text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3> Customized input of type file </h3>
<input id="myInput" type="file" style="visibility:hidden"/>

        <span title="attach file" class="attachFileSpan" onclick="document.getElementById('myInput').click()">
        Attach file
        </span></code>```

Reference

OwnerDisplayName: Shivanand

Title: Styling an input type="file" button

Body:
Here we use a span to trigger input of type file and we simply customized that span, so we can add any styling using this way.

Note that we use input tag with visibility:hidden option and trigger it in the span.

.attachFileSpan{
color:#2b6dad;
cursor:pointer;
}
.attachFileSpan:hover{
text-decoration: underline;
}

<h3> Customized input of type file </h3>
<input id="myInput" type="file" style="visibility:hidden"/>

        <span title="attach file" class="attachFileSpan" onclick="document.getElementById('myInput').click()">
        Attach file
        </span>

Reference


问:
Django: redirect to DetailView without pk in URL

I want to make sign-up forms with Django1.11.

urls.py

```<code>app_name = 'accounts'

urlpatterns = [
    url(r'^create/$', views.SignUpView.as_view(), name='create'),
    url(r'^check/$', views.CheckView.as_view(), name='check'),
    url(r'^update/$', views.CorrectView.as_view(), name='update'),
    # ...
]
</code>```

views.py

```<code>class SignUpView(CreateView):
    model = User
    form_class = UserForm
    template_name = "accounts/create.html"

    def get_success_url(self):
        check_view = CheckView.as_view()
        return redirect(check_view, pk=self.object.pk)

class CheckView(DetailView):
    model = User
    template_name = "accounts/check.html"

class CorrectView(UpdateView):
    model = User
    form_class = UserForm
    template_name = "accounts/create.html"

    def get_success_url(self):
        check_view = CheckView.as_view()
        return redirect(check_view, pk=self.object.pk)
</code>```

After a new user inputs his information in SignUpView(generic.CreateView), he will see what he just has input in CheckView(generic.DetailView), and if he notice that he has made some mistakes, he reinput his information in CorrectView(generic.UpdateView).

I want not to make url r'^check/(?P<pk>[0-9]+)$' for example. This is because if an user inputs a URL .../check/1 for example in browser, unfortunately he can see the information of another person.

When I run the code above, the error Reverse for 'accounts.views.CheckView' not found. 'accounts.views.CheckView' is not a valid view function or pattern name.
 is occurred. Please tell me how to redirect to CheckView(generic.DetailView) without url include pk.

答:
You can change the structure of your url to not using a slug, for example:

```<code># Url dell'app accounts.
url(r'^accounts/register/$', RegistrationView.as_view(form_class=CustomUserForm), name='registration-register'),
url(r'^accounts/profile/$', UserProfileView.as_view(), name='user-profile'),
url(
    r'^accounts/profile/(?P<company>[-\w]+)/modifica/$',
    UpdateCompanyView.as_view(),
    name='update-company-view-profile'
),
url(
    r'^accounts/change-password/$',
    password_change, {'post_change_redirect': 'user-profile'}, name='password_change'
),
url(r'^accounts/update/$', UserProfileUpdateView.as_view(), name='user-profile-update'),
url(r'^accounts/', include('registration.backends.hmac.urls')),
</code>```

This is the structure of the urls i am using in my project..
then i am able to manipulate the user, or obtain information from it simply by using request.user!

Body:
I want to make sign-up forms with Django1.11.

urls.py

app_name = 'accounts'

urlpatterns = [
    url(r'^create/$', views.SignUpView.as_view(), name='create'),
    url(r'^check/$', views.CheckView.as_view(), name='check'),
    url(r'^update/$', views.CorrectView.as_view(), name='update'),
    # ...
]

views.py

class SignUpView(CreateView):
    model = User
    form_class = UserForm
    template_name = "accounts/create.html"

    def get_success_url(self):
        check_view = CheckView.as_view()
        return redirect(check_view, pk=self.object.pk)

class CheckView(DetailView):
    model = User
    template_name = "accounts/check.html"

class CorrectView(UpdateView):
    model = User
    form_class = UserForm
    template_name = "accounts/create.html"

    def get_success_url(self):
        check_view = CheckView.as_view()
        return redirect(check_view, pk=self.object.pk)

After a new user inputs his information in SignUpView(generic.CreateView), he will see what he just has input in CheckView(generic.DetailView), and if he notice that he has made some mistakes, he reinput his information in CorrectView(generic.UpdateView).

I want not to make url r'^check/(?P<pk>[0-9]+)$' for example. This is because if an user inputs a URL .../check/1 for example in browser, unfortunately he can see the information of another person.

When I run the code above, the error Reverse for 'accounts.views.CheckView' not found. 'accounts.views.CheckView' is not a valid view function or pattern name.
 is occurred. Please tell me how to redirect to CheckView(generic.DetailView) without url include pk.

Body:
You can change the structure of your url to not using a slug, for example:

# Url dell'app accounts.
url(r'^accounts/register/$', RegistrationView.as_view(form_class=CustomUserForm), name='registration-register'),
url(r'^accounts/profile/$', UserProfileView.as_view(), name='user-profile'),
url(
    r'^accounts/profile/(?P<company>[-\w]+)/modifica/$',
    UpdateCompanyView.as_view(),
    name='update-company-view-profile'
),
url(
    r'^accounts/change-password/$',
    password_change, {'post_change_redirect': 'user-profile'}, name='password_change'
),
url(r'^accounts/update/$', UserProfileUpdateView.as_view(), name='user-profile-update'),
url(r'^accounts/', include('registration.backends.hmac.urls')),

This is the structure of the urls i am using in my project..
then i am able to manipulate the user, or obtain information from it simply by using request.user!


答:
Use it like below

```<code>  public static void init() {
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Looper.prepare();
            recordWork();
            Looper.loop();
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 1000, 30000);
}
</code>```

Use Timer as a global variable. and cancel it its need done.

```<code> if(timer != null) {
    timer.cancel();
    timer.purge();
    timer = null;
}
</code>```

Title: Timer can not be repeated on android How to fix?

Body:
Use it like below

  public static void init() {
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Looper.prepare();
            recordWork();
            Looper.loop();
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 1000, 30000);
}

Use Timer as a global variable. and cancel it its need done.

 if(timer != null) {
    timer.cancel();
    timer.purge();
    timer = null;
}


问:
Passing MouseEvent Args in MVVM Light
I am programming an application where I can crop and resize an image by mouse. Because I had problems figuring out how I could pass Event Args in MVVM, I decided to give MVVM Light a try. Now everytime my mouse is over the image I receive the error:

An unhandled exception of type 'System.InvalidCastException' occurred in GalaSoft.MvvmLight.Platform.dll

Additional information: Das Objekt des Typs "System.Windows.Point" kann nicht in Typ "System.Windows.Input.MouseEventArgs" umgewandelt werden.

I don't really know how to fix this although I assume that my RelayCommands are implemented wrong.

I did the bindings in the XAML as following:

```<code> <Image x:Name="_image" Margin="10" Source="{Binding CurrentImage.ImagePath, UpdateSourceTrigger=PropertyChanged}"
               HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="Fill" MaxHeight="300">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseDown">
                    <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseDownCommand}"
                                        EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
                                        EventArgsConverterParameter="{Binding ElementName=_image}"
                                        PassEventArgsToCommand="True" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseMove">
                    <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseMoveCommand}"
                                        EventArgsConverter="{StaticResource MouseEventArgsToPointConverter}"
                                        EventArgsConverterParameter="{Binding ElementName=_image}"
                                        PassEventArgsToCommand="True" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseUp">
                    <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseUpCommand}"
                                        EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
                                        EventArgsConverterParameter="{Binding ElementName=_image}"
                                        PassEventArgsToCommand="True" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Image>
</code>```

My ViewModel looks like this:

```<code>RelayCommand<MouseButtonEventArgs> mouseDownCommand;
    public RelayCommand<MouseButtonEventArgs> MouseDownCommand
    {
        get
        {
            if (mouseDownCommand == null)
            {
                mouseDownCommand = new RelayCommand<MouseButtonEventArgs>(MouseDown);
            }
            return mouseDownCommand;
        }
    }

    public void MouseDown(MouseButtonEventArgs e)
    {
        this.currentImage.StartPoint = e.GetPosition(this.currentImage.CnvImage);
    }

    RelayCommand<System.Windows.Input.MouseEventArgs> mouseMoveCommand;
    public RelayCommand<System.Windows.Input.MouseEventArgs> MouseMoveCommand
    {
      get
        {
            if (mouseMoveCommand == null)
            {
                mouseMoveCommand = new RelayCommand<System.Windows.Input.MouseEventArgs>(MouseMove);
            }
            return mouseMoveCommand;
        }
    }

    public void MouseMove(System.Windows.Input.MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            var pos = e.GetPosition(this.currentImage.CnvImage);

            var x = Math.Min(pos.X, this.currentImage.StartPoint.X);
            var y = Math.Min(pos.Y, this.currentImage.StartPoint.Y);

            var w = Math.Max(pos.X, this.currentImage.StartPoint.X) - x;
            var h = Math.Max(pos.Y, this.currentImage.StartPoint.Y) - y;

            var rect = new System.Windows.Shapes.Rectangle
            {
                Stroke = System.Windows.Media.Brushes.LightBlue,
                StrokeThickness = 2
            };

            this.currentImage.RectSelectArea = rect;

            this.currentImage.RectSelectArea.Width = w;
            this.currentImage.RectSelectArea.Height = h;

            Canvas.SetLeft(this.currentImage.RectSelectArea, x);
            Canvas.SetTop(this.currentImage.RectSelectArea, y);
        }
    }

    RelayCommand<MouseButtonEventArgs> mouseUpCommand;
    public RelayCommand<MouseButtonEventArgs> MouseUpCommand
    {
       get
        {
            if (mouseUpCommand == null)
            {
                mouseUpCommand = new RelayCommand<MouseButtonEventArgs>(MouseUp);
            }
            return mouseUpCommand;
        }
    }

    public void MouseUp(MouseButtonEventArgs e)
    {
        System.Windows.Controls.Image croppedImage = new System.Windows.Controls.Image();
        croppedImage.Width = 100;
        croppedImage.Margin = new Thickness(5);

        this.currentImage.CropXPosition = (int)this.currentImage.StartPoint.X;
        this.currentImage.CropYPosition = (int)this.currentImage.StartPoint.Y;
        this.currentImage.CropWidth = (int)this.currentImage.RectSelectArea.Width;
        this.currentImage.CropHeight = (int)this.currentImage.RectSelectArea.Height;
        CroppedBitmap cb = new CroppedBitmap(
            (BitmapSource)this.currentImage.ImagePath, new Int32Rect(
                this.currentImage.CropXPosition, this.currentImage.CropYPosition, this.currentImage.CropWidth, this.currentImage.CropHeight));
        croppedImage.Source = cb;
    }
</code>```

The MouseButtonEventToArgsToPointConverter:

```<code>  class MouseButtonEventArgsToPointConverter : IEventArgsConverter
{
    public object Convert(object value, object parameter)
    {
        var args = (MouseButtonEventArgs)value;
        var element = (FrameworkElement)parameter;

        var point = args.GetPosition(element);
        return point;
    }
}
</code>```

I also followed this advice from a similar question if not same question, but the RelayCommand won't work as a type Point.
How can I fix this? Or is my approach wrong? Really thankful for any kind of help or suggestions.

答:
You are converting the MouseButtonEventArgs to a Point in the MouseButtonEventArgsToPointConverter but the commands are expecting a MouseButtonEventArgs parameter - hence the cast exception.  You convert it to a Point and then the Point is passed to the RelayCommand<MouseButtonEventArgs>, an attempt is then made to cast Point to MouseButtonEventArgs which it obviously cannot do.  Do you want to pass the Point or the event args?  If point then change the command to RelayCommand<Point>, if event args then remove use of the converter

Either:

```<code> <cmd:EventToCommand Command="{Binding Mode=OneWay,
    Path=MouseDownCommand}"
    EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
    EventArgsConverterParameter="{Binding ElementName=_image}"
    PassEventArgsToCommand="True" />

public RelayCommand<Point> MouseDownCommand
{
    get
    {
       ...
    }
}
</code>```

Also in this case you need to change MouseDown to this:

```<code>public void MouseDown(Point p)
</code>```

Or:

```<code><cmd:EventToCommand Command="{Binding Mode=OneWay,
    Path=MouseDownCommand}"  PassEventArgsToCommand="True" />

public RelayCommand<MouseButtonEventArgs> MouseDownCommand
{
    get
    {
        ...
    }
}
</code>```

Title: Passing MouseEvent Args in MVVM Light

Body:
I am programming an application where I can crop and resize an image by mouse. Because I had problems figuring out how I could pass Event Args in MVVM, I decided to give MVVM Light a try. Now everytime my mouse is over the image I receive the error:

An unhandled exception of type 'System.InvalidCastException' occurred in GalaSoft.MvvmLight.Platform.dll

Additional information: Das Objekt des Typs "System.Windows.Point" kann nicht in Typ "System.Windows.Input.MouseEventArgs" umgewandelt werden.

I don't really know how to fix this although I assume that my RelayCommands are implemented wrong.

I did the bindings in the XAML as following:

 <Image x:Name="_image" Margin="10" Source="{Binding CurrentImage.ImagePath, UpdateSourceTrigger=PropertyChanged}"
               HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="Fill" MaxHeight="300">

                    <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseDownCommand}"
                                        EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
                                        EventArgsConverterParameter="{Binding ElementName=_image}"
                                        PassEventArgsToCommand="True" />

                    <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseMoveCommand}"
                                        EventArgsConverter="{StaticResource MouseEventArgsToPointConverter}"
                                        EventArgsConverterParameter="{Binding ElementName=_image}"
                                        PassEventArgsToCommand="True" />

                    <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseUpCommand}"
                                        EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
                                        EventArgsConverterParameter="{Binding ElementName=_image}"
                                        PassEventArgsToCommand="True" />

        </Image>

My ViewModel looks like this:

RelayCommand<MouseButtonEventArgs> mouseDownCommand;
    public RelayCommand<MouseButtonEventArgs> MouseDownCommand
    {
        get
        {
            if (mouseDownCommand == null)
            {
                mouseDownCommand = new RelayCommand<MouseButtonEventArgs>(MouseDown);
            }
            return mouseDownCommand;
        }
    }

    public void MouseDown(MouseButtonEventArgs e)
    {
        this.currentImage.StartPoint = e.GetPosition(this.currentImage.CnvImage);
    }

    RelayCommand<System.Windows.Input.MouseEventArgs> mouseMoveCommand;
    public RelayCommand<System.Windows.Input.MouseEventArgs> MouseMoveCommand
    {
      get
        {
            if (mouseMoveCommand == null)
            {
                mouseMoveCommand = new RelayCommand<System.Windows.Input.MouseEventArgs>(MouseMove);
            }
            return mouseMoveCommand;
        }
    }

    public void MouseMove(System.Windows.Input.MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            var pos = e.GetPosition(this.currentImage.CnvImage);

            var x = Math.Min(pos.X, this.currentImage.StartPoint.X);
            var y = Math.Min(pos.Y, this.currentImage.StartPoint.Y);

            var w = Math.Max(pos.X, this.currentImage.StartPoint.X) - x;
            var h = Math.Max(pos.Y, this.currentImage.StartPoint.Y) - y;

            var rect = new System.Windows.Shapes.Rectangle
            {
                Stroke = System.Windows.Media.Brushes.LightBlue,
                StrokeThickness = 2
            };

            this.currentImage.RectSelectArea = rect;

            this.currentImage.RectSelectArea.Width = w;
            this.currentImage.RectSelectArea.Height = h;

            Canvas.SetLeft(this.currentImage.RectSelectArea, x);
            Canvas.SetTop(this.currentImage.RectSelectArea, y);
        }
    }

    RelayCommand<MouseButtonEventArgs> mouseUpCommand;
    public RelayCommand<MouseButtonEventArgs> MouseUpCommand
    {
       get
        {
            if (mouseUpCommand == null)
            {
                mouseUpCommand = new RelayCommand<MouseButtonEventArgs>(MouseUp);
            }
            return mouseUpCommand;
        }
    }

    public void MouseUp(MouseButtonEventArgs e)
    {
        System.Windows.Controls.Image croppedImage = new System.Windows.Controls.Image();
        croppedImage.Width = 100;
        croppedImage.Margin = new Thickness(5);

        this.currentImage.CropXPosition = (int)this.currentImage.StartPoint.X;
        this.currentImage.CropYPosition = (int)this.currentImage.StartPoint.Y;
        this.currentImage.CropWidth = (int)this.currentImage.RectSelectArea.Width;
        this.currentImage.CropHeight = (int)this.currentImage.RectSelectArea.Height;
        CroppedBitmap cb = new CroppedBitmap(
            (BitmapSource)this.currentImage.ImagePath, new Int32Rect(
                this.currentImage.CropXPosition, this.currentImage.CropYPosition, this.currentImage.CropWidth, this.currentImage.CropHeight));
        croppedImage.Source = cb;
    }

The MouseButtonEventToArgsToPointConverter:

  class MouseButtonEventArgsToPointConverter : IEventArgsConverter
{
    public object Convert(object value, object parameter)
    {
        var args = (MouseButtonEventArgs)value;
        var element = (FrameworkElement)parameter;

        var point = args.GetPosition(element);
        return point;
    }
}

I also followed this advice from a similar question if not same question, but the RelayCommand won't work as a type Point.
How can I fix this? Or is my approach wrong? Really thankful for any kind of help or suggestions.

Body:
You are converting the MouseButtonEventArgs to a Point in the MouseButtonEventArgsToPointConverter but the commands are expecting a MouseButtonEventArgs parameter - hence the cast exception.  You convert it to a Point and then the Point is passed to the RelayCommand<MouseButtonEventArgs>, an attempt is then made to cast Point to MouseButtonEventArgs which it obviously cannot do.  Do you want to pass the Point or the event args?  If point then change the command to RelayCommand<Point>, if event args then remove use of the converter

Either:

 <cmd:EventToCommand Command="{Binding Mode=OneWay,
    Path=MouseDownCommand}"
    EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
    EventArgsConverterParameter="{Binding ElementName=_image}"
    PassEventArgsToCommand="True" />

public RelayCommand<Point> MouseDownCommand
{
    get
    {
       ...
    }
}

Also in this case you need to change MouseDown to this:

public void MouseDown(Point p)

Or:

<cmd:EventToCommand Command="{Binding Mode=OneWay,
    Path=MouseDownCommand}"  PassEventArgsToCommand="True" />

public RelayCommand<MouseButtonEventArgs> MouseDownCommand
{
    get
    {
        ...
    }
}


问:
Error: Uncaught (in promise): Error: Cannot match any routes Angular 2
##Error
I have implemented nested routing in my app. when application loads its shows login screen after login its redirects to admin page where further child routes exist like user, product, api etc. now when I navigate to admin it by default loads user screen but further <routeLinks> not working and its shows this error.
Error: Uncaught (in promise): Error: Cannot match any routes: 'product'

After Click Product it shows this

##Code main.ts

```<code>import { bootstrap }    from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from '../app/app.routes';
import { AppComponent } from '../app/app.component';

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);
</code>```

##app.component

```<code>import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  selector: 'demo-app',
  template: `

    <div class="outer-outlet">
      <router-outlet></router-outlet>
    </div>
  `,
  directives: [ROUTER_DIRECTIVES]
})
export class AppComponent { }
</code>```

##app.routes

```<code>import { provideRouter, RouterConfig } from '@angular/router';

import { AboutComponent, AboutHomeComponent, AboutItemComponent } from '../app/about.component';
import { HomeComponent } from '../app/home.component';

export const routes: RouterConfig = [
  {
    path: '',
    component: HomeComponent
   },
  {
    path: 'admin',
    component: AboutComponent,
    children: [
      {
        path: '',
        component: AboutHomeComponent
       },
      {
        path: '/product',
        component: AboutItemComponent
      }
    ]
  }
];

export const APP_ROUTER_PROVIDERS = [
  provideRouter(routes)
];
</code>```

##home.component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl:'../app/layouts/login.html'
})
export class HomeComponent { }
</code>```

##about.component

```<code>import { Component } from '@angular/core';
import { ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  selector: 'about-home',
  template: `<h3>user</h3>`
})
export class AboutHomeComponent { }

@Component({
  selector: 'about-item',
  template: `<h3>product</h3>`
})
export class AboutItemComponent { }

@Component({
    selector: 'app-about',
    templateUrl: '../app/layouts/admin.html',
    directives: [ROUTER_DIRECTIVES]
})
export class AboutComponent { }

</code>```

答:
I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem

```<code>export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}
</code>```

Hope this will help you.

Body:
##Error
I have implemented nested routing in my app. when application loads its shows login screen after login its redirects to admin page where further child routes exist like user, product, api etc. now when I navigate to admin it by default loads user screen but further <routeLinks> not working and its shows this error.
Error: Uncaught (in promise): Error: Cannot match any routes: 'product'

After Click Product it shows this

##Code main.ts

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from '../app/app.routes';
import { AppComponent } from '../app/app.component';

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);

##app.component

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  selector: 'demo-app',
  template: `

      <router-outlet></router-outlet>

  `,
  directives: [ROUTER_DIRECTIVES]
})
export class AppComponent { }

##app.routes

import { provideRouter, RouterConfig } from '@angular/router';

import { AboutComponent, AboutHomeComponent, AboutItemComponent } from '../app/about.component';
import { HomeComponent } from '../app/home.component';

export const routes: RouterConfig = [
  {
    path: '',
    component: HomeComponent
   },
  {
    path: 'admin',
    component: AboutComponent,
    children: [
      {
        path: '',
        component: AboutHomeComponent
       },
      {
        path: '/product',
        component: AboutItemComponent
      }
    ]
  }
];

export const APP_ROUTER_PROVIDERS = [
  provideRouter(routes)
];

##home.component

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl:'../app/layouts/login.html'
})
export class HomeComponent { }

##about.component

import { Component } from '@angular/core';
import { ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  selector: 'about-home',
  template: `<h3>user</h3>`
})
export class AboutHomeComponent { }

@Component({
  selector: 'about-item',
  template: `<h3>product</h3>`
})
export class AboutItemComponent { }

@Component({
    selector: 'app-about',
    templateUrl: '../app/layouts/admin.html',
    directives: [ROUTER_DIRECTIVES]
})
export class AboutComponent { }

Body:
I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.


问:
How to serialise a JSON string inside a JSON object
I have an object that contains a property "Data". This property holds additional, meta data in Json format.

However, I now need to send the entire object down to a web page as a Json string. I'm using .Net Core 2.0 with the following code

```<code>var content = JsonConvert.SerializeObject(model);
content = content.Replace("\\r\\n", "");
return View("Index", content);
</code>```

In StartUp.ConfigureService I also have the following

```<code>services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
</code>```

Unfortunately, I'm now getting

Uncaught SyntaxError: Unexpected token i in JSON at position 3159
    at JSON.parse ()

How do I ensure that my Data property isn't seen as Json until it's actually needed (at which case I'll use JQuery to deserialise the bit I need)

My Json string that is being returned looks like so

```<code>{content:"this", foo: "bar", data:"["array1","array2","array3"]" }
</code>```

Obviously I have quote issues.....

Thanks

答:
Solved the issue.

I just needed to escape the double quotes in the data property Json so that the complete Json returned as such

```<code>{content:"this", foo: "bar", data:"[\"array1\",\"array2\",\"array3\"]" }
</code>```

Body:
I have an object that contains a property "Data". This property holds additional, meta data in Json format.

However, I now need to send the entire object down to a web page as a Json string. I'm using .Net Core 2.0 with the following code

var content = JsonConvert.SerializeObject(model);
content = content.Replace("\\r\\n", "");
return View("Index", content);

In StartUp.ConfigureService I also have the following

services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

Unfortunately, I'm now getting

Uncaught SyntaxError: Unexpected token i in JSON at position 3159
    at JSON.parse ()

How do I ensure that my Data property isn't seen as Json until it's actually needed (at which case I'll use JQuery to deserialise the bit I need)

My Json string that is being returned looks like so

{content:"this", foo: "bar", data:"["array1","array2","array3"]" }

Obviously I have quote issues.....

Thanks

Body:
Solved the issue.

I just needed to escape the double quotes in the data property Json so that the complete Json returned as such

{content:"this", foo: "bar", data:"[\"array1\",\"array2\",\"array3\"]" }


问:
Scroll then lock row
I have a worksheet that has header data in the first few rows, followed by a table with column headers.  The header data includes parameters that are used to calculate values in the table.

What I want is to allow the user to scroll the sheet so that the header data is no longer visible but then freeze the table heading row when it becomes the first row.  Then if they need to change a parameter, they can scroll back up and the top few rows come back into view.

I thought this was fairly easy to do but I can't remember how to do it.  The only option I can find is the Freeze Panes option, but that freezes everything and I only want it to freeze when the header row is at the top.

Is this even possible?

Edited - To add a little more clarification, the freeze panes option freezes everything above the selected row (unless I have missed it), which is not what I am looking for.  I want the sheet to behave similar to a website where there may be an ad banner at the top, followed by a navigation bar/logo/etc., then the content.  As you scroll down, the ad banner moves out of view but when the nav bar is at the top, it stops and remains in view while the content continues to scroll.

Let's say I have the first 5 rows that have cells to capture input values.  Then row 6 is a table heading and rows 7-100 are the table data.  I want the user to be able to hit the scroll down button 5 times to move past the input values.  Then I want row 6 to freeze at the top so that as the user continues scrolling, the table heading is visible.  Conversely, when the user scrolls up, row 6 remains at the top until the user gets to row 7, then if they continue scrolling, the input values move into view.

Excel does something similar if you use the "format as table" function and indicate that the selection has a header row.  Then when scrolling, the column headers will replace the "A", "B", "C", etc. address labels.  This won't work directly for me because the table structure is a little more complex.

答:
I had the same problem and have much less tech savvy to do all the coding above.
My workaround is very simple.
Insert a new row right at the top of the sheet.
Copy the headings of the table to the new row 1 and then freeze the top row as normal.
As you scroll the top dummy row stays above your table and the rest disapears.
Your original headings still stay in place for filtering as needed if you scroll up.</p>

Title: Scroll then lock row


问:
org.sonar.batch.bootstrapper.IssueListener not found in sonar-scanner-engine-shaded:6.7
Having the following setup:

https://github.com/TouK/sputnik 1.8.0

SonarQube 6.7

Jenkins 2.36

When executing the following Post step in Jenkins

```<code>sputnik --conf sputnik.properties --changeId xxxxxx --revisionId xxxxx
</code>```

I'm getting the error

```<code>DEBUG: Extract sonar-runner-batch in temp...
DEBUG: Get bootstrap index...
DEBUG: Download: http://localhost:9000/sonar/batch_bootstrap/index
DEBUG: Get bootstrap completed
DEBUG: Create isolated classloader...
DEBUG: Start temp cleaning...
DEBUG: Temp cleaning done
DEBUG: Execution getVersion
DEBUG: Execution start
Exception in thread "main" java.lang.NoClassDefFoundError: org/sonar/batch/bootstrapper/IssueListener
    at org.sonar.runner.batch.DefaultBatchFactory.createBatch(DefaultBatchFactory.java:44)
    at org.sonar.runner.batch.BatchIsolatedLauncher.start(BatchIsolatedLauncher.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.sonar.runner.impl.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:61)
    at com.sun.proxy.$Proxy0.start(Unknown Source)
    at org.sonar.runner.api.EmbeddedRunner.doStart(EmbeddedRunner.java:251)
    at org.sonar.runner.api.EmbeddedRunner.start(EmbeddedRunner.java:187)
    at org.sonar.runner.api.EmbeddedRunner.start(EmbeddedRunner.java:182)
    at org.sonar.runner.api.EmbeddedRunner.execute(EmbeddedRunner.java:209)
    at pl.touk.sputnik.processor.sonar.SonarRunner.run(SonarRunner.java:62)
    at pl.touk.sputnik.processor.sonar.SonarProcessor.process(SonarProcessor.java:49)
    at pl.touk.sputnik.engine.ReviewRunner.review(ReviewRunner.java:25)
    at pl.touk.sputnik.engine.Engine.run(Engine.java:40)
    at pl.touk.sputnik.Main.main(Main.java:36)
Caused by: java.lang.ClassNotFoundException: org.sonar.batch.bootstrapper.IssueListener
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at org.sonar.runner.impl.IsolatedClassloader.loadClass(IsolatedClassloader.java:82)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more
</code>```

Digging a little deeper I had to notice that Sputnik 1.8.0 is using sonar-runner-api-2.5.1.jar that contains DefaultBatchFactory.createBatch which fails due to the following declaration:

```<code>public class Compatibility {
    static class IssueListenerAdapter
        implements org.sonar.batch.bootstrapper.IssueListener {
    }
}
</code>```

As far as I can see org.sonarsource.sonarqube:sonar-scanner-engine-shaded:6.5 was still supporting that IssueListener while org.sonarsource.sonarqube:sonar-scanner-engine-shaded:6.6 is not anymore. Furthermore I cannot find any newer version of sonar-runner-api-2.5.1.jar which Sputnik could use. Do you have any idea how this issue is to be resolved?

答:
sonar-runner-api-2.5.1 is not supported anymore. Please upgrade to a more recent version. Note that artifactId has been changed to sonar-scanner-api.

See available versions:
https://repo1.maven.org/maven2/org/sonarsource/scanner/api/sonar-scanner-api/

Body:
Having the following setup:

https://github.com/TouK/sputnik 1.8.0

SonarQube 6.7

Jenkins 2.36

When executing the following Post step in Jenkins

sputnik --conf sputnik.properties --changeId xxxxxx --revisionId xxxxx

I'm getting the error

DEBUG: Extract sonar-runner-batch in temp...
DEBUG: Get bootstrap index...
DEBUG: Download: http://localhost:9000/sonar/batch_bootstrap/index
DEBUG: Get bootstrap completed
DEBUG: Create isolated classloader...
DEBUG: Start temp cleaning...
DEBUG: Temp cleaning done
DEBUG: Execution getVersion
DEBUG: Execution start
Exception in thread "main" java.lang.NoClassDefFoundError: org/sonar/batch/bootstrapper/IssueListener
    at org.sonar.runner.batch.DefaultBatchFactory.createBatch(DefaultBatchFactory.java:44)
    at org.sonar.runner.batch.BatchIsolatedLauncher.start(BatchIsolatedLauncher.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.sonar.runner.impl.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:61)
    at com.sun.proxy.$Proxy0.start(Unknown Source)
    at org.sonar.runner.api.EmbeddedRunner.doStart(EmbeddedRunner.java:251)
    at org.sonar.runner.api.EmbeddedRunner.start(EmbeddedRunner.java:187)
    at org.sonar.runner.api.EmbeddedRunner.start(EmbeddedRunner.java:182)
    at org.sonar.runner.api.EmbeddedRunner.execute(EmbeddedRunner.java:209)
    at pl.touk.sputnik.processor.sonar.SonarRunner.run(SonarRunner.java:62)
    at pl.touk.sputnik.processor.sonar.SonarProcessor.process(SonarProcessor.java:49)
    at pl.touk.sputnik.engine.ReviewRunner.review(ReviewRunner.java:25)
    at pl.touk.sputnik.engine.Engine.run(Engine.java:40)
    at pl.touk.sputnik.Main.main(Main.java:36)
Caused by: java.lang.ClassNotFoundException: org.sonar.batch.bootstrapper.IssueListener
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at org.sonar.runner.impl.IsolatedClassloader.loadClass(IsolatedClassloader.java:82)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more

Digging a little deeper I had to notice that Sputnik 1.8.0 is using sonar-runner-api-2.5.1.jar that contains DefaultBatchFactory.createBatch which fails due to the following declaration:

public class Compatibility {
    static class IssueListenerAdapter
        implements org.sonar.batch.bootstrapper.IssueListener {
    }
}

As far as I can see org.sonarsource.sonarqube:sonar-scanner-engine-shaded:6.5 was still supporting that IssueListener while org.sonarsource.sonarqube:sonar-scanner-engine-shaded:6.6 is not anymore. Furthermore I cannot find any newer version of sonar-runner-api-2.5.1.jar which Sputnik could use. Do you have any idea how this issue is to be resolved?


问:
onCharacteristicChanged is not callBack in Android 5.0
It is callback that 'onCharacteristicChanged' in Android 4.3 but it is not call in Android 5.0 above. 'WriteCharacteristic' and 'setCharaceristicNotification' is successful and 'onCharacteristicWrite' callback is successful yet.Why it is not call in Android5.0 or Android 6.0.

This is my notification code:

```<code>private void notification(BluetoothGattCharacteristic gattCharacteristic, String tag) {
    boolean success = mBluetoothGatt.setCharacteristicNotification(gattCharacteristic, true);
    if (success) {
        for (BluetoothGattDescriptor dp : gattCharacteristic.getDescriptors()) {
            if (dp != null) {
                if ((gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
                    dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    Log.i(TAG,"notification NOTIFICATION value = "+ Arrays.toString(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
                } else if ((gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
                    dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                    Log.i(TAG,"notification INDICATION value = "+ Arrays.toString(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));

                }
                mBluetoothGatt.writeDescriptor(dp);
                Log.i(TAG, tag + " notification successful");
            }
        }
    }
}
</code>```

答: "BluetoothGatt.writeDescriptor(dp)" is failed, and it is a asynchronous thread. It is stop to write descriptor when the thread busy. So I write descriptor one by one. It's ok.</p>

Body:
It is callback that 'onCharacteristicChanged' in Android 4.3 but it is not call in Android 5.0 above. 'WriteCharacteristic' and 'setCharaceristicNotification' is successful and 'onCharacteristicWrite' callback is successful yet.Why it is not call in Android5.0 or Android 6.0.

This is my notification code:

private void notification(BluetoothGattCharacteristic gattCharacteristic, String tag) {
    boolean success = mBluetoothGatt.setCharacteristicNotification(gattCharacteristic, true);
    if (success) {
        for (BluetoothGattDescriptor dp : gattCharacteristic.getDescriptors()) {
            if (dp != null) {
                if ((gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
                    dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    Log.i(TAG,"notification NOTIFICATION value = "+ Arrays.toString(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
                } else if ((gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
                    dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                    Log.i(TAG,"notification INDICATION value = "+ Arrays.toString(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));

                }
                mBluetoothGatt.writeDescriptor(dp);
                Log.i(TAG, tag + " notification successful");
            }
        }
    }
}


问:
Rails 3 - Help with a Email Validation Regex
the following REGEX if provided an email domain that does not match INVALID_EMAILs seems to run indefinitely and lock up the rails server (my local env).

```<code>INVALID_EMAILS = %w(gmail.com googlemail.com yahoo.com ymail.com rocketmail.com hotmail.com facebook.com)

  def valid_email_domain(emailAddy)
    reg = Regexp.new /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/
    if emailAddy.scan(reg).size == 0
      return true
    else
      return false
    end
  end
</code>```

Any regex experts out there that can provide feedback? Thanks

UPDATED:

controller:

```<code>  def create

    @user = User.new

    # User EmailVeracity to validate the email address
    email = EmailVeracity::Address.new(params[:user][:email])

    Rails.logger.info 'Email Check Result'
Rails.logger.info valid_email_domain(params[:user][:email])
    Rails.logger.info 'Email Check Result'

    if email.valid?
      Rails.logger.info 'Sign this email up'
    else
      Rails.logger.info 'Bad email, dont touch that'
    end

    respond_to do |format|
      format.html
      format.js
    end

  end
protected

  def valid_email_domain(emailAddy)
    !(emailAddy =~ /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/)
  end
</code>```

User Model:

```<code>INVALID_EMAILS = %w(gmail.com googlemail.com yahoo.com ymail.com rocketmail.com hotmail.com facebook.com)
</code>```

答:
You're making this way too complicated. This should be enough:</p>

```<code>def valid_email_domain(email_address)
  !(email_address =~ /#{INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/)
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
the following REGEX if provided an email domain that does not match INVALID_EMAILs seems to run indefinitely and lock up the rails server (my local env).

INVALID_EMAILS = %w(gmail.com googlemail.com yahoo.com ymail.com rocketmail.com hotmail.com facebook.com)

  def valid_email_domain(emailAddy)
    reg = Regexp.new /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/
    if emailAddy.scan(reg).size == 0
      return true
    else
      return false
    end
  end

Any regex experts out there that can provide feedback? Thanks

UPDATED:

controller:

  def create

    @user = User.new

    # User EmailVeracity to validate the email address
    email = EmailVeracity::Address.new(params[:user][:email])

    Rails.logger.info 'Email Check Result'
Rails.logger.info valid_email_domain(params[:user][:email])
    Rails.logger.info 'Email Check Result'

    if email.valid?
      Rails.logger.info 'Sign this email up'
    else
      Rails.logger.info 'Bad email, dont touch that'
    end

    respond_to do |format|
      format.html
      format.js
    end

  end
protected

  def valid_email_domain(emailAddy)
    !(emailAddy =~ /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/)
  end

User Model:

INVALID_EMAILS = %w(gmail.com googlemail.com yahoo.com ymail.com rocketmail.com hotmail.com facebook.com)

Body:
You're making this way too complicated. This should be enough:

def valid_email_domain(email_address)
  !(email_address =~ /#{INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/)
end


问:
list adapter shows null on debug android
I have a listview to populate some data from a static arraylist of class Common.the list adapter shows null on debugging.I am using ArrayAdapter and I saw a lot of solutions on stack but still the same issue.please help me

my code where I am calling the adapter

```<code>    displayListAdapter = new DisplayListAdapter(this);
    listView_contacts.setAdapter(displayListAdapter);
</code>```

my adapter class

```<code>public class DisplayListAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private Context context;
FragmentTransaction ft;
int clickedPosition;
String displayContacts,displayContactNumber;
private WebServiceCoordinator mWebServiceCoordinator;
TextView name_contactList;
Button call_contact;

public DisplayListAdapter(Context context) {
    super(context, R.layout.contacts_list1_row);
    this.mInflater = LayoutInflater.from(context);
    this.context = context;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.contacts_list1_row, parent, false);

    name_contactList = (TextView) rowView.findViewById(R.id.contactlist_name);
    call_contact = (Button) rowView.findViewById(R.id.contactlist_call);
    try {
        //if(Common.FLAG_contactsLoaded)
        //{
        displayContacts = Common.selectedContactName.get(position);
        displayContactNumber = Common.selectedContactNos.get(position);
        //}
            /*else {
                displayContacts = ((DisplayContacts) context).selectedContactName.get(position);
                displayContactNumber = ((DisplayContacts) context).selectedContactNos.get(position);
            }*/
        //String displayContacts = Common.selectedContactName.get(position);
        //String displayContactNumber = Common.selectedContactNos.get(position);
        Toast.makeText(context, "name to display" + displayContacts, Toast.LENGTH_SHORT).show();
        Toast.makeText(context, "no.to display" + displayContactNumber, Toast.LENGTH_SHORT).show();
        //name_contactList.setText(((DisplayContacts) context).selectedContactName.get(position));
        name_contactList.setText(displayContacts);
        //name_contactList.setText("dummy text");
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Log.i("populating error",e.getLocalizedMessage());
    }
    return rowView;
}

}
</code>```

答:
Did you add data to your adapter? I didn't see any code related to it.

You should write like:

```<code>displayListAdapter = new DisplayListAdapter(this);
displayListAdapter.add("1");
displayListAdapter.add("2");
</code>```

or using

```<code>super(context, R.layout.contacts_list1_row, "your data list")
</code>```

constructor instead of

```<code>super(context, R.layout.contacts_list1_row);
</code>```

hope that may help :)

Body:
I have a listview to populate some data from a static arraylist of class Common.the list adapter shows null on debugging.I am using ArrayAdapter and I saw a lot of solutions on stack but still the same issue.please help me

my code where I am calling the adapter

    displayListAdapter = new DisplayListAdapter(this);
    listView_contacts.setAdapter(displayListAdapter);

my adapter class

public class DisplayListAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private Context context;
FragmentTransaction ft;
int clickedPosition;
String displayContacts,displayContactNumber;
private WebServiceCoordinator mWebServiceCoordinator;
TextView name_contactList;
Button call_contact;

public DisplayListAdapter(Context context) {
    super(context, R.layout.contacts_list1_row);
    this.mInflater = LayoutInflater.from(context);
    this.context = context;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.contacts_list1_row, parent, false);

    name_contactList = (TextView) rowView.findViewById(R.id.contactlist_name);
    call_contact = (Button) rowView.findViewById(R.id.contactlist_call);
    try {
        //if(Common.FLAG_contactsLoaded)
        //{
        displayContacts = Common.selectedContactName.get(position);
        displayContactNumber = Common.selectedContactNos.get(position);
        //}
            /*else {
                displayContacts = ((DisplayContacts) context).selectedContactName.get(position);
                displayContactNumber = ((DisplayContacts) context).selectedContactNos.get(position);
            }*/
        //String displayContacts = Common.selectedContactName.get(position);
        //String displayContactNumber = Common.selectedContactNos.get(position);
        Toast.makeText(context, "name to display" + displayContacts, Toast.LENGTH_SHORT).show();
        Toast.makeText(context, "no.to display" + displayContactNumber, Toast.LENGTH_SHORT).show();
        //name_contactList.setText(((DisplayContacts) context).selectedContactName.get(position));
        name_contactList.setText(displayContacts);
        //name_contactList.setText("dummy text");
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Log.i("populating error",e.getLocalizedMessage());
    }
    return rowView;
}

}

Body:
Did you add data to your adapter? I didn't see any code related to it.

You should write like:

displayListAdapter = new DisplayListAdapter(this);
displayListAdapter.add("1");
displayListAdapter.add("2");

or using

super(context, R.layout.contacts_list1_row, "your data list")

constructor instead of

super(context, R.layout.contacts_list1_row);

hope that may help :)


问:
PHP Regex replace all instances of a character in similar strings
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

```<code>Data_*: " ... "
</code>```

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

```<code>Data_83: "He said, "Yes!" to the question"
</code>```

to become this...

```<code>Data_83: "He said, Yes! to the question"
</code>```

I am familiar with PHP and would like to use this. I know how to do something like...

```<code><?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);
</code>```

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

```<code><?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}
</code>```

答:
One more step after str_replace with implode and explode. You can just do it like this.

```<code><?php
$string = 'Data_83: "He said, "Yes!" to the question"';
$string = str_replace('"', '', $string);
echo $string =implode(': "',explode(': ',$string)).'"';
?>
</code>```

Demo : https://eval.in/912466

Program Output

```<code>Data_83: "He said, Yes! to the question"
</code>```

Just to replace " quotes

```<code><?php
$string = 'Data_83: "He said, "Yes!" to the question"';
echo preg_replace('/"/', '', $string);
?>
</code>```

Demo : https://eval.in/912457

Body:
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

Data_*: " ... "

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

Data_83: "He said, "Yes!" to the question"

to become this...

Data_83: "He said, Yes! to the question"

I am familiar with PHP and would like to use this. I know how to do something like...

<?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

<?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}

Body:
One more step after str_replace with implode and explode. You can just do it like this.

<?php
$string = 'Data_83: "He said, "Yes!" to the question"';
$string = str_replace('"', '', $string);
echo $string =implode(': "',explode(': ',$string)).'"';
?>

Demo : https://eval.in/912466

Program Output

Data_83: "He said, Yes! to the question"

Just to replace " quotes

<?php
$string = 'Data_83: "He said, "Yes!" to the question"';
echo preg_replace('/"/', '', $string);
?>

Demo : https://eval.in/912457


问:
Converting a C-style string to a C++ std::string
What is the best way to convert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?

答:
Check the different constructors of the string class: documentation
You maybe interested in:

```<code>//string(char* s)
std::string str(cstring);
</code>```

And:

```<code>//string(char* s, size_t n)
std::string str(cstring, len_str);
</code>```

Body:
Check the different constructors of the string class: documentation
You maybe interested in:

//string(char* s)
std::string str(cstring);

And:

//string(char* s, size_t n)
std::string str(cstring, len_str);


问:
hadoop windows org.codehaus.mojo:exec-maven-plugin
I am trying to install hadoop on my windows machine.
I am following this guide: https://wiki.apache.org/hadoop/Hadoop2OnWindows
but when I have to execute this line:

```<code>mvn package -Pdist,native-win -DskipTests -Dtar
</code>```

I have this error:

[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:exec (com
pile-ms-winutils) on project hadoop-common: Command execution failed. Process ex
ited with an error: 1(Exit value: 1) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionE
xception```

I already read this post build hadoop 2.2 on windows
but I am not able to understand how to solve.

Thank you in advance for your help.

Alex

答:
If you are using recent versions of Hadoop, i.e. Hadoop-2.8, or 2.7 then there is no need to built the Hadoop-src using Maven, there is an easy way to configure (higher versions) Hadoop in windows.

Download & Install Java in c:/java/

make sure the path is this way, if java is installed in program
  files, then hadoop-env.cmd will not recognize java path

Download Hadoop binary distribution.

I am using binary distribution Hadoop-2.8.1

Set Environment Variables:

```<code>JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"
</code>```

Hadoop will work on windows if Hadoop-src is built using maven in
  your windows machine. Building the Hadoop-src(distribution) will
  create a Hadoop binary distribution, which will work as windows native
  version.

But if you don't want to do that, then download pre-builted winutils of Hadoop distribution.
Here is a GitHub link, which has winutils of some versions of Hadoop.

if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link & set JAVA_HOME path in hadoop-env.cmd file

From cmd go to:

```<code><HADOOP_HOME>/bin/> hdfs namenode -format
<HADOOP_HOME>/sbin> start-all.cmd
</code>```

Hope this helps.

Body:
I am trying to install hadoop on my windows machine.
I am following this guide: https://wiki.apache.org/hadoop/Hadoop2OnWindows
but when I have to execute this line:

mvn package -Pdist,native-win -DskipTests -Dtar

I have this error:

[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:exec (com
pile-ms-winutils) on project hadoop-common: Command execution failed. Process ex
ited with an error: 1(Exit value: 1) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionE
xception

I already read this post build hadoop 2.2 on windows
but I am not able to understand how to solve.

Thank you in advance for your help.

Alex

Body:
If you are using recent versions of Hadoop, i.e. Hadoop-2.8, or 2.7 then there is no need to built the Hadoop-src using Maven, there is an easy way to configure (higher versions) Hadoop in windows.

Download & Install Java in c:/java/

make sure the path is this way, if java is installed in program
  files, then hadoop-env.cmd will not recognize java path

Download Hadoop binary distribution.

I am using binary distribution Hadoop-2.8.1

Set Environment Variables:

JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"

Hadoop will work on windows if Hadoop-src is built using maven in
  your windows machine. Building the Hadoop-src(distribution) will
  create a Hadoop binary distribution, which will work as windows native
  version.

But if you don't want to do that, then download pre-builted winutils of Hadoop distribution.
Here is a GitHub link, which has winutils of some versions of Hadoop.

if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link & set JAVA_HOME path in hadoop-env.cmd file

From cmd go to:

<HADOOP_HOME>/bin/> hdfs namenode -format
<HADOOP_HOME>/sbin> start-all.cmd

Hope this helps.