问:
Efficient conversion from Indeterminate Value to Unspecified Value
Sometimes in C it is necessary to read a possibly-written item from a partially-written array, such that:

If the item has been written, the read will yield the value that was in fact written, and

If the item hasn't been written, the read will convert an Unspecified bit pattern to a value of the appropriate type, with no side-effects.

There are a variety of algorithms where finding a solution from scratch is expensive, but validating a proposed solution is cheap.  If an array holds solutions for all cases where they have been found, and arbitrary bit patterns for other cases, reading the array, testing whether it holds a valid solution, and slowly computing the solution only if the one in the array isn't valid, may be a useful optimization.

If an attempt to read a non-written array element of a types like uint32_t could be guaranteed to always yield a value of the appropriate type, efficiently such an approach would be easy and straightforward.  Even if that requirement only held for unsigned char, it might still be workable.  Unfortunately, compilers sometimes behave as though reading an Indeterminate Value, even of type unsigned char, may yield something that doesn't behave consistently as a value of that type.  Further, discussions in a Defect Report suggest that operations involving Indeterminate values yield Indeterminate results, so even given something like unsigned char x, *p=&x; unsigned y=*p & 255; unsigned z=(y < 256); it would be possible for z to receive the value 0.

From what I can tell, the function:

```<code>unsigned char solidify(unsigned char *p)
{
  unsigned char result = 0;
  unsigned char mask = 1;
  do
  {
    if (*p & mask) result |= mask;
    mask += (unsigned)mask; // Cast only needed for capricious type ranges
  } while(mask);
  return result;
}
</code>```

would be guaranteed to always yield a value in the range of type unsigned char any time the storage identified can be accessed as that type, even if it happens to hold Indeterminate Value.  Such an approach seems rather slow and clunky, however, given that the required machine code to obtain the desired effect should usually be equivalent to returning x.

Are there any better approaches that would be guaranteed by the Standard to always yield a value within the range of unsigned char, even if the source value is Indeterminate?

Addendum

The ability to solidify values is necessary, among other things, when performing I/O with partially-written arrays and structures, in cases where nothing will care about what bits get output for the parts that were never set.  Whether or not the Standard would require that fwrite be usable with partially-writtten structures or arrays, I would regard I/O routines that can be used in such fashion (writing arbitrary values for portions that weren't set) to be of higher quality than those which might jump the rails in such cases.

My concern is largely with guarding against optimizations which are unlikely to be used in dangerous combinations, but which could nonetheless occur as compilers get more and more "clever".

A problem with something like:

```<code>unsigned char solidify_alt(unsigned char *p)
{ return *p; }
</code>```

is that compilers may combine an optimization which could be troublesome but tolerable in isolation, with one that would be good in isolation but deadly in combination with the first:

If the function is passed the address of an unsigned char which has been optimized to e.g. a 32-bit register, a function like the above may blindly return the contents of that register without clipping it to the range 0-255.  Requiring that callers manually clip the results of such functions would be annoying but survivable if that were the only problem.  Unfortunately...

Since the above function function will "always" return a value 0-255, compilers may omit any "downstream" code that would try to mask the value into that range, check if it was outside, or otherwise do things that would be irrelevant for values outside the range 0-255.

Some I/O devices may require that code wishing to write an octet perform a 16-bit or 32-bit store to an I/O register, and may require that 8 bits contain the data to be written and other bits hold a certain pattern.  They may malfunction badly if any of the other bits are set wrong.  Consider the code:

```<code>void send_byte(unsigned char *p, unsigned int n)
{
  while(n--)
    OUTPUT_REG = solidify_alt(*p++) | 0x0200;
}
void send_string4(char *st)
{
  unsigned char buff[5]; // Leave space for zero after 4-byte string
  strcpy((char*)buff, st);
  send_bytes(buff, 4);
}
</code>```

with the indended semantics that send_string4("Ok"); should send out an 'O', a 'k', a zero byte, and an arbitrary value 0-255.  Since the code uses solidify_alt rather than solidify, a compiler could legally turn that into:

```<code>void send_string4(char *st)
{
  unsigned buff0, buff1, buff2, buff3;
  buff0 = st[0]; if (!buff0) goto STRING_DONE;
  buff1 = st[1]; if (!buff1) goto STRING_DONE;
  buff2 = st[2]; if (!buff2) goto STRING_DONE;
  buff3 = st[3];
 STRING_DONE:
  OUTPUT_REG = buff0 | 0x0200;
  OUTPUT_REG = buff1 | 0x0200;
  OUTPUT_REG = buff2 | 0x0200;
  OUTPUT_REG = buff3 | 0x0200;
}
</code>```

with the effect that OUTPUT_REG may receive values with bits set outside the proper range.  Even if output expression were changed to ((unsigned char)solidify_alt(*p++) | 0x0200) & 0x02FF) a compiler could still simplify that to yield the code given above.

The authors of the Standard refrained from requiring compiler-generated initialization of automatic variables because it would have made code slower in cases where such initialization would be semantically unnecessary.  I don't think they intended that programmers should have to manually initialize automatic variables in cases where all bit patterns would be equally acceptable.

Note, btw, that when dealing with short arrays, initializing all the values will be inexpensive and would often be a good idea, and when using large arrays a compiler would be unlikely to impose the above "optimization".  Omitting the initialization in cases where the array is large enough that the cost matters, however, would make the program's correct operation reliant upon "hope".

答:
I think this is pretty clear. C11 3.19.2

indeterminate value

  either an unspecified value or a trap
  representation

Period. It cannot be anything else than the two cases above.

So code such as unsigned z=(y < 256) can never return 0, because x in your example cannot hold a value larger than 255. As per the representation of character types, 6.2.6, an unsigned char is not allowed to contain padding bits or trap representations.

Other types, on wildly exotic systems, could in theory hold values outside their range, padding bits and trap representations.

On real-world systems, that are extremely likely to use two's complement, trap representations do not exist. So the indeterminate value can only be unspecified. Unspecified, not undefined! There is a myth saying that "reading an indeterminate value is always undefined behavior". Save for trap representations and some other special cases, this is not true, see this. This is merely unspecified behavior.

Unspecified behavior does not mean that the compiler can run havoc and make weird assumptions, as it can when it encounters undefined behavior. It will have to assume that the variable values are in range. What the compiler cannot assume, is that the value is the same between reads - this was addressed by some DR.

Body:
Sometimes in C it is necessary to read a possibly-written item from a partially-written array, such that:

If the item has been written, the read will yield the value that was in fact written, and

If the item hasn't been written, the read will convert an Unspecified bit pattern to a value of the appropriate type, with no side-effects.

There are a variety of algorithms where finding a solution from scratch is expensive, but validating a proposed solution is cheap.  If an array holds solutions for all cases where they have been found, and arbitrary bit patterns for other cases, reading the array, testing whether it holds a valid solution, and slowly computing the solution only if the one in the array isn't valid, may be a useful optimization.

If an attempt to read a non-written array element of a types like uint32_t could be guaranteed to always yield a value of the appropriate type, efficiently such an approach would be easy and straightforward.  Even if that requirement only held for unsigned char, it might still be workable.  Unfortunately, compilers sometimes behave as though reading an Indeterminate Value, even of type unsigned char, may yield something that doesn't behave consistently as a value of that type.  Further, discussions in a Defect Report suggest that operations involving Indeterminate values yield Indeterminate results, so even given something like unsigned char x, *p=&x; unsigned y=*p & 255; unsigned z=(y < 256); it would be possible for z to receive the value 0.

From what I can tell, the function:

unsigned char solidify(unsigned char *p)
{
  unsigned char result = 0;
  unsigned char mask = 1;
  do
  {
    if (*p & mask) result |= mask;
    mask += (unsigned)mask; // Cast only needed for capricious type ranges
  } while(mask);
  return result;
}

would be guaranteed to always yield a value in the range of type unsigned char any time the storage identified can be accessed as that type, even if it happens to hold Indeterminate Value.  Such an approach seems rather slow and clunky, however, given that the required machine code to obtain the desired effect should usually be equivalent to returning x.

Are there any better approaches that would be guaranteed by the Standard to always yield a value within the range of unsigned char, even if the source value is Indeterminate?

Addendum

The ability to solidify values is necessary, among other things, when performing I/O with partially-written arrays and structures, in cases where nothing will care about what bits get output for the parts that were never set.  Whether or not the Standard would require that fwrite be usable with partially-writtten structures or arrays, I would regard I/O routines that can be used in such fashion (writing arbitrary values for portions that weren't set) to be of higher quality than those which might jump the rails in such cases.

My concern is largely with guarding against optimizations which are unlikely to be used in dangerous combinations, but which could nonetheless occur as compilers get more and more "clever".

A problem with something like:

unsigned char solidify_alt(unsigned char *p)
{ return *p; }

is that compilers may combine an optimization which could be troublesome but tolerable in isolation, with one that would be good in isolation but deadly in combination with the first:

If the function is passed the address of an unsigned char which has been optimized to e.g. a 32-bit register, a function like the above may blindly return the contents of that register without clipping it to the range 0-255.  Requiring that callers manually clip the results of such functions would be annoying but survivable if that were the only problem.  Unfortunately...

Since the above function function will "always" return a value 0-255, compilers may omit any "downstream" code that would try to mask the value into that range, check if it was outside, or otherwise do things that would be irrelevant for values outside the range 0-255.

Some I/O devices may require that code wishing to write an octet perform a 16-bit or 32-bit store to an I/O register, and may require that 8 bits contain the data to be written and other bits hold a certain pattern.  They may malfunction badly if any of the other bits are set wrong.  Consider the code:

void send_byte(unsigned char *p, unsigned int n)
{
  while(n--)
    OUTPUT_REG = solidify_alt(*p++) | 0x0200;
}
void send_string4(char *st)
{
  unsigned char buff[5]; // Leave space for zero after 4-byte string
  strcpy((char*)buff, st);
  send_bytes(buff, 4);
}

with the indended semantics that send_string4("Ok"); should send out an 'O', a 'k', a zero byte, and an arbitrary value 0-255.  Since the code uses solidify_alt rather than solidify, a compiler could legally turn that into:

void send_string4(char *st)
{
  unsigned buff0, buff1, buff2, buff3;
  buff0 = st[0]; if (!buff0) goto STRING_DONE;
  buff1 = st[1]; if (!buff1) goto STRING_DONE;
  buff2 = st[2]; if (!buff2) goto STRING_DONE;
  buff3 = st[3];
 STRING_DONE:
  OUTPUT_REG = buff0 | 0x0200;
  OUTPUT_REG = buff1 | 0x0200;
  OUTPUT_REG = buff2 | 0x0200;
  OUTPUT_REG = buff3 | 0x0200;
}

with the effect that OUTPUT_REG may receive values with bits set outside the proper range.  Even if output expression were changed to ((unsigned char)solidify_alt(*p++) | 0x0200) & 0x02FF) a compiler could still simplify that to yield the code given above.

The authors of the Standard refrained from requiring compiler-generated initialization of automatic variables because it would have made code slower in cases where such initialization would be semantically unnecessary.  I don't think they intended that programmers should have to manually initialize automatic variables in cases where all bit patterns would be equally acceptable.

Note, btw, that when dealing with short arrays, initializing all the values will be inexpensive and would often be a good idea, and when using large arrays a compiler would be unlikely to impose the above "optimization".  Omitting the initialization in cases where the array is large enough that the cost matters, however, would make the program's correct operation reliant upon "hope".


来源: stackexchange

问:
openhtmltopdf / flying saucer: many links in huge PDF are not clickable (PDF annotations not set)
I generate huge catalogs (~ 1500 pages) as HTML and convert is via Jsoup to and openhtmltopdf (which uses flying saucer) to PDF. In the resulting PDF many links are not clickable, and I can't find out why.

Consider the following program:

```<code>import org.jsoup.helper.W3CDom;
import org.w3c.dom.Document;
import org.jsoup.Jsoup;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws Exception {

        PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();

        String html = "<html><head></head><body>";
        for (Integer i = 0; i < 10000; i++) {
            html += "<a href='http://www.google.de?q=" + i + "'>blabla</a>    <br>";
        }
        html += "</body></html>";

        File file = new File("/tmp/tmp.pdf");
        FileOutputStream fop = new FileOutputStream(file);

        W3CDom w3cDom = new W3CDom();
        Document w3cDoc = w3cDom.fromJsoup(Jsoup.parse(html));

        pdfBuilder.withW3cDocument(w3cDoc, "/");
        pdfBuilder.toStream(fop);
        try {
            pdfBuilder.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

It creates a PDF with 176 pages and 10.000 links. On page 1 to 3 they are clickable, afterwards they are not, although identical. The last clickable link is the number 112 and in the source code I find:

```<code>870 0 obj
<<
/W 0.0
/S /S
>>
endobj
871 0 obj
<<
/S /URI
/URI (http://www.google.de?q=111)
>>
endobj
872 0 obj
<<
/W 0.0
/S /S
>>
endobj
873 0 obj
<<
/S /URI
/URI (http://www.google.de?q=112)
>>
endobj
874 0 obj
<<
/W 0.0
/S /S
>>
endobj
875 0 obj
<<
/F1 1049 0 R
>>
endobj
</code>```

Apparently after number 112 there are no URLs stored anymore in the annotation objects.

My Program is much more complicated naturally. On the first five or six pages of it's result all the links are clickable, after that some are and most are not. Which ones are still clickable seems to be completely random though.

Can anyone help here? Any Idea what may cause this issue or how to fix it? A bug in openhtmltopdf?

--

edit 1:
Using withHtmlContent instead of withW3cDocument has the same problem.

答:
The generated PDF works perfectly with jsoup 1.11.2 and openhtmltopdf-pdfbox-0.0.1-RC11.

The problem is likely caused by a bug in an older version of openhtmltopdf, which has been fixed.

ContentLicense: CC BY-SA 3.0

Body:
I generate huge catalogs (~ 1500 pages) as HTML and convert is via Jsoup to and openhtmltopdf (which uses flying saucer) to PDF. In the resulting PDF many links are not clickable, and I can't find out why.

Consider the following program:

import org.jsoup.helper.W3CDom;
import org.w3c.dom.Document;
import org.jsoup.Jsoup;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws Exception {

        PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();

        String html = "";
        for (Integer i = 0; i < 10000; i++) {
            html += "blabla
";
        }
        html += "";

        File file = new File("/tmp/tmp.pdf");
        FileOutputStream fop = new FileOutputStream(file);

        W3CDom w3cDom = new W3CDom();
        Document w3cDoc = w3cDom.fromJsoup(Jsoup.parse(html));

        pdfBuilder.withW3cDocument(w3cDoc, "/");
        pdfBuilder.toStream(fop);
        try {
            pdfBuilder.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

It creates a PDF with 176 pages and 10.000 links. On page 1 to 3 they are clickable, afterwards they are not, although identical. The last clickable link is the number 112 and in the source code I find:

870 0 obj
<<
/W 0.0
/S /S
>>
endobj
871 0 obj
<<
/S /URI
/URI (http://www.google.de?q=111)
>>
endobj
872 0 obj
<<
/W 0.0
/S /S
>>
endobj
873 0 obj
<<
/S /URI
/URI (http://www.google.de?q=112)
>>
endobj
874 0 obj
<<
/W 0.0
/S /S
>>
endobj
875 0 obj
<<
/F1 1049 0 R
>>
endobj

Apparently after number 112 there are no URLs stored anymore in the annotation objects.

My Program is much more complicated naturally. On the first five or six pages of it's result all the links are clickable, after that some are and most are not. Which ones are still clickable seems to be completely random though.

Can anyone help here? Any Idea what may cause this issue or how to fix it? A bug in openhtmltopdf?

--

edit 1:
Using withHtmlContent instead of withW3cDocument has the same problem.


问:
Unable to Run Kotlin Application in Eclipse
In order to create my first, simple Kotlin project in Eclipse, I followed the steps in Getting Started with Eclipse Luna tutorial from Kotlin official website, i.e.:

Install Kotlin Plugin for Eclipse from Eclipse Marketplace

Open the Kotlin perspective and created a Kotlin Project

Created the file "hello.kt" inside the "src" folder with the main method

Right-clicked the file > Run As > Kotlin Application

However, I keep get the following error in Eclipse console:

Error: Could not find or load main class HelloKt

I have double-checked the Run Configuration for my project, and it does set the "Main class" as HelloKt (which I'm 100% sure it does not exist). Also, when I hit the "Search" button, the only item that Eclipse finds is HelloKt - (default package) (which, again, does not exist).

For the sake of completeness, find below the code for hello.kt file:

```<code>fun main(args: Array<String>) {
    println("Hello, World")
}
</code>```

I noticed the following divergences between the tutorial and what I did:

I'm using a different Eclipse version (the tutorial suggests Luna; I'm using Mars.2).

I'm using a different JDK version (the tutorial DOES not suggest any specific version, but from the images, we can see they have used jdk1.6.0_45, while I'm using jdk1.7.0_79.

Note that I'm using the latest version of Kotlin Eclipse Plugin, so this is not the same case as in this post. These are the versions in my current installation:

Kotlin 0.7.2.v20160930-0748

kotlin-eclipse-policy 0.7.2.v20160928-1525

kotlin-weaving-feature 0.7.2.v20160928-1525

Can any of these divergences be the cause of the error while running the application?

Do you see/know any potential cause or known bug regarding this scenario?

UPDATE (May 14th, 2017)

Tried with Eclipse Neon.3 (eclipse.buildId=4.6.3.M20170301-0400), JDK 1.8.0_111, Kotlin 0.8.2.v20170314-0957 (kotlin-eclipse-policy 0.8.2.v20170314-0957, kotlin-weaving-feature 0.8.2.v20170314-0957, Equinox Weaving SDK 1.2.0.201701131634). The problem persists.

答:
Tried with Java 8 (1.8.0_144) and Eclipse Oxygen.1a Release (4.7.1a - build id 20171005-1200) with the following plugin versions:

```<code>  Kotlin    0.8.2.v20170314-0957    org.jetbrains.kotlin.feature.feature.group  JetBrains
    kotlin-eclipse-policy   0.8.2.v20170314-0957    org.jetbrains.kotlin.policy.feature.group   JetBrains
    kotlin-weaving-feature  0.8.2.v20170314-0957    org.jetbrains.kotlin.weaving.feature.feature.group  JetBrains
</code>```

Everything worked as expected, without the need to create a separate workspace and/or use Kotlin File instead of Kotlin Class:

Body:
In order to create my first, simple Kotlin project in Eclipse, I followed the steps in Getting Started with Eclipse Luna tutorial from Kotlin official website, i.e.:

Install Kotlin Plugin for Eclipse from Eclipse Marketplace

Open the Kotlin perspective and created a Kotlin Project

Created the file "hello.kt" inside the "src" folder with the main method

Right-clicked the file > Run As > Kotlin Application

However, I keep get the following error in Eclipse console:

Error: Could not find or load main class HelloKt

I have double-checked the Run Configuration for my project, and it does set the "Main class" as HelloKt (which I'm 100% sure it does not exist). Also, when I hit the "Search" button, the only item that Eclipse finds is HelloKt - (default package) (which, again, does not exist).

For the sake of completeness, find below the code for hello.kt file:

fun main(args: Array<String>) {
    println("Hello, World")
}

I noticed the following divergences between the tutorial and what I did:

I'm using a different Eclipse version (the tutorial suggests Luna; I'm using Mars.2).

I'm using a different JDK version (the tutorial DOES not suggest any specific version, but from the images, we can see they have used jdk1.6.0_45, while I'm using jdk1.7.0_79.

Note that I'm using the latest version of Kotlin Eclipse Plugin, so this is not the same case as in this post. These are the versions in my current installation:

Kotlin 0.7.2.v20160930-0748

kotlin-eclipse-policy 0.7.2.v20160928-1525

kotlin-weaving-feature 0.7.2.v20160928-1525

Can any of these divergences be the cause of the error while running the application?

Do you see/know any potential cause or known bug regarding this scenario?

UPDATE (May 14th, 2017)

Tried with Eclipse Neon.3 (eclipse.buildId=4.6.3.M20170301-0400), JDK 1.8.0_111, Kotlin 0.8.2.v20170314-0957 (kotlin-eclipse-policy 0.8.2.v20170314-0957, kotlin-weaving-feature 0.8.2.v20170314-0957, Equinox Weaving SDK 1.2.0.201701131634). The problem persists.

Body:
Tried with Java 8 (1.8.0_144) and Eclipse Oxygen.1a Release (4.7.1a - build id 20171005-1200) with the following plugin versions:

  Kotlin    0.8.2.v20170314-0957    org.jetbrains.kotlin.feature.feature.group  JetBrains
    kotlin-eclipse-policy   0.8.2.v20170314-0957    org.jetbrains.kotlin.policy.feature.group   JetBrains
    kotlin-weaving-feature  0.8.2.v20170314-0957    org.jetbrains.kotlin.weaving.feature.feature.group  JetBrains

Everything worked as expected, without the need to create a separate workspace and/or use Kotlin File instead of Kotlin Class:


问:
Updating object in Firebase based on a if condition
I'm trying to update an object in Firebase only if one of his property doesn't exist.

The logic so far is : you loop over photos of a defined trip, and if in this photo you don't find the property "location", you update the object by inserting the property "location" (which itself is an object with properties "coord", "locationname", "regioncode", "thumbnailurl").

The problem is that after I load the page, the object "location" is not inserted for photos which don't have the property "location".

My database structure :

My JS :

```<code>db.ref('photos/' + owneruid + '/trips/' + tripuid).once('value').then(snap => {
    var photos = snap.val()
    for (var key in photos) {
        console.log('Photo ID is ' + key)
        var thisPhoto = photos[key]
        this.photos.push(thisPhoto)
        var hasLocation = 'location';
        if(photos[key].hasOwnProperty(hasLocation)){
            console.log("location exists")
        }
        else{
            console.log("NO LOCATION")
            var location = {coord:"", locationname:"", regioncode:"", thumbnailurl:""}
            function writeLocation(location) {
                db.ref('photos/' + owneruid + '/trips/' + tripuid + thisPhoto).update(location)
             }
             this.photos.push(thisPhoto)
             }
        }
        this.photosDataIsReady = true
})
</code>```

As we can see in the console, the if condition in the loop works:

答:
Try this code

db.ref('photos/' + owneruid + '/trips/' + tripuid).once('value').then(snap => {
    var photos = snap.val()
    for (var key in photos) {
        console.log('Photo ID is ' + key)
        var thisPhoto = photos[key]
        this.photos.push(thisPhoto)
        var hasLocation = 'location';
        if(photos[key].hasOwnProperty(hasLocation)){
            console.log("location exists")
        }
        else{
            console.log("NO LOCATION")
            var location = {coord:"", locationname:"", regioncode:"", thumbnailurl:""}
                db.ref('photos/' + owneruid + '/trips/' + tripuid + thisPhoto).update(location);
             this.photos.push(thisPhoto)
             }
        }
        this.photosDataIsReady = true
})```

Body:
I'm trying to update an object in Firebase only if one of his property doesn't exist.

The logic so far is : you loop over photos of a defined trip, and if in this photo you don't find the property "location", you update the object by inserting the property "location" (which itself is an object with properties "coord", "locationname", "regioncode", "thumbnailurl").

The problem is that after I load the page, the object "location" is not inserted for photos which don't have the property "location".

My database structure :

My JS :

db.ref('photos/' + owneruid + '/trips/' + tripuid).once('value').then(snap => {
    var photos = snap.val()
    for (var key in photos) {
        console.log('Photo ID is ' + key)
        var thisPhoto = photos[key]
        this.photos.push(thisPhoto)
        var hasLocation = 'location';
        if(photos[key].hasOwnProperty(hasLocation)){
            console.log("location exists")
        }
        else{
            console.log("NO LOCATION")
            var location = {coord:"", locationname:"", regioncode:"", thumbnailurl:""}
            function writeLocation(location) {
                db.ref('photos/' + owneruid + '/trips/' + tripuid + thisPhoto).update(location)
             }
             this.photos.push(thisPhoto)
             }
        }
        this.photosDataIsReady = true
})

As we can see in the console, the if condition in the loop works:


问:
JavaScript invalid date from DateTime Picker
I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.

But my first value (rtime) always gives an invalid date. Where am I wrong?

Note: stime is not editable, the user only uses the DateTime Picker for rtime field.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);```

This result shows that LastOut is an invalid date:

答:
You need to convert your date from DD/MM/YYYY HH:MM:SS format to MM/DD/YYYY HH:MM:SS format.

For conversion, you can use string#replace.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

stime = stime.replace(/(..)\/(..)\/(.*)/, '$2/$1/$3');
rtime = rtime.replace(/(..)\/(..)\/(.*)/, '$2/$1/$3');

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);```

Body:
I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.

But my first value (rtime) always gives an invalid date. Where am I wrong?

Note: stime is not editable, the user only uses the DateTime Picker for rtime field.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);

This result shows that LastOut is an invalid date:


问:
Swift4 app crashes when loading local HTML
While working on a web app for weeks, I used a external URL in my (WKWebView) web view. Now I'm moving towards production I want to embed the webapp and load a local webpage.

I simply moved from

```<code>let url = URL(string: "http://hidden-url.com/")
self.webView!.load(URLRequest(url: url!))
</code>```

To

```<code>let url = URL(string: Bundle.main.path(forResource: "index_prod", ofType: "html")!)
self.webView!.load(URLRequest(url: url!))
</code>```

But this causes my app to crash. I'm sure the file is loaded correctly and a print before, in-between and after the lines will appear in the console.

The error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)

答:
You need to load the string content from the file, use contentsOfFile method to get the string and use loadHTMLString method of webview, print the error or create some enum which shows the error</p>

```<code>enum WebError: Swift.Error {
    case fileNotFound(name: String)
    case parsing(contentsOfFile: String)
}

guard let url = Bundle.main.path(forResource: "index_prod", ofType: "html") else {
   throw WebError.fileNotFound(name: file) // throw file not found error
}

do {
      let html = try String(contentsOfFile: url)
      self.webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
} catch {
      throw WebError.parsingError(contentsOfFile: file)
}
</code>```

Body:
While working on a web app for weeks, I used a external URL in my (WKWebView) web view. Now I'm moving towards production I want to embed the webapp and load a local webpage.

I simply moved from

let url = URL(string: "http://hidden-url.com/")
self.webView!.load(URLRequest(url: url!))

To

let url = URL(string: Bundle.main.path(forResource: "index_prod", ofType: "html")!)
self.webView!.load(URLRequest(url: url!))

But this causes my app to crash. I'm sure the file is loaded correctly and a print before, in-between and after the lines will appear in the console.

The error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)

Body:
You need to load the string content from the file, use contentsOfFile method to get the string and use loadHTMLString method of webview, print the error or create some enum which shows the error

enum WebError: Swift.Error {
    case fileNotFound(name: String)
    case parsing(contentsOfFile: String)
}

guard let url = Bundle.main.path(forResource: "index_prod", ofType: "html") else {
   throw WebError.fileNotFound(name: file) // throw file not found error
}

do {
      let html = try String(contentsOfFile: url)
      self.webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
} catch {
      throw WebError.parsingError(contentsOfFile: file)
}


问:
onCreateView() is never called in Fragment
i want to build the next UI:

TabLayout with 2 tabs and 2 different Fragments (Solved and Unsolved)
My onCreateView in Fragment is never called.

Here I inflate my viewPager:

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mAdapter.addFragment(new UnsolvedTasksFragment());
    mAdapter.addFragment(new SolvedTasksFragment());
    viewPager.setAdapter(mAdapter);

    mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mTabLayout.setupWithViewPager(viewPager);

    mTabLayout.getTabAt(0).setText(getString(R.string.tablayout_unsolved));
    mTabLayout.getTabAt(1).setText(getString(R.string.tablayout_solved));

}
</code>```

My custom ViewPagerAdapter:

```<code> public class ViewPagerAdapter extends FragmentPagerAdapter {
 private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    if (!mFragmentList.isEmpty() && mFragmentList.size() > id)
        return mFragmentList.get(position);
    return new Fragment();
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

@Override
public CharSequence getPageTitle(int position) {
    return null;
}
}
</code>```

Here an example of my Fragment:

```<code> public class SolvedTasksFragment extends Fragment implements RecyclerViewClickListenerSolved {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       //Some code here;
        return rootView;
    }

    @Override
    public void itemClick(View v, int position) {
       }
}
</code>```

Maybe somebody can tell what is wrong.

I don't need  the whole solution.

答:
From docs

The value of id is 16842960 so

```<code>if (true && 2 > 16842960) // will not be executed
   // true && false => false
</code>```

Solution : you can check the size against position or remove this check if not specific to the implementation

```<code>@Override
public Fragment getItem(int position) {
    if (mFragmentList.size() > position)
        return mFragmentList.get(position);
    return new Fragment();
}
</code>```

Body:
i want to build the next UI:

TabLayout with 2 tabs and 2 different Fragments (Solved and Unsolved)
My onCreateView in Fragment is never called.

Here I inflate my viewPager:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mAdapter.addFragment(new UnsolvedTasksFragment());
    mAdapter.addFragment(new SolvedTasksFragment());
    viewPager.setAdapter(mAdapter);

    mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mTabLayout.setupWithViewPager(viewPager);

    mTabLayout.getTabAt(0).setText(getString(R.string.tablayout_unsolved));
    mTabLayout.getTabAt(1).setText(getString(R.string.tablayout_solved));

}

My custom ViewPagerAdapter:

 public class ViewPagerAdapter extends FragmentPagerAdapter {
 private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    if (!mFragmentList.isEmpty() && mFragmentList.size() > id)
        return mFragmentList.get(position);
    return new Fragment();
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

@Override
public CharSequence getPageTitle(int position) {
    return null;
}
}

Here an example of my Fragment:

 public class SolvedTasksFragment extends Fragment implements RecyclerViewClickListenerSolved {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       //Some code here;
        return rootView;
    }

    @Override
    public void itemClick(View v, int position) {
       }
}

Maybe somebody can tell what is wrong.

I don't need  the whole solution.

Body:
From docs

The value of id is 16842960 so

if (true && 2 > 16842960) // will not be executed
   // true && false => false

Solution : you can check the size against position or remove this check if not specific to the implementation

@Override
public Fragment getItem(int position) {
    if (mFragmentList.size() > position)
        return mFragmentList.get(position);
    return new Fragment();
}


问:
Please help parse this html table using BeautifulSoup and lxml the pythonic way
I have searched a lot about BeautifulSoup and some suggested lxml as the future of BeautifulSoup while that makes sense, I am having a tough time parsing the following table from a whole list of tables on the webpage.

I am interested in the three columns with varied number of rows depending on the page and the time it was checked. A BeautifulSoup and lxml solution is well appreciated. That way I can ask the admin to install lxml on the dev. machine.

Desired output :

```<code>Website                    Last Visited          Last Loaded
http://google.com          01/14/2011
http://stackoverflow.com   01/10/2011
...... more if present
</code>```

Following is a code sample from a messy web page :

```<code><table border="2" width="100%">
  <tbody><tr>
    <td width="33%" class="BoldTD">Website</td>
    <td width="33%" class="BoldTD">Last Visited</td>
    <td width="34%" class="BoldTD">Last Loaded</td>
  </tr>
  <tr>
    <td width="33%">
      <a href="http://google.com"</a>
    </td>
    <td width="33%">01/14/2011
            </td>
    <td width="34%">
            </td>
  </tr>
  <tr>
    <td width="33%">
      <a href="http://stackoverflow.com"</a>
    </td>
    <td width="33%">01/10/2011
            </td>
    <td width="34%">
            </td>
  </tr>
</tbody></table>
</code>```

答:
Here's a version that uses elementtree and the limited XPath it provides:

```<code>from xml.etree.ElementTree import ElementTree

doc = ElementTree().parse('table.html')

for t in doc.findall('.//table'):
  # there may be multiple tables, check we have the right one
  if t.find('./tbody/tr/td').text == 'Website':
    for tr in t.findall('./tbody/tr/')[1:]: # skip the header row
      tds = tr.findall('./td')
      print tds[0][0].attrib['href'], tds[1].text.strip(), tds[2].text.strip()
</code>```

Results:

```<code>http://google.com 01/14/2011
http://stackoverflow.com 01/10/2011
</code>```

Body:
I have searched a lot about BeautifulSoup and some suggested lxml as the future of BeautifulSoup while that makes sense, I am having a tough time parsing the following table from a whole list of tables on the webpage.

I am interested in the three columns with varied number of rows depending on the page and the time it was checked. A BeautifulSoup and lxml solution is well appreciated. That way I can ask the admin to install lxml on the dev. machine.

Desired output :

Website                    Last Visited          Last Loaded
http://google.com          01/14/2011
http://stackoverflow.com   01/10/2011
...... more if present

Following is a code sample from a messy web page :

    Website
    Last Visited
    Last Loaded

      <a href="http://google.com"

    01/14/2011

      <a href="http://stackoverflow.com"

    01/10/2011

Body:
Here's a version that uses elementtree and the limited XPath it provides:

from xml.etree.ElementTree import ElementTree

doc = ElementTree().parse('table.html')

for t in doc.findall('.//table'):
  # there may be multiple tables, check we have the right one
  if t.find('./tbody/tr/td').text == 'Website':
    for tr in t.findall('./tbody/tr/')[1:]: # skip the header row
      tds = tr.findall('./td')
      print tds[0][0].attrib['href'], tds[1].text.strip(), tds[2].text.strip()

Results:

http://google.com 01/14/2011
http://stackoverflow.com 01/10/2011

ContentLicense: CC BY-SA 2.5


问:
C Program not exiting input mode

I'm trying to find out the number of tabs, spaces and newlines in my C program. The code is :

```<code>#include <stdio.h>

void main()
{
    char c;
    int tabs=0 , spaces=0 , nl=0 ;
    printf("Provide the input");
    scanf("%c" , &c);
    while(c != EOF)
    {
        if(c == ' ')
        spaces++;
        else if(c == '\n')
        nl++;
        else if(c == '\t')
        tabs++;
        scanf("%c" , &c);
    }
    printf("blanks:%d\nspaces:%d\nnewlines:%d" , spaces , tabs , nl);
}
</code>```

Well, I'm expecting it to do just that but the code is just not moving beyond accepting the input phase. What am I doing wrong? Below is what my command line looks like:

```<code>[tejas@localhost The_C_Programming_Language]$ cc Exercise_1-8.c

[tejas@localhost The_C_Programming_Language]$ ./a.out

Provide the input seguiofgawie

gweuigwh

e u w   f qw[uwf
[PHWUO FEFF
qah fuwpfyh fweor
</code>```

(I keep pressing the Return key but to no end. Please help. Thank you for reading. This is my first question, hope i didn't do anything wrong...)

EDIT: getchar() doesn't work either, and I'm currently using Fedora 26 and GEDIT as my text editor

EDIT: getchar() works, in order to send the EOF character, one should press Ctrl+D on an empty line and if you want it done in with just one press of the RETURN key, change your loop condition to variable != '\n'. I apologize for spreading misinformation.

答: i think, a character given by the user cannot be compared to EOF(end of file) as you are not dealing with any file i.e., you have not opened any file in order to verify its end.</p>

Title: C Program not exiting input mode

Body:
I'm trying to find out the number of tabs, spaces and newlines in my C program. The code is :

#include <stdio.h>

void main()
{
    char c;
    int tabs=0 , spaces=0 , nl=0 ;
    printf("Provide the input");
    scanf("%c" , &c);
    while(c != EOF)
    {
        if(c == ' ')
        spaces++;
        else if(c == '\n')
        nl++;
        else if(c == '\t')
        tabs++;
        scanf("%c" , &c);
    }
    printf("blanks:%d\nspaces:%d\nnewlines:%d" , spaces , tabs , nl);
}

Well, I'm expecting it to do just that but the code is just not moving beyond accepting the input phase. What am I doing wrong? Below is what my command line looks like:

[tejas@localhost The_C_Programming_Language]$ cc Exercise_1-8.c

[tejas@localhost The_C_Programming_Language]$ ./a.out

Provide the input seguiofgawie

gweuigwh

e u w   f qw[uwf
[PHWUO FEFF
qah fuwpfyh fweor

(I keep pressing the Return key but to no end. Please help. Thank you for reading. This is my first question, hope i didn't do anything wrong...)

EDIT: getchar() doesn't work either, and I'm currently using Fedora 26 and GEDIT as my text editor

EDIT: getchar() works, in order to send the EOF character, one should press Ctrl+D on an empty line and if you want it done in with just one press of the RETURN key, change your loop condition to variable != '\n'. I apologize for spreading misinformation.


问:
How to export every table to csv in a kdb+ database?
Assume my kdb+ database has a few tables. How can I export all tables to csv files where the name of each csv is same as the table name? </p>

答:
An alternative method to save is to use 0: to prepare text, specifying a delimiter of ",":

```<code>q)tab:([]a:1 2 3;b:`a`b`c)
q)show t:","0:tab
"a,b"
"1,a"
"2,b"
"3,c"
</code>```

And again to save text:

```<code>q)`:tab 0: t
`:tab
</code>```

The advantage of this method is that the delimiter can be specified before saving to disk.

Body:
An alternative method to save is to use 0: to prepare text, specifying a delimiter of ",":

q)tab:([]a:1 2 3;b:`a`b`c)
q)show t:","0:tab
"a,b"
"1,a"
"2,b"
"3,c"

And again to save text:

q)`:tab 0: t
`:tab

The advantage of this method is that the delimiter can be specified before saving to disk.


问:
How to get a Docker container's IP address from the host
Is there a command I can run to get the container's IP address right from the host after a new container is created?

Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.

答:
If you forgot container ID or don't want to manipulate with shell commands, it's better to use UI like Portainer.

https://portainer.io/

```<code>$ docker volume create portainer_data
$ docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer
</code>```

There you can find all information about container also IP.

ContentLicense: CC BY-SA 4.0

Body:
If you forgot container ID or don't want to manipulate with shell commands, it's better to use UI like Portainer.

https://portainer.io/

$ docker volume create portainer_data
$ docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

There you can find all information about container also IP.


问:
Bootstrap not compatible with angular 5
I am using Angular 5. After installing ng-bootstrap there are few errors. Is ng-bootstrap not compatible with Angular 5, or are their any other packages that are compatible?

答:
You should be using ng-bootstrap instead of regular old bootstrap...

Try this:

```<code>npm install --save @ng-bootstrap/ng-bootstrap
</code>```

source: ng-bootstrap docs

Title: Bootstrap not compatible with angular 5

Body:
You should be using ng-bootstrap instead of regular old bootstrap...

Try this:

npm install --save @ng-bootstrap/ng-bootstrap

source: ng-bootstrap docs


问:
What should be passed for BeginInvoke's @object parameter?
I have an event delegate that is defined as follows:

```<code>public delegate void CallbackDelegate(Data data);
public event CallbackDelegate OnDataComplete;
</code>```

I raise the event asynchronously:

```<code>// Raise the OnDataComplete event
OnDataComplete.BeginInvoke(new Data(), null, null);
</code>```

Subsequently, the signature of BeginInvoke looks like:

```<code>IAsyncResult CallbackDelegate.BeginInvoke(Data data, AsyncCallback callback, object @object)
</code>```

In most examples I've seen BeginInvoke is called with the @object parameter being null, but I can't find the documentation which explains what is the purpose of that parameter.

So what is the purpose of that parameter? What can we use it for?

答: You can provide anything you want there. In the AsyncResult method you can retrieve this value with IAsyncResult.AsyncState. It's there for your use.</p>

Body:
I have an event delegate that is defined as follows:

public delegate void CallbackDelegate(Data data);
public event CallbackDelegate OnDataComplete;

I raise the event asynchronously:

// Raise the OnDataComplete event
OnDataComplete.BeginInvoke(new Data(), null, null);

Subsequently, the signature of BeginInvoke looks like:

IAsyncResult CallbackDelegate.BeginInvoke(Data data, AsyncCallback callback, object @object)

In most examples I've seen BeginInvoke is called with the @object parameter being null, but I can't find the documentation which explains what is the purpose of that parameter.

So what is the purpose of that parameter? What can we use it for?


问:
Improve speed execution of MySQL select query
I have 2 MySQL tables with several millions of rows and I'm trying to perform a query selection for get specific data column from both tables. Despite my first good expectations the execution of the query selection takes several seconds (around 5 seconds) also with an index applied on the WHERE condition.

Create statement for the 2 MySQL tables:

```<code>CREATE TABLE `T1` (
  `T1_id` int(15) NOT NULL AUTO_INCREMENT,
  `T1_val1` varchar(45) NOT NULL,
  `T1_val2` varchar(45) NOT NULL,
  `T1_val3` bigint(11) NOT NULL,
  `T1_val4` datetime NOT NULL,
  `T1_val5` varchar(100) NOT NULL,
  `T1_val6` float NOT NULL,
  `T1_val7` datetime NOT NULL,
  `T1_val8` varchar(100) NOT NULL,
  `T1_val9` varchar(100) NOT NULL,
  `T1_val10` varchar(100) NOT NULL,
  PRIMARY KEY (`T1_id`),
  KEY `T1_val4` (`T1_val4`)
) ENGINE=InnoDB AUTO_INCREMENT=53885653 DEFAULT CHARSET=latin1;

CREATE TABLE `T2` (
  `T2_id` int(11) NOT NULL,
  `T2_val1` float NOT NULL,
  `T2_val2` float NOT NULL,
  `T2_val3` varchar(45) NOT NULL,
  PRIMARY KEY (`T2_id`),
  KEY `T2_val3` (`T2_val3`),
  KEY `T2_val1_2` (`T2_val1`,`T2_val2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

As you can see both tables have an AI primary key and foreign key that matches as one-to-one relationship between them (T1_id and T2_id). And we have an index applied on T1 for T1_val4 that is in a datetime format.

The selection query

```<code>SELECT
      T1_val5,
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      count(T2_val1) as cnt,
      T1_val4
   FROM
      T1 USE INDEX (T1_val4)
         INNER JOIN T2
            ON T1.T1_id = T2.T2_id
   WHERE
      T1_val4 BETWEEN '2016-02-18 15:00:00'
                  AND '2016-02-18 16:59:59'
   GROUP BY
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      T1_val5
   order by
      T1_val4 ASC;
</code>```

As you can notice, I have specified a HINT for the index in order to tell to MySQL to use that specific index for the datetime column. Actually if I extend the datetime range in the WHERE condition to several hours well.. for example BETWEEN '2016-02-18 15:00:00' AND '2016-02-18 23:59:59' the execution time grows up till 50/100 seconds. Probably I'm missing something in the logic.

The EXPLAIN output

```<code>+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS   |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   T1_val4         |   T1_val4 |      5        |   NULL    |   10670   |   "Using index condition; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   PRIMARY         |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                   |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
</code>```

The EXPLAIN output updated with compound index

(As suggested from @O. Jones)

```<code>+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS              |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                   |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   "PRIMARY,ix_rlf"           |   ix_rlf  |      5        |   NULL    |   10906   |   "Using where; Using index; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   "PRIMARY,ix_cc"            |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                      |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
</code>```

ix_rlf is the compound index of T1_val4, T1_val9, T1_val5and ix_cc is the compound index suggested from @Tom Shir for T2 made of T2_id, T2_val1, T2_val2, T2_val3.

Query execution plan visual schema

(considering 2 HOURS as interval, and in this case the result of the query it's around 6632 rows and 6/7 seconds as execution time)

答:
By leaving out T1_val4 from your GROUP BY clause you're taking advantage of MySQL's nonstandard extension. You may be getting undesired results. Please read this. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

Generally, using BETWEEN for datetime-like columns is a bad idea because it handles range-end conditions poorly.  If I were you I'd write this

```<code>WHERE T1_val4 >= '2016-02-18 15:00:00' AND T1_val4 < '2016-02-18 17:00:00'
</code>```

You have the right idea indexing your datestamp column. You might try using a compound covering index instead of your simple datestamp index. It looks like your query is pulling about ten thousand rows from T1, so a compound covering index will help.  Put all the columns you need in the index, with the range scan column first. That means MySQL can satisfy the whole query by doing the index range scan, which is faster. The index should be on these columns.

```<code> T1_val4, T1_val9, T1_val5
</code>```

Because you're using InnoDB, you don't have to include the primary key in your compound index.

This should be a little faster. But, still, you're asking MySQL to retrieve and index ten thousand rows, and that is actually real work.

Body:
I have 2 MySQL tables with several millions of rows and I'm trying to perform a query selection for get specific data column from both tables. Despite my first good expectations the execution of the query selection takes several seconds (around 5 seconds) also with an index applied on the WHERE condition.

Create statement for the 2 MySQL tables:

CREATE TABLE `T1` (
  `T1_id` int(15) NOT NULL AUTO_INCREMENT,
  `T1_val1` varchar(45) NOT NULL,
  `T1_val2` varchar(45) NOT NULL,
  `T1_val3` bigint(11) NOT NULL,
  `T1_val4` datetime NOT NULL,
  `T1_val5` varchar(100) NOT NULL,
  `T1_val6` float NOT NULL,
  `T1_val7` datetime NOT NULL,
  `T1_val8` varchar(100) NOT NULL,
  `T1_val9` varchar(100) NOT NULL,
  `T1_val10` varchar(100) NOT NULL,
  PRIMARY KEY (`T1_id`),
  KEY `T1_val4` (`T1_val4`)
) ENGINE=InnoDB AUTO_INCREMENT=53885653 DEFAULT CHARSET=latin1;

CREATE TABLE `T2` (
  `T2_id` int(11) NOT NULL,
  `T2_val1` float NOT NULL,
  `T2_val2` float NOT NULL,
  `T2_val3` varchar(45) NOT NULL,
  PRIMARY KEY (`T2_id`),
  KEY `T2_val3` (`T2_val3`),
  KEY `T2_val1_2` (`T2_val1`,`T2_val2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

As you can see both tables have an AI primary key and foreign key that matches as one-to-one relationship between them (T1_id and T2_id). And we have an index applied on T1 for T1_val4 that is in a datetime format.

The selection query

SELECT
      T1_val5,
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      count(T2_val1) as cnt,
      T1_val4
   FROM
      T1 USE INDEX (T1_val4)
         INNER JOIN T2
            ON T1.T1_id = T2.T2_id
   WHERE
      T1_val4 BETWEEN '2016-02-18 15:00:00'
                  AND '2016-02-18 16:59:59'
   GROUP BY
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      T1_val5
   order by
      T1_val4 ASC;

As you can notice, I have specified a HINT for the index in order to tell to MySQL to use that specific index for the datetime column. Actually if I extend the datetime range in the WHERE condition to several hours well.. for example BETWEEN '2016-02-18 15:00:00' AND '2016-02-18 23:59:59' the execution time grows up till 50/100 seconds. Probably I'm missing something in the logic.

The EXPLAIN output

+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS   |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   T1_val4         |   T1_val4 |      5        |   NULL    |   10670   |   "Using index condition; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   PRIMARY         |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                   |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+

The EXPLAIN output updated with compound index

(As suggested from @O. Jones)

+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS              |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                   |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   "PRIMARY,ix_rlf"           |   ix_rlf  |      5        |   NULL    |   10906   |   "Using where; Using index; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   "PRIMARY,ix_cc"            |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                      |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+

ix_rlf is the compound index of T1_val4, T1_val9, T1_val5and ix_cc is the compound index suggested from @Tom Shir for T2 made of T2_id, T2_val1, T2_val2, T2_val3.

Query execution plan visual schema

(considering 2 HOURS as interval, and in this case the result of the query it's around 6632 rows and 6/7 seconds as execution time)

Body:
By leaving out T1_val4 from your GROUP BY clause you're taking advantage of MySQL's nonstandard extension. You may be getting undesired results. Please read this. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

Generally, using BETWEEN for datetime-like columns is a bad idea because it handles range-end conditions poorly.  If I were you I'd write this

WHERE T1_val4 >= '2016-02-18 15:00:00' AND T1_val4 < '2016-02-18 17:00:00'

You have the right idea indexing your datestamp column. You might try using a compound covering index instead of your simple datestamp index. It looks like your query is pulling about ten thousand rows from T1, so a compound covering index will help.  Put all the columns you need in the index, with the range scan column first. That means MySQL can satisfy the whole query by doing the index range scan, which is faster. The index should be on these columns.

 T1_val4, T1_val9, T1_val5

Because you're using InnoDB, you don't have to include the primary key in your compound index.

This should be a little faster. But, still, you're asking MySQL to retrieve and index ten thousand rows, and that is actually real work.


问:
how to resolve DTS_E_OLEDBERROR. in ssis
In an  ssis package consists of  data flow task,contains
OLEDB source and OLDB Target ..provider is sql native client..This used to run fine ..but now got an error as shown below..

Please tell me how to resolve it ?changing it to ado.net?

OS :windows 7 professional and the DB is SQL Server 2000

[Axe_Data [737]] Error: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80004005  Description: "Communication link failure".
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80004005  Description: "TCP Provider: The semaphore timeout period has expired.
".

I am in much needed help resolving a problem with SSIS.  I am trying to export/import data using SSIS from one SQL Cluster to another.  Both are SQL 2008 Ent. 64bit.  Both are running on Win2k8 Ent.  64bit.  The destination is Win2k8 R2.

The problem I experience is intermittent but very frequent.  The SSIS connection drops at various steps.  Sometimes failing on the first task, sometimes on the last.. sometimes it completes the first iteration completely (in for-each loop) and fails on following iteration.

An identical version of this package was running against a different destination in the past without failures.  The previous destination was a single server (non-clustered) running on Win2k3 Standard, and SQL 2005 Std. 64 bit.

The new destination server is completely free of traffic.  Has plenty of CPU/Memory, etc..   The package has been executed from either the Source server or the Destination server with similar results.

Here is an output of a simple import/export task:

Copying to [dbo].[AGGSLIVE_Bandwidth] (Error)
Messages
Error 0xc0202009: Data Flow Task 1: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"

Hresult: 0x80004005  Description: "Communication link failure".
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"

Hresult: 0x80004005  Description: "TCP Provider: An existing connection was forcibly closed by the remote host.
".
(SQL Server Import and Export Wizard)

Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "input "Destination Input" (62)" failed because error code 0xC020907B occurred, and the error row disposition on "input "Destination Input" (62)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
(SQL Server Import and Export Wizard)

Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Destination - AGGSLIVE_Bandwidth" (49) failed with error code 0xC0209029 while processing input "Destination Input" (62). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.
(SQL Server Import and Export Wizard)

Error 0xc0209017: Data Flow Task 1: Setting the end of rowset for the buffer failed with error code 0xC0047020.
(SQL Server Import and Export Wizard)

Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on component "Source - Query" (1) returned error code 0xC0209017.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
(SQL Server Import and Export Wizard)

答:
I faced the similar issue.

Deselect the check box ("In wizard deselect the checkbox stating "First row has columns names") and before running the wizard make sure you have opened your
excel sheet.

Then run the wizard by deselecting the checkbox.

This resolved my issue.


问:
In Eclipse how can we can connect H2 database using Hibernate for Maven project
How to connect H2 database using Hibernate for Maven project?</p>

答:
You may use Spring-boot initializer. Just visit this page - https://start.spring.io/

For simple Spring WebMVC select the next tools: Web, H2, JPA and i would recommend DevTools.

In application you need to create JPA repository interface like this:

package ru.arvsoft.server.core.repository;

```<code>import org.springframework.data.jpa.repository.JpaRepository;
import ru.arvsoft.server.core.domain.Author;

public interface AuthorRepository extends JpaRepository<Author, Long> {
}
</code>```

And use it in some classes:

```<code>@Service
public class AuthorService {

    private final AuthorRepository repository;
    private final AuthorMapper mapper;

    @Autowired
    public AuthorService(AuthorRepository repository, AuthorMapper mapper) {
        this.repository = repository;
        this.mapper = mapper;
    }

    public Author getById(Long id) {
        return repository.findOne(id);
    }

    public List<AuthorShortDTO> getAuthors() {
        return repository.findAll().stream().map(mapper::mapToShortDTO).collect(Collectors.toList());
    }

...
</code>```

Body:
You may use Spring-boot initializer. Just visit this page - https://start.spring.io/

For simple Spring WebMVC select the next tools: Web, H2, JPA and i would recommend DevTools.

In application you need to create JPA repository interface like this:

package ru.arvsoft.server.core.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import ru.arvsoft.server.core.domain.Author;

public interface AuthorRepository extends JpaRepository<Author, Long> {
}

And use it in some classes:

@Service
public class AuthorService {

    private final AuthorRepository repository;
    private final AuthorMapper mapper;

    @Autowired
    public AuthorService(AuthorRepository repository, AuthorMapper mapper) {
        this.repository = repository;
        this.mapper = mapper;
    }

    public Author getById(Long id) {
        return repository.findOne(id);
    }

    public List<AuthorShortDTO> getAuthors() {
        return repository.findAll().stream().map(mapper::mapToShortDTO).collect(Collectors.toList());
    }

...


问:
default ansible template returns error
do Ansible in default configuration works with other vendors? For example Huawei ?

If i'm running some testing commands like:

sudo ansible -m shell -a 'display version' servers

```<code>10.46.1.1 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: \r\n**********************************************************************\r\n* Jus esate prisijunge prie privacios irangos. Visi veiksmai,vykdomi *\r\n* su sia iranga, yra fiksuojami. Tam, kad prieiti prie sios irangos  *\r\n* ir (ar) atlikti irangos konfiguracija ar kitus veiksmus, jus turite*\r\n* tureti atitinkama leidima.                                         *\r\n* Uz neteiseta prisijungima bei neteisetus veiksmus su iranga taikoma*\r\n* istatymuose numatyta atsakomybe,iskaitant ir baudziamaja atsakomybe*\r\n* Prasome  atsijungti.Jeigu  jus esate   autorizuotas  vartotojas,   *\r\n* prisijungdamas, jus atsakote uz teisingai atlikta konfiguracija ir *\r\n* kitus savo vardu atliktus veiksmus.                                *\r\n**********************************************************************\r\n* You are connected to private equipment. All the actions performed  *\r\n* with the equipment are recorded. In order to access this equipment *\r\n* and (or) perform its configuration or other  actions, you must have*\r\n* an appropriate permission. Illegal connection and illegal actions  *\r\n* with the equipment.                                                *\r\n* Will be subject to liability, including criminal liability, as     *\r\n* provided for in the laws of the Republic of Lithuania. Please      *\r\n* disconnect immediately. If you are an authorized user, by          *\r\n* connecting  to the equipment, you assume liability for performing  *\r\n* correct configuration and other actions under your behalf.         *\r\n**********************************************************************\r\nUser Authentication\r\npacket_write_wait: Connection to 10.46.1.1 port 22: Broken pipe\r\n",
    "unreachable": true
}
</code>```

or

osboxes@osboxes:~$ sudo ansible -m ping servers

```<code>10.46.1.1 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: \r\n**********************************************************************\r\n* Jus esate prisijunge prie privacios irangos. Visi veiksmai,vykdomi *\r\n* su sia iranga, yra fiksuojami. Tam, kad prieiti prie sios irangos  *\r\n* ir (ar) atlikti irangos konfiguracija ar kitus veiksmus, jus turite*\r\n* tureti atitinkama leidima.                                         *\r\n* Uz neteiseta prisijungima bei neteisetus veiksmus su iranga taikoma*\r\n* istatymuose numatyta atsakomybe,iskaitant ir baudziamaja atsakomybe*\r\n* Prasome  atsijungti.Jeigu  jus esate   autorizuotas  vartotojas,   *\r\n* prisijungdamas, jus atsakote uz teisingai atlikta konfiguracija ir *\r\n* kitus savo vardu atliktus veiksmus.                                *\r\n**********************************************************************\r\n* You are connected to private equipment. All the actions performed  *\r\n* with the equipment are recorded. In order to access this equipment *\r\n* and (or) perform its configuration or other  actions, you must have*\r\n* an appropriate permission. Illegal connection and illegal actions  *\r\n* with the equipment.                                                *\r\n* Will be subject to liability, including criminal liability, as     *\r\n* provided for in the laws of the Republic of Lithuania. Please      *\r\n* disconnect immediately. If you are an authorized user, by          *\r\n* connecting  to the equipment, you assume liability for performing  *\r\n* correct configuration and other actions under your behalf.         *\r\n**********************************************************************\r\nUser Authentication\r\nchannel_by_id: 2: bad id: channel free\r\nDisconnecting: Received data for nonexistent channel 2.\r\n",
    "unreachable": true
}
</code>```

it just connects and immediatly disconnects without entering any command, like "display version". Could it be because im running it not on Cisco device, but on other vendor ? Maybe some special modules ir required ?

Thanks

答:
You can use other module different from 'shell' to access Huawei equipaments. If you look here you will see some Cloud Engine modules. Shell module is for servers, not for switches.

So, I'll would write something like this: ansible -m ce_command -a 'display version' servers

Title: default ansible template returns error

Body:
do Ansible in default configuration works with other vendors? For example Huawei ?

If i'm running some testing commands like:

sudo ansible -m shell -a 'display version' servers

10.46.1.1 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: \r\n**********************************************************************\r\n* Jus esate prisijunge prie privacios irangos. Visi veiksmai,vykdomi *\r\n* su sia iranga, yra fiksuojami. Tam, kad prieiti prie sios irangos  *\r\n* ir (ar) atlikti irangos konfiguracija ar kitus veiksmus, jus turite*\r\n* tureti atitinkama leidima.                                         *\r\n* Uz neteiseta prisijungima bei neteisetus veiksmus su iranga taikoma*\r\n* istatymuose numatyta atsakomybe,iskaitant ir baudziamaja atsakomybe*\r\n* Prasome  atsijungti.Jeigu  jus esate   autorizuotas  vartotojas,   *\r\n* prisijungdamas, jus atsakote uz teisingai atlikta konfiguracija ir *\r\n* kitus savo vardu atliktus veiksmus.                                *\r\n**********************************************************************\r\n* You are connected to private equipment. All the actions performed  *\r\n* with the equipment are recorded. In order to access this equipment *\r\n* and (or) perform its configuration or other  actions, you must have*\r\n* an appropriate permission. Illegal connection and illegal actions  *\r\n* with the equipment.                                                *\r\n* Will be subject to liability, including criminal liability, as     *\r\n* provided for in the laws of the Republic of Lithuania. Please      *\r\n* disconnect immediately. If you are an authorized user, by          *\r\n* connecting  to the equipment, you assume liability for performing  *\r\n* correct configuration and other actions under your behalf.         *\r\n**********************************************************************\r\nUser Authentication\r\npacket_write_wait: Connection to 10.46.1.1 port 22: Broken pipe\r\n",
    "unreachable": true
}

or

osboxes@osboxes:~$ sudo ansible -m ping servers

10.46.1.1 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: \r\n**********************************************************************\r\n* Jus esate prisijunge prie privacios irangos. Visi veiksmai,vykdomi *\r\n* su sia iranga, yra fiksuojami. Tam, kad prieiti prie sios irangos  *\r\n* ir (ar) atlikti irangos konfiguracija ar kitus veiksmus, jus turite*\r\n* tureti atitinkama leidima.                                         *\r\n* Uz neteiseta prisijungima bei neteisetus veiksmus su iranga taikoma*\r\n* istatymuose numatyta atsakomybe,iskaitant ir baudziamaja atsakomybe*\r\n* Prasome  atsijungti.Jeigu  jus esate   autorizuotas  vartotojas,   *\r\n* prisijungdamas, jus atsakote uz teisingai atlikta konfiguracija ir *\r\n* kitus savo vardu atliktus veiksmus.                                *\r\n**********************************************************************\r\n* You are connected to private equipment. All the actions performed  *\r\n* with the equipment are recorded. In order to access this equipment *\r\n* and (or) perform its configuration or other  actions, you must have*\r\n* an appropriate permission. Illegal connection and illegal actions  *\r\n* with the equipment.                                                *\r\n* Will be subject to liability, including criminal liability, as     *\r\n* provided for in the laws of the Republic of Lithuania. Please      *\r\n* disconnect immediately. If you are an authorized user, by          *\r\n* connecting  to the equipment, you assume liability for performing  *\r\n* correct configuration and other actions under your behalf.         *\r\n**********************************************************************\r\nUser Authentication\r\nchannel_by_id: 2: bad id: channel free\r\nDisconnecting: Received data for nonexistent channel 2.\r\n",
    "unreachable": true
}

it just connects and immediatly disconnects without entering any command, like "display version". Could it be because im running it not on Cisco device, but on other vendor ? Maybe some special modules ir required ?

Thanks


问:
Is there a formal name for a function that accepts a function(s) as an argument?
Is there a formal name for a type of function that accepts a function(s) as an argument?

I've tried searching for the answer to this question but I haven't been able to find it either here or via Google.  Perhaps there is no formal name?

答: You're looking for Higher-Order functions I think.</p>


问: How to refresh the page

答: You can use location.reload() to refresh the page

Title: How to refresh the page


问:
Not know exception with firebase filters
This code:

```<code>var query: Query = store.collection(COLLECTION_USERS)
        query = query.whereGreaterThanOrEqualTo("age", filter.startAge).whereLessThanOrEqualTo("age", filter.endAge)
        query = query.whereGreaterThanOrEqualTo("start_date", filter.startDate).whereLessThanOrEqualTo("end_date", filter.endDate)
        query = query.whereEqualTo("sex", filter.sex)
        return query.get()
</code>```

throw exception: java.lang.IllegalArgumentException: All where filters other than whereEqualTo() must be on the same field. But you have filters on 'age' and 'start_date' how to fix?

答:
Official documentation of Firestore says that range filters on different fields are forbidden. So Firestore allows to chain multiple where() methods to create more specific queries but only on the same field.

To achieve what you want, you need to query your database twice, once for each fiter because you cannot use both methods in the same query.

Another way to make it happen would be to store a special flag that might fit the query, although in real world applications it will almost impossible to store every single way a user might query the data.

Body:
This code:

var query: Query = store.collection(COLLECTION_USERS)
        query = query.whereGreaterThanOrEqualTo("age", filter.startAge).whereLessThanOrEqualTo("age", filter.endAge)
        query = query.whereGreaterThanOrEqualTo("start_date", filter.startDate).whereLessThanOrEqualTo("end_date", filter.endDate)
        query = query.whereEqualTo("sex", filter.sex)
        return query.get()

throw exception: java.lang.IllegalArgumentException: All where filters other than whereEqualTo() must be on the same field. But you have filters on 'age' and 'start_date' how to fix?


问:
git pull using different SSH key
I am trying to pull changes into a repo. The repo's origin was originally located on a different git server, now the origin has moved to another server. On the new server we have a generic user called 'app', on other machines we have added the app user private key and a config file like so:

```<code># in /root/.ssh/config
Host gitlab-app
  HostName git.ist
  User git
  IdentityFile /root/.ssh/id_rsa_app
  IdentitiesOnly yes
</code>```

and could use a command like this to clone the repo:

```<code>git clone gitlab-app:software-development/my_repo.git
</code>```

Which works. The problem is that on the particular server im talking about the repo had already been cloned from the previous location. I've changed the remote url of the repo to the new location but when trying to pull over ssh I am asked for a password. I guess because there is no key from this server on the gitlab host. Hence the generic 'app' user.

My question is, how do I configure my repo to use the app user key for ssh when I am running the pull command as root user?

In some other threads I saw this:

```<code>git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_app -F /dev/null'
</code>```

But it had no effect for me.

答:
Ok so it was a simple solution. When I changed the remote-url of the repo on the server I just copied and pasted the standard url from the gitlab page. What I needed to change it to was:

from

```<code>git@git.ist:software-development/my_repo.git
</code>```

to

```<code>gitlab-app:software-development/my_repo.git
</code>```

So that the git config file is actually used. Just like in the clone link.

So basically:

```<code>git remote set-url origin gitlab-app:software-development/my_repo.git
</code>```

Title: git pull using different SSH key

Body:
I am trying to pull changes into a repo. The repo's origin was originally located on a different git server, now the origin has moved to another server. On the new server we have a generic user called 'app', on other machines we have added the app user private key and a config file like so:

# in /root/.ssh/config
Host gitlab-app
  HostName git.ist
  User git
  IdentityFile /root/.ssh/id_rsa_app
  IdentitiesOnly yes

and could use a command like this to clone the repo:

git clone gitlab-app:software-development/my_repo.git

Which works. The problem is that on the particular server im talking about the repo had already been cloned from the previous location. I've changed the remote url of the repo to the new location but when trying to pull over ssh I am asked for a password. I guess because there is no key from this server on the gitlab host. Hence the generic 'app' user.

My question is, how do I configure my repo to use the app user key for ssh when I am running the pull command as root user?

In some other threads I saw this:

git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_app -F /dev/null'

But it had no effect for me.

Body:
Ok so it was a simple solution. When I changed the remote-url of the repo on the server I just copied and pasted the standard url from the gitlab page. What I needed to change it to was:

from

git@git.ist:software-development/my_repo.git

to

gitlab-app:software-development/my_repo.git

So that the git config file is actually used. Just like in the clone link.

So basically:

git remote set-url origin gitlab-app:software-development/my_repo.git


问:
How do I programmatically access data about my database?
I'd like to access the list of tables and for each table report number of rows, disk space used, etc. It would be nice to get these details at the database level, too.

How do I do this programmatically?

答:
This script doesn't include schema names but gets you most of the information you want for the current database. I'm sure you can adapt it into a stored procedure.</p>

```<code>SET NOCOUNT ON
GO
DECLARE @tblSpaceUsed TABLE
(
    [name] sysname NOT NULL,
    [rows] int NOT NULL,
    [reserved] nvarchar(50) NOT NULL,
    [reservedKB] int NULL,
    [data] nvarchar(50) NOT NULL,
    [dataKB] int NULL,
    [index] nvarchar(50) NOT NULL,
    [indexKB] int NULL,
    [unused] nvarchar(50) NOT NULL,
    [unusedKB] int NULL
)

DECLARE @tableName sysname
DECLARE @tableNames CURSOR

SET @tableNames = CURSOR
FAST_FORWARD
FOR
SELECT DISTINCT
    ss.name + '.' + st.name
FROM
    sys.tables st
    INNER JOIN
    sys.schemas ss
        ON st.schema_id = ss.schema_id

OPEN @tableNames
FETCH NEXT FROM @tableNames INTO @tableName

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO @tblSpaceUsed ([name], [rows], [reserved], [data], [index], [unused]) EXEC sp_spaceused @tableName

    FETCH NEXT FROM @tableNames INTO @tableName
END

CLOSE @tableNames

UPDATE
    @tblSpaceUsed
SET
    [reservedKB] = CONVERT(int, LEFT([reserved], LEN([reserved]) - 3)),
    [dataKB] = CONVERT(int, LEFT([data], LEN([data]) - 3)),
    [indexKB] = CONVERT(int, LEFT([index], LEN([index]) - 3)),
    [unusedKB] = CONVERT(int, LEFT([unused], LEN([unused]) - 3))

SELECT
    *
FROM
    @tblSpaceUsed
</code>```

Body:
This script doesn't include schema names but gets you most of the information you want for the current database. I'm sure you can adapt it into a stored procedure.

SET NOCOUNT ON
GO
DECLARE @tblSpaceUsed TABLE
(
    [name] sysname NOT NULL,
    [rows] int NOT NULL,
    [reserved] nvarchar(50) NOT NULL,
    [reservedKB] int NULL,
    [data] nvarchar(50) NOT NULL,
    [dataKB] int NULL,
    [index] nvarchar(50) NOT NULL,
    [indexKB] int NULL,
    [unused] nvarchar(50) NOT NULL,
    [unusedKB] int NULL
)

DECLARE @tableName sysname
DECLARE @tableNames CURSOR

SET @tableNames = CURSOR
FAST_FORWARD
FOR
SELECT DISTINCT
    ss.name + '.' + st.name
FROM
    sys.tables st
    INNER JOIN
    sys.schemas ss
        ON st.schema_id = ss.schema_id

OPEN @tableNames
FETCH NEXT FROM @tableNames INTO @tableName

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO @tblSpaceUsed ([name], [rows], [reserved], [data], [index], [unused]) EXEC sp_spaceused @tableName

    FETCH NEXT FROM @tableNames INTO @tableName
END

CLOSE @tableNames

UPDATE
    @tblSpaceUsed
SET
    [reservedKB] = CONVERT(int, LEFT([reserved], LEN([reserved]) - 3)),
    [dataKB] = CONVERT(int, LEFT([data], LEN([data]) - 3)),
    [indexKB] = CONVERT(int, LEFT([index], LEN([index]) - 3)),
    [unusedKB] = CONVERT(int, LEFT([unused], LEN([unused]) - 3))

SELECT
    *
FROM
    @tblSpaceUsed


问:
Array Sum & Average in Java
I have a homework assignment where I have to create an array, sum the elements in the array, and then find the average of the elements in the array, but I have to do it in the same method as the summing method. </p>

<p>This is what I have so far, I've looked in my book and put that in my code, but it won't compile right. </p>

```<code>class SumArray{
   public static void main(String args[]){
       double[] array = {7,8,9,10,11,12,13};
      sumArray(array);
   }

   public static double sumArray(double[] array){
      double sum = 0;
      for ( int i = 0; i < array.length; i++){
         sum += array[i];
         //System.out.println("Sum is = " + sum);
         }
      //System.out.println("Sum is = " +sum);
      //after summing then get average
      return sum;

    double average = sum/array.length;

    System.out.println("Average value of array element is " + average);
    return average;
    }
}
</code>```

答:
Think you should add little bit more OOP. Create such kind of class, and you teacher will be impressed, will gave money grant, and send you to IT competition:</p>

```<code>class MathArray {
    private double[] data;
    public MathArray(double[] data) {
        this.data = data;
    }
    public double getSum() {
        double out = 0;
        for(double d : data) {
            out += d;
        }
        return out;
    }

    public double getAverage() {
        return getSum() / data.length;
    }
}
</code>```

Title: Array Sum & Average in Java

Body:
I have a homework assignment where I have to create an array, sum the elements in the array, and then find the average of the elements in the array, but I have to do it in the same method as the summing method.

This is what I have so far, I've looked in my book and put that in my code, but it won't compile right.

class SumArray{
   public static void main(String args[]){
       double[] array = {7,8,9,10,11,12,13};
      sumArray(array);
   }

   public static double sumArray(double[] array){
      double sum = 0;
      for ( int i = 0; i < array.length; i++){
         sum += array[i];
         //System.out.println("Sum is = " + sum);
         }
      //System.out.println("Sum is = " +sum);
      //after summing then get average
      return sum;

    double average = sum/array.length;

    System.out.println("Average value of array element is " + average);
    return average;
    }
}

Body:
Think you should add little bit more OOP. Create such kind of class, and you teacher will be impressed, will gave money grant, and send you to IT competition:

class MathArray {
    private double[] data;
    public MathArray(double[] data) {
        this.data = data;
    }
    public double getSum() {
        double out = 0;
        for(double d : data) {
            out += d;
        }
        return out;
    }

    public double getAverage() {
        return getSum() / data.length;
    }
}


问:
Conditional tag for single post of Custom Taxonomy
I have a situation where I need to set cookie when a single page of a Custom Taxonomy is executed.

As WordPress not allowing to set cookie from template file I need to use setcookie inside init action.

Reference : https://wordpress.stackexchange.com/questions/67074/issues-with-set-cookie

So my function is as follows,

```<code>function set_location_cookie() {

    // Taxonomy : `store_location`
    if( is_tax( 'store_location' )) {

        die('Yeah. It Worked !!');

        $school = "Some Value";
        setcookie('default_school', $school, time()+3600);
    }
}
add_action( 'init', 'set_location_cookie');
</code>```

I have gone through this document, https://codex.wordpress.org/Function_Reference/is_tax and a post from StackOverflow, Conditional Tags for Custom Taxonomy in Custom Post Type

In every situation they are targeting the archive page for Taxonomy or condition with array of locations as follows,

```<code>is_tax( 'store_location', array('ny', 'tx', 'ga') );
</code>```

Instead of getting all taxonomies in an array, is there any way to detect taxonomy single page easily.

答:
To check if post have some terms in some taxonomy you can use is_object_in_term($post_id, $taxonomy)

For Example

```<code>function set_location_cookie() {
    $post_id = get_the_ID();
    // Taxonomy : `store_location`
    if( is_object_in_term($post_id, 'store_location') ) {

        die('Yeah. It Worked !!');

        $school = "Some Value";
        setcookie('default_school', $school, time()+3600);
    }
}
add_action( 'wp', 'set_location_cookie');
</code>```

Body:
I have a situation where I need to set cookie when a single page of a Custom Taxonomy is executed.

As WordPress not allowing to set cookie from template file I need to use setcookie inside init action.

Reference : https://wordpress.stackexchange.com/questions/67074/issues-with-set-cookie

So my function is as follows,

function set_location_cookie() {

    // Taxonomy : `store_location`
    if( is_tax( 'store_location' )) {

        die('Yeah. It Worked !!');

        $school = "Some Value";
        setcookie('default_school', $school, time()+3600);
    }
}
add_action( 'init', 'set_location_cookie');

I have gone through this document, https://codex.wordpress.org/Function_Reference/is_tax and a post from StackOverflow, Conditional Tags for Custom Taxonomy in Custom Post Type

In every situation they are targeting the archive page for Taxonomy or condition with array of locations as follows,

is_tax( 'store_location', array('ny', 'tx', 'ga') );

Instead of getting all taxonomies in an array, is there any way to detect taxonomy single page easily.

Body:
To check if post have some terms in some taxonomy you can use is_object_in_term($post_id, $taxonomy)

For Example

function set_location_cookie() {
    $post_id = get_the_ID();
    // Taxonomy : `store_location`
    if( is_object_in_term($post_id, 'store_location') ) {

        die('Yeah. It Worked !!');

        $school = "Some Value";
        setcookie('default_school', $school, time()+3600);
    }
}
add_action( 'wp', 'set_location_cookie');


问:
How we can Convert large size of decimal values to float and without exponential values
When I try to convert values from decimal to float, they are shown with exponential values

When I converted numeric to decimal values then they show with .00 fractional,
but I required only in numeric.

check blow mention query.

```<code>select  cast(CAST(435468867990778789.89 as decimal(35, 2))as float) as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select CAST(43546886799090787.89 as float)
</code>```

Above Query result are

```<code>4.35468867990779E+17
43546886799090787.00
43546886799090787.00
4.35468867990908E+16
</code>```

But I require a result like "435468867990778789.89".

答:
You can use the following

```<code>declare @testFloat decimal(38,2) = 435468867990778789.89
SELECT CONVERT(varchar, @testFloat)
</code>```

OR

```<code>SELECT cast(@testFloat as varchar)
</code>```

Result : 435468867990778789.89

Edit

Based on the comment: you can do the following

Explanation

Split the string into two parts, before dot and after dot.

Then concat both result by taking only two characters after the dot only.

Query

```<code>declare @testFloat numeric(38,6) = 435468867990778789.89656,
        @string varchar(100)
set @string = cast(@testFloat as varchar)

select @string = substring(@string,0,charindex('.',@string,0))
                 + '.'
                 + substring(@string,charindex('.',@string,0)+1,2)

select @string
</code>```

Result : 435468867990778789.89

Hope this will help you

Body:
When I try to convert values from decimal to float, they are shown with exponential values

When I converted numeric to decimal values then they show with .00 fractional,
but I required only in numeric.

check blow mention query.

select  cast(CAST(435468867990778789.89 as decimal(35, 2))as float) as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select CAST(43546886799090787.89 as float)

Above Query result are

4.35468867990779E+17
43546886799090787.00
43546886799090787.00
4.35468867990908E+16

But I require a result like "435468867990778789.89".

Body:
You can use the following

declare @testFloat decimal(38,2) = 435468867990778789.89
SELECT CONVERT(varchar, @testFloat)

OR

SELECT cast(@testFloat as varchar)

Result : 435468867990778789.89

Edit

Based on the comment: you can do the following

Explanation

Split the string into two parts, before dot and after dot.

Then concat both result by taking only two characters after the dot only.

Query

declare @testFloat numeric(38,6) = 435468867990778789.89656,
        @string varchar(100)
set @string = cast(@testFloat as varchar)

select @string = substring(@string,0,charindex('.',@string,0))
                 + '.'
                 + substring(@string,charindex('.',@string,0)+1,2)

select @string

Result : 435468867990778789.89

Hope this will help you


问:
Casting type inside Optional
I have the following:

```<code>class Foo implements Inter {
    void doSomething();
}

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    possible.ifPresent(Foo::doSomething);
    return possible.map(f -> f);
}
</code>```

getPossible needs to return an Optional<Inter> because it's overriding a superclass's implementation.

That map at the end of the method is purely to convert the type. Is there a more elegant option?

答: Return a Optional<? extends Inter> instead of an Optional<Inter>.

Title: Casting type inside Optional

Body:
I have the following:

class Foo implements Inter {
    void doSomething();
}

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    possible.ifPresent(Foo::doSomething);
    return possible.map(f -> f);
}

getPossible needs to return an Optional<Inter> because it's overriding a superclass's implementation.

That map at the end of the method is purely to convert the type. Is there a more elegant option?


问:
jQuery - selecting elements from inside a element
let's say I have a markup like this:

```<code><div id="foo">
  ...
  <span id="moo">
    ...
  </span>
  ...
</div>
</code>```

and I want to select #moo.

why $('#foo').find('span') works, but $('span', $('#foo')); doesn't ?

答:
You can use find option to select an element inside another.  For example, to find an element with id txtName in a particular div, you can use like

```<code>var name = $('#div1').find('#txtName').val();
</code>```

Body:
let's say I have a markup like this:

  ...

    ...

  ...

and I want to select #moo.

why $('#foo').find('span') works, but $('span', $('#foo')); doesn't ?

Body:
You can use find option to select an element inside another.  For example, to find an element with id txtName in a particular div, you can use like

var name = $('#div1').find('#txtName').val();