问:
How do I split a Text with 3 delimiters in SQL (Oracle) into multiple rows and columns?
I need to split a text like "Aa:One|Bb:Two,Three,Four|Cc:Five,Six" into rows and columns for the result to look like -

Col1    Col2

AA       One

Bb       Two

Bb       Three

Bb       Four

Cc       Five

Cc       Six

I have tried using

```<code>SELECT REGEXP_SUBSTR (str, '[^:]+', 1, 1)    AS COL1
      ,REGEXP_SUBSTR (str, '[^:]+', 1, 2)    AS COL2
FROM (SELECT REGEXP_SUBSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '[^|]+', 1, LEVEL) AS str
      FROM DUAL
      CONNECT BY INSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '|', 1, LEVEL - 1) > 0
      )
</code>```

But I could only create

Col1    Col2

Aa   One

Bb   Two,Three,Four

Cc Five,Six

I am not sure how to split it further with  comma(,) in Col2 into rows against the Col1 value's first occurrence

Any help in this regard would be greatly appreciated.

Thanks in advance! :-)

答:
I used the temp table logic 'WITH t AS ()' to create the result set with the below query -

```<code>WITH t AS (
SELECT TRIM(REGEXP_SUBSTR (str, '[^:]+', 1, 1))    AS tempCol1
  ,TRIM(REGEXP_SUBSTR (str, '[^:]+', 1, 2))    AS tempCol2
FROM (
  SELECT TRIM(REGEXP_SUBSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six|Dd:Seven, Eight, Nine, Ten', '[^|]+', 1, LEVEL)) str
  FROM DUAL
  CONNECT BY INSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six|Dd:Seven, Eight, Nine, Ten', '|', 1, LEVEL - 1) > 0)
)

SELECT DISTINCT(Col1)
   , Col2
FROM (
   SELECT t.tempCol1 AS Col1
     ,TRIM(REGEXP_SUBSTR(t.tempCol2, '[^,]+', 1, LEVEL)) Col2
   FROM t
   CONNECT BY INSTR(t.tempCol2, ',', 1, LEVEL - 1) > 0)
ORDER BY Col1, Col2
</code>```

Apparently, I had to use 'Distinct' for Col1 as the query would fetch duplicate rows.

Thanks all for the help ! :)

Body:
I need to split a text like "Aa:One|Bb:Two,Three,Four|Cc:Five,Six" into rows and columns for the result to look like -

Col1    Col2

AA       One

Bb       Two

Bb       Three

Bb       Four

Cc       Five

Cc       Six

I have tried using

SELECT REGEXP_SUBSTR (str, '[^:]+', 1, 1)    AS COL1
      ,REGEXP_SUBSTR (str, '[^:]+', 1, 2)    AS COL2
FROM (SELECT REGEXP_SUBSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '[^|]+', 1, LEVEL) AS str
      FROM DUAL
      CONNECT BY INSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '|', 1, LEVEL - 1) > 0
      )

But I could only create

Col1    Col2

Aa   One

Bb   Two,Three,Four

Cc Five,Six

I am not sure how to split it further with  comma(,) in Col2 into rows against the Col1 value's first occurrence

Any help in this regard would be greatly appreciated.

Thanks in advance! :-)

Body:
I used the temp table logic 'WITH t AS ()' to create the result set with the below query -

WITH t AS (
SELECT TRIM(REGEXP_SUBSTR (str, '[^:]+', 1, 1))    AS tempCol1
  ,TRIM(REGEXP_SUBSTR (str, '[^:]+', 1, 2))    AS tempCol2
FROM (
  SELECT TRIM(REGEXP_SUBSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six|Dd:Seven, Eight, Nine, Ten', '[^|]+', 1, LEVEL)) str
  FROM DUAL
  CONNECT BY INSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six|Dd:Seven, Eight, Nine, Ten', '|', 1, LEVEL - 1) > 0)
)

SELECT DISTINCT(Col1)
   , Col2
FROM (
   SELECT t.tempCol1 AS Col1
     ,TRIM(REGEXP_SUBSTR(t.tempCol2, '[^,]+', 1, LEVEL)) Col2
   FROM t
   CONNECT BY INSTR(t.tempCol2, ',', 1, LEVEL - 1) > 0)
ORDER BY Col1, Col2

Apparently, I had to use 'Distinct' for Col1 as the query would fetch duplicate rows.

Thanks all for the help ! :)


来源: stackexchange

问:
When using flexbox, is there a functional difference between
 and
I recognize that a
 and a  are displayed differently in a most contexts. They also imply two different structural purposes for an element. But from what I can tell, when using flexbox, elements are displayed the same way, whether they have a
 or a  tag.

Assuming that the these two elements have the same styling, are there any visual differences between between them or will they always act the same when using flex?

答: I have found it is generally best to use block (e.g. div) or inline-block elements as children of flexbox instead of inline elements (e.g. span). You will probably not see a difference in most scenarios, but certain browsers (especially IE) have issue displaying inline elements correctly when they are flex items. See https://github.com/philipwalton/flexbugs#12-inline-elements-are-not-treated-as-flex-items and issues logged there.</p>

ContentLicense: CC BY-SA 3.0

Title: When using flexbox, is there a functional difference between <div> and <span>


问:
Find and extract a number from a string
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

```<code>string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
</code>```

How can I do this?

答:
You can also try this</p>

```<code>string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
</code>```

Title: Find and extract a number from a string

Body:
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

How can I do this?

Body:
You can also try this

string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));


问:
Why does instantiating a new FileHandler not work in my java program?
I'm trying to create my own logging class by using java.util.logging.  Part of this class allows the caller to specify a log file using the FileHandler class.  However, I can't seem to get one of my methods to create a new FileHandler object. Here is basically what I have:

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.FileHandler;

```<code>public class myLogger {
  private FileHandler logFileHdl = null;

  ...
  public void setLogFilename(String filename) {
     this.logFileHdl = new FileHandler(filename)
     ...
  }
</code>```

When I run this I get:  "java: unreported exception java.io.IOException".

I also get this same error if I get rid of the setLogFilename method and just try to create new FileHandler object when I declare the logFileHdl attribute like:

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.FileHandler;

```<code>public class myLogger {
  private FileHandler logFileHdl = new FileHandler();
</code>```

I'm not sure why.

答: Ok, so question was because I am a Java newbie.  Apparently because the FileHandler constructor can throw an IOException, I am forced to handle the exception (or declare that I my class can throw that exception.)  I didn't realized that was the case.  So if I add a "try/catch" for IOException then the error goes away.</p>

Body:
I'm trying to create my own logging class by using java.util.logging.  Part of this class allows the caller to specify a log file using the FileHandler class.  However, I can't seem to get one of my methods to create a new FileHandler object. Here is basically what I have:

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.FileHandler;

public class myLogger {
  private FileHandler logFileHdl = null;

  ...
  public void setLogFilename(String filename) {
     this.logFileHdl = new FileHandler(filename)
     ...
  }

When I run this I get:  "java: unreported exception java.io.IOException".

I also get this same error if I get rid of the setLogFilename method and just try to create new FileHandler object when I declare the logFileHdl attribute like:

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.FileHandler;

public class myLogger {
  private FileHandler logFileHdl = new FileHandler();

I'm not sure why.


问:
jQuery .eq(index) vs [index] if both return an object?
I'm having some trouble distinguishing why exactly one method works and the other one doesn't. I have a workable solution by using .eq() but wanted to understand properly why I can't call the .css method using the [] notation if it still returns an object?

Here is my test code, tried to figure it out myself:

```<code>$('.slider').each(function() {
  var $slides = $('.slide');

  console.log(jQuery.type($slides.eq(1)));
  console.log(jQuery.type($slides[2]));

  $slides.eq(1).css( {color: 'red'} );
  $slides[2].css( {color: 'red'} );
});
</code>```

console logs tell me that both selectors are returning an object. So why do I get a typeError on the [] notation like it isn't an object?

Appreciate any clarification.

Thanks,

答:
The array syntax returns an object but if you want to access JQuery functions on it you will need to call $(object) on it, where .eq() returns a JQuery object.  For example:

console.log('By eq:', $('button').eq(0).text())
console.log('By Array as a JQuery Object', $( $('button')[0]).text())
try {
  console.log('By Array:', $('button')[0].text())
} catch(e) {
  console.log('You get an exception because the element doens\'t have a  property named text');
  console.log(e);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A button</button></code>```

Body:
I'm having some trouble distinguishing why exactly one method works and the other one doesn't. I have a workable solution by using .eq() but wanted to understand properly why I can't call the .css method using the [] notation if it still returns an object?

Here is my test code, tried to figure it out myself:

$('.slider').each(function() {
  var $slides = $('.slide');

  console.log(jQuery.type($slides.eq(1)));
  console.log(jQuery.type($slides[2]));

  $slides.eq(1).css( {color: 'red'} );
  $slides[2].css( {color: 'red'} );
});

console logs tell me that both selectors are returning an object. So why do I get a typeError on the [] notation like it isn't an object?

Appreciate any clarification.

Thanks,

Body:
The array syntax returns an object but if you want to access JQuery functions on it you will need to call $(object) on it, where .eq() returns a JQuery object.  For example:

console.log('By eq:', $('button').eq(0).text())
console.log('By Array as a JQuery Object', $( $('button')[0]).text())
try {
  console.log('By Array:', $('button')[0].text())
} catch(e) {
  console.log('You get an exception because the element doens\'t have a  property named text');
  console.log(e);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A button</button>


问:
C++ template class inheritance
I have been porting some C++ code, which was written long time ago, and is normally compiled with Visual C++ (Visual Studio 7.1 version) and Intel C++ Compiler 11.0, the target platform is Linux (Suse x86-64), with GCC 4.3.2 and Intel C++ Compiler 11.1

The problem is that code like this

FileA.h

```<code>template<typename T, int dim>
class A
{
 public:
  A(){};
  ~A(){};
 protected:
  void foo1(){};
}
</code>```

FileB.h

```<code>#include "FileA.h"
template<typename T>
class B : public A<T, 2>
{
 public:
  B(){};
  ~B(){};
  void foo(){ foo1(); }
}
</code>```

main.cpp

```<code>#include "FileB.h"
int main()
{
 B<float> b = B<float>();
}
</code>```

does not compile on Linux (Intel C++ 11.1, GCC 4.3.2), but perfectly compiles on Windows (Visual C++ 7.1, Intel C++ 11.0), althow it surely must not depend on platform.
GCC tells that if I change foo1() to foo1(T a) it will work (and it does), but I can not change the code, and have to use Intel C++ for final release.

I would be glad if anyone could help with any advice.

答:
On gcc 4.4.1 (os is Ubuntu) version I could turn the compile error into a compile warning, by using the -fpermissive option to the compiler.

Edit: The fact that some compiler accept it, doesn't mean it will continue to accept it in future versions.

ContentLicense: CC BY-SA 2.5

Title: C++ template class inheritance

Body:
I have been porting some C++ code, which was written long time ago, and is normally compiled with Visual C++ (Visual Studio 7.1 version) and Intel C++ Compiler 11.0, the target platform is Linux (Suse x86-64), with GCC 4.3.2 and Intel C++ Compiler 11.1

The problem is that code like this

FileA.h

template<typename T, int dim>
class A
{
 public:
  A(){};
  ~A(){};
 protected:
  void foo1(){};
}

FileB.h

#include "FileA.h"
template<typename T>
class B : public A<T, 2>
{
 public:
  B(){};
  ~B(){};
  void foo(){ foo1(); }
}

main.cpp

#include "FileB.h"
int main()
{
 B<float> b = B<float>();
}

does not compile on Linux (Intel C++ 11.1, GCC 4.3.2), but perfectly compiles on Windows (Visual C++ 7.1, Intel C++ 11.0), althow it surely must not depend on platform.
GCC tells that if I change foo1() to foo1(T a) it will work (and it does), but I can not change the code, and have to use Intel C++ for final release.

I would be glad if anyone could help with any advice.


问:
What are the steps to implement single sign on against Active Directory using LDAP?
I need to authenticate users against Active Directory in my C++ application. I know I need to bind to something and authenticate using the user's distinguished name and password. This distinguished name is often long with commas and contains the username.

Say the user enters something in my application's username and password box. How do I find the distinguished name to bind to? Do I have to write a search query for it?

答:
You need to:

Search the AD for the user's DN based on what he entered into your form, typically an email address or a user ID or something else that is unique. Unless the AD supports anonymous searching you will need to bind to it using an adminstrative account/password that has permission to do this search. THis is done via an LDAP filter expression, a topic which you need to look up.

When/if you've found it, rebind to AD using the DN of that entry and the password from the form.

If either step fails, the login fails, and don't tell the user which step it was, i.e. don't tell him 'no such user' or 'wrong password', just tell him 'bad credentials' or similar in both cases. Otherwise you are leaking information to the attacker.


问:
neutralize non-visible ASCII characters for printing ASCII table
I'm trying to write a short script (for a tutorial) to show which of the first 128 ASCII characters are printable, recognizable characters.

The following script using `is in string.printable' partially works, but is still triggering off of things like line feeds, etc.

Is there one or two more lines I can add to trap and replace these control characters with spaces so that the table looks nice and shows printable characters?

Written out longhand for noob-readability:

```<code>import string
lines = []
for i in range(8):
    line = []
    for j in range(16):
        k = i + j *16
        thing = chr(k)
        if thing not in string.printable:
            thing = ' '
        line.append(thing)
    lines.append(line)

for line in lines:
    print "".join(line)
</code>```

IDLE:

Copy/paste into SE including four spaces:

```<code>   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
         )9IYiy

 *:JZjz
 +;K[k{
 ,<L\l|
</code>```

-=M]m}
      .>N^n~
      /?O_o

答:
Updated code to replace unprintable characters as per OP's comment.

from string import printable, whitespace

replace_ch = ' '  # The character to replace non-printable characters with
whitespace_ch = ' '  # The character to replace whitespace characters with

# For console output
out_width = 8
out_height = 16

chars = [chr(i) for i in range(128)]
# Replace whitespace characters
chars = [whitespace_ch if c in whitespace else c for c in chars]
# Replace non-printable characters
chars = [c if c in printable else replace_ch for c in chars]
# Form lines for printing
lines = [[chars[i + j * out_height] for j in range(out_width)] for i in range(out_height)]

for line in lines:
    print(''.join(line))
```

<p>Outputs:</p>

```   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
  )9IYiy
  *:JZjz
  +;K[k{
  ,<L\l|
  -=M]m}
  .>N^n~
  /?O_o
```

An alternative is to simply avoid the first 32 characters of ASCII as they are defined as control characters. It may be more efficient to check the ord(c) of a character, c.

Body:
I'm trying to write a short script (for a tutorial) to show which of the first 128 ASCII characters are printable, recognizable characters.

The following script using `is in string.printable' partially works, but is still triggering off of things like line feeds, etc.

Is there one or two more lines I can add to trap and replace these control characters with spaces so that the table looks nice and shows printable characters?

Written out longhand for noob-readability:

import string
lines = []
for i in range(8):
    line = []
    for j in range(16):
        k = i + j *16
        thing = chr(k)
        if thing not in string.printable:
            thing = ' '
        line.append(thing)
    lines.append(line)

for line in lines:
    print "".join(line)

IDLE:

Copy/paste into SE including four spaces:

   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
         )9IYiy

 *:JZjz
 +;K[k{
 ,<L\l|

-=M]m}
      .>N^n~
      /?O_o

Body:
Updated code to replace unprintable characters as per OP's comment.

from string import printable, whitespace

replace_ch = ' '  # The character to replace non-printable characters with
whitespace_ch = ' '  # The character to replace whitespace characters with

# For console output
out_width = 8
out_height = 16

chars = [chr(i) for i in range(128)]
# Replace whitespace characters
chars = [whitespace_ch if c in whitespace else c for c in chars]
# Replace non-printable characters
chars = [c if c in printable else replace_ch for c in chars]
# Form lines for printing
lines = [[chars[i + j * out_height] for j in range(out_width)] for i in range(out_height)]

for line in lines:
    print(''.join(line))

Outputs:

   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
  )9IYiy
  *:JZjz
  +;K[k{
  ,<L\l|
  -=M]m}
  .>N^n~
  /?O_o

An alternative is to simply avoid the first 32 characters of ASCII as they are defined as control characters. It may be more efficient to check the ord(c) of a character, c.


问:
wordpress get url of registered script
If I register a script or style (using wp_register_script() or wp_register_style()), is there a way I can get the URL of that script/style?

(If you must know why, I'm trying to put those URL's into another function that generates prefetch link tags so I can prefetch certain scripts/styles for a performance boost in my site.)

答:
You can use wp_scripts() to get the instance of the WP_Scripts class which contains the registered scripts (this class extends WP_Dependencies).

Basically, try looking in:

```<code>$wp_scripts = wp_scripts();
var_dump( $wp_scripts->registered );
var_dump( $wp_scripts );
</code>```

Title: wordpress get url of registered script

Body:
You can use wp_scripts() to get the instance of the WP_Scripts class which contains the registered scripts (this class extends WP_Dependencies).

Basically, try looking in:

$wp_scripts = wp_scripts();
var_dump( $wp_scripts->registered );
var_dump( $wp_scripts );


问:
Why does Python's IDLE crash when I type a parenthesis on Mac?
Ok, I realize this may be an extremely nuanced question, but it has been bugging me for a while.  I like the simple scripting interface of IDLE, but it keeps crashing on me when: (1) I am coding on an external monitor and (2) I type the parenthesis button, "(". IDLE never crashes for me for any other reason than this very specific situation.  Strangely, if I have an external monitor connected, but I have the IDLE dev window on my laptop's main screen, I have ZERO problems with crashing. (???) I have lost a substantial amount of code due to this problem.

I am running on Mac OSX Version 10.11.3 and I have a MacBook Pro (Retina, 15-inch, Mid 2015)  Any thoughts would be appreciated!

答:
I found a fix! One that doesn't require changing monitor settings.

In IDLE:

Options Menu > Configure Extensions > CallTips > set to FALSE

Then restart.

Took much research to find that super simple solution... the problem is caused not by an error in IDLE but by an error in the mac's Tcl/Tk code when calltips are called in external monitors above the default monitor.


问:
HttpClient PostAsycn Always returns 404 Not Found but controller works with Postman and Javascript application
I have a Post Web Api Method in a controller and it's already working, I've been testing the method sending file from postman and a my own web application and it works but now I'm trying to send file from console application using Httpclient but always get 404.

Controller Method

```<code>public async Task<IHttpActionResult> Post()
    {
        FileServerConfig config = FileServerConfiguration.ObtenerConfiguracion(ConfigurationManager.AppSettings);

        var path = string.Empty;
        try
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return StatusCode(HttpStatusCode.UnsupportedMediaType);
            }

            var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

            foreach (var stream in filesReadToProvider.Contents)
            {
                IFileServerWrapper _cliente = FileServerConfiguration.CrearCliente(config);
                var name = stream.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\\", "");
                var fileUploaded = await _cliente.FileUpload(path, await stream.ReadAsStreamAsync(), name, false);
            }
            return Ok();
        }
        catch (HttpException httpex)
        {
            if (httpex.GetHttpCode() == (int)HttpStatusCode.Conflict)
            {
                return Conflict();
            }
            else
            {
                return InternalServerError(httpex);
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

    }
</code>```

Console application

```<code>static void Main(string[] args)
    {
        string filePath = @"C:\Software\itextTifftoPDF.rar";
        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            // Make sure to change API address
            //client.BaseAddress = new Uri("http://localhost:80/FileServerAPI/");
            client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6,ru;q=0.4");
            client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            // Add first file content
            var fileContent1 = new ByteArrayContent(File.ReadAllBytes(filePath));
            fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = "itextTifftoPDF.rar"
            };

            content.Add(fileContent1);

            // Make a call to Web API
            var result = client.PostAsync("http://localhost/FileServerAPI/api/File", content).Result;

            Console.WriteLine(result.StatusCode);
            Console.ReadLine();
        }
    }
</code>```

答:
Finally I found a solution. the code is ugly because it was made just to be sure it works but I'll hope it may help others with the same problem.</p>

```<code>string filePath = @"C:\temp\webdavtest.txt";
        using (HttpClient httpClient = new HttpClient())
        {
            using (MultipartFormDataContent content =
                             new MultipartFormDataContent())
            {
                using (FileStream stream = File.Open(
                      filePath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamContent streamConent =
                                        new StreamContent(stream))
                    {
                        content.Add(
                        streamConent, "webdavtest.txt", "webdavtest.txt");
                        var result = await httpClient.PostAsync("http://localhost:3983/api/File?path=/nivel5/", content);
                        return result.StatusCode.ToString();
                    }
                }
            }
        }
</code>```

Body:
I have a Post Web Api Method in a controller and it's already working, I've been testing the method sending file from postman and a my own web application and it works but now I'm trying to send file from console application using Httpclient but always get 404.

Controller Method

public async Task<IHttpActionResult> Post()
    {
        FileServerConfig config = FileServerConfiguration.ObtenerConfiguracion(ConfigurationManager.AppSettings);

        var path = string.Empty;
        try
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return StatusCode(HttpStatusCode.UnsupportedMediaType);
            }

            var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

            foreach (var stream in filesReadToProvider.Contents)
            {
                IFileServerWrapper _cliente = FileServerConfiguration.CrearCliente(config);
                var name = stream.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\\", "");
                var fileUploaded = await _cliente.FileUpload(path, await stream.ReadAsStreamAsync(), name, false);
            }
            return Ok();
        }
        catch (HttpException httpex)
        {
            if (httpex.GetHttpCode() == (int)HttpStatusCode.Conflict)
            {
                return Conflict();
            }
            else
            {
                return InternalServerError(httpex);
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

    }

Console application

static void Main(string[] args)
    {
        string filePath = @"C:\Software\itextTifftoPDF.rar";
        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            // Make sure to change API address
            //client.BaseAddress = new Uri("http://localhost:80/FileServerAPI/");
            client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6,ru;q=0.4");
            client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            // Add first file content
            var fileContent1 = new ByteArrayContent(File.ReadAllBytes(filePath));
            fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = "itextTifftoPDF.rar"
            };

            content.Add(fileContent1);

            // Make a call to Web API
            var result = client.PostAsync("http://localhost/FileServerAPI/api/File", content).Result;

            Console.WriteLine(result.StatusCode);
            Console.ReadLine();
        }
    }

Body:
Finally I found a solution. the code is ugly because it was made just to be sure it works but I'll hope it may help others with the same problem.

string filePath = @"C:\temp\webdavtest.txt";
        using (HttpClient httpClient = new HttpClient())
        {
            using (MultipartFormDataContent content =
                             new MultipartFormDataContent())
            {
                using (FileStream stream = File.Open(
                      filePath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamContent streamConent =
                                        new StreamContent(stream))
                    {
                        content.Add(
                        streamConent, "webdavtest.txt", "webdavtest.txt");
                        var result = await httpClient.PostAsync("http://localhost:3983/api/File?path=/nivel5/", content);
                        return result.StatusCode.ToString();
                    }
                }
            }
        }


问:
Adding data from multiple check boxes to cell
I've seen some similar posts to this one but I'm not 100% sure how to make it work for my existing UserForm.  What I have is 5 check boxes that if checked will enter data to the cell, including if multiple boxes are checked.  So if HU and OS are checked it will read something like HU,OS.

The form right now adds information to a new line and I would like for it to continue doing that. I've tried some of the other methods I've seen but they don't seem to work with my very basic coding here.   Below are screenshots of the form and the coding.

Coding:

```<code>Private Sub CommandButton1_Click()

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Cells(emptyRow, 1).Value = Position.Value
Cells(emptyRow, 2).Value = Time.Value
Cells(emptyRow, 3).Value = Callpriority.Value

If CellCB.Value = True Then Cells(emptyRow, 4).Value = Cells(emptyRow, 4).Value & "Yes"

Cells(emptyRow, 5).Value = Calltype.Value
Cells(emptyRow, 6).Value = Transferto.Value

If HUCB.Value = True Then Cells(emptyRow, 7).Value = HUCB.Caption

If OSCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & OSCB.Caption

If CBCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & CBCB.Caption

If SCCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & SCCB.Caption

If TestCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & TestCB.Caption

Cells(emptyRow, 8).Value = Code.Value
Cells(emptyRow, 9).Value = Phonenumber.Value
Cells(emptyRow, 10).Value = Comments.Value

ActiveWorkbook.Save

End Sub

Private Sub CommandButton2_Click()

Application.ScreenUpdating = False
Unload Me
Testlog.Show
Application.ScreenUpdating = True

End Sub

Private Sub CommandButton3_Click()

Unload Me

End Sub

Private Sub UserForm_Initialize()

'Fill Position
With Position
    .AddItem "Police A"
    .AddItem "Police B"
    .AddItem "Fire A"
    .AddItem "Fire B"
    .AddItem "Trainer"
    .AddItem "Supervisor"
End With

'Empty Time
Time.Value = ""

'Fill Callpriority
With Callpriority
    .AddItem "Non-Emergency"
    .AddItem "Emergency"
    .AddItem "Unknown"
End With

'Fill Calltype
With Calltype
    .AddItem "Police"
    .AddItem "Fire"
    .AddItem "Medical"
End With

'Empty Transferto
Transferto.Value = ""

'Uncheck DataCheckBoxes
HUCB.Value = False
OSCB.Value = False
CBCB.Value = False
SCCB.Value = False
TestCB.Value = False
CellCB.Value = False

'Fill Code
With Code
    .AddItem "1"
    .AddItem "2"
    .AddItem "3"
    .AddItem "4"
    .AddItem "5"
    .AddItem "6"
    .AddItem "7"
    .AddItem "8"
    .AddItem "9"
    .AddItem "10"
End With

'Empty Phonenumber
Phonenumber.Value = ""

'Empty Comments
Comments.Value = ""

End Sub
</code>```

Log and Form

Form

答:
```<code>Dim sDisposition As String

Dim aaa As String
Dim bbb As String
Dim ccc As String
Dim ddd As String
Dim eee As String

aaa = ""
bbb = ""
ccc = ""
ddd = ""
eee = ""

If HUCB.Value Then aaa = HUCB.Caption        ' do not use   If true = true then ...
If OSCB.Value Then bbb = OSCB.Caption        ' just use     If true then ...
If CBCB.Value Then ccc = CBCB.Caption
If SCCB.Value Then ddd = SCCB.Caption
If TestCB.Value Then eee = TestCB.Caption

sDisposition = aaa & " " & bbb & " " & ccc & " " & ddd & " " & eee    ' concatenate string values

Cells(emptyRow, 7).Value = sDisposition

' or do not use sDisposition and do this
Cells(emptyRow, 7).Value = aaa & " " & bbb & " " & ccc & " " & ddd & " " & eee
</code>```

Body:
I've seen some similar posts to this one but I'm not 100% sure how to make it work for my existing UserForm.  What I have is 5 check boxes that if checked will enter data to the cell, including if multiple boxes are checked.  So if HU and OS are checked it will read something like HU,OS.

The form right now adds information to a new line and I would like for it to continue doing that. I've tried some of the other methods I've seen but they don't seem to work with my very basic coding here.   Below are screenshots of the form and the coding.

Coding:

Private Sub CommandButton1_Click()

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Cells(emptyRow, 1).Value = Position.Value
Cells(emptyRow, 2).Value = Time.Value
Cells(emptyRow, 3).Value = Callpriority.Value

If CellCB.Value = True Then Cells(emptyRow, 4).Value = Cells(emptyRow, 4).Value & "Yes"

Cells(emptyRow, 5).Value = Calltype.Value
Cells(emptyRow, 6).Value = Transferto.Value

If HUCB.Value = True Then Cells(emptyRow, 7).Value = HUCB.Caption

If OSCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & OSCB.Caption

If CBCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & CBCB.Caption

If SCCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & SCCB.Caption

If TestCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & TestCB.Caption

Cells(emptyRow, 8).Value = Code.Value
Cells(emptyRow, 9).Value = Phonenumber.Value
Cells(emptyRow, 10).Value = Comments.Value

ActiveWorkbook.Save

End Sub

Private Sub CommandButton2_Click()

Application.ScreenUpdating = False
Unload Me
Testlog.Show
Application.ScreenUpdating = True

End Sub

Private Sub CommandButton3_Click()

Unload Me

End Sub

Private Sub UserForm_Initialize()

'Fill Position
With Position
    .AddItem "Police A"
    .AddItem "Police B"
    .AddItem "Fire A"
    .AddItem "Fire B"
    .AddItem "Trainer"
    .AddItem "Supervisor"
End With

'Empty Time
Time.Value = ""

'Fill Callpriority
With Callpriority
    .AddItem "Non-Emergency"
    .AddItem "Emergency"
    .AddItem "Unknown"
End With

'Fill Calltype
With Calltype
    .AddItem "Police"
    .AddItem "Fire"
    .AddItem "Medical"
End With

'Empty Transferto
Transferto.Value = ""

'Uncheck DataCheckBoxes
HUCB.Value = False
OSCB.Value = False
CBCB.Value = False
SCCB.Value = False
TestCB.Value = False
CellCB.Value = False

'Fill Code
With Code
    .AddItem "1"
    .AddItem "2"
    .AddItem "3"
    .AddItem "4"
    .AddItem "5"
    .AddItem "6"
    .AddItem "7"
    .AddItem "8"
    .AddItem "9"
    .AddItem "10"
End With

'Empty Phonenumber
Phonenumber.Value = ""

'Empty Comments
Comments.Value = ""

End Sub

Log and Form

Form


问:
iOS entitlements where is it stored inside the .app
I have an iOS app and I couldn't find entitlements.plist or somethig inside the app but I can find info.plist and the contents of entitlements are not there too.

when I run the below command in terminal I am getting the entitlements.

```<code>codesign -d --entitlements - test.app
</code>```

so Where is it stored ?

Its definitely not stored in info.plist I checked it out.

Help me understand where is it ?

答:
Inside embedded.mobileprobision under the 'Entitlements' key.

In addition, The Mach-O executable (stored inside the IPA archive) may have an embedded copy of the entitlements dictionary.

p.s. Apple's Technical Note TN2415 specify: "When a profile is used for code signing, Xcode transfers the profile's associated entitlements to the resulting code signature of the .app".

Body:
I have an iOS app and I couldn't find entitlements.plist or somethig inside the app but I can find info.plist and the contents of entitlements are not there too.

when I run the below command in terminal I am getting the entitlements.

codesign -d --entitlements - test.app

so Where is it stored ?

Its definitely not stored in info.plist I checked it out.

Help me understand where is it ?


问:
Javascript keyup call other table value
I have a table like this:

```<code><tbody id="invoice_item">
<tr>
<td><input name='qty[]' type='text' class='form-control form-control-sm qty' value='0'></td>
        <td><input name='price[]' type='text' class='form-control form-control-sm price' value='0'></td>
        <td><input name='sub_total[]' type='text' class='form-control form-control-sm sub_total' value='0' readonly></td>
</tr>
</tbody>
</code>```

I want to make Javascript when qty/price change subtotal changed too.
My js:

```<code> $("#invoice_item").delegate(".qty","keyup",function(){
    var qty = $(this).val();
    var price = tr.find(".price").val();
    alert(price);
    var sub_total = qty * price;
    alert(sub_total);
    tr.find(".sub_total").html(sub_total);

    })
    $("#invoice_item").delegate(".price","keyup",function(){
      var price = $(this).val();
      var qty = tr.find(".qty").val();
      alert(qty);

      })
</code>```

It seems the trouble is tr.find(".").val();.
I try to alert it, but no use.. anyone can help? How I can call the other input?
$(this).val(); is no problem.

答:
delegate() is deprecated in v 3.0. Which jquery are you using?

You can attach the events to the input tags themselves using the new on method, like so:

```<code>$(".qty").on("keyup",function(){}
</code>```

To get the other input value you can use this:

```<code>$(".price").val()
</code>```

Title: Javascript keyup call other table value

Body:
I have a table like this:

<input name='qty[]' type='text' class='form-control form-control-sm qty' value='0'>
        <input name='price[]' type='text' class='form-control form-control-sm price' value='0'>
        <input name='sub_total[]' type='text' class='form-control form-control-sm sub_total' value='0' readonly>

I want to make Javascript when qty/price change subtotal changed too.
My js:

 $("#invoice_item").delegate(".qty","keyup",function(){
    var qty = $(this).val();
    var price = tr.find(".price").val();
    alert(price);
    var sub_total = qty * price;
    alert(sub_total);
    tr.find(".sub_total").html(sub_total);

    })
    $("#invoice_item").delegate(".price","keyup",function(){
      var price = $(this).val();
      var qty = tr.find(".qty").val();
      alert(qty);

      })

It seems the trouble is tr.find(".").val();.
I try to alert it, but no use.. anyone can help? How I can call the other input?
$(this).val(); is no problem.

Body:
delegate() is deprecated in v 3.0. Which jquery are you using?

You can attach the events to the input tags themselves using the new on method, like so:

$(".qty").on("keyup",function(){}

To get the other input value you can use this:

$(".price").val()


问:
Using Static methods or none static methods in Dao Class?
Hi I generate Dao classes for some DB operations

in this manner making methods of Dao class  as static or none static is better?

Using sample dao class below ,İf more than one client got to use the AddSampleItem method in same time?how this may result?

```<code>public class SampleDao
{
  static DataAcessor dataAcessor

  public static void AddSampleItem(object[] params)
  {
      dataAcessor =new DataAcessor();
       //generate query here
       string query="..."
      dataAcessor.ExecuteQery(query);
      dataAcessor.Close();
   }

  public static void UpdateSampleItem(object[] params)
  {
      dataAcessor =new DataAcessor();
       //generate query here
       string query="..."
      dataAcessor.ExecuteQery(query);
      dataAcessor.Close();
   }
}
</code>```

答: Bruno is correct. However, you could also add a singleton and use "lock" to single-thread that part of your app. Keep in mind, though, that requests are going to queue up and if your query takes time your app's performance will degrade. This is especially noticeable in a web app. For a mobile or desktop app "lock" is definitely appropriate.</p>

Body:
Hi I generate Dao classes for some DB operations

in this manner making methods of Dao class  as static or none static is better?

Using sample dao class below ,İf more than one client got to use the AddSampleItem method in same time?how this may result?

public class SampleDao
{
  static DataAcessor dataAcessor

  public static void AddSampleItem(object[] params)
  {
      dataAcessor =new DataAcessor();
       //generate query here
       string query="..."
      dataAcessor.ExecuteQery(query);
      dataAcessor.Close();
   }

  public static void UpdateSampleItem(object[] params)
  {
      dataAcessor =new DataAcessor();
       //generate query here
       string query="..."
      dataAcessor.ExecuteQery(query);
      dataAcessor.Close();
   }
}


问:
Angular 2 unit test case using Function not provider
I am using a function in my actual service but I want to know how can i inject that function in unit test case. Below isSameDay is a function not provider. How can i inject it into test case as this function is working fine in actual service.

```<code>import { LoggerService, isSameDay } from '../../../shared';

describe('NavBaseComponent', () => {
  let component: NavBaseComponent;
  let fixture: ComponentFixture<NavBaseComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [NavBaseComponent],
      providers: [
        LoggerService
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NavBaseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

Code for isSameDay function

```<code>export function isSameDay(d1: Date, d2: Date): boolean {
    return !!d1 && !!d2 &&
        d1.getDate() === d2.getDate() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getFullYear() === d2.getFullYear();
};
</code>```

答:
If I were you, I would use a stub service like
providers:    [ {provide: UserService, useValue: userServiceStub } ]

and you can get it like this
userService = fixture.debugElement.injector.get(UserService); or userService = TestBed.get(UserService);

For example:

```<code>TestBed.configureTestingModule({
     declarations: [ WelcomeComponent ],
     providers:    [ {provide: UserService, useValue: userServiceStub } ]
  });

  fixture = TestBed.createComponent(WelcomeComponent);
  comp    = fixture.componentInstance;

  // UserService from the root injector
  userService = TestBed.get(UserService);
  ...
</code>```

Body:
I am using a function in my actual service but I want to know how can i inject that function in unit test case. Below isSameDay is a function not provider. How can i inject it into test case as this function is working fine in actual service.

import { LoggerService, isSameDay } from '../../../shared';

describe('NavBaseComponent', () => {
  let component: NavBaseComponent;
  let fixture: ComponentFixture<NavBaseComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [NavBaseComponent],
      providers: [
        LoggerService
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NavBaseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});

Code for isSameDay function

export function isSameDay(d1: Date, d2: Date): boolean {
    return !!d1 && !!d2 &&
        d1.getDate() === d2.getDate() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getFullYear() === d2.getFullYear();
};

Body:
If I were you, I would use a stub service like
providers:    [ {provide: UserService, useValue: userServiceStub } ]

and you can get it like this
userService = fixture.debugElement.injector.get(UserService); or userService = TestBed.get(UserService);

For example:

TestBed.configureTestingModule({
     declarations: [ WelcomeComponent ],
     providers:    [ {provide: UserService, useValue: userServiceStub } ]
  });

  fixture = TestBed.createComponent(WelcomeComponent);
  comp    = fixture.componentInstance;

  // UserService from the root injector
  userService = TestBed.get(UserService);
  ...


问:
How do I exclude a directory when using `find`?
How do I exclude a specific directory when searching for *.js files using find?

```<code>find . -name '*.js'
</code>```

答:
-prune definitely works and is the best answer because it prevents descending into the dir that you want to exclude. -not -path which still searches the excluded dir, it just doesn't print the result, which could be an issue if the excluded dir is mounted network volume or you don't permissions.

The tricky part is that find is very particular about the order of the arguments, so if you don't get them just right, your command may not work. The order of arguments is generally as such:

```<code>find {path} {options} {action}
</code>```

{path}: Put all the path related arguments first, like . -path './dir1' -prune -o

{options}: I have the most success when putting -name, -iname, etc as the last option in this group. E.g. -type f -iname '*.js'

{action}: You'll want to add -print when using -prune

Here's a working example:

```<code># setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js

# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print

# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I exclude a specific directory when searching for *.js files using find?

find . -name '*.js'

Body:
-prune definitely works and is the best answer because it prevents descending into the dir that you want to exclude. -not -path which still searches the excluded dir, it just doesn't print the result, which could be an issue if the excluded dir is mounted network volume or you don't permissions.

The tricky part is that find is very particular about the order of the arguments, so if you don't get them just right, your command may not work. The order of arguments is generally as such:

find {path} {options} {action}

{path}: Put all the path related arguments first, like . -path './dir1' -prune -o

{options}: I have the most success when putting -name, -iname, etc as the last option in this group. E.g. -type f -iname '*.js'

{action}: You'll want to add -print when using -prune

Here's a working example:

# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js

# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print

# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print


问:
Should I manipulate data on a Laravel database migration? Or should I do it somewhere else?
I'm planning a major change to my database that will require a set of SQL instructions (and probably also a non-SQL script) to accommodate the old data to the new schema.

Now, is it a good idea to manipulate data on a migration script? Or is it just meant for schema (DB structure) changes?

答:
Two concerns are important when thinking about migrations.

speed: php usually has a timeout. What happens when your migration is 1/2 done?

running in the future: your app code might be different if you run this migration in a couple months.

Raw queries helps with both these issues.

```<code>$elements = DB::Select(DB::Raw('SELECT element_id FROM record GROUP BY element_id'));

foreach ($elements as $element)
{
    DB::Statement('
        INSERT INTO account (created_at, updated_at, name, element_id)
        VALUES (NOW(), NOW(), "Migrated account", '. $element->element_id .')
    ');
}
</code>```

Body:
Two concerns are important when thinking about migrations.

speed: php usually has a timeout. What happens when your migration is 1/2 done?

running in the future: your app code might be different if you run this migration in a couple months.

Raw queries helps with both these issues.

$elements = DB::Select(DB::Raw('SELECT element_id FROM record GROUP BY element_id'));

foreach ($elements as $element)
{
    DB::Statement('
        INSERT INTO account (created_at, updated_at, name, element_id)
        VALUES (NOW(), NOW(), "Migrated account", '. $element->element_id .')
    ');
}


问:
Angular 2+ Enter animation on child component works but leave does not
i have a sub component like this

```<code>@Component({
selector: 'is-time-controlled',
templateUrl: './is-time-controlled.html',
styleUrls: ['./is-time-controlled.less'],
animations: [
    trigger(
        'myAnimation',
        [
            transition(
                ':enter', [
                    style({ transform: 'translateX(100%)', opacity: 0 }),
                    animate('500ms', style({ transform: 'translateX(0)', 'opacity': 1 }))
                ]
            ),
            transition(
                ':leave', [
                    style({ transform: 'translateX(0)', opacity: 1 }),
                    animate('500ms', style({ transform: 'translateX(100%)', 'opacity': 0 }))
                ]
            )
        ]
    )
]
</code>```

})

and the sub component has a template with first div like this

```<code><div class="card card-padding" [@myAnimation]>
</code>```

parent component has *ngIf

```<code> <is-time-controlled  *ngIf="somelogic"> </is-time-controlled>
</code>```

when logic is true i see enter animation but when logic becomes false i dont see leaving animation.

i see various opened issues. do we have a fix for this?

答:
I suggest you to try like this:

```<code>animations: [trigger('myAnimation', [
            state('enter', style({
                transform: 'translateX(100%)';
                opacity: '0';
            })),
            state('leave', style({
                transform: 'translateX(0)';
                opacity: '1';
            })),
            transition('enter <=> leave', [animate(500)])
        ]
    )]
</code>```

This creates two states. All you have to do now is to create a variable to fetch the state, right after changing 'somelogic' to true/false

```<code>export class AppComponent implements OnInit {

    public state: string;
    public somelogic: boolean;

    function1(): any {
        this.somelogic = true;
        this.state = 'enter';
    }

    function2(): any {
        this.somelogic = false;
        this.state = 'leave';
    }
}
</code>```

In your HTML

```<code><div class="card card-padding" [@myAnimation]="state">
</code>```

Hope it helps

Body:
i have a sub component like this

@Component({
selector: 'is-time-controlled',
templateUrl: './is-time-controlled.html',
styleUrls: ['./is-time-controlled.less'],
animations: [
    trigger(
        'myAnimation',
        [
            transition(
                ':enter', [
                    style({ transform: 'translateX(100%)', opacity: 0 }),
                    animate('500ms', style({ transform: 'translateX(0)', 'opacity': 1 }))
                ]
            ),
            transition(
                ':leave', [
                    style({ transform: 'translateX(0)', opacity: 1 }),
                    animate('500ms', style({ transform: 'translateX(100%)', 'opacity': 0 }))
                ]
            )
        ]
    )
]

})

and the sub component has a template with first div like this

parent component has *ngIf

 <is-time-controlled  *ngIf="somelogic"> </is-time-controlled>

when logic is true i see enter animation but when logic becomes false i dont see leaving animation.

i see various opened issues. do we have a fix for this?

Body:
I suggest you to try like this:

animations: [trigger('myAnimation', [
            state('enter', style({
                transform: 'translateX(100%)';
                opacity: '0';
            })),
            state('leave', style({
                transform: 'translateX(0)';
                opacity: '1';
            })),
            transition('enter <=> leave', [animate(500)])
        ]
    )]

This creates two states. All you have to do now is to create a variable to fetch the state, right after changing 'somelogic' to true/false

export class AppComponent implements OnInit {

    public state: string;
    public somelogic: boolean;

    function1(): any {
        this.somelogic = true;
        this.state = 'enter';
    }

    function2(): any {
        this.somelogic = false;
        this.state = 'leave';
    }
}

In your HTML

<div class="card card-padding" [@myAnimation]="state">

Hope it helps


问:
jQuery countdown timer for minutes and seconds
I want create a jquery countdown timer, i tried as the following code but it does not work.what do i do?

DEMO: https://jsfiddle.net/tbosn210/

var interval = setInterval(function() {

    var timer2 = $("5:01");
    var timer = timer2.split(':');
    //by parsing integer, I avoid all extra string processing
    var minutes = parseInt(timer[0],10);
    var seconds = parseInt(timer[1],10);
    --seconds;
    minutes = (seconds < 0) ? --minutes : minutes;
    if (minutes < 0) clearInterval(interval);
    seconds = (seconds < 0) ? 59 : seconds;
    seconds = (seconds < 10) ? '0' + seconds : seconds;
    //minutes = (minutes < 10) ?  minutes : minutes;
    $('.countdown').html(minutes + ':' + seconds);
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div></code>```

答:
var timer2 = "5:01";
var interval = setInterval(function() {

  var timer = timer2.split(':');
  //by parsing integer, I avoid all extra string processing
  var minutes = parseInt(timer[0], 10);
  var seconds = parseInt(timer[1], 10);
  --seconds;
  minutes = (seconds < 0) ? --minutes : minutes;
  if (minutes < 0) clearInterval(interval);
  seconds = (seconds < 0) ? 59 : seconds;
  seconds = (seconds < 10) ? '0' + seconds : seconds;
  //minutes = (minutes < 10) ?  minutes : minutes;
  $('.countdown').html(minutes + ':' + seconds);
  timer2 = minutes + ':' + seconds;
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div></code>```

how can you make stop in oo oo  instead -1:59

Body:
var timer2 = "5:01";
var interval = setInterval(function() {

  var timer = timer2.split(':');
  //by parsing integer, I avoid all extra string processing
  var minutes = parseInt(timer[0], 10);
  var seconds = parseInt(timer[1], 10);
  --seconds;
  minutes = (seconds < 0) ? --minutes : minutes;
  if (minutes < 0) clearInterval(interval);
  seconds = (seconds < 0) ? 59 : seconds;
  seconds = (seconds < 10) ? '0' + seconds : seconds;
  //minutes = (minutes < 10) ?  minutes : minutes;
  $('.countdown').html(minutes + ':' + seconds);
  timer2 = minutes + ':' + seconds;
}, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>

how can you make stop in oo oo  instead -1:59


问:
Django Reverse Error: NoReverseMatch at
Hello StackOverFlow Members, before i get down to the point, let me retrace my thought/process here to help further slim down my issue. When i click a location object in "location_tree.html" it would redirect me to a new page, "location.html", displaying the location name and its type. From the very same page, the name would be a hyperlink to another page with more details about the "location".

Above is the general flow i want, but when i attempt to click the name from location.html, it redirects me to this error:

NoReverseMatch at /accounts/location/2/
  Reverse for 'continent' with keyword arguments '{u'pk': 2}' not found. 1 >pattern(s) tried: ['accounts/location/(?>P\d+)/location_continent/(?P\d+)/']

Some key things to note, i am using python2.7. Lastly, when i remove the {% url %} from location.html everything works perfectly fine.
Here is my working code,

App/models.py:

```<code>class Location(models.Model):
    title = models.CharField(max_length=255)
    location_type = models.CharField(max_length=255, choices=LOCATION_TYPES)
    parent = models.ForeignKey("Location", null=True, blank=True,
         related_name="parent_location")

    def __unicode__(self):
        return self.title

class Continent(models.Model):
    title = models.CharField(max_length=255)
    location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True)
    is_an_island = models.BooleanField(default=False)

    def __unicode__(self):
        return self.location.title
</code>```

App/views.py:

```<code>def view_page_location(request, location_id):
    location = Location.objects.get(id=location_id)
    if location.location_type == 'Continent':
        continent = Continent(location=location, is_an_island=False)
    return render(request, 'accounts/location.html', {'location':location, 'continent':continent})

def view_continent(request, pk):
    get_continent=get_object_or_404(Continent, pk)
    return render(request, 'accounts/location_continent.html', {'get_continent':get_continent})
</code>```

Project/urls.py:

```<code>from App.views import *

url(r'^accounts/location/(?P<location_id>\d+)/', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent'),
</code>```

Templates,

location_tree.html:

```<code>{% for child in locations %}
                {% if child.parent == location %}
                    <ul>
                        <a href="{% url 'location' location_id=child.id %}">{{ child }}</a>
</code>```

location.html:

```<code>{% if location.location_type == 'Continent' %}
    <h2> Location: <a href="{% url 'continent' pk=location.pk %}">{{ location.title }}</a></h2>
    <h3> Type: {{ location.location_type }} </h3></br>
</code>```

location_continent.html:

```<code><p> hello </p>
</code>```

I left location_continent pretty generic because i wanted to see if i can get it to work. I feel that something is wrong somewhere in my Urls.py or maybe i'm not properly constructing my views.py.

So the BIG question is, what changes/modifications do i need to alter in order to fix that error? I can't see it myself so i turn to 'you'. Any links for me to read up on and find the answer myself is appreciated as well. I hope my question is clear and not vague.

答:
Two issues.

Your continent url in the location.html doesn't provide location_id argument, you provided only pk. Change it to something like:

```<code><a href="{% url 'continent' location_id=location_id pk=location.pk %}">{{ location.title }}</a>
</code>```

In the urls.py, you must add $ at the end of the location url, else there is going to be confusion between location and continent urls. $ has a special meaning in regular expression and means that it requires that the pattern matches the end of the string. Change urls to:

```<code>url(r'^accounts/location/(?P<location_id>\d+)/$', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent')
</code>```

Title: Django Reverse Error: NoReverseMatch at

Body:
Hello StackOverFlow Members, before i get down to the point, let me retrace my thought/process here to help further slim down my issue. When i click a location object in "location_tree.html" it would redirect me to a new page, "location.html", displaying the location name and its type. From the very same page, the name would be a hyperlink to another page with more details about the "location".

Above is the general flow i want, but when i attempt to click the name from location.html, it redirects me to this error:

NoReverseMatch at /accounts/location/2/
  Reverse for 'continent' with keyword arguments '{u'pk': 2}' not found. 1 >pattern(s) tried: ['accounts/location/(?>P\d+)/location_continent/(?P\d+)/']

Some key things to note, i am using python2.7. Lastly, when i remove the {% url %} from location.html everything works perfectly fine.
Here is my working code,

App/models.py:

class Location(models.Model):
    title = models.CharField(max_length=255)
    location_type = models.CharField(max_length=255, choices=LOCATION_TYPES)
    parent = models.ForeignKey("Location", null=True, blank=True,
         related_name="parent_location")

    def __unicode__(self):
        return self.title

class Continent(models.Model):
    title = models.CharField(max_length=255)
    location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True)
    is_an_island = models.BooleanField(default=False)

    def __unicode__(self):
        return self.location.title

App/views.py:

def view_page_location(request, location_id):
    location = Location.objects.get(id=location_id)
    if location.location_type == 'Continent':
        continent = Continent(location=location, is_an_island=False)
    return render(request, 'accounts/location.html', {'location':location, 'continent':continent})

def view_continent(request, pk):
    get_continent=get_object_or_404(Continent, pk)
    return render(request, 'accounts/location_continent.html', {'get_continent':get_continent})

Project/urls.py:

from App.views import *

url(r'^accounts/location/(?P<location_id>\d+)/', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent'),

Templates,

location_tree.html:

{% for child in locations %}
                {% if child.parent == location %}

                        {{ child }}

location.html:

{% if location.location_type == 'Continent' %}

 Location: {{ location.title }}

 Type: {{ location.location_type }}

location_continent.html:

 hello

I left location_continent pretty generic because i wanted to see if i can get it to work. I feel that something is wrong somewhere in my Urls.py or maybe i'm not properly constructing my views.py.

So the BIG question is, what changes/modifications do i need to alter in order to fix that error? I can't see it myself so i turn to 'you'. Any links for me to read up on and find the answer myself is appreciated as well. I hope my question is clear and not vague.

Body:
Two issues.

Your continent url in the location.html doesn't provide location_id argument, you provided only pk. Change it to something like:

<a href="{% url 'continent' location_id=location_id pk=location.pk %}">{{ location.title }}</a>

In the urls.py, you must add $ at the end of the location url, else there is going to be confusion between location and continent urls. $ has a special meaning in regular expression and means that it requires that the pattern matches the end of the string. Change urls to:

url(r'^accounts/location/(?P<location_id>\d+)/$', view_page_location, name='location'),
url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent')


问:
How do I enable password complexity in batch
In windows local security policies there is a complexity requirement. I would like to be able to enable it in a batch-file that enables other password stuff like length, age, etc.

```<code>::this will change the minimum length of the password
net accounts /minpwlen:8
::this will change the maximum age of the password
net accounts /maxpwage:30
::this will change the minimum age of the password
net accounts /minpwage:5
::this will change the number of passwords stored
net accounts /uniquepw:5
</code>```

Above is most of what I want but I can't figure out how I enable the complexity in batch. Thanks in advance. also if you have any other ideas how to do this I'm open.

答:
I had similar situation once and what I did was:

```<code>setlocal EnableDelayedExpansion

SecEdit.exe /export /cfg "%temp%\sec-template.cfg" >nul 2>&1

set names=MaximumPasswordAge MinimumPasswordLength PasswordComplexity PasswordHistorySize
set values[MaximumPasswordAge]=90
set values[MinimumPasswordLength]=6
set values[PasswordComplexity]=1
set values[PasswordHistorySize]=10

for /F "delims== tokens=1,*" %%X in ('type "%temp%\sec-template.cfg"') do (
    call :trim "%%X"
    set cur_name=!result!
    for %%I in (%names%) do (
        if "!cur_name!" equ "%%I" (
            set value== !values[%%I]!
        )
    )

    if not defined value if "%%Y" neq "" (
        call :trim "%%Y"
        set value== !result!
    )

    echo !cur_name! !value! >> "%temp%\sec-template2.cfg"
    set value=
)

SecEdit.exe /configure /db secedit.sdb /cfg "%temp%\sec-template2.cfg" >nul 2>&1

del /q "%temp%\sec-template2*.cfg" >nul 2>&1

if exist "%~dp0secedit.sdb" del "%~dp0secedit.sdb" >nul 2>&1

goto :eof

:trim
set result=%~1

set "f=!result:~0,1!" & set "l=!result:~-1!"

if "!f!" neq " " if "!l!" neq " " goto :eof
if "!f!" equ " " set result=!result:~1!
if "!l!" equ " " set result=!result:~0,-1!

call :trim "!result!"
goto :eof
</code>```

Hope it helps.

Body:
In windows local security policies there is a complexity requirement. I would like to be able to enable it in a batch-file that enables other password stuff like length, age, etc.

::this will change the minimum length of the password
net accounts /minpwlen:8
::this will change the maximum age of the password
net accounts /maxpwage:30
::this will change the minimum age of the password
net accounts /minpwage:5
::this will change the number of passwords stored
net accounts /uniquepw:5

Above is most of what I want but I can't figure out how I enable the complexity in batch. Thanks in advance. also if you have any other ideas how to do this I'm open.

Body:
I had similar situation once and what I did was:

setlocal EnableDelayedExpansion

SecEdit.exe /export /cfg "%temp%\sec-template.cfg" >nul 2>&1

set names=MaximumPasswordAge MinimumPasswordLength PasswordComplexity PasswordHistorySize
set values[MaximumPasswordAge]=90
set values[MinimumPasswordLength]=6
set values[PasswordComplexity]=1
set values[PasswordHistorySize]=10

for /F "delims== tokens=1,*" %%X in ('type "%temp%\sec-template.cfg"') do (
    call :trim "%%X"
    set cur_name=!result!
    for %%I in (%names%) do (
        if "!cur_name!" equ "%%I" (
            set value== !values[%%I]!
        )
    )

    if not defined value if "%%Y" neq "" (
        call :trim "%%Y"
        set value== !result!
    )

    echo !cur_name! !value! >> "%temp%\sec-template2.cfg"
    set value=
)

SecEdit.exe /configure /db secedit.sdb /cfg "%temp%\sec-template2.cfg" >nul 2>&1

del /q "%temp%\sec-template2*.cfg" >nul 2>&1

if exist "%~dp0secedit.sdb" del "%~dp0secedit.sdb" >nul 2>&1

goto :eof

:trim
set result=%~1

set "f=!result:~0,1!" & set "l=!result:~-1!"

if "!f!" neq " " if "!l!" neq " " goto :eof
if "!f!" equ " " set result=!result:~1!
if "!l!" equ " " set result=!result:~0,-1!

call :trim "!result!"
goto :eof

Hope it helps.


问:
C# - IComparer - If datetime is null then should be sorted to the bottom not the top
I have a list of dates that I want to sort in an ascending order. However, the default comparer means that I have:

```<code>null
null
18/01/2011
23/01/2011
</code>```

Can someone help with a IComparer that will mean that the dates sorted in ascending order will look like:

```<code>18/01/2011
23/01/2011
null
null
</code>```

答:
```<code>public class DateTimeComparer : IComparer<DateTime?>
{
    #region IComparer<DateTime?> Members

    public int Compare(DateTime? x, DateTime? y)
    {
        DateTime nx = x ?? DateTime.MaxValue;
        DateTime ny = y ?? DateTime.MaxValue;

        return nx.CompareTo(ny);
    }

    #endregion
}
</code>```

No extra null checking is required.

Body:
I have a list of dates that I want to sort in an ascending order. However, the default comparer means that I have:

null
null
18/01/2011
23/01/2011

Can someone help with a IComparer that will mean that the dates sorted in ascending order will look like:

18/01/2011
23/01/2011
null
null

Body:
public class DateTimeComparer : IComparer<DateTime?>
{
    #region IComparer<DateTime?> Members

    public int Compare(DateTime? x, DateTime? y)
    {
        DateTime nx = x ?? DateTime.MaxValue;
        DateTime ny = y ?? DateTime.MaxValue;

        return nx.CompareTo(ny);
    }

    #endregion
}

No extra null checking is required.


问:
BingAPIv7 paging mechanism not working for both Web and News search
We have tried the Bing V7 paging mechanism for both Web and News.
count=100 for news, count=50 for web, as per the documentation.

However, very quickly (around offset=200) the number of returned results is less than 5, and in any case the results are duplicates of already returned pages. The ApproxCount also indicates a problem: starts out as millions and when the offset is increased it quickly becomes 400 or less.

News query example Here

Thanks in advance,

Ofer

答:
This behavior seems to be similar for all search APIs across different offerings. This has to do with 1) Cost of indexing huge number of webpages, and 2) Utility of those. Most users finish their search within first 2 pages or search with a new string again. So, even if you have millions of matched pages, they are potentially useless. Search engines do this to optimize their indexing and reduce serving redundant pages - you already see some with higher offset values.

You can restrict users to go to very high offset pages by 1) Having related searches, and 2) Taking care from UX side.


问:
Bash: Getting PID of daemonized screen session
If I start a GNU screen session as a daemon, how would I retrieve its PID programmatically? I don't know how consistent the output of  screen -ls is, so I'd like to know how to do this with one of bash's constants, $$, $! or a better alternative.

I am starting the screen with screen -dmS screenname.

How would I get the PID of a screen right before or immediately after starting the screen session?

答:
Another way is using screen's -Q parameter for querying the session:

```<code>screen -S nameofscreen -Q echo '$PID'
</code>```

Note that this will also display the PID inside the screen session as a notification.

Body:
Another way is using screen's -Q parameter for querying the session:

screen -S nameofscreen -Q echo '$PID'

Note that this will also display the PID inside the screen session as a notification.


问:
Change Color of Controls FX PopOver Title
Would like to change the color of a controls FX PopOver title which is set to always be on. I would like to do this in CSS, where I have already changed the background color. I have tried a couple of different options under .popover.

This is an example with the CSS of the last thing I tried:

```<code>public class HelloPopOver extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Build PopOver look and feel
        Label lblName = new Label("John Doe");
        Label lblStreet = new Label("123 Hello Street");
        Label lblCityStateZip = new Label("MadeUpCity, XX 55555");
        VBox vBox = new VBox(lblName, lblStreet, lblCityStateZip);
        //Create PopOver and add look and feel
        PopOver popOver = new PopOver(vBox);

        // I always want to see my header
        popOver.setHeaderAlwaysVisible(true);

        Label label = new Label("Mouse mouse over me");
        label.setOnMouseEntered(mouseEvent -> {
            popOver.show(label);
            ((Parent)popOver.getSkin().getNode()).getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
        });

        StackPane root = new StackPane();
        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
   }
}
</code>```

And the CSS:

```<code>.popover > .border {
    -fx-stroke-width: 0.5;
    -fx-fill: rgba(200,200,200, 1);
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
}
.popover > .label {
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
 }
</code>```

How can CSS change the title color to red?

答:
I had the same problem and figured it out by taking a look into the popover.css file in org.controlsfx.control .

This should do the trick:

```<code>.popover > .content > .title > .text  {
    -fx-text-fill: red;
}
</code>```

Body:
Would like to change the color of a controls FX PopOver title which is set to always be on. I would like to do this in CSS, where I have already changed the background color. I have tried a couple of different options under .popover.

This is an example with the CSS of the last thing I tried:

public class HelloPopOver extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Build PopOver look and feel
        Label lblName = new Label("John Doe");
        Label lblStreet = new Label("123 Hello Street");
        Label lblCityStateZip = new Label("MadeUpCity, XX 55555");
        VBox vBox = new VBox(lblName, lblStreet, lblCityStateZip);
        //Create PopOver and add look and feel
        PopOver popOver = new PopOver(vBox);

        // I always want to see my header
        popOver.setHeaderAlwaysVisible(true);

        Label label = new Label("Mouse mouse over me");
        label.setOnMouseEntered(mouseEvent -> {
            popOver.show(label);
            ((Parent)popOver.getSkin().getNode()).getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
        });

        StackPane root = new StackPane();
        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
   }
}

And the CSS:

.popover > .border {
    -fx-stroke-width: 0.5;
    -fx-fill: rgba(200,200,200, 1);
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
}
.popover > .label {
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
 }

How can CSS change the title color to red?

Body:
I had the same problem and figured it out by taking a look into the popover.css file in org.controlsfx.control .

This should do the trick:

.popover > .content > .title > .text  {
    -fx-text-fill: red;
}


问:
Why in XAML XmlDataProvider do we have to say "x:Key" instead of "Key"?
What is the function of the namespace here?

I would think in this simple example I would be able to put "Key" and "XData" instead of "x:Key" and "x:XData" but when I do it says "Key" was not found in XmlDataProvider.

```<code><Window x:Class="DataBindingWPF.XmlBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataBindingWPF" Height="300" Width="300"
    >
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="Colors" Source="Colors.xml"  XPath="/colors"></XmlDataProvider>
            <XmlDataProvider x:Key="MoreColors" XPath="/colors">
                <x:XData>
...
</code>```

答:
The "Key" property is not an actual property of the XmlDataProvider. It's a Xaml attribute that lives in the "http://schemas.microsoft.com/winfx/2006/xaml" namespace you prefixed with "x".

StackPanel.Resources is a ResourceDictionary. In order to add something to a dictionary you need a Key/value pair. The Key attribute is the key for the resource, and the XmlDataProvider is the value. This is the mechanism WPF uses to uniquely identify resources.

You can change xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" to xmlns:ns="http://schemas.microsoft.com/winfx/2006/xaml" and then you would refer to it as "ns:Key" instead of "x:Key".

OwnerDisplayName: Edward Tanguay

Body:
What is the function of the namespace here?

I would think in this simple example I would be able to put "Key" and "XData" instead of "x:Key" and "x:XData" but when I do it says "Key" was not found in XmlDataProvider.

<Window x:Class="DataBindingWPF.XmlBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataBindingWPF" Height="300" Width="300"
    >
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="Colors" Source="Colors.xml"  XPath="/colors"></XmlDataProvider>
            <XmlDataProvider x:Key="MoreColors" XPath="/colors">
                <x:XData>
...

OwnerDisplayName: Micah


问:
Div above another one JQuery script didn't work !
I have two divs, and I just want the second one to be under [in z-index] the first one, I read about it here and I figured out that I have to use the following JQuery script:

```<code><script type="text/javascript">
    $('#secondDiv').insertBefore('#firstDiv');
</script>
</code>```

I tried it, but it didn't work with me, Any help!!

```<code><DetailedTemplate>
<div id="firstDiv" style="background-color:Black">
    <asp:ImageButton ID="SelectButton" Visible='<%# org.SelectedValue == null || Container.DataElement("ID").ToString() != org.SelectedValue.ToString() %>' runat="server" CommandName="Select" CommandArgument='<%# Container.DataElement("ID") %>'
      OnPreRender="SelectButton_PreRender" style="border-style:none; Height:58px; width:113px; cursor:hand"  ImageUrl="~/Contents/Images/item-background.png"/>
</div>

<div id="secondDiv" style="background-color:Red" >
    <center style=" margin: 5px; padding-top: 5px; padding-right: 5px; padding-left: 5px;">
        <asp:LinkButton ID="lnkTitle" ForeColor="#6c1b24" Font-Bold="true" runat="server"
            Text='<%# Container.DataElement("Name") %>' NavigateUrl="http://google.com">
        </asp:LinkButton>
        <div runat="server" visible='<%# Convert.ToInt32(Container.DataElement("NumOfChildren")) > 0 %>'
            style="border: 1px solid #6c1b24; width: 15px; text-align: center; height: 15px;
            margin-top: 25px; background-color: #fddb73; font-size: larger; font-family: Courier New;">
            <asp:LinkButton ID="btnExpand" runat="server" ForeColor="#6c1b24" CommandArgument='<%# Container.DataElement("ID")%>'
                CommandName="Expand" Font-Underline="false" Text='<%# Container.NumberOfChildren > 0 ? "-" : "+" %>' />
        </div>
    </center>
</div>

<script type="text/javascript">
    $('#secondDiv').insertBefore('#firstDiv');
</script>
</DetailedTemplate>
</code>```

Note: I can't put my divs as absolute in my situation.

答:
You don't need any javascript or jQuery for this, it can be done easily with pure css

You can see an example here: http://jsfiddle.net/MQgAM/ but there are lots of otehr ways to do it, in pure css...

Remember that when you position elements in css you do it based on the nearest parent that is also positioned or the body tag if none exists. that why i wrapped the two inner divs in an outer that ahs position relative - setting an element to position relative will not change where it is on the page, it will work as any other inline or block level element, but it will reset the starting point for all children of it, that is positioned, so this way you can contain positioned elements.

You can learn more about css positioning here

If you absolutely cannot use position absolute, you can do the same trick with position relative, it will just take a bit of math on your side :)

Lastly, if you don't position your elemnts, z-index has no effect, and this cannot be done, unless you change your markup so the top elements lives inside the bottom element

In general try not to use javascript if you can do it by pure css, it will make your web application much better :)

Body:
I have two divs, and I just want the second one to be under [in z-index] the first one, I read about it here and I figured out that I have to use the following JQuery script:

I tried it, but it didn't work with me, Any help!!

<DetailedTemplate>

    <asp:ImageButton ID="SelectButton" Visible='<%# org.SelectedValue == null || Container.DataElement("ID").ToString() != org.SelectedValue.ToString() %>' runat="server" CommandName="Select" CommandArgument='<%# Container.DataElement("ID") %>'
      OnPreRender="SelectButton_PreRender" style="border-style:none; Height:58px; width:113px; cursor:hand"  ImageUrl="~/Contents/Images/item-background.png"/>

        <asp:LinkButton ID="lnkTitle" ForeColor="#6c1b24" Font-Bold="true" runat="server"
            Text='<%# Container.DataElement("Name") %>' NavigateUrl="http://google.com">
        </asp:LinkButton>
        <div runat="server" visible='<%# Convert.ToInt32(Container.DataElement("NumOfChildren")) > 0 %>'
            style="border: 1px solid #6c1b24; width: 15px; text-align: center; height: 15px;
            margin-top: 25px; background-color: #fddb73; font-size: larger; font-family: Courier New;">
            <asp:LinkButton ID="btnExpand" runat="server" ForeColor="#6c1b24" CommandArgument='<%# Container.DataElement("ID")%>'
                CommandName="Expand" Font-Underline="false" Text='<%# Container.NumberOfChildren > 0 ? "-" : "+" %>' />

</DetailedTemplate>

Note: I can't put my divs as absolute in my situation.


问:
Intermittent "Not a Product" Javascript Error
We have a website (.Net / jquery / Bootstrap 4), using Rollbar to log Javascript errors. Rollbar is logging an intermittent Javascript error with the message "Not a Product." For the trace, it only includes:

```<code>File "(unknown)" line (unknown) col 0 in [anonymous]
</code>```

The error only occurs on Chrome 60, 61, and 62 on Windows and Mac. Our client information and telemetry do not expose any browser extensions that could be responsible, but I don't know how to rule that out. Is there some way to troubleshoot this, or do we have to assume it's a Chrome extension unless it occurs on other clients?

答: I had the same issue. It was being caused by the "Honey" chrome extension.</p>

Body:
We have a website (.Net / jquery / Bootstrap 4), using Rollbar to log Javascript errors. Rollbar is logging an intermittent Javascript error with the message "Not a Product." For the trace, it only includes:

File "(unknown)" line (unknown) col 0 in [anonymous]

The error only occurs on Chrome 60, 61, and 62 on Windows and Mac. Our client information and telemetry do not expose any browser extensions that could be responsible, but I don't know how to rule that out. Is there some way to troubleshoot this, or do we have to assume it's a Chrome extension unless it occurs on other clients?


问:
crontab multiple postgresql issue
I'm trying to run a script (automation.sh) automated in crontab.
(I'm on Ubuntu 14.04).

```<code>#!/usr/bin/env bash

day=$(date +%F -d'yesterday')

cat /home/tomi/logs/$day |grep registration > /home/tomi/registrations/$day
cat /home/tomi/logs/$day |grep free_tree > /home/tomi/free_tree/$day
cat /home/tomi/logs/$day |grep super_tree > /home/tomi/super_tree/$day

psql -U hello -d postgres -c "\COPY registrations FROM '/home/tomi/registrations/$day' DELIMITER ' '";
psql -U hello -d postgres -c "\COPY free_tree FROM '/home/tomi/free_tree/$day' DELIMITER ' '";
psql -U hello -d postgres -c "\COPY super_tree FROM '/home/tomi/super_tree/$day' DELIMITER ' '";

psql -U hello -d postgres -f daily_active_users.sql > /home/tomi/tmp1
psql -U hello -d postgres -f daily_revenue.sql > /home/tomi/tmp2
</code>```

If I run this script normally from the command line, then the last two lines generate tmp1 and tmp2 with data in them. (That's the expected result.)

However, if I run this very same script in crontab, everything works, but the last two lines generate empty files (tmp1 and tmp2).

The tricky thing is that when I break this script into two scripts (eg. automated.sh and automated2.sh) and run the last two lines in crontab 5 minutes later (via this automated2.sh script), tmp1 and tmp2 are generated correctly, with data in them.

Any idea, what can cause this?

答:
Answer is in the comments:
full path is missing on last two lines in automation.sh!
Thanks!</p>

Title: crontab multiple postgresql issue

Body:
I'm trying to run a script (automation.sh) automated in crontab.
(I'm on Ubuntu 14.04).

#!/usr/bin/env bash

day=$(date +%F -d'yesterday')

cat /home/tomi/logs/$day |grep registration > /home/tomi/registrations/$day
cat /home/tomi/logs/$day |grep free_tree > /home/tomi/free_tree/$day
cat /home/tomi/logs/$day |grep super_tree > /home/tomi/super_tree/$day

psql -U hello -d postgres -c "\COPY registrations FROM '/home/tomi/registrations/$day' DELIMITER ' '";
psql -U hello -d postgres -c "\COPY free_tree FROM '/home/tomi/free_tree/$day' DELIMITER ' '";
psql -U hello -d postgres -c "\COPY super_tree FROM '/home/tomi/super_tree/$day' DELIMITER ' '";

psql -U hello -d postgres -f daily_active_users.sql > /home/tomi/tmp1
psql -U hello -d postgres -f daily_revenue.sql > /home/tomi/tmp2

If I run this script normally from the command line, then the last two lines generate tmp1 and tmp2 with data in them. (That's the expected result.)

However, if I run this very same script in crontab, everything works, but the last two lines generate empty files (tmp1 and tmp2).

The tricky thing is that when I break this script into two scripts (eg. automated.sh and automated2.sh) and run the last two lines in crontab 5 minutes later (via this automated2.sh script), tmp1 and tmp2 are generated correctly, with data in them.

Any idea, what can cause this?


问:
How to position the center of a div to the center of the mouse cursor on mouse movement with JS?
I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements.

Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor.

WORKFLOW

The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. When the mouse leaves the div it should be hidden.

CODE

HTML post item:

```<code><article class="col-md-4 col-sm-6 post-entry">
    <a href="#" title="">
        <figure class="post-thumb">
            <img src="http://placehold.it/300x300" alt="">
            <div class="pointer" style="background: red;"></div>
        </figure><!-- End figure.post-thumb -->
    </a>
</article><!-- End article.col-md-4 post-entry -->
</code>```

JS:

```<code>$('.entry .post-entry').each(function() {
  $(this).on("mouseenter", mouseEnter);
  $(this).on("mousemove", mouseMove);
  $(this).on("mouseleave", mouseLeave);
});

function mouseEnter(event) {

  console.log('enter');

  var target = $(this);
  var dot = target.find('.pointer');

  var mX = (event.clientX);
  var mY = (event.clientY);

  set(
    dot, {
      x: mX,
      y: mY,
      force3D: !0
    }
  );

};

function mouseMove(event) {

  console.log('move');

  var target = $(this);
  var dot = target.find('.pointer');

  // var offset = target.offset();
  // var width = target.width();
  // var height = target.height();
  // var top = offset.top;
  // var left = offset.left;

  var mX = (event.clientX);
  var mY = (event.clientY);

  $(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');

};

function mouseLeave(event) {

  console.log('leave');

    var target = $(this);
    var dot = target.find('.pointer');

    $(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');

};

function onClick(event) {
  event.preventDefault();
  console.log('click');
};

function set(el, obj) {
  var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
  return dot;
};

</code>```

PROBLEM / DEMO

As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. It will be offset the mouse. See live demo here

I tried already something like this for the mX and mY variables, but with no succes:

```<code>var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();
</code>```

Also the answer from @hiEven doesn't work and will let me with the same issue:

```<code>transform: calc(mX - 50%, mY - 50%)
</code>```

I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me.

UPDATE

I created two new Codepen projects:

Use without images: http://codepen.io/anon/pen/GqGOLv. When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item.

When I use images: http://codepen.io/anon/pen/QExOkx. The problem by this example is that when you at the very top of the first column, you will see the brown pointer. When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images.

Both pointer should follow the mouse cursor correctly. And I am searching for a solution that works with the use of an image.

Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero.

So I don't know what's missing and why it only works with the first example (without images) and only for the first item?

答:
Try the code below

```<code><html>
  <head>
    <style>
          #mouse_div{
            position: absolute;
            background-color: black;
          }
    </style>
    <script>
          var div_width = 100;
          var div_height = 100;
          var div_x, div_y;
          function mouse_position(event){
            var mouse_x = event.clientX;
            var mouse_y = event.clientY;
            document.getElementById("mouse_div").style.width = div_width + "px";
            document.getElementById("mouse_div").style.height = div_height + "px";
            div_x = mouse_x - (div_width / 2);
            div_y = mouse_y - (div_height / 2);
            document.getElementById("mouse_div").style.left = div_x + "px";
            document.getElementById("mouse_div").style.top = div_y + "px";
          }
    </script>
  </head>
  <body onmousemove="mouse_position(event)" onload="mouse_position(event)">
    <div id="mouse_div"></div>
  </body>
</html>
</code>```

This program gets the position of your mouse, the width, and the height of the div. Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). The program then does the same thing for the mouse y. Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be.

Note: you must make sure that the position of the div is set to absolute or the program will not work.

Body:
I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements.

Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor.

WORKFLOW

The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. When the mouse leaves the div it should be hidden.

CODE

HTML post item:

JS:

$('.entry .post-entry').each(function() {
  $(this).on("mouseenter", mouseEnter);
  $(this).on("mousemove", mouseMove);
  $(this).on("mouseleave", mouseLeave);
});

function mouseEnter(event) {

  console.log('enter');

  var target = $(this);
  var dot = target.find('.pointer');

  var mX = (event.clientX);
  var mY = (event.clientY);

  set(
    dot, {
      x: mX,
      y: mY,
      force3D: !0
    }
  );

};

function mouseMove(event) {

  console.log('move');

  var target = $(this);
  var dot = target.find('.pointer');

  // var offset = target.offset();
  // var width = target.width();
  // var height = target.height();
  // var top = offset.top;
  // var left = offset.left;

  var mX = (event.clientX);
  var mY = (event.clientY);

  $(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');

};

function mouseLeave(event) {

  console.log('leave');

    var target = $(this);
    var dot = target.find('.pointer');

    $(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');

};

function onClick(event) {
  event.preventDefault();
  console.log('click');
};

function set(el, obj) {
  var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
  return dot;
};

PROBLEM / DEMO

As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. It will be offset the mouse. See live demo here

I tried already something like this for the mX and mY variables, but with no succes:

var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();

Also the answer from @hiEven doesn't work and will let me with the same issue:

transform: calc(mX - 50%, mY - 50%)

I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me.

UPDATE

I created two new Codepen projects:

Use without images: http://codepen.io/anon/pen/GqGOLv. When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item.

When I use images: http://codepen.io/anon/pen/QExOkx. The problem by this example is that when you at the very top of the first column, you will see the brown pointer. When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images.

Both pointer should follow the mouse cursor correctly. And I am searching for a solution that works with the use of an image.

Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero.

So I don't know what's missing and why it only works with the first example (without images) and only for the first item?

Body:
Try the code below

<html>
  <head>
    <style>
          #mouse_div{
            position: absolute;
            background-color: black;
          }
    </style>
    <script>
          var div_width = 100;
          var div_height = 100;
          var div_x, div_y;
          function mouse_position(event){
            var mouse_x = event.clientX;
            var mouse_y = event.clientY;
            document.getElementById("mouse_div").style.width = div_width + "px";
            document.getElementById("mouse_div").style.height = div_height + "px";
            div_x = mouse_x - (div_width / 2);
            div_y = mouse_y - (div_height / 2);
            document.getElementById("mouse_div").style.left = div_x + "px";
            document.getElementById("mouse_div").style.top = div_y + "px";
          }
    </script>
  </head>
  <body onmousemove="mouse_position(event)" onload="mouse_position(event)">
    <div id="mouse_div"></div>
  </body>
</html>

This program gets the position of your mouse, the width, and the height of the div. Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). The program then does the same thing for the mouse y. Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be.

Note: you must make sure that the position of the div is set to absolute or the program will not work.


问:
How and when does the Android system send the ACTION_BATTERY_CHANGED sticky broadcast?
My goal is : when I call some function, I want to get the exact current battery status(level,voltage and etc..).

First I tried to do it in my application as shown on the website. Then I have found actually the ACTION_BATTERY_CHANGED broadcast is sticky which means what I got is from last broadcast, not the exact current value.

Actually, I have looked into the android source code. For the battery interface, the driver has functions to read the registers inside the battery which contain the current soc(state of charge), voltage and etc..

So I am just wondering how and when the system sends the sticky broadcast ACTION_BATTERY_CHANGED? Does it send it periodically(e.g.,every 10 seconds it will read the registers in battery and send the broadcast)? Or does it send based on other criteria(e.g, change of soc, voltage? But voltage will change so frequently in terms of mV)?

To realize my goal, one troublesome way is to  implement a system call to call the driver functions and then recompile the NDK to make it usable in my application code. But I just want to know whether I can do this directly through the ACTION_BATTERY_CHANGED broadcast considering what I have mentioned above? Does registering the broadcast again have any effect?

答:
In response to the  of the question:

Does it send it periodically(e.g.,every 10 seconds it will read the
  registers in battery and send the broadcast)? Or does it send based on
  other criteria(e.g, change of soc, voltage? But voltage will change so
  frequently in terms of mV)?

There is no single correct answer, Android makes no guarantees and it varies by device.

Based on my experience working with different board bring-ups it is highly dependant on the linux kernel drivers managing power. I've seen it firing uevents off once per second or once every 30 seconds. Even the same device will fire it differently based on whether it is attached to a power source or not. I tend to see that usually there is some fixed timer that triggers it and additionally major events such as attaching/detaching a charger will trigger it as well.

Also see: ACTION_BATTERY_CHANGED firing like crazy