问:
How do I vectorize this calculation in numpy
How do I vectorize the following calculation if a and b are appropriately sized numpy arrays?</p>

```<code>total = a[0]
for ix in range(1, len(a)):
   total = total*b[ix-1] + a[ix]
</code>```

答:
Never mind, there is a ufunc trick that works if you do some algebra.  In this case the ufunc is multiply and the trick is accumulate.

```<code>c = np.r_[np.multiply.accumulate(b[0:-1][::-1])[::-1], 1]
total2 = np.sum(a * c)
</code>```

What this does: Algebraically, you are summing a[i] times the product of b[i:] over for i in range(a.size).  To do this, flip b and get the running product of all but the last number (assuming a and b are the same length) and then flip it back.  The last value should be 1 because the final a value is just added.

Testing

```<code>a = np.random.randint(1, 10, 40)
b = 1 + np.random.rand(40)

total = a[0]
for ix in range(1, len(a)):
   total = total*b[ix-1] + a[ix]

total
278443993.10494208

total2
278443993.10494208
</code>```

Body:
How do I vectorize the following calculation if a and b are appropriately sized numpy arrays?

total = a[0]
for ix in range(1, len(a)):
   total = total*b[ix-1] + a[ix]

Body:
Never mind, there is a ufunc trick that works if you do some algebra.  In this case the ufunc is multiply and the trick is accumulate.

c = np.r_[np.multiply.accumulate(b[0:-1][::-1])[::-1], 1]
total2 = np.sum(a * c)

What this does: Algebraically, you are summing a[i] times the product of b[i:] over for i in range(a.size).  To do this, flip b and get the running product of all but the last number (assuming a and b are the same length) and then flip it back.  The last value should be 1 because the final a value is just added.

Testing

a = np.random.randint(1, 10, 40)
b = 1 + np.random.rand(40)

total = a[0]
for ix in range(1, len(a)):
   total = total*b[ix-1] + a[ix]

total
278443993.10494208

total2
278443993.10494208


来源: stackexchange

问:
image overlay picture from Camer_net library showing a lot of pink color
I am making an windows form application in which i am overlaying an image during a webcam stream   from the laptop.
the overlayed image is showing absurd colours. it is showing alot of pink colour. is there anything i can do to make the overlayed image look properly.
 i am using  the camera_Net Library to connect to the webcam
suggestions for overlaying an image during during a webcam video shall also be appreciated.

here is my code to draw the image

```<code>string filepath = @"E:\office\lux desktop app\Camera_Net-master\Camera_Net-master\Samples\CameraControlTool\water_PNG3290.png";
                    Bitmap bitmap1 = new Bitmap(filepath);
                    g.DrawImage(bitmap1, new Rectangle(400 , 0, 250, 600));
</code>```

here is the look of the image during webcam stream

and here is the orignal image being overlayed

答:
I think the problem is the image itself. It's an .png image, so I it has the possibility of an alpha-value. The white in the back is cropped out but in between the water, the light blue values are pink.

I would first try to use an easier image. Something like this. I think this will work just fine. Then search for some more complex images and try to find the weak-spot and find some alternative options to bring the image in to the cam.

ContentLicense: CC BY-SA 4.0

Body:
I am making an windows form application in which i am overlaying an image during a webcam stream   from the laptop.
the overlayed image is showing absurd colours. it is showing alot of pink colour. is there anything i can do to make the overlayed image look properly.
 i am using  the camera_Net Library to connect to the webcam
suggestions for overlaying an image during during a webcam video shall also be appreciated.

here is my code to draw the image

string filepath = @"E:\office\lux desktop app\Camera_Net-master\Camera_Net-master\Samples\CameraControlTool\water_PNG3290.png";
                    Bitmap bitmap1 = new Bitmap(filepath);
                    g.DrawImage(bitmap1, new Rectangle(400 , 0, 250, 600));

here is the look of the image during webcam stream

and here is the orignal image being overlayed

ContentLicense: CC BY-SA 3.0


问:
Reading timestamp data in R from multiple time zones
I have a column of time stamps in character format that looks like this:

2015-09-24 06:00:00 UTC

2015-09-24 05:00:00 UTC

```<code>dateTimeZone <- c("2015-09-24 06:00:00 UTC","2015-09-24 05:00:00 UTC")
</code>```

I'd like to convert this character data into time data using POSIXct, and if I knew that all the time stamps were in UTC, I would do it like this:

```<code>dateTimeZone <- asPOSIXct(dateTimeZone, tz="UTC")
</code>```

However, I don't necessarily know that all the time stamps are in UTC, so I tried

```<code>dateTimeZone <- asPOSIXct(dateTimeZodateTimeZone, format = "%Y-%m-%d %H:%M:%S %Z")
</code>```

However, because strptime supports %Z only for output, this returns the following error:

Error in strptime(x, format, tz = tz) :
    use of %Z for input is not supported

I checked the documentation for the lubridate package, and I couldn't see that it handled this issue any differently than POSIXct.

Is my only option to check the time zone of each row and then use the appropriate time zone with something like the following?

```<code>temp[grepl("UTC",datetimezone)] <- as.POSIXct(datetimezone, tz="UTC")
temp[grepl("PDT",datetimezone)] <- as.POSIXct(datetimezone, tz="America/Los_Angeles")
</code>```

答:
A data.table solution:

```<code>library(data.table)

data <- data.table(dateTimeZone=c("2015-09-24 06:00:00 UTC",
                                  "2015-09-24 05:00:00 America/Los_Angeles"))
data[, timezone:=tstrsplit(dateTimeZone, split=" ")[[3]]]
data[, datetime.local:=as.POSIXct(dateTimeZone, tz=timezone), by=timezone]
data[, datetime.utc:=format(datetime.local, tz="UTC")]
</code>```

The key thing is to split the data on the timezone field so that you can feed each set of timezones to as.POSIXct separately (I'm not really sure why as.POSIXct won't let you give it a vector of timezones, actually). Here I make use of data.table's efficient split-apply-combine syntax, but you could apply the same general idea with base R or using dplyr.

Body:
I have a column of time stamps in character format that looks like this:

2015-09-24 06:00:00 UTC

2015-09-24 05:00:00 UTC

dateTimeZone <- c("2015-09-24 06:00:00 UTC","2015-09-24 05:00:00 UTC")

I'd like to convert this character data into time data using POSIXct, and if I knew that all the time stamps were in UTC, I would do it like this:

dateTimeZone <- asPOSIXct(dateTimeZone, tz="UTC")

However, I don't necessarily know that all the time stamps are in UTC, so I tried

dateTimeZone <- asPOSIXct(dateTimeZodateTimeZone, format = "%Y-%m-%d %H:%M:%S %Z")

However, because strptime supports %Z only for output, this returns the following error:

Error in strptime(x, format, tz = tz) :
    use of %Z for input is not supported

I checked the documentation for the lubridate package, and I couldn't see that it handled this issue any differently than POSIXct.

Is my only option to check the time zone of each row and then use the appropriate time zone with something like the following?

temp[grepl("UTC",datetimezone)] <- as.POSIXct(datetimezone, tz="UTC")
temp[grepl("PDT",datetimezone)] <- as.POSIXct(datetimezone, tz="America/Los_Angeles")

Body:
A data.table solution:

library(data.table)

data <- data.table(dateTimeZone=c("2015-09-24 06:00:00 UTC",
                                  "2015-09-24 05:00:00 America/Los_Angeles"))
data[, timezone:=tstrsplit(dateTimeZone, split=" ")[[3]]]
data[, datetime.local:=as.POSIXct(dateTimeZone, tz=timezone), by=timezone]
data[, datetime.utc:=format(datetime.local, tz="UTC")]

The key thing is to split the data on the timezone field so that you can feed each set of timezones to as.POSIXct separately (I'm not really sure why as.POSIXct won't let you give it a vector of timezones, actually). Here I make use of data.table's efficient split-apply-combine syntax, but you could apply the same general idea with base R or using dplyr.


问:
Is there a way for Unix sort to ignore delimiter based on escape characters?
I want to use Unix sort but sometimes I want the field delimiter if enclosed by a pair of enclosing delimiter to not be treated as the field delimiter. For example, lets look at the base case and then then later look at the specific case:

Base Case:

```<code>"xyz"|27
"abc"|15
"xyz"|25
</code>```

When I perform the following command:

sort -t'|' -k1,1 -k2,2n test1.txt

I get what I want:

```<code>"abc"|15
"xyz"|25
"xyz"|27
</code>```

Now let's look at the second case with an escape character pair <> provided:

```<code>"x<|>yz"|27
"abc"|15
"xyz"|25
</code>```

If I run the same command, I get something that I don't want:

```<code>"abc"|15
"x<|>yz"|27
"xyz"|25
</code>```

Is there anyway to tell unix sort that if <> or {} or () or even a weird pair like <) is provided, then ignore the actual field delimiter inside the enclosing delimiter pair? The actual field delimiter will always be a pipe.

The desired result that I am aiming for is:

```<code>"abc"|15
"xyz"|25
"x<|>yz"|27
</code>```

答:
I don't think so but instead you could:

duplicate the key and clean the duplicate off the <|>

move the original key to the end

sort on the cleaned key

remove the cleaned key and move the original key back to its place

Using awk:

```<code>$ awk 'BEGIN{FPAT="([^|]+|(\"[^\"]+\"))";OFS="|"}{i=$1;gsub(/<.*>/,"",i);print i,$2,$1}' file | sort -t\| -k1 -k2 | awk 'BEGIN{FPAT="([^|]+|(\"[^\"]+\"))";OFS="|"}{print $NF,$2}'
"abc"|15
"xyz"|25
"x<|>yz"|27
</code>```

Explained (1. and 2.):

```<code>$ awk 'BEGIN{FPAT="([^|]+|(\"[^\"]+\"))";OFS="|"}{i=$1;gsub(/<.*>/,"",i);print i,$2,$1}' file
</code>```

outputs:

```<code>"xyz"|27|"x<|>yz"
"abc"|15|"abc"
"xyz"|25|"xyz"
</code>```

Code explained:

```<code>BEGIN {
    FPAT="([^|]+|(\"[^\"]+\"))"  # define fields to allow field separators in quotes
    OFS="|"                      # output field separator to |
}
{
    i=$1                         # copy first field to var i
    gsub(/<.*>/,"",i)            # remove "escaped" part
    print i,$2,$1                # output
}
</code>```

piping to sort -t\| -k1 -k2 outputs (3.):

```<code>"abc"|15|"abc"
"xyz"|25|"xyz"
"xyz"|27|"x<|>yz"
</code>```

Code explained:

```<code>...                               # see previous explanation
{
    print $NF,$2                  # print last first then second (original order)
}
</code>```

and the result of (4.) is right up there.

Body:
I want to use Unix sort but sometimes I want the field delimiter if enclosed by a pair of enclosing delimiter to not be treated as the field delimiter. For example, lets look at the base case and then then later look at the specific case:

Base Case:

"xyz"|27
"abc"|15
"xyz"|25

When I perform the following command:

sort -t'|' -k1,1 -k2,2n test1.txt

I get what I want:

"abc"|15
"xyz"|25
"xyz"|27

Now let's look at the second case with an escape character pair <> provided:

"x<|>yz"|27
"abc"|15
"xyz"|25

If I run the same command, I get something that I don't want:

"abc"|15
"x<|>yz"|27
"xyz"|25

Is there anyway to tell unix sort that if <> or {} or () or even a weird pair like <) is provided, then ignore the actual field delimiter inside the enclosing delimiter pair? The actual field delimiter will always be a pipe.

The desired result that I am aiming for is:

"abc"|15
"xyz"|25
"x<|>yz"|27

Body:
I don't think so but instead you could:

duplicate the key and clean the duplicate off the <|>

move the original key to the end

sort on the cleaned key

remove the cleaned key and move the original key back to its place

Using awk:

$ awk 'BEGIN{FPAT="([^|]+|(\"[^\"]+\"))";OFS="|"}{i=$1;gsub(/<.*>/,"",i);print i,$2,$1}' file | sort -t\| -k1 -k2 | awk 'BEGIN{FPAT="([^|]+|(\"[^\"]+\"))";OFS="|"}{print $NF,$2}'
"abc"|15
"xyz"|25
"x<|>yz"|27

Explained (1. and 2.):

$ awk 'BEGIN{FPAT="([^|]+|(\"[^\"]+\"))";OFS="|"}{i=$1;gsub(/<.*>/,"",i);print i,$2,$1}' file

outputs:

"xyz"|27|"x<|>yz"
"abc"|15|"abc"
"xyz"|25|"xyz"

Code explained:

BEGIN {
    FPAT="([^|]+|(\"[^\"]+\"))"  # define fields to allow field separators in quotes
    OFS="|"                      # output field separator to |
}
{
    i=$1                         # copy first field to var i
    gsub(/<.*>/,"",i)            # remove "escaped" part
    print i,$2,$1                # output
}

piping to sort -t\| -k1 -k2 outputs (3.):

"abc"|15|"abc"
"xyz"|25|"xyz"
"xyz"|27|"x<|>yz"

Code explained:

...                               # see previous explanation
{
    print $NF,$2                  # print last first then second (original order)
}

and the result of (4.) is right up there.


问:
view.frame.width IS correct in viewDidLoad with storyboard, why?
Ok, so this is somewhat of a weird question. I've been developing iOS-apps for quite a while and have always respected that viewDidLoad is the incorrect place for using the frame of the view.

However, in one app that I'm about to solve some bugs for, it seems that the frame is actually set correctly in viewDidLoad!

The storyboard is using "View as: iPhone 7", so I'm expecting to get 375px width for the frame in viewDidLoad. I'm using normal push segues.

However, the width is actually set correctly to the current devices screen width. I'm using a simulator.

What am I missing? Can we use the width for calculations in viewDidLoad nowadays?

答:
No you still can't use viewDidLoad for anything size/position related.

The first method that will have the actual "proper" dimensions is the viewDidLayoutSubviews.

Regarding the phenomenon you are experiencing.

You are probably talking about the "root view" from your view controller.

As the apple docs say (bolding is mine):

A view controller’s root view is always sized to fit its assigned
  space. For other views in your view hierarchy, use Interface Builder
  to specify the Auto Layout constraints that govern how each view is
  positioned and sized within its superview’s bounds. You can also
  create constraints programmatically and add them to your views at
  appropriate times. For more information about how to create
  constraints, see Auto Layout Guide.

https://developer.apple.com/documentation/uikit/uiviewcontroller

This is why you are getting the correct width.

If you'd like to test, try adding a subview that fills the whole "root view" area. This one will probably just give you the dimensions that that are shown on the Interface Builder.

My test results:

Interface Builder -> "View as iPhone 7"

Simulator iPhone 5s:

```<code>Root View dimensions: (0.0, 0.0, 320.0, 568.0)
Sub View dimensions: (0.0, 0.0, 375.0, 667.0)
</code>```

Simulator iPhone 7:

```<code>Root View dimensions: (0.0, 0.0, 375.0, 667.0)
Sub View dimensions: (0.0, 0.0, 375.0, 667.0)
</code>```

Simulator iPhone 7 Plus:

```<code>Root View dimensions: (0.0, 0.0, 414.0, 736.0)
Sub View dimensions: (0.0, 0.0, 375.0, 667.0)
</code>```

Interface Builder -> "View as iPhone 4s"

Simulator iPhone 5s:

```<code>Root View dimensions: (0.0, 0.0, 320.0, 568.0)
Sub View dimensions: (0.0, 0.0, 320.0, 480.0)
</code>```

Simulator iPhone 7:

```<code>Root View dimensions: (0.0, 0.0, 375.0, 667.0)
Sub View dimensions: (0.0, 0.0, 320.0, 480.0)
</code>```

Simulator iPhone 7 Plus:

```<code>Root View dimensions: (0.0, 0.0, 414.0, 736.0)
Sub View dimensions: (0.0, 0.0, 320.0, 480.0)
</code>```

As you can see, the root view dimensions will always correspond to the device you are using as stated in the documents. While any other views will have the dimensions you can see on the interface builder.

This question will also help you understand how the life cycle works:
Why am I having to manually set my view's frame in viewDidLoad?

Body:
No you still can't use viewDidLoad for anything size/position related.

The first method that will have the actual "proper" dimensions is the viewDidLayoutSubviews.

Regarding the phenomenon you are experiencing.

You are probably talking about the "root view" from your view controller.

As the apple docs say (bolding is mine):

A view controller’s root view is always sized to fit its assigned
  space. For other views in your view hierarchy, use Interface Builder
  to specify the Auto Layout constraints that govern how each view is
  positioned and sized within its superview’s bounds. You can also
  create constraints programmatically and add them to your views at
  appropriate times. For more information about how to create
  constraints, see Auto Layout Guide.

https://developer.apple.com/documentation/uikit/uiviewcontroller

This is why you are getting the correct width.

If you'd like to test, try adding a subview that fills the whole "root view" area. This one will probably just give you the dimensions that that are shown on the Interface Builder.

My test results:

Interface Builder -> "View as iPhone 7"

Simulator iPhone 5s:

Root View dimensions: (0.0, 0.0, 320.0, 568.0)
Sub View dimensions: (0.0, 0.0, 375.0, 667.0)

Simulator iPhone 7:

Root View dimensions: (0.0, 0.0, 375.0, 667.0)
Sub View dimensions: (0.0, 0.0, 375.0, 667.0)

Simulator iPhone 7 Plus:

Root View dimensions: (0.0, 0.0, 414.0, 736.0)
Sub View dimensions: (0.0, 0.0, 375.0, 667.0)

Interface Builder -> "View as iPhone 4s"

Simulator iPhone 5s:

Root View dimensions: (0.0, 0.0, 320.0, 568.0)
Sub View dimensions: (0.0, 0.0, 320.0, 480.0)

Simulator iPhone 7:

Root View dimensions: (0.0, 0.0, 375.0, 667.0)
Sub View dimensions: (0.0, 0.0, 320.0, 480.0)

Simulator iPhone 7 Plus:

Root View dimensions: (0.0, 0.0, 414.0, 736.0)
Sub View dimensions: (0.0, 0.0, 320.0, 480.0)

As you can see, the root view dimensions will always correspond to the device you are using as stated in the documents. While any other views will have the dimensions you can see on the interface builder.

This question will also help you understand how the life cycle works:
Why am I having to manually set my view's frame in viewDidLoad?


问:
Can I change the Perl 6 slang inside a method?
A Perl 6 Regex is a more specific type of Method, so I had the idea that maybe I could do something black-magicky in a regular method that produces the same thing. I particularly am curious about doing this without changing any grammars.

However, looking at Perl6/Grammar.nqp (which I barely understand), that this is really not an inheritance thing. I think, based on my reading, that the Perl 6 grammar switches slangs (sub languages) when it sees one of the regex declarators. That is, a different grammar parses the guts of regex { ... } and method {...}.

So, first, is that right?

Then, just for giggles, I thought that maybe I could be inside a method block but tell it to use a different slang (see for instance, "Slangs" from the 2013 Perl 6 Advent Calendar or "Slangs Today").

However, everything I've found looks like it wants to change the grammar. Is there a way to do it without that and return a string that is treated as if it had come out of regex { ... }?

```<code>method actually-returns-a-regex {
     ...
     }
</code>```

I don't have any practical use for this. I just keep wondering about it.

答:
First of all, the Perl 6 design documents mandate an API where regexes return a lazy list of possible matches. If Rakudo adhered to that API, you could easily write a method that acted as a regex, but parsing would be very slow (because lazy lists tend to perform much worse than a compact list of string positions (integers) that act as a backtracking stack).

Instead, Perl 6 regexes return matches. And you can do the same. Here is an example of a method that is called like a regex inside of a grammar:

```<code>grammar Foo {
    token TOP { a <rest> }

    method rest() {
        if self.target.substr(self.pos, 1) eq 'b' {
            return Match.new(
                orig   => self.orig,
                target => self.target,
                from => self.pos,
                to   => self.target.chars,
            );
        }
        else {
            return Match.new();
        }
    }
}

say Foo.parse('abc');
say Foo.parse('axc');
</code>```

Method rest implements the equivalent of the regex b.*. I hope this answers your question.

Update: I might have misunderstood the question. If the question is "How can I create a regex object" (and not "how can I write code that acts like a regex", as I understood it), the answer is that you have to go through the rx// quoting construct:

```<code>my $str = 'ab.*';
my $re = rx/ <$str> /;

say 'fooabc' ~~ $re;       # Output: ｢abc｣
</code>```

Body:
A Perl 6 Regex is a more specific type of Method, so I had the idea that maybe I could do something black-magicky in a regular method that produces the same thing. I particularly am curious about doing this without changing any grammars.

However, looking at Perl6/Grammar.nqp (which I barely understand), that this is really not an inheritance thing. I think, based on my reading, that the Perl 6 grammar switches slangs (sub languages) when it sees one of the regex declarators. That is, a different grammar parses the guts of regex { ... } and method {...}.

So, first, is that right?

Then, just for giggles, I thought that maybe I could be inside a method block but tell it to use a different slang (see for instance, "Slangs" from the 2013 Perl 6 Advent Calendar or "Slangs Today").

However, everything I've found looks like it wants to change the grammar. Is there a way to do it without that and return a string that is treated as if it had come out of regex { ... }?

method actually-returns-a-regex {
     ...
     }

I don't have any practical use for this. I just keep wondering about it.

Body:
First of all, the Perl 6 design documents mandate an API where regexes return a lazy list of possible matches. If Rakudo adhered to that API, you could easily write a method that acted as a regex, but parsing would be very slow (because lazy lists tend to perform much worse than a compact list of string positions (integers) that act as a backtracking stack).

Instead, Perl 6 regexes return matches. And you can do the same. Here is an example of a method that is called like a regex inside of a grammar:

grammar Foo {
    token TOP { a <rest> }

    method rest() {
        if self.target.substr(self.pos, 1) eq 'b' {
            return Match.new(
                orig   => self.orig,
                target => self.target,
                from => self.pos,
                to   => self.target.chars,
            );
        }
        else {
            return Match.new();
        }
    }
}

say Foo.parse('abc');
say Foo.parse('axc');

Method rest implements the equivalent of the regex b.*. I hope this answers your question.

Update: I might have misunderstood the question. If the question is "How can I create a regex object" (and not "how can I write code that acts like a regex", as I understood it), the answer is that you have to go through the rx// quoting construct:

my $str = 'ab.*';
my $re = rx/ <$str> /;

say 'fooabc' ~~ $re;       # Output: ｢abc｣


问:
Azure App Service - DateTime changes during Sync
I'm working on an App wich uses Xamarin.Forms and Azure App Service (include offline Sync).

On the client there is a piece of code like this:

```<code>appointment.StartDate = System.DateTime.Now;
</code>```

Let's suppose appointment.StartDate is now 2017-07-05 12:00:00.

After the user syncs the data against the server, this happens:

Date in SqlLite database (on client):  2017-07-05 12:00:00

Date in server database: 2017-07-05 10:00:00

So, I assume that Azure changes my date to UTC. That might be technically correct because you should always store UTC in a database and handle timezone conversions in the client. But unfortunately, the server database is old and stores locale dates.

How can I make the Azure store the local date from the client in the server database and not UTC?

I tried to change the WEBSITE_TIME_ZONE property in Azure to my local timezone but this doesn't work: http://www.louischarlesgagnon.com/post/azure-app-service-set-timezone-for-your-web-application

Update 06.07.2017:

After some further research, I found out that this is a known "problem".

Look here:

https://github.com/Azure/azure-mobile-apps-net-client/issues/131

Azure Mobile Apps saves incorrect datetime in Sqlite database

https://forums.asp.net/t/1808269.aspx?DateTime+issues+with+Azure+c+javascript+sql+so+confused+

After reading this I was able to build a solution that resolves a part of the problem. On the client side, I'm now doing something like this.

```<code> public System.DateTime? Start
    {
        get
        {
            System.DateTime? dateTime = GetValue<System.DateTime?>(_start);
            if (dateTime.HasValue)
                dateTime = System.DateTime.SpecifyKind(dateTime.Value, System.DateTimeKind.Utc);

            return dateTime;
        }
        set
        {
            System.DateTime? dateTime = value;
            if (dateTime.HasValue)
                dateTime = System.DateTime.SpecifyKind(dateTime.Value, System.DateTimeKind.Utc);

            SetValue<System.DateTime?>(_start, dateTime);
        }
    }
</code>```

This tells Azure that the date is already in UTC and Azure does not have to convert. This works in the scenario that the System.DateTime, which was created on the client side, is now successfully stored in the server database without conversion.

But there is now an another problem:

When Azure returns the date stored in the server database to the client, Azure converts the "UTC date" to local date. Here is an example of the current situation:

Client Date: 06.07.2017 14:30

-> Client push date to server

Server date: 06.07.2017 14:30

-> Client gets date from server

Client date: 06.07.2017 16:30

答:
But unfortunately the server database is old and stores locale dates.How can I make Azure to store the local date from the client in the server database and not UTC?

According to your description, I suggest you could store long type value DateTime.UtcNow.Ticks as your datetime not use datetime type.

This value will not be changed in your server database and it could be converted back to UTC time.

When you want to use the time, you could convert Ticks back to the datetime.

More details, you could refer to these codes:

```<code>    //get utc time ticks
    long i = DateTime.UtcNow.Ticks;
    //convert back to local time
    DateTime myDate = new DateTime(i).ToLocalTime();
</code>```

I'm correct that I have to adapt my legacy applications so that they can deal with UTC?

In my opinion, I suggest you could store UTC time to your database. Then you could convert the UTC time to local time. This is right way to design your application. If there are different timezone customer, how you convert the database's local time to customer timezone's local time?

UTC is the time standard commonly used across the world. The world's timing centers have agreed to keep their time scales closely synchronized - or coordinated - therefore the name Coordinated Universal Time.

So I suggest you could use tolocaltime method to convert the UTC time to local time in your apps.

Body:
I'm working on an App wich uses Xamarin.Forms and Azure App Service (include offline Sync).

On the client there is a piece of code like this:

appointment.StartDate = System.DateTime.Now;

Let's suppose appointment.StartDate is now 2017-07-05 12:00:00.

After the user syncs the data against the server, this happens:

Date in SqlLite database (on client):  2017-07-05 12:00:00

Date in server database: 2017-07-05 10:00:00

So, I assume that Azure changes my date to UTC. That might be technically correct because you should always store UTC in a database and handle timezone conversions in the client. But unfortunately, the server database is old and stores locale dates.

How can I make the Azure store the local date from the client in the server database and not UTC?

I tried to change the WEBSITE_TIME_ZONE property in Azure to my local timezone but this doesn't work: http://www.louischarlesgagnon.com/post/azure-app-service-set-timezone-for-your-web-application

Update 06.07.2017:

After some further research, I found out that this is a known "problem".

Look here:

https://github.com/Azure/azure-mobile-apps-net-client/issues/131

Azure Mobile Apps saves incorrect datetime in Sqlite database

https://forums.asp.net/t/1808269.aspx?DateTime+issues+with+Azure+c+javascript+sql+so+confused+

After reading this I was able to build a solution that resolves a part of the problem. On the client side, I'm now doing something like this.

 public System.DateTime? Start
    {
        get
        {
            System.DateTime? dateTime = GetValue<System.DateTime?>(_start);
            if (dateTime.HasValue)
                dateTime = System.DateTime.SpecifyKind(dateTime.Value, System.DateTimeKind.Utc);

            return dateTime;
        }
        set
        {
            System.DateTime? dateTime = value;
            if (dateTime.HasValue)
                dateTime = System.DateTime.SpecifyKind(dateTime.Value, System.DateTimeKind.Utc);

            SetValue<System.DateTime?>(_start, dateTime);
        }
    }

This tells Azure that the date is already in UTC and Azure does not have to convert. This works in the scenario that the System.DateTime, which was created on the client side, is now successfully stored in the server database without conversion.

But there is now an another problem:

When Azure returns the date stored in the server database to the client, Azure converts the "UTC date" to local date. Here is an example of the current situation:

Client Date: 06.07.2017 14:30

-> Client push date to server

Server date: 06.07.2017 14:30

-> Client gets date from server

Client date: 06.07.2017 16:30

Body:
But unfortunately the server database is old and stores locale dates.How can I make Azure to store the local date from the client in the server database and not UTC?

According to your description, I suggest you could store long type value DateTime.UtcNow.Ticks as your datetime not use datetime type.

This value will not be changed in your server database and it could be converted back to UTC time.

When you want to use the time, you could convert Ticks back to the datetime.

More details, you could refer to these codes:

    //get utc time ticks
    long i = DateTime.UtcNow.Ticks;
    //convert back to local time
    DateTime myDate = new DateTime(i).ToLocalTime();

I'm correct that I have to adapt my legacy applications so that they can deal with UTC?

In my opinion, I suggest you could store UTC time to your database. Then you could convert the UTC time to local time. This is right way to design your application. If there are different timezone customer, how you convert the database's local time to customer timezone's local time?

UTC is the time standard commonly used across the world. The world's timing centers have agreed to keep their time scales closely synchronized - or coordinated - therefore the name Coordinated Universal Time.

So I suggest you could use tolocaltime method to convert the UTC time to local time in your apps.


问:
Predicate inside a Where<> query not hit?
I need to call the method for each item in the list. So, I have used Where<> query as follows,

```<code>List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});
</code>```

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

答:
When you look at the Where-Method source code you can easily see why:

```<code>    internal static IEnumerable<T> Where<T>(this IEnumerable<T> enumerable, Func<T, bool> where) {
        foreach (T t in enumerable) {
            if (where(t)) {
                yield return t;
            }
        }
    }
</code>```

The yield will cause the execution to only happen once the returned IEnumerable<T> is actually accessed. That is what is called deferred execution.

Body:
I need to call the method for each item in the list. So, I have used Where<> query as follows,

List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

Body:
When you look at the Where-Method source code you can easily see why:

    internal static IEnumerable<T> Where<T>(this IEnumerable<T> enumerable, Func<T, bool> where) {
        foreach (T t in enumerable) {
            if (where(t)) {
                yield return t;
            }
        }
    }

The yield will cause the execution to only happen once the returned IEnumerable<T> is actually accessed. That is what is called deferred execution.


问:
Dynamic Reports Generation in laravel
I'm trying to develop a custom reports generation for my application, in which the user will dynamically input the model and its related model.And will select the related columns for which the report is needed and will have conditional statements for 'AND' and 'OR' conditions.

The same functionality is done is vtiger ,Zoho CRM and sales force .

My doubt is which is the efficient way of doing it.

1.Either by creating tables for each modules and defining its column in database
2.Or by providing a config file for all the set up
3.Or by creating a model class for all reports and defining its related model attributes and binding data using getter and setter(accessors and mutators).
4.Or suggest me any other preferrable method or any packages with have minimal functionalities relating this

I know is complex but please suggest me few hints from your point of view.

Please find the below for the flow.

答:
you can use a Querybuilder to generate queries by users themselves.
then use something similar to JSReport to allow users to design reports.
There are very good web report designers out there, but most of them are for a price. if you still wanna make your own, refer these;
Seal reports
JSReports for reference what you looking for is real ;-)

use JQueryQueryBuilder and customize according to your need.
use Laravel Boilerplate or something to start-off with.
use Handlebars.js / Mustache.js or Blade as the template engine.
be creative...

cheers!!!

Title: Dynamic Reports Generation in laravel


问:
Error:Cannot get property 'args' on null object when build on android studio
I am doing an react native project. When I open the project on Android Studio. The following error is shown.

```<code>Error:Cannot get property 'args' on null object
</code>```

I have checked setting gradle. It is just like bellow:

```<code>rootProject.name = 'my_app_name'
include ':app'
</code>```

I also wonder what is 'args' in this statement.

答:
I've had this error.My solution is find 'your project root path'/node_modules/react-native-config/android/dotenv.gradle
enter image description here

def getCurrentFlavor() {
Gradle gradle = getGradle()
String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

Pattern pattern = Pattern.compile("(assemble|generate|install)(.*?)(Debug|Release)")
Matcher matcher = pattern.matcher(tskReqStr)

if( matcher.find() ) {
String variant = matcher.group(2) + matcher.group(3)
return variant.toLowerCase()
} else {
return "";
}
}```

enter image description here

I hope it help you!

Body:
I am doing an react native project. When I open the project on Android Studio. The following error is shown.

Error:Cannot get property 'args' on null object

I have checked setting gradle. It is just like bellow:

rootProject.name = 'my_app_name'
include ':app'

I also wonder what is 'args' in this statement.

Body:
I've had this error.My solution is find 'your project root path'/node_modules/react-native-config/android/dotenv.gradle
enter image description here

def getCurrentFlavor() {
Gradle gradle = getGradle()
String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

Pattern pattern = Pattern.compile("(assemble|generate|install)(.*?)(Debug|Release)")
Matcher matcher = pattern.matcher(tskReqStr)

if( matcher.find() ) {
String variant = matcher.group(2) + matcher.group(3)
return variant.toLowerCase()
} else {
return "";
}
}

enter image description here

I hope it help you!


问:
Replace view in Snowflake
I created a view (Let's say 'ViewA') and I want to replace it, what supporting syntax do we have? I went through the documentation, maybe not thoroughly enough, and found nothing.

I got this: https://docs.snowflake.net/manuals/sql-reference/sql/create-view.html#syntax

But this is of little help.

These are the commands I am using:

```<code>CREATE VIEW view_name (alias_1, alias_2) AS
 SELECT col_1, col_2
 FROM table
 WHERE col_3 > 2;

 alter VIEW view_name (alias_1, alias_2) AS
 SELECT col_1 as 'Employee Name',
 col_2 as 'alias_3'
 FROM table
 WHERE col_3 > 2;
</code>```

答:
You can use the CREATE OR REPLACE syntax, documented on the page you linked. Example:

```<code>create or replace VIEW view_name (alias_1, alias_2) AS
SELECT col_1 as 'Employee Name',
col_2 as 'alias_3'
FROM table
WHERE col_3 > 2
</code>```

This should be an atomic operation.

If this is not what you're looking for, please explain what you mean by "replace" exactly.

Title: Replace view in Snowflake

Body:
I created a view (Let's say 'ViewA') and I want to replace it, what supporting syntax do we have? I went through the documentation, maybe not thoroughly enough, and found nothing.

I got this: https://docs.snowflake.net/manuals/sql-reference/sql/create-view.html#syntax

But this is of little help.

These are the commands I am using:

CREATE VIEW view_name (alias_1, alias_2) AS
 SELECT col_1, col_2
 FROM table
 WHERE col_3 > 2;

 alter VIEW view_name (alias_1, alias_2) AS
 SELECT col_1 as 'Employee Name',
 col_2 as 'alias_3'
 FROM table
 WHERE col_3 > 2;

Body:
You can use the CREATE OR REPLACE syntax, documented on the page you linked. Example:

create or replace VIEW view_name (alias_1, alias_2) AS
SELECT col_1 as 'Employee Name',
col_2 as 'alias_3'
FROM table
WHERE col_3 > 2

This should be an atomic operation.

If this is not what you're looking for, please explain what you mean by "replace" exactly.


问:
Efficient alternative way than using multiple if statements to check keys in a dictionary
I have around 45 if statements that checks the dictionary  to see if it has that key.

```<code>    private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
    {
            MessageName msgName = null;
            List<MessageName> msgNameList = new List<MessageName>();
            var msgObjOuter = new MessageName();

            if (infoHash.ContainsKey("redis_version"))
            {
                msgName = new MessageName();
                msgName.MessageID = msgDescritionAndID["redis_version"];
                msgName.DiagnosticCnt = 0;
                msgName.DiagnosticStr = infoHash["redis_version"];
                msgNameList.Add(msgName);
            }
           if (infoHash.ContainsKey("uptime_in_seconds"))
           {
            msgName = new MessageName();
            msgName.MessageID = msgDescritionAndID["uptime_in_seconds"];
            msgName.DiagnosticCnt = Convert.ToInt32(infoHash["uptime_in_seconds"]);
            msgName.DiagnosticStr = "";
            msgNameList.Add(msgName);
          }
          //... 40 more if statements
         return msgNameList;
   }
</code>```

This really hasn't had a hit on performance but I was wondering if there was a more efficient way to check all the keys in that dictionary and if it does insert it's property in to a MessageName object and insert that object into a list. I don't know if switch statements would help in performance.

答:
There is no need to perform an dictionary lookup for all of your messages, unless your dictionary has a lot of keys you are not interested in, in which case stick with what you have.

Otherwise, You already know what keys are in the dictionary so you can just enumerate them.

For those that message that you are currently looking up the value after checking for the key you will be eliminating another lookup because enumerating the dictionary has the extra benefit of getting the value for free.

Then all that is left to do is lookup the int16 from your second dictionary for those keys that you want to process.

You can process this more efficiently and reduce your code base like this (assuming infoHash has only keys you want):

```<code>private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
{
    MessageName msgName = null;
    List<MessageName> msgNameList = new List<MessageName>();
    var msgObjOuter = new MessageName();
    // there is no need to perform an o(1) lookup of infoHash for 40 variables.
    // You already have a list of keys it contains so just enumerate them.
    foreach (KeyValuePair<string, string> info in infoHash)
    {
        var msg = new MessageName() { MessageID = msgDescritionAndID[info.Key] };
        switch (info.Key)
        {
            // switch all of your int16 versions first:
            case "redis_version":
            case "hash_int_message_2":
            case "hash_int_message_3":
                msg.DiagnosticCnt = Convert.ToInt32(infoHash[info.Value]);
                break;
            // switch on all message types getting int16 from info.Key
            case "msg_int_message_1":
            case "msg_int_message_2":
                msg.DiagnosticCnt = Convert.ToInt32(msgDescritionAndID[info.Key]);
                break;
            // everything left over is reading value from our current info.
            //  default:
                msg.DiagnosticStr = info.Value;
                break;

        }
        msgNameList.Add(msgName);
    }
    return msgNameList;
}
</code>```

Even if infoHash contains keys your not interested in, you can code it like this:

```<code>private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
{
    MessageName msgName = null;
    List<MessageName> msgNameList = new List<MessageName>();
    var msgObjOuter = new MessageName();
    // there is no need to perform an o(1) lookup of infoHash for 40 variables.
    // You already have a list of keys it contains so just enumerate them.
    foreach (KeyValuePair<string, string> info in infoHash)
    {
        var msg = new MessageName() { MessageID = msgDescritionAndID[info.Key] };
        switch (info.Key)
        {
            // switch all of your int16 versions first:
            case "redis_version":
            case "hash_int_message_2":
            case "hash_int_message_3":
                msg.DiagnosticCnt = Convert.ToInt32(infoHash[info.Value]);
                break;
            // switch on all message types getting int16 from info.Key
            case "msg_int_message_1":
            case "msg_int_message_2":
                msg.DiagnosticCnt = Convert.ToInt32(msgDescritionAndID[info.Key]);
                break;
            // switch on all message types that have DiagnosticStr in info.Value;
            case "msg_str_message_1":
            case "msg_str_message_2":
                msg.DiagnosticStr = info.Value;

                break;
            default:    // everything left over we are not interested in
                continue;
                break;

        }
        msgNameList.Add(msgName);
    }
    return msgNameList;
}
</code>```

Body:
I have around 45 if statements that checks the dictionary  to see if it has that key.

    private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
    {
            MessageName msgName = null;
            List<MessageName> msgNameList = new List<MessageName>();
            var msgObjOuter = new MessageName();

            if (infoHash.ContainsKey("redis_version"))
            {
                msgName = new MessageName();
                msgName.MessageID = msgDescritionAndID["redis_version"];
                msgName.DiagnosticCnt = 0;
                msgName.DiagnosticStr = infoHash["redis_version"];
                msgNameList.Add(msgName);
            }
           if (infoHash.ContainsKey("uptime_in_seconds"))
           {
            msgName = new MessageName();
            msgName.MessageID = msgDescritionAndID["uptime_in_seconds"];
            msgName.DiagnosticCnt = Convert.ToInt32(infoHash["uptime_in_seconds"]);
            msgName.DiagnosticStr = "";
            msgNameList.Add(msgName);
          }
          //... 40 more if statements
         return msgNameList;
   }

This really hasn't had a hit on performance but I was wondering if there was a more efficient way to check all the keys in that dictionary and if it does insert it's property in to a MessageName object and insert that object into a list. I don't know if switch statements would help in performance.

Body:
There is no need to perform an dictionary lookup for all of your messages, unless your dictionary has a lot of keys you are not interested in, in which case stick with what you have.

Otherwise, You already know what keys are in the dictionary so you can just enumerate them.

For those that message that you are currently looking up the value after checking for the key you will be eliminating another lookup because enumerating the dictionary has the extra benefit of getting the value for free.

Then all that is left to do is lookup the int16 from your second dictionary for those keys that you want to process.

You can process this more efficiently and reduce your code base like this (assuming infoHash has only keys you want):

private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
{
    MessageName msgName = null;
    List<MessageName> msgNameList = new List<MessageName>();
    var msgObjOuter = new MessageName();
    // there is no need to perform an o(1) lookup of infoHash for 40 variables.
    // You already have a list of keys it contains so just enumerate them.
    foreach (KeyValuePair<string, string> info in infoHash)
    {
        var msg = new MessageName() { MessageID = msgDescritionAndID[info.Key] };
        switch (info.Key)
        {
            // switch all of your int16 versions first:
            case "redis_version":
            case "hash_int_message_2":
            case "hash_int_message_3":
                msg.DiagnosticCnt = Convert.ToInt32(infoHash[info.Value]);
                break;
            // switch on all message types getting int16 from info.Key
            case "msg_int_message_1":
            case "msg_int_message_2":
                msg.DiagnosticCnt = Convert.ToInt32(msgDescritionAndID[info.Key]);
                break;
            // everything left over is reading value from our current info.
            //  default:
                msg.DiagnosticStr = info.Value;
                break;

        }
        msgNameList.Add(msgName);
    }
    return msgNameList;
}

Even if infoHash contains keys your not interested in, you can code it like this:

private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
{
    MessageName msgName = null;
    List<MessageName> msgNameList = new List<MessageName>();
    var msgObjOuter = new MessageName();
    // there is no need to perform an o(1) lookup of infoHash for 40 variables.
    // You already have a list of keys it contains so just enumerate them.
    foreach (KeyValuePair<string, string> info in infoHash)
    {
        var msg = new MessageName() { MessageID = msgDescritionAndID[info.Key] };
        switch (info.Key)
        {
            // switch all of your int16 versions first:
            case "redis_version":
            case "hash_int_message_2":
            case "hash_int_message_3":
                msg.DiagnosticCnt = Convert.ToInt32(infoHash[info.Value]);
                break;
            // switch on all message types getting int16 from info.Key
            case "msg_int_message_1":
            case "msg_int_message_2":
                msg.DiagnosticCnt = Convert.ToInt32(msgDescritionAndID[info.Key]);
                break;
            // switch on all message types that have DiagnosticStr in info.Value;
            case "msg_str_message_1":
            case "msg_str_message_2":
                msg.DiagnosticStr = info.Value;

                break;
            default:    // everything left over we are not interested in
                continue;
                break;

        }
        msgNameList.Add(msgName);
    }
    return msgNameList;
}


问:
PHP Extract HTML content by HTML parse get null object
I am trying to extract content from a local HTML file. And I use the HTML parse method, however get nothing.

PHP code is as below:

```<code>$doc = new \DOMDocument();
$doc->loadHTML("assets.html");
$tables = $doc->getElementsByTagName('table');
foreach($tables as $table) {
   $content = $doc->saveHTML($table);
 }
echo $content;
</code>```

Debug step by step,$doc->loadHTML("assets.html") return true,and got DOMNodeList::__set_state(array(
)) for $tables .

The part of assets.html is as below:

                                    <button type="button" class="btn btn-info dropdown-toggle" id="manage" data-toggle="dropdown">
                                            新增

                                        </button>

增加资产

增加明细

                                    <button type="button" class="btn btn-danger" id="deleteassets" value="" >删除</button>
                                    <button type="button" class="btn btn-success" id="modifyassets" value="" >修改</button>
                                    <button type="button" class="btn btn-warning" id="lend-lease" value="" >领用</button>

                                          序号
                                          资产类别
                                          资产名称
                                          型号
                                          单位
                                          数量

```

答:
You are loading HTML from a file so use: $doc->loadHTMLFile("assets.html"); instead of $doc->loadHTML("assets.html");

You should get data inside $content after that.

Body:
I am trying to extract content from a local HTML file. And I use the HTML parse method, however get nothing.

PHP code is as below:

$doc = new \DOMDocument();
$doc->loadHTML("assets.html");
$tables = $doc->getElementsByTagName('table');
foreach($tables as $table) {
   $content = $doc->saveHTML($table);
 }
echo $content;

Debug step by step,$doc->loadHTML("assets.html") return true,and got DOMNodeList::__set_state(array(
)) for $tables .

The part of assets.html is as below:

                                    <button type="button" class="btn btn-info dropdown-toggle" id="manage" data-toggle="dropdown">
                                            新增

                                        </button>

增加资产

增加明细

                                    <button type="button" class="btn btn-danger" id="deleteassets" value="" >删除</button>
                                    <button type="button" class="btn btn-success" id="modifyassets" value="" >修改</button>
                                    <button type="button" class="btn btn-warning" id="lend-lease" value="" >领用</button>

                                          序号
                                          资产类别
                                          资产名称
                                          型号
                                          单位
                                          数量


问:
Need help with: jquery prepend doctype to html
Here's my situation:

I am editing an application's CSS style sheet.

I can ONLY edit the CSS style sheet (unless I can creatively glom onto another file using the CSS, or possibly add a small jQuery prepend statement in an existing .js)

Application is ONLY ie6, ie7 and ie8 compliant. They never use FireFox, and it's not an option.

Looking for help with:

1) I think I need to use jQuery to "prepend/prependTo" a "doctype " on to

```<code>html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"
</code>```

Without the !doctype it throws ie8 into quirksmode and of course doesn't accept any styles such as "input[type=checkbox]"

I have not used prepend before. Can you help me with full and correct syntax on how to make the following:

CURRENT:

DESIRED: <doctype html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

This has not worked for me yet $("html ").prepend("doctype ")

答:
It's not <doctype html>. It's:

```<code><!DOCTYPE html>
<html (xmlns or any other attributes you want)>
</code>```

<!DOCTYPE is not an element. It has <! at the start, which is invalid for an element. This is the the “doctype declaration”, and it cannot usefully be altered after initial parsing.

Even on browsers whose DOM interfaces let you move/replace the DocumentType node representing the doctype declaration, this does not have the effect of changing between Quirks and Standards mode, which is something that is decided only at initial load time. You cannot mutate a document between modes.

You can load a new document from the existing document but with a changed mode:

```<code><!-- no doctype, loads in Quirks Mode (BackCompat) -->
<html>
    <!-- rest of the document, then at the end: -->

    <script>
        alert('now in compatMode '+document.compatMode);
        if (document.compatMode==='BackCompat') {
            setTimeout(function() {
                var markup= document.documentElement.innerHTML;
                markup= '<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+markup+'</html>';
                document.open();
                document.write(markup);
                document.close();
            }, 0);
        }
    </script>
</html>
</code>```

But I would strongly advise against it. It's ugly, will reset any state and redraw at the end of load time, and has all sorts of negative implications for scripting.

If you want Standards Mode, you really need to be adding the doctype to the HTML itself. If you absolutely can't touch the application, how about using an ISAPI filter (assuming your web server is IIS) to add the doctype to its HTML output?

ContentLicense: CC BY-SA 2.5

Body:
Here's my situation:

I am editing an application's CSS style sheet.

I can ONLY edit the CSS style sheet (unless I can creatively glom onto another file using the CSS, or possibly add a small jQuery prepend statement in an existing .js)

Application is ONLY ie6, ie7 and ie8 compliant. They never use FireFox, and it's not an option.

Looking for help with:

1) I think I need to use jQuery to "prepend/prependTo" a "doctype " on to

html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"

Without the !doctype it throws ie8 into quirksmode and of course doesn't accept any styles such as "input[type=checkbox]"

I have not used prepend before. Can you help me with full and correct syntax on how to make the following:

CURRENT:

DESIRED: <doctype html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

This has not worked for me yet $("html ").prepend("doctype ")

Body:
It's not <doctype html>. It's:

<!DOCTYPE html>
<html (xmlns or any other attributes you want)>

<!DOCTYPE is not an element. It has <! at the start, which is invalid for an element. This is the the “doctype declaration”, and it cannot usefully be altered after initial parsing.

Even on browsers whose DOM interfaces let you move/replace the DocumentType node representing the doctype declaration, this does not have the effect of changing between Quirks and Standards mode, which is something that is decided only at initial load time. You cannot mutate a document between modes.

You can load a new document from the existing document but with a changed mode:

<!-- no doctype, loads in Quirks Mode (BackCompat) -->
<html>
    <!-- rest of the document, then at the end: -->

    <script>
        alert('now in compatMode '+document.compatMode);
        if (document.compatMode==='BackCompat') {
            setTimeout(function() {
                var markup= document.documentElement.innerHTML;
                markup= '<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+markup+'</html>';
                document.open();
                document.write(markup);
                document.close();
            }, 0);
        }
    </script>
</html>

But I would strongly advise against it. It's ugly, will reset any state and redraw at the end of load time, and has all sorts of negative implications for scripting.

If you want Standards Mode, you really need to be adding the doctype to the HTML itself. If you absolutely can't touch the application, how about using an ISAPI filter (assuming your web server is IIS) to add the doctype to its HTML output?


问:
Textbox compulsory when radio button is selected
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button. When yes radiobutton is clicked. the quantity textbox should not be empty. But it can be empty if no radiobutton is clicked.
This functionality should work when submit button is clicked with yes radiobutton is selected.

```<code> <HTML>
    <head>
    radio
    </head>
    <body>
    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>
</code>```

I'm new to mvc and javascript. Please help me with javascript code too, and the way i should link it with my view. Javascript:

```<code>function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}
</code>```

答:
I can say that the code you have posted works fine with small changes

function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required', true);
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required', false);
        alert("Text Box not required");
    }
}```
<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>
   <form id="radio">
     Add to electronic
     <input type="radio" name="yes" onclick="validate(this)" id="yes"/>Yes
     <input type="radio" name="yes" id="no" onclick="validate(this)"/> No<br />
       <label>Quantity</label>
    <input type="text" size="25" name="dir" id="dir"/>
    <button type="submit" name="insert">insert</button>
</form></code>```

You have missed double quotes in form id and <button> attributes.

You have missed </form> close tag

validate(_this) inside the radio input must be validate(this)

$('#dir').attr('required'); should be $('#dir').attr('required', boolean_value);

Body:
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button. When yes radiobutton is clicked. the quantity textbox should not be empty. But it can be empty if no radiobutton is clicked.
This functionality should work when submit button is clicked with yes radiobutton is selected.

    radio

    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No

    Quantity<input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>

I'm new to mvc and javascript. Please help me with javascript code too, and the way i should link it with my view. Javascript:

function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

Body:
I can say that the code you have posted works fine with small changes

function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required', true);
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required', false);
        alert("Text Box not required");
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <form id="radio">
     Add to electronic
     <input type="radio" name="yes" onclick="validate(this)" id="yes"/>Yes
     <input type="radio" name="yes" id="no" onclick="validate(this)"/> No<br />
       <label>Quantity</label>
    <input type="text" size="25" name="dir" id="dir"/>
    <button type="submit" name="insert">insert</button>
</form>

You have missed double quotes in form id and <button> attributes.

You have missed </form> close tag

validate(_this) inside the radio input must be validate(this)

$('#dir').attr('required'); should be $('#dir').attr('required', boolean_value);


问:
Reverse RecyclerView items in Chat application(First item at bottom)
I want to implement a chat application what i want is when i send a message it should show at the last...., just like chat application.

```<code><android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stackFromBottom="true"/>
</code>```

javaclass.xml

```<code>layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
</code>```

答:
Add this code in your java class.</p>

```<code>layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(true);
layoutManager.setReverseLayout(true);
</code>```

Body:
I want to implement a chat application what i want is when i send a message it should show at the last...., just like chat application.

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stackFromBottom="true"/>

javaclass.xml

layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);

Body:
Add this code in your java class.

layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(true);
layoutManager.setReverseLayout(true);


问:
Difference between 2 ways of declaring String
I would like to know what is the difference between 2 ways of declaring String as the example below:</p>

```<code>String str = "Java String";

String str = new String("Java String);
</code>```

答:
Simply put, new String("Java String"); explicitly creates a new and referentially distinct instance of a String object;

String s = "Java String"; may reuse an instance from the string constant pool if one is already available.

So if you have already created a String object with the value of "Java String", no new String will be created here.

Body:
I would like to know what is the difference between 2 ways of declaring String as the example below:

String str = "Java String";

String str = new String("Java String);


问:
How to know how many rows have been inserted till now?
Question 1:

I'm running a query like this:

```<code>select *
into table
from view
</code>```

The view has a lot of calculations and the query is running for over 15 hours. I know how many rows I need to have in the data. Is there a way to know how many rows were insert to table till now so I will know if to keep with this process or find another way to execute this.

Question 2: is the Insert into , select from more efficient than select * into? when you are trying to move data from view to a table?

Thanks

答:
try

select count(*) from table

Body:
Question 1:

I'm running a query like this:

select *
into table
from view

The view has a lot of calculations and the query is running for over 15 hours. I know how many rows I need to have in the data. Is there a way to know how many rows were insert to table till now so I will know if to keep with this process or find another way to execute this.

Question 2: is the Insert into , select from more efficient than select * into? when you are trying to move data from view to a table?

Thanks

Body:
try

select count(*) from table


问:
Can't bring up JPA console in Intellij
When I try to open the JPA console from the Persistence tool window in IntelliJ, it's grayed out, I have a persistence.xml file with the entities classes mapped out, I have data-sources also mapped out. I haven't set any properties in the persistence unit in persistence.xml file - what am I missing?

Intellij version: 2017.1.4

答: As noted in help documentation make sure that the Java EE: EJB, JPA, Servlets plugin is enabled. Also JPA facet must be configured for the module (with set JPA configuration file and JPA Provided). Then you can make JPA Console available after associating your persistence unit with the corresponding data source.</p>

Title: Can't bring up JPA console in Intellij


问:
PHP string with unicode character (\u2022) won't echo as bullet
I have a string which contains bullets • in  the following format:

```<code>$string = "Yay bullets!!\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n#somany";
</code>```

I need to echo the string displaying the bullets. The closest I've come to printing this out is by making $string = "\u2022"; and then echoing json_decode('"' . $string . '"'); which prints the bullet just fine.

When I try to do the same to the full $string I get no result at all and no error.

Here are some things I have tried with their resulting output:

```<code>$raw = htmlspecialchars("Yay bullets!!\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n#yes", ENT_QUOTES);

echo $raw;
</code>```

Result:

```<code>Yay bullets!!
\u2022
\u2022
\u2022
\u2022
\u2022
#yes
</code>```

When I try:

```<code>echo mb_convert_encoding($raw, 'UTF-8', 'HTML-ENTITIES');
</code>```

Result: Same as above. No change.

When I try:

```<code>echo json_decode('"' . $raw . '"');
</code>```

Result: No output.

When I try:

```<code>echo mb_convert_encoding($raw, 'UTF-8', 'UTF-16BE');
</code>```

Result: 奡礠扵汬整猡ℊ屵㈰㈲ੜ甲〲㈊屵㈰㈲ੜ甲〲㈊屵㈰㈲ਣ祥

I would really appreciate help figuring out how to output this properly.

Thanks.

EDIT

In addition to bullets, I am also failing to print emoji reference codes such as \\ud83d\\udc93. Reference here: http://emojipedia.org/face-with-tears-of-joy/

答:
you can do like this. It working for both. please check</p>

```<code> function decodeEmoticons($src) {
    $replaced = preg_replace("/\\\\u([0-9A-F]{1,4})/i", "&#x$1;", $src);
    $result = mb_convert_encoding($replaced, "UTF-16", "HTML-ENTITIES");
    $result = mb_convert_encoding($result, 'utf-8', 'utf-16');
    return $result;
}
$r = "Yay bullets!!\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n#somany";
echo decodeEmoticons($r);
$src = "\u263a\ud83d\ude00\ud83d\ude01\ud83d\ude02\ud83d\ude03";
echo decodeEmoticons($src);
</code>```

Body:
I have a string which contains bullets • in  the following format:

$string = "Yay bullets!!\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n#somany";

I need to echo the string displaying the bullets. The closest I've come to printing this out is by making $string = "\u2022"; and then echoing json_decode('"' . $string . '"'); which prints the bullet just fine.

When I try to do the same to the full $string I get no result at all and no error.

Here are some things I have tried with their resulting output:

$raw = htmlspecialchars("Yay bullets!!\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n#yes", ENT_QUOTES);

echo $raw;

Result:

Yay bullets!!
\u2022
\u2022
\u2022
\u2022
\u2022
#yes

When I try:

echo mb_convert_encoding($raw, 'UTF-8', 'HTML-ENTITIES');

Result: Same as above. No change.

When I try:

echo json_decode('"' . $raw . '"');

Result: No output.

When I try:

echo mb_convert_encoding($raw, 'UTF-8', 'UTF-16BE');

Result: 奡礠扵汬整猡ℊ屵㈰㈲ੜ甲〲㈊屵㈰㈲ੜ甲〲㈊屵㈰㈲ਣ祥

I would really appreciate help figuring out how to output this properly.

Thanks.

EDIT

In addition to bullets, I am also failing to print emoji reference codes such as \\ud83d\\udc93. Reference here: http://emojipedia.org/face-with-tears-of-joy/

Body:
you can do like this. It working for both. please check

 function decodeEmoticons($src) {
    $replaced = preg_replace("/\\\\u([0-9A-F]{1,4})/i", "&#x$1;", $src);
    $result = mb_convert_encoding($replaced, "UTF-16", "HTML-ENTITIES");
    $result = mb_convert_encoding($result, 'utf-8', 'utf-16');
    return $result;
}
$r = "Yay bullets!!\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n\\u2022\n#somany";
echo decodeEmoticons($r);
$src = "\u263a\ud83d\ude00\ud83d\ude01\ud83d\ude02\ud83d\ude03";
echo decodeEmoticons($src);


问:
How display a loading image correctly on Android phone
I have been trying to use a .gif file from my resources, but I get no movement when it loads.  I am using it as a loading image while I am doing an asynchronous task.  I was previously using a progress dialog but now I would like to display the image myself and not use a dialog.    How can I get this image to display correctly?</p>

答:
Try using AnimationDrawable:
http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

Basically, you should split each of the frames in your gif into separate files - such as .png file (say if it had transparency) and specify these files in the <animation-list> instead. You can also control the duration of each frame.

See the link for code example


问:
Liberator Custom Not Authorized Message
How do I pass in a custom 401 Not Authorized message when :not-authorized? is true? I'd like to show a more useful message like Key must have admin permissions.

答:
You need to take a look at handlers:

For every http status code there is a handler function defined in liberator. All have sensible defaults and will return a simple english error message or an empty response, whatever is appropriate.

In your case you need to provide your own handler for :handle-unauthorized key:

```<code>(defresource my-resource
  ...
  :handle-unauthorized (fn [ctx] ...))
</code>```

Title: Liberator Custom Not Authorized Message

Body:
You need to take a look at handlers:

For every http status code there is a handler function defined in liberator. All have sensible defaults and will return a simple english error message or an empty response, whatever is appropriate.

In your case you need to provide your own handler for :handle-unauthorized key:

(defresource my-resource
  ...
  :handle-unauthorized (fn [ctx] ...))


问:
Creating a method with generic param
I am trying to create a generic method in a static class like below
to which I will pass paramData at run time.

```<code> public static void InsertBulk<T>(string procedure, IDictionary<T,T> paramData)

    {
        //Body
    }
</code>```

This is valid but as soon as i remove <T> following method name like below, it start showing
type error. Why is it behaving so.

```<code>public static void InsertBulk(string procedure, IDictionary<T,T> paramData)
        {

       }

IDictionary<int,string> myparams= new IDictionary<int,string>();
</code>```

As far as my understanding I can call this method using classname.InsertBulk("MyProc",myparams);
so, why is it asking for  after method name. What is its use.

答:
There are two separate things to understand here:

How you declare a generic method

How you call a generic method

You need to include the <T> in the method declaration to make it a generic method. Without that, the compiler doesn't know what T is... it expects it to be the name of a regular type.

Now when you call a generic method, you can specify type arguments like this:

```<code>InsertBulk<int>("MyProc", myParams);
</code>```

Here there's just one type argument: int. (This won't compile for reasons described below, but it's an example of specifying a type argument.)

... or you can let the compiler try to infer the type arguments based on the arguments to the method - in this case, it will look at myParams and work out what the type argument has to be to make the call compile. The details of type inference are very complicated, but they're designed so that where reasonable, you can get away without specifying type arguments.

In your case, as myParams is an IDictionary<int, string> it can't compile anyway, as there's no T for which an IDictionary<int, string> is an IDictionary<T, T>. You could potentially make your method have two type parameters instead:

```<code>public static void InsertBulk<TKey, TValue>(
    string procedure, IDictionary<TKey, TValue> paramData)
</code>```

That that point you can call InsertBulk("MyProc", myParams) and the compiler will infer type arguments of int and string.

Title: Creating a method with generic param

Body:
I am trying to create a generic method in a static class like below
to which I will pass paramData at run time.

 public static void InsertBulk<T>(string procedure, IDictionary<T,T> paramData)

    {
        //Body
    }

This is valid but as soon as i remove <T> following method name like below, it start showing
type error. Why is it behaving so.

public static void InsertBulk(string procedure, IDictionary<T,T> paramData)
        {

       }

IDictionary<int,string> myparams= new IDictionary<int,string>();

As far as my understanding I can call this method using classname.InsertBulk("MyProc",myparams);
so, why is it asking for  after method name. What is its use.

Body:
There are two separate things to understand here:

How you declare a generic method

How you call a generic method

You need to include the <T> in the method declaration to make it a generic method. Without that, the compiler doesn't know what T is... it expects it to be the name of a regular type.

Now when you call a generic method, you can specify type arguments like this:

InsertBulk<int>("MyProc", myParams);

Here there's just one type argument: int. (This won't compile for reasons described below, but it's an example of specifying a type argument.)

... or you can let the compiler try to infer the type arguments based on the arguments to the method - in this case, it will look at myParams and work out what the type argument has to be to make the call compile. The details of type inference are very complicated, but they're designed so that where reasonable, you can get away without specifying type arguments.

In your case, as myParams is an IDictionary<int, string> it can't compile anyway, as there's no T for which an IDictionary<int, string> is an IDictionary<T, T>. You could potentially make your method have two type parameters instead:

public static void InsertBulk<TKey, TValue>(
    string procedure, IDictionary<TKey, TValue> paramData)

That that point you can call InsertBulk("MyProc", myParams) and the compiler will infer type arguments of int and string.