问:
Why isn't my Thread starting and why it's having compile error “Use of unassigned local variable 'thread'”?
My thread isn't starting at all. So I added thread.Start() and now I having the error Use of unassigned local variable 'thread'. The Form shows, but then nothing happens.

```<code>        Thread thread = new Thread(() => {

            {
                PagSeguroWork.Execute(vlTotal, tipoPagamento, nrParcelas);
                thread.Start(); // here's the error
            };

            });

            using (FrmPagamento frm = new FrmPagamento())
            {
                frm.ShowDialog();
            }
</code>```

答:
You're trying to start the thread from within the thread.  Move thread.Start(); to after the definition of the Thread object:

```<code>Thread thread = new Thread(() => {
    PagSeguroWork.Execute(vlTotal, tipoPagamento, nrParcelas);
});
thread.Start();
</code>```

Body:
My thread isn't starting at all. So I added thread.Start() and now I having the error Use of unassigned local variable 'thread'. The Form shows, but then nothing happens.

        Thread thread = new Thread(() => {

            {
                PagSeguroWork.Execute(vlTotal, tipoPagamento, nrParcelas);
                thread.Start(); // here's the error
            };

            });

            using (FrmPagamento frm = new FrmPagamento())
            {
                frm.ShowDialog();
            }

Body:
You're trying to start the thread from within the thread.  Move thread.Start(); to after the definition of the Thread object:

Thread thread = new Thread(() => {
    PagSeguroWork.Execute(vlTotal, tipoPagamento, nrParcelas);
});
thread.Start();


来源: stackexchange

问:
How can I Pull base image of JDK and TOMCAT for building an image for my application
My Application needs JDK and Tomcat as dependencies. How can I pull both during the build process?

Below is my Dockerfile...

```<code>FROM tomcat:8.0

MAINTAINER admin

COPY /App-UI.war /usr/local/tomcat/webapps/
COPY /App-Backend.war /usr/local/tomcat/webapps/
</code>```

I want to have Tomcat and jdk in my image/container . Please help

答:
You don't need to pull jdk container into tomcat. Because the Tomcat runs on java.

You can find the java -version by adding RUN java -version command to your Dockerfile.

```<code>FROM tomcat:8.0

RUN java -version

Step 2/2 : RUN java -version
 ---> Running in 0ebfd70e0e47
java version "1.7.0_181"
OpenJDK Runtime Environment (IcedTea 2.6.14) (7u181-2.6.14-1~deb8u1)
OpenJDK 64-Bit Server VM (build 24.181-b01, mixed mode)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My Application needs JDK and Tomcat as dependencies. How can I pull both during the build process?

Below is my Dockerfile...

FROM tomcat:8.0

MAINTAINER admin

COPY /App-UI.war /usr/local/tomcat/webapps/
COPY /App-Backend.war /usr/local/tomcat/webapps/

I want to have Tomcat and jdk in my image/container . Please help

Body:
You don't need to pull jdk container into tomcat. Because the Tomcat runs on java.

You can find the java -version by adding RUN java -version command to your Dockerfile.

FROM tomcat:8.0

RUN java -version

Step 2/2 : RUN java -version
 ---> Running in 0ebfd70e0e47
java version "1.7.0_181"
OpenJDK Runtime Environment (IcedTea 2.6.14) (7u181-2.6.14-1~deb8u1)
OpenJDK 64-Bit Server VM (build 24.181-b01, mixed mode)


问:
React-pdf - image renders twice
I am using https://react-pdf.org/styling and I would like to display the loaded images when I hit the print button. However, when I print the image renders twice.

```<code>import React from "react";
import phoneLogo from "./images/phone.png";

import {
  Document,
  Page,
  Text,
  View,
  Font,
  StyleSheet,
  Image,
} from "@react-pdf/renderer";

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src={phoneLogo} />
    </Page>
  </Document>
);

class App extends React.Component {
  render() {
    return (
      <div className="w-full">
        <div className="text-center py-12">
          <BlobProvider document={MyDoc()}>
            {({ url }) => (
              <a href={url} target="_blank">
                Print
              </a>
            )}
          </BlobProvider>
        </div>
      </div>
    );
  }
}

export default App;
</code>```

I have tried to load the image like this, but it doesn't show up at all.

```<code>const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src='/images/phone.png />
    </Page>
  </Document>
);
</code>```

Any suggestions? Thank you!!

答:
Sorted!!!

The png is indeed rendered twice when importing the images like this

```<code>const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src={phoneLogo} />
    </Page>
  </Document>
);
</code>```

But it works with an image address, where it renders only once.

```<code>const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src="https://img.icons8.com/android/96/000000/phone.png" />
    </Page>
  </Document>
);
</code>```

Title: React-pdf - image renders twice

Body:
I am using https://react-pdf.org/styling and I would like to display the loaded images when I hit the print button. However, when I print the image renders twice.

import React from "react";
import phoneLogo from "./images/phone.png";

import {
  Document,
  Page,
  Text,
  View,
  Font,
  StyleSheet,
  Image,
} from "@react-pdf/renderer";

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src={phoneLogo} />
    </Page>
  </Document>
);

class App extends React.Component {
  render() {
    return (

          <BlobProvider document={MyDoc()}>
            {({ url }) => (

                Print

            )}
          </BlobProvider>

    );
  }
}

export default App;

I have tried to load the image like this, but it doesn't show up at all.

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src='/images/phone.png />
    </Page>
  </Document>
);

Any suggestions? Thank you!!

Body:
Sorted!!!

The png is indeed rendered twice when importing the images like this

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src={phoneLogo} />
    </Page>
  </Document>
);

But it works with an image address, where it renders only once.

const MyDoc = () => (
  <Document>
    <Page wrap>
      <Image src="https://img.icons8.com/android/96/000000/phone.png" />
    </Page>
  </Document>
);


答:
Because you are trying to access thread variable in lambda which initializes thread variable (so basically tin this case it would meanthat you are trying to start thread from itself). Try moving thread.Start()  out:

```<code>Thread thread = new Thread(() => PagSeguroWork.Execute(vlTotal, tipoPagamento, nrParcelas));
thread.Start();
</code>```

Also nowadays in general it is recommended to use in C# Task API and not to create Thread's manually.

Title: Why isn't my Thread starting and why it's having compile error “Use of unassigned local variable 'thread'”?

Body:
Because you are trying to access thread variable in lambda which initializes thread variable (so basically tin this case it would meanthat you are trying to start thread from itself). Try moving thread.Start()  out:

Thread thread = new Thread(() => PagSeguroWork.Execute(vlTotal, tipoPagamento, nrParcelas));
thread.Start();

Also nowadays in general it is recommended to use in C# Task API and not to create Thread's manually.


问:
deparse(substitute()) with lapply
I want to give labels to data frames using a combination of a small function in combination with lapply()

I have the following code:

```<code>df1 <- data.frame(c(1,2,3), c(3,4,5))
df2 <- data.frame(c(6,7,8), c(9,10,11))

f.generate.name <- function(x) {
  x$name <- deparse(substitute(x))
  return(x)
  }

my_list <- list(df1, df2)

# This works fine.
f.generate.name(df1)

# This does not work.
lapply(my_list, f.generate.name)

</code>```

which produces the following output

```<code>[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 X[[i]]
2          2          4 X[[i]]
3          3          5 X[[i]]

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 X[[i]]
2          7           10 X[[i]]
3          8           11 X[[i]]

</code>```

What I want instead is:

```<code>[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 df1
2          2          4 df1
3          3          5 df1

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 df2
2          7           10 df2
3          8           11 df2
</code>```

What is the best way of dong this without using loops? How can I tweak the lapply() function or the function that I created in order to achieve the desired result?

答:
Base R

lapply() cannot iterate over more than one argument. You can use mapply() or its wrapper Map() in this case that always returns a list.

```<code>Map(f = function(x, y){
    x$name <- y
    x },
  my_list,
  names(my_list))
$df1
  c.1..2..3. c.3..4..5. name
1          1          3  df1
2          2          4  df1
3          3          5  df1

$df2
  c.6..7..8. c.9..10..11. name
1          6            9  df2
2          7           10  df2
3          8           11  df2
</code>```

Tidyverse

In case you are open to a purrr solution, you can use imap(). It makes the names of the object conveniently available. There is no need to write a function then:

```<code>my_list <- list(df1 = df1, df2 = df2)

imap(my_list, ~{
  .x$name <- .y
  .x
  })
$df1
  c.1..2..3. c.3..4..5. name
1          1          3  df1
2          2          4  df1
3          3          5  df1

$df2
  c.6..7..8. c.9..10..11. name
1          6            9  df2
2          7           10  df2
3          8           11  df2
</code>```

Title: deparse(substitute()) with lapply

Body:
I want to give labels to data frames using a combination of a small function in combination with lapply()

I have the following code:

df1 <- data.frame(c(1,2,3), c(3,4,5))
df2 <- data.frame(c(6,7,8), c(9,10,11))

f.generate.name <- function(x) {
  x$name <- deparse(substitute(x))
  return(x)
  }

my_list <- list(df1, df2)

# This works fine.
f.generate.name(df1)

# This does not work.
lapply(my_list, f.generate.name)

which produces the following output

[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 X[[i]]
2          2          4 X[[i]]
3          3          5 X[[i]]

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 X[[i]]
2          7           10 X[[i]]
3          8           11 X[[i]]

What I want instead is:

[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 df1
2          2          4 df1
3          3          5 df1

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 df2
2          7           10 df2
3          8           11 df2

What is the best way of dong this without using loops? How can I tweak the lapply() function or the function that I created in order to achieve the desired result?

Body:
Base R

lapply() cannot iterate over more than one argument. You can use mapply() or its wrapper Map() in this case that always returns a list.

Map(f = function(x, y){
    x$name <- y
    x },
  my_list,
  names(my_list))
$df1
  c.1..2..3. c.3..4..5. name
1          1          3  df1
2          2          4  df1
3          3          5  df1

$df2
  c.6..7..8. c.9..10..11. name
1          6            9  df2
2          7           10  df2
3          8           11  df2

Tidyverse

In case you are open to a purrr solution, you can use imap(). It makes the names of the object conveniently available. There is no need to write a function then:

my_list <- list(df1 = df1, df2 = df2)

imap(my_list, ~{
  .x$name <- .y
  .x
  })
$df1
  c.1..2..3. c.3..4..5. name
1          1          3  df1
2          2          4  df1
3          3          5  df1

$df2
  c.6..7..8. c.9..10..11. name
1          6            9  df2
2          7           10  df2
3          8           11  df2


问:
How to make image jump only on the ground?
I am trying to make an image jump. I when I press the up arrow it goes up until it arrives at a certain position on the Y axis and starts going down. But I have a problem, the image is able to jump infinitely in the air kind of like flappy bird. I would like it to be only able to jump when it arrives at the jump.
Here is my code for now:

```<code>#Variables
display_width = 900
display_height = 800
gameName = 'Slash'

#Settings
gameTitle = pygame.display.set_caption(gameName)
wn = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()

#Game Loop
def gameLoop():
   #stick man
    manImg = pygame.image.load('blueStickman.png')
    man_width = 58
    man_height = 146
    Xchange = 0
    Ychange = 0
    x = (display_width/2) - (man_width/2) + 1
    y = display_height - man_height
    def man(x,y):
        wn.blit(manImg, (x,y))
    while True:
        wn.fill(white)
        man(x,y)
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:
                    pygame.display.quit()
                    pygame.quit()

                if event.key == pygame.K_UP:
                        Ychange = -5
                if event.key == pygame.K_LEFT:
                    Xchange = -4
                if event.key == pygame.K_RIGHT:
                    Xchange = 4

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                        Ychange = -5
                if event.key == pygame.K_LEFT:
                    Xchange = 0
                if event.key == pygame.K_RIGHT:
                    Xchange = 0

        x += Xchange
        y += Ychange
        if y <= 385:
            Ychange = 5
        if y >= display_height - man_height:
            Ychange = 0

        clock.tick(60)

gameLoop()
</code>```

Hope you can help and thanks if you can!

答:
First of all I recommend to use pygame.key.get_pressed() for the left and right movement of the player, rather than the KEYDOWN and KEYUP event:

keys = pygame.key.get_pressed()
Xchange = 0
if keys[pygame.K_LEFT]:
    Xchange -= 4
if keys[pygame.K_RIGHT]:
    Xchange += 4
```

<hr>

<p>Define the ground level of the payer:</p>

<pre class="lang-py prettyprint-override"><code>y = display_height - man_height
ground_y = y
</code>```

Evaluate if the player is on the ground in the main application loop and discard jumping if the player is not on the ground:

while True:
    # [...]

    on_ground = y == ground_y

    for event in pygame.event.get():
            # [...]

            if event.type == pygame.KEYDOWN:
                # [...]

                if event.key == pygame.K_UP and on_ground:
                    Ychange = -5
```

<hr>

<p>See the example:</p>

<pre class="lang-py prettyprint-override"><code>import pygame

white = (255, 255, 255)

#Variables
display_width = 900
display_height = 800
gameName = 'Slash'

#Settings
gameTitle = pygame.display.set_caption(gameName)
wn = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()

#Game Loop
def gameLoop():
    #stick man
    manImg = pygame.image.load('blueStickman.png')
    man_width, man_height = 58, 156
    Xchange, Ychange = 0, 0
    x = (display_width/2) - (man_width/2) + 1
    y = display_height - man_height
    ground_y = y

    def man(x,y):
        wn.blit(manImg, (x,y))

    while True:
        wn.fill(white)
        man(x,y)
        pygame.display.update()

        on_ground = y == ground_y

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:
                    pygame.display.quit()
                    pygame.quit()

                if event.key == pygame.K_UP and on_ground:
                    Ychange = -5

        keys = pygame.key.get_pressed()
        Xchange = 0
        if keys[pygame.K_LEFT]:
            Xchange -= 4
        if keys[pygame.K_RIGHT]:
            Xchange += 4

        x += Xchange
        y += Ychange
        if y <= 385:
            Ychange = 5
        if y >= display_height - man_height:
            Ychange = 0

        clock.tick(60)

gameLoop()
</code>```

Body:
I am trying to make an image jump. I when I press the up arrow it goes up until it arrives at a certain position on the Y axis and starts going down. But I have a problem, the image is able to jump infinitely in the air kind of like flappy bird. I would like it to be only able to jump when it arrives at the jump.
Here is my code for now:

#Variables
display_width = 900
display_height = 800
gameName = 'Slash'

#Settings
gameTitle = pygame.display.set_caption(gameName)
wn = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()

#Game Loop
def gameLoop():
   #stick man
    manImg = pygame.image.load('blueStickman.png')
    man_width = 58
    man_height = 146
    Xchange = 0
    Ychange = 0
    x = (display_width/2) - (man_width/2) + 1
    y = display_height - man_height
    def man(x,y):
        wn.blit(manImg, (x,y))
    while True:
        wn.fill(white)
        man(x,y)
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:
                    pygame.display.quit()
                    pygame.quit()

                if event.key == pygame.K_UP:
                        Ychange = -5
                if event.key == pygame.K_LEFT:
                    Xchange = -4
                if event.key == pygame.K_RIGHT:
                    Xchange = 4

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                        Ychange = -5
                if event.key == pygame.K_LEFT:
                    Xchange = 0
                if event.key == pygame.K_RIGHT:
                    Xchange = 0

        x += Xchange
        y += Ychange
        if y <= 385:
            Ychange = 5
        if y >= display_height - man_height:
            Ychange = 0

        clock.tick(60)

gameLoop()

Hope you can help and thanks if you can!

Body:
First of all I recommend to use pygame.key.get_pressed() for the left and right movement of the player, rather than the KEYDOWN and KEYUP event:

keys = pygame.key.get_pressed()
Xchange = 0
if keys[pygame.K_LEFT]:
    Xchange -= 4
if keys[pygame.K_RIGHT]:
    Xchange += 4

Define the ground level of the payer:

y = display_height - man_height
ground_y = y

Evaluate if the player is on the ground in the main application loop and discard jumping if the player is not on the ground:

while True:
    # [...]

    on_ground = y == ground_y

    for event in pygame.event.get():
            # [...]

            if event.type == pygame.KEYDOWN:
                # [...]

                if event.key == pygame.K_UP and on_ground:
                    Ychange = -5

See the example:

import pygame

white = (255, 255, 255)

#Variables
display_width = 900
display_height = 800
gameName = 'Slash'

#Settings
gameTitle = pygame.display.set_caption(gameName)
wn = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()

#Game Loop
def gameLoop():
    #stick man
    manImg = pygame.image.load('blueStickman.png')
    man_width, man_height = 58, 156
    Xchange, Ychange = 0, 0
    x = (display_width/2) - (man_width/2) + 1
    y = display_height - man_height
    ground_y = y

    def man(x,y):
        wn.blit(manImg, (x,y))

    while True:
        wn.fill(white)
        man(x,y)
        pygame.display.update()

        on_ground = y == ground_y

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:
                    pygame.display.quit()
                    pygame.quit()

                if event.key == pygame.K_UP and on_ground:
                    Ychange = -5

        keys = pygame.key.get_pressed()
        Xchange = 0
        if keys[pygame.K_LEFT]:
            Xchange -= 4
        if keys[pygame.K_RIGHT]:
            Xchange += 4

        x += Xchange
        y += Ychange
        if y <= 385:
            Ychange = 5
        if y >= display_height - man_height:
            Ychange = 0

        clock.tick(60)

gameLoop()


问:
Dynamically create UI5-Controls with properties from json-string. Problems with events in json-string
in my actual development i create an app which needs to create UI5-Controls dynmaically at runtime from an database customizing-table.

As an simplyfied example when creating an input field:

```<code>var loProObj = JSON.parse(pData.TEMPLATE);
var loInp = new sap.m.Input(loProObj);

</code>```

This works so far for most of the properties when pData.TEMPLATE is a JSON-String.
But it does not work for Event-Method Properties.Then i get an error like: Uncaught TypeError: I.fFunction.call is not a function

So as simpliefied JSON-String for code above take this string:

```<code>'{"value":"{boundVariable}","change":"onChange"}'
</code>```

When this string is parsed (remember its a string comming from a database to be parsed to JSON, not a JSON-Object), onChange is still a string. this might be the problem. But what can i do to transport the information about the eventhandler methods in a json-string?

Any hints would be great

Kind regards
MatHay

答:
loProObj.change = this[loProObj.change]

This converts the string "onChange" (or any other event name) into the actual function (if it is available within the this context). This function can then be called when the event is triggered.

If you need to access this in your event handler I suggest:

loProObj.change = this[loProObj.change].bind(this)

Body:
in my actual development i create an app which needs to create UI5-Controls dynmaically at runtime from an database customizing-table.

As an simplyfied example when creating an input field:

var loProObj = JSON.parse(pData.TEMPLATE);
var loInp = new sap.m.Input(loProObj);

This works so far for most of the properties when pData.TEMPLATE is a JSON-String.
But it does not work for Event-Method Properties.Then i get an error like: Uncaught TypeError: I.fFunction.call is not a function

So as simpliefied JSON-String for code above take this string:

'{"value":"{boundVariable}","change":"onChange"}'

When this string is parsed (remember its a string comming from a database to be parsed to JSON, not a JSON-Object), onChange is still a string. this might be the problem. But what can i do to transport the information about the eventhandler methods in a json-string?

Any hints would be great

Kind regards
MatHay


问:
Stacking images on top of each other CSS
I've been trying for hours to make these images appear on top of each other. I've tried using position and z-index but I can't make it work.Please help. CSS/HTML.

HTML.

```<code><div class="test">
    <img class="bg" src="images/pattern-bg.svg" alt="">
    <img class="img" src="images\image-tanya.jpg" alt="tanya">
</div>

CSS
`````````````````````````````````````````````````````````````````
.bg {
  position: relative;
  height: 450px;
  width: 450px;
  margin: 0;
}

img {
  position: relative;
  float: right;
  height: 350px;
  width: 350px;
}
``````````````````````````````````````````````````````````````````
Thank You.

```

答:
Try this..

    .rect
    {
      position: relative;
      top: 0;
      left: 0;
    }
    .another-rec
    {
      position: absolute;
      top: 60px;
      left: 80px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="position: relative; left: 0; top: 0;">
            <img src="https://dummyimage.com/600x400/000/fff" class="rect"/>
            <img src="https://dummyimage.com/600x400/ccc/fff" class="another-rec"/>
          </div></code>```

Body:
I've been trying for hours to make these images appear on top of each other. I've tried using position and z-index but I can't make it work.Please help. CSS/HTML.

HTML.

CSS
`````````````````````````````````````````````````````````````````
.bg {
  position: relative;
  height: 450px;
  width: 450px;
  margin: 0;
}

img {
  position: relative;
  float: right;
  height: 350px;
  width: 350px;
}
``````````````````````````````````````````````````````````````````
Thank You.

Body:
Try this..

    .rect
    {
      position: relative;
      top: 0;
      left: 0;
    }
    .another-rec
    {
      position: absolute;
      top: 60px;
      left: 80px;
    }

<div style="position: relative; left: 0; top: 0;">
            <img src="https://dummyimage.com/600x400/000/fff" class="rect"/>
            <img src="https://dummyimage.com/600x400/ccc/fff" class="another-rec"/>
          </div>


问:
iPhone SDK: SQLite error: no such table:, even though a terminal query returns successful
I have a problem with sqlite database integration in my app.
My app uses a translator style function, whereby a users text entry is converted into another way of wording the same word, the word alternatives are listed in a SQLite database.

Basically the code is designed to take text, split it into individual words, and search for them on the database, and return the result for each word, however, the application ends up not returning results and I get the error "error: no such table: dictionary" Even though a query on terminal returns results successfully.

Can anyone give me a hand in identifying what's been done wrong? Thanks

This is the code I used:

```<code>-(void)translate{
//take input and break into an array
NSString *clearText = [[NSString alloc] init];
clearText=inputBox.text;
NSArray *words = [[NSArray alloc] init];
words= [clearText componentsSeparatedByString:@" "];
numOfWords=words.count;
NSString *newText=@"";
//open database
sqlite3 *db = [self getNewDBConnection];
//loop through array
for(i=0;i<numOfWords;i++){
    sqlite3_stmt *resultStatement= nil;
    NSString *res = [NSString stringWithFormat:@"select * from dictionary where plain='%@'",[words objectAtIndex:i]];
    if((sqlite3_prepare_v2(db, [res UTF8String], -1, &resultStatement, nil))!=SQLITE_OK){
        NSLog(@"Error getting result, maybe word not found\n");
         //NSLog(@"tried query:%@",res);
        NSLog(@"error: %s", sqlite3_errmsg(db));
    }
    else{
        if(sqlite3_step(resultStatement)==SQLITE_ROW){
            //in the line below, 1 is the column number of the replacement word
            NSString *add = [[NSString alloc] initWithUTF8String: (char*)sqlite3_column_text(resultStatement,1)];
            newText=[newText stringByAppendingString:add];
            [add release];
        }
    }
    sqlite3_finalize(resultStatement);
}
//output result
outputBox.text=newText;
sqlite3_close(db);
}
-(sqlite3 *) getNewDBConnection{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data9.sqlite"];

if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {

    NSLog(@"Database Successfully Opened");

} else {
    NSLog(@"Error in opening database");
}

return newDBconnection;
}
</code>```

This is the code used to copy the database:

```<code>- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"data9.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)  return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data9.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
   }
}
</code>```

答: Based on the missing table, it looks like it is creating a new database at the path. So either the path is wrong, or it is possible that you might not have copied the master database to that location. The SQLite file is usually in the bundle and needs to be copied first.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with sqlite database integration in my app.
My app uses a translator style function, whereby a users text entry is converted into another way of wording the same word, the word alternatives are listed in a SQLite database.

Basically the code is designed to take text, split it into individual words, and search for them on the database, and return the result for each word, however, the application ends up not returning results and I get the error "error: no such table: dictionary" Even though a query on terminal returns results successfully.

Can anyone give me a hand in identifying what's been done wrong? Thanks

This is the code I used:

-(void)translate{
//take input and break into an array
NSString *clearText = [[NSString alloc] init];
clearText=inputBox.text;
NSArray *words = [[NSArray alloc] init];
words= [clearText componentsSeparatedByString:@" "];
numOfWords=words.count;
NSString *newText=@"";
//open database
sqlite3 *db = [self getNewDBConnection];
//loop through array
for(i=0;i<numOfWords;i++){
    sqlite3_stmt *resultStatement= nil;
    NSString *res = [NSString stringWithFormat:@"select * from dictionary where plain='%@'",[words objectAtIndex:i]];
    if((sqlite3_prepare_v2(db, [res UTF8String], -1, &resultStatement, nil))!=SQLITE_OK){
        NSLog(@"Error getting result, maybe word not found\n");
         //NSLog(@"tried query:%@",res);
        NSLog(@"error: %s", sqlite3_errmsg(db));
    }
    else{
        if(sqlite3_step(resultStatement)==SQLITE_ROW){
            //in the line below, 1 is the column number of the replacement word
            NSString *add = [[NSString alloc] initWithUTF8String: (char*)sqlite3_column_text(resultStatement,1)];
            newText=[newText stringByAppendingString:add];
            [add release];
        }
    }
    sqlite3_finalize(resultStatement);
}
//output result
outputBox.text=newText;
sqlite3_close(db);
}
-(sqlite3 *) getNewDBConnection{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data9.sqlite"];

if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {

    NSLog(@"Database Successfully Opened");

} else {
    NSLog(@"Error in opening database");
}

return newDBconnection;
}

This is the code used to copy the database:

- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"data9.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)  return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data9.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
   }
}


问:
How can I check if an array contains a value of another array?
I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.

I'm looking for any value not one specific value.

答:
You can use any and contains methods to check if there is a common element.

```<code>val a = arrayOf(1, 2, 5, 7, 9, 15)
val b = arrayOf(15, 3, 5, 8)

println(a.any(b::contains))
// true
</code>```

Please note: This method is not very efficient. It has a worst case complexity of n^2. One way to improve performance is to convert the array on which look up is done (b in this eg) to a Set

Body:
You can use any and contains methods to check if there is a common element.

val a = arrayOf(1, 2, 5, 7, 9, 15)
val b = arrayOf(15, 3, 5, 8)

println(a.any(b::contains))
// true

Please note: This method is not very efficient. It has a worst case complexity of n^2. One way to improve performance is to convert the array on which look up is done (b in this eg) to a Set


问:
how to install pip on windows
I've tried installing pip on windows using instructions from https://www.liquidweb.com/kb/install-pip-windows/, (which I've listed below), but when I run pip -V, I keep getting 'pip' is not recognized as an internal or external command,
operable program or batch file. Does anyone know what to do?

These were the instructions I followed:

Download get-pip.py to a folder on your computer. (right clicked and selected save link as...)

Open a command prompt and navigate to the folder containing get-pip.py.

Run the following command:
python get-pip.py

Pip is now installed!

You can verify that Pip was installed correctly by opening a command prompt and entering the following command:

pip -V

答: I recommend you to uninstall python and then reinstall it again. In the installation window, use custom installation and check all the option which includes pip and also check to add pip to your environment variables.</p>

Title: how to install pip on windows


问:
How can I change link color and hover color in Bootstrap version 4?
In my design, I want to change my link and hover color in a specific part. I try my best but I can't do that. I am new in bootstrap. How can I change it for Bootstrap 4? A simple code is here-

```<code><div class="card" style="max-width: 320px;">
     <div class="card-header text-center"><h3>Navigation</h3></div>
          <div class="card-block">
               <ul class="nav navbar-nav" style="font-size: 1.50em;">
                   <li><a href="#" class="nav-link">Home</a></li>
                    <li><a href="#" class="nav-link">Documents</a></li>
                    <li><a href="#" class="nav-link">Videos</a></li>
                    <li><a href="#" class="nav-link">Gallery</a></li>
                    <li><a href="#" class="nav-link">Download</a></li>
                </ul>
           </div>
</div>
</code>```

答:
2020 - Google brought me here for something similar.

Bootstrap 4.5

For those who would like to change only the link color or the  tag  upon hover, just apply a custom class, say hover_black as follows;

Note - my links are white but black when hovered upon

```<code>//CSS

.text_white          { color: white;  }
a.hover_black:hover  { color: black !important;  }

</code>```
```<code>// HTML
<a class="text_white hover_black"> Link </a>
</code>```

Body:
In my design, I want to change my link and hover color in a specific part. I try my best but I can't do that. I am new in bootstrap. How can I change it for Bootstrap 4? A simple code is here-

Navigation

Home

Documents

Videos

Gallery

Download

Body:
2020 - Google brought me here for something similar.

Bootstrap 4.5

For those who would like to change only the link color or the < a > tag  upon hover, just apply a custom class, say hover_black as follows;

Note - my links are white but black when hovered upon

//CSS

.text_white          { color: white;  }
a.hover_black:hover  { color: black !important;  }

// HTML
<a class="text_white hover_black"> Link </a>


问:
SparkConf as Kubernetes ConfigMap
I am playing with the spark-on-k8s-operator. I wondered upfront if anyone has good examples/manifests for providing spark conf via Kubernetes ConfigMaps?

Appreciate some pointers.

For now, I am using:import com.typesafe.config.{Config, ConfigFactory} and an explicit application.conf file in src/main/resources

```<code>  @transient lazy val logger: Logger = LoggerFactory.getLogger(getClass)
  val config: Config                 = ConfigFactory.parseResources("application.conf")
  config.checkValid(ConfigFactory.defaultReference(), topicName)
  private val source: String = config.getString(s"${topicName}.source")
  private val topic: String =
    config.getString(s"${topicName}.topic")
  private val brokers: String =
    config.getString(s"${topicName}.kafka_bootstrap_servers")
  private val offsets: String =
    config.getString(s"${topicName}.auto_offset_reset")
  private val failOnLoss: String =
    config.getString(s"${topicName}.fail_on_data_loss")
</code>```

答:
I dont have any examples, but i can suggest an offer.

Instead use application.conf, you can use any YAML library(or other types of config files extention), and take the path of the config.yaml from environment variable (for example: app.config.dir=/etc/app/config.yaml),

Than configure kubernetes config map file (config.yaml) to /etc/app,
and when your app is started it`ll read from there the configuration (offcourse you should setup the environment variable of app.config.dir).

Title: SparkConf as Kubernetes ConfigMap

Body:
I am playing with the spark-on-k8s-operator. I wondered upfront if anyone has good examples/manifests for providing spark conf via Kubernetes ConfigMaps?

Appreciate some pointers.

For now, I am using:import com.typesafe.config.{Config, ConfigFactory} and an explicit application.conf file in src/main/resources

  @transient lazy val logger: Logger = LoggerFactory.getLogger(getClass)
  val config: Config                 = ConfigFactory.parseResources("application.conf")
  config.checkValid(ConfigFactory.defaultReference(), topicName)
  private val source: String = config.getString(s"${topicName}.source")
  private val topic: String =
    config.getString(s"${topicName}.topic")
  private val brokers: String =
    config.getString(s"${topicName}.kafka_bootstrap_servers")
  private val offsets: String =
    config.getString(s"${topicName}.auto_offset_reset")
  private val failOnLoss: String =
    config.getString(s"${topicName}.fail_on_data_loss")


问:
How to check many columns for boundaries set in another table?
I'm using PostgreSQL v10.12

Table 1: Threshold with total rows ~800 (Each sensor's minimum and maximum threshold level is store in this table)

Description:

```<code>SensorName Varchar(10),
MinLimit numeric,
MaxLimit numeric
</code>```

Data:

SensorName | MinLimit | MaxLimit
Sensor1    | 80       | 115
Sensor2    | 60       | 70
Sensor3    | 100      | 120
...
Sensor800  | 60       | 70
```

<p><strong>Table 2: IoTData</strong> with total columns <code>~800+</code> (Each sensor in Threshold table is the column in IoTData table)</p>

<p>Description: </p>

```IoTDateTime timestamp without time zone,
sensor1 numeric(3)
sensor2 numeric(8,5)
sensor3 numeric(5,2)
....
Sensor800 numeric(5,2)
```

<p>For every 5 minutes record will be generated in this table.
This table is partitioned with date range (4 months data will be in a partition). Likewise there are 6 partitions in for this table so far.</p>

<p>*e.g:   </p>

<pre class="lang-none prettyprint-override"><code>        IoTDateTime         |   Sensor1
    2020-01-01 11:05:00     |      85
    2020-01-01 11:10:00     |      80
    2020-01-01 11:15:00     |      77
    ...
    2020-01-31 23:50:00     |      70
    2020-01-31 23:55:00     |      70
</code>```

From Table 1 Threshold this Sensor1's MinLimit is 80 and MaxLimit is 115. Anything below MinLimit (80) or greater than MaxLimit (115) is considered as alert or sensor is malfunctioning.

I need to find the alert count of all 800+ sensors for each day of a month.

I wrote below function to perform this logic.

Need your help to rewrite this function in better way to reduce the line of code and optimistic logic.
Thanks in advance :)

```<code>CREATE OR REPLACE FUNCTION public.udf_SensorFailedForeachDay
(   pimono integer,
    pstartdate timestamp without time zone,
    penddate timestamp without time zone)

    RETURNS TABLE(date_of_month double precision, Sensor1 double precision, Sensor2 double precision,
    ...
    , Sensor800 double precision)
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
    ROWS 1000
AS $BODY$

declare Sensor1min  numeric(3);declare Sensor1max  numeric(3);

declare Sensor2min  numeric(8,5);declare Sensor2max  numeric(8,5);
....
declare Sensor800min  numeric(5,2);declare Sensor800max  numeric(5,2);
BEGIN

select minlimit,maxlimit Into Sensor1min,Sensor1max from threshold where channelname='Sensor1';
select minlimit,maxlimit Into Sensor2min,Sensor2max from threshold where channelname='Sensor2';
...

select minlimit,maxlimit Into Sensor800min,Sensor800max from threshold where channelname='Sensor800';
Return query
select extract(day from a.IoTDateTime) as date_of_month,
(cast(sum(case when a.Sensor1 between Sensor1min and Sensor1max then 1 end) as float)/cast(count(a.IoTDateTime) as float) )*100 as Sensor1,
(cast(sum(case when a.Sensor2 between Sensor2min and Sensor2max then 1 end) as float)/cast(count(a.IoTDateTime) as float))*100 as Sensor2,
...
(cast(sum(case when a.Sensor800 between Sensor800min and Sensor800max then 1 end) as float)/cast(count(a.IoTDateTime) as float))*100 as Sensor800
from IoTData a where a.IoTDateTime between Pstartdate and Penddate
group by extract(day from a.IoTDateTime) order by extract(day from a.IoTDateTime);

END;
$BODY$;
</code>```

答:
If you have a fixed number of sensors and hardly ever update rows, storing data in IoTData with a single row per timestamp, like you did, can make sense to get minimum storage size and good performance.

However, you are getting close to the absolute maximum number of columns allowed, which is an indicator that you may be moving in the wrong direction. See:

Database Columns In Select or create statements

If you later need to add / remove sensors, you have to adapt the table structure and everything that depends on it, including the function I am going to supply. A painful process. So, typically, it would be more reasonable to use a more generic model with one row per measurement (800 rows instead of just 1). That bloats storage, but is much more versatile.

That said, it can work like this:

```<code>CREATE TEMP TABLE threshold (
   sensorname varchar(10),
   minlimit numeric,
   maxlimit numeric
);

INSERT INTO threshold VALUES
  ('Sensor1', 80 , 115)
, ('Sensor2', 60 , 70)
, ('Sensor3', 100, 120)
-- more
;

CREATE TABLE iotdata (
   iotdatetime timestamp PRIMARY KEY
 , sensor1 numeric(3)
 , sensor2 numeric(8,5)
 , sensor3 numeric(5,2)
);

INSERT INTO iotdata VALUES
  ('2020-01-01 11:05:00', 85, 65, 110)
, ('2020-01-01 11:10:00', 86, 11, 109)  -- low
, ('2020-01-01 11:15:00', 77, 15, 666)  -- low + hi
;
</code>```

```<code>TABLE threshold;
</code>```

```
sensorname | minlimit | maxlimit
:--------- | -------: | -------:
Sensor1    |       80 |      115
Sensor2    |       60 |       70
Sensor3    |      100 |      120
```

```<code>-- pivot table threshold to match pivoted data
CREATE TABLE dim_threshold AS
SELECT *
FROM  crosstab(
 $$(
   SELECT 'min' AS dimension, sensorname, minlimit
   FROM   threshold
   ORDER  BY sensorname
   )
   UNION ALL
   (
   SELECT 'max' AS dimension, sensorname, maxlimit
   FROM   threshold
   ORDER  BY sensorname
   )$$
   , $$(SELECT unnest('{Sensor1,Sensor2,Sensor3}'::text[]))$$
   ) AS (dimension text, sensor1 numeric, sensor2 numeric, sensor3 numeric);

TABLE dim_threshold;
</code>```

```

dimension | sensor1 | sensor2 | sensor3
:-------- | ------: | ------: | ------:
min       |      80 |      60 |     100
max       |     115 |      70 |     120
```

```<code>TABLE iotdata;
</code>```

```
iotdatetime         | sensor1 |  sensor2 | sensor3
:------------------ | ------: | -------: | ------:
2020-01-01 11:05:00 |      85 | 65.00000 |  110.00
2020-01-01 11:10:00 |      86 | 11.00000 |  109.00
2020-01-01 11:15:00 |      77 | 15.00000 |  666.00
```

```<code>-- aux function to calculate percentage
CREATE FUNCTION f_calc_pct(bigint, bigint)
  RETURNS float LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
'SELECT ($1 * 100)::float / $2';
</code>```

```<code>-- main function
CREATE OR REPLACE FUNCTION udf_sensor_fail_per_day(pstartdate timestamp
                                                 , penddate   timestamp)
  RETURNS TABLE(the_day date, dimenstion text, sensor1 float, sensor2 float, sensor3 float) -- more?
  LANGUAGE sql ROWS 100 AS
$func$
WITH cte AS (
   SELECT iotdatetime::date AS the_day
        , count(*) AS ct
        , count(*) FILTER (WHERE i.sensor1 < min.sensor1) AS s1_min
        , count(*) FILTER (WHERE i.sensor2 < min.sensor2) AS s2_min
        , count(*) FILTER (WHERE i.sensor3 < min.sensor3) AS s3_min
      -- more ...
        , count(*) FILTER (WHERE i.sensor1 > max.sensor1) AS s1_max
        , count(*) FILTER (WHERE i.sensor2 > max.sensor2) AS s2_max
        , count(*) FILTER (WHERE i.sensor3 > max.sensor3) AS s3_max
      -- more ...
   FROM   iotdata i
   CROSS  JOIN (SELECT * FROM dim_threshold WHERE dimension = 'min') min
   CROSS  JOIN (SELECT * FROM dim_threshold WHERE dimension = 'max') max
   WHERE  iotdatetime >= pstartdate
   AND    iotdatetime <  penddate
   GROUP  BY 1
   )
SELECT the_day, 'min' AS dimension
     , f_calc_pct(s1_min, ct) -- AS s1
     , f_calc_pct(s2_min, ct) -- AS s2
     , f_calc_pct(s3_min, ct) -- AS s3
    -- more ...
FROM   cte
UNION ALL
SELECT the_day, 'max' AS dimension
     , f_calc_pct(s1_max, ct) -- AS s1
     , f_calc_pct(s2_max, ct) -- AS s2
     , f_calc_pct(s3_max, ct) -- AS s3
    -- more ...
FROM   cte;
$func$;
</code>```

```<code>-- call
SELECT * FROM udf_sensor_fail_per_day('2020-01-01 00:00', '2020-01-11 00:00');
</code>```

```<code>TABLE threshold;
</code>```0

db<>fiddle here

Body:
I'm using PostgreSQL v10.12

Table 1: Threshold with total rows ~800 (Each sensor's minimum and maximum threshold level is store in this table)

Description:

SensorName Varchar(10),
MinLimit numeric,
MaxLimit numeric

Data:

SensorName | MinLimit | MaxLimit
Sensor1    | 80       | 115
Sensor2    | 60       | 70
Sensor3    | 100      | 120
...
Sensor800  | 60       | 70

Table 2: IoTData with total columns ~800+ (Each sensor in Threshold table is the column in IoTData table)

Description:

IoTDateTime timestamp without time zone,
sensor1 numeric(3)
sensor2 numeric(8,5)
sensor3 numeric(5,2)
....
Sensor800 numeric(5,2)

For every 5 minutes record will be generated in this table.
This table is partitioned with date range (4 months data will be in a partition). Likewise there are 6 partitions in for this table so far.

*e.g:

        IoTDateTime         |   Sensor1
    2020-01-01 11:05:00     |      85
    2020-01-01 11:10:00     |      80
    2020-01-01 11:15:00     |      77
    ...
    2020-01-31 23:50:00     |      70
    2020-01-31 23:55:00     |      70

From Table 1 Threshold this Sensor1's MinLimit is 80 and MaxLimit is 115. Anything below MinLimit (80) or greater than MaxLimit (115) is considered as alert or sensor is malfunctioning.

I need to find the alert count of all 800+ sensors for each day of a month.

I wrote below function to perform this logic.

Need your help to rewrite this function in better way to reduce the line of code and optimistic logic.
Thanks in advance :)

CREATE OR REPLACE FUNCTION public.udf_SensorFailedForeachDay
(   pimono integer,
    pstartdate timestamp without time zone,
    penddate timestamp without time zone)

    RETURNS TABLE(date_of_month double precision, Sensor1 double precision, Sensor2 double precision,
    ...
    , Sensor800 double precision)
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
    ROWS 1000
AS $BODY$

declare Sensor1min  numeric(3);declare Sensor1max  numeric(3);

declare Sensor2min  numeric(8,5);declare Sensor2max  numeric(8,5);
....
declare Sensor800min  numeric(5,2);declare Sensor800max  numeric(5,2);
BEGIN

select minlimit,maxlimit Into Sensor1min,Sensor1max from threshold where channelname='Sensor1';
select minlimit,maxlimit Into Sensor2min,Sensor2max from threshold where channelname='Sensor2';
...

select minlimit,maxlimit Into Sensor800min,Sensor800max from threshold where channelname='Sensor800';
Return query
select extract(day from a.IoTDateTime) as date_of_month,
(cast(sum(case when a.Sensor1 between Sensor1min and Sensor1max then 1 end) as float)/cast(count(a.IoTDateTime) as float) )*100 as Sensor1,
(cast(sum(case when a.Sensor2 between Sensor2min and Sensor2max then 1 end) as float)/cast(count(a.IoTDateTime) as float))*100 as Sensor2,
...
(cast(sum(case when a.Sensor800 between Sensor800min and Sensor800max then 1 end) as float)/cast(count(a.IoTDateTime) as float))*100 as Sensor800
from IoTData a where a.IoTDateTime between Pstartdate and Penddate
group by extract(day from a.IoTDateTime) order by extract(day from a.IoTDateTime);

END;
$BODY$;

Body:
If you have a fixed number of sensors and hardly ever update rows, storing data in IoTData with a single row per timestamp, like you did, can make sense to get minimum storage size and good performance.

However, you are getting close to the absolute maximum number of columns allowed, which is an indicator that you may be moving in the wrong direction. See:

Database Columns In Select or create statements

If you later need to add / remove sensors, you have to adapt the table structure and everything that depends on it, including the function I am going to supply. A painful process. So, typically, it would be more reasonable to use a more generic model with one row per measurement (800 rows instead of just 1). That bloats storage, but is much more versatile.

That said, it can work like this:

CREATE TEMP TABLE threshold (
   sensorname varchar(10),
   minlimit numeric,
   maxlimit numeric
);

INSERT INTO threshold VALUES
  ('Sensor1', 80 , 115)
, ('Sensor2', 60 , 70)
, ('Sensor3', 100, 120)
-- more
;

CREATE TABLE iotdata (
   iotdatetime timestamp PRIMARY KEY
 , sensor1 numeric(3)
 , sensor2 numeric(8,5)
 , sensor3 numeric(5,2)
);

INSERT INTO iotdata VALUES
  ('2020-01-01 11:05:00', 85, 65, 110)
, ('2020-01-01 11:10:00', 86, 11, 109)  -- low
, ('2020-01-01 11:15:00', 77, 15, 666)  -- low + hi
;

TABLE threshold;

sensorname | minlimit | maxlimit
:--------- | -------: | -------:
Sensor1    |       80 |      115
Sensor2    |       60 |       70
Sensor3    |      100 |      120

-- pivot table threshold to match pivoted data
CREATE TABLE dim_threshold AS
SELECT *
FROM  crosstab(
 $$(
   SELECT 'min' AS dimension, sensorname, minlimit
   FROM   threshold
   ORDER  BY sensorname
   )
   UNION ALL
   (
   SELECT 'max' AS dimension, sensorname, maxlimit
   FROM   threshold
   ORDER  BY sensorname
   )$$
   , $$(SELECT unnest('{Sensor1,Sensor2,Sensor3}'::text[]))$$
   ) AS (dimension text, sensor1 numeric, sensor2 numeric, sensor3 numeric);

TABLE dim_threshold;

dimension | sensor1 | sensor2 | sensor3
:-------- | ------: | ------: | ------:
min       |      80 |      60 |     100
max       |     115 |      70 |     120

TABLE iotdata;

iotdatetime         | sensor1 |  sensor2 | sensor3
:------------------ | ------: | -------: | ------:
2020-01-01 11:05:00 |      85 | 65.00000 |  110.00
2020-01-01 11:10:00 |      86 | 11.00000 |  109.00
2020-01-01 11:15:00 |      77 | 15.00000 |  666.00

-- aux function to calculate percentage
CREATE FUNCTION f_calc_pct(bigint, bigint)
  RETURNS float LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
'SELECT ($1 * 100)::float / $2';

-- main function
CREATE OR REPLACE FUNCTION udf_sensor_fail_per_day(pstartdate timestamp
                                                 , penddate   timestamp)
  RETURNS TABLE(the_day date, dimenstion text, sensor1 float, sensor2 float, sensor3 float) -- more?
  LANGUAGE sql ROWS 100 AS
$func$
WITH cte AS (
   SELECT iotdatetime::date AS the_day
        , count(*) AS ct
        , count(*) FILTER (WHERE i.sensor1 < min.sensor1) AS s1_min
        , count(*) FILTER (WHERE i.sensor2 < min.sensor2) AS s2_min
        , count(*) FILTER (WHERE i.sensor3 < min.sensor3) AS s3_min
      -- more ...
        , count(*) FILTER (WHERE i.sensor1 > max.sensor1) AS s1_max
        , count(*) FILTER (WHERE i.sensor2 > max.sensor2) AS s2_max
        , count(*) FILTER (WHERE i.sensor3 > max.sensor3) AS s3_max
      -- more ...
   FROM   iotdata i
   CROSS  JOIN (SELECT * FROM dim_threshold WHERE dimension = 'min') min
   CROSS  JOIN (SELECT * FROM dim_threshold WHERE dimension = 'max') max
   WHERE  iotdatetime >= pstartdate
   AND    iotdatetime <  penddate
   GROUP  BY 1
   )
SELECT the_day, 'min' AS dimension
     , f_calc_pct(s1_min, ct) -- AS s1
     , f_calc_pct(s2_min, ct) -- AS s2
     , f_calc_pct(s3_min, ct) -- AS s3
    -- more ...
FROM   cte
UNION ALL
SELECT the_day, 'max' AS dimension
     , f_calc_pct(s1_max, ct) -- AS s1
     , f_calc_pct(s2_max, ct) -- AS s2
     , f_calc_pct(s3_max, ct) -- AS s3
    -- more ...
FROM   cte;
$func$;

-- call
SELECT * FROM udf_sensor_fail_per_day('2020-01-01 00:00', '2020-01-11 00:00');

the_day    | dimenstion | sensor1          | sensor2          | sensor3
:--------- | :--------- | :--------------- | :--------------- | :---------------
2020-01-01 | min        | 33.3333333333333 | 66.6666666666667 | 0
2020-01-01 | max        | 0                | 0                | 33.3333333333333

db<>fiddle here


问:
PHPStorm Xdebug always breaks on first line
I've setup Xdebug with the following configuration:

```<code>[xdebug]
zend_extension="/usr/local/Cellar/php55-xdebug/2.2.5/xdebug.so"
xdebug.remote_enable= "On"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_port = 9000
xdebug.remote_autostart = "Off"
xdebug.profiler_enable = "On"
xdebug.profiler_output_dir = "/tmp"
xdebug.idekey="PHPSTORM"
</code>```

and using "remote debugging" with the Xdebug toggler plugin for safari.

But in PHPStorm it always breaks on the first line even though I have no breakpoint set there. I have looked in the settings of and found a setting related to this. But I have unchecked those. But even after a restart it still breaks on the first line of the first file.

How can I disable this behaviour?

答:
In my case, I tried these steps:

step 1: uncheck these two options at xdebug section

step 2: copy & paste the directory of your project at /xampp/htdocs/{your-project}

Body:
I've setup Xdebug with the following configuration:

[xdebug]
zend_extension="/usr/local/Cellar/php55-xdebug/2.2.5/xdebug.so"
xdebug.remote_enable= "On"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_port = 9000
xdebug.remote_autostart = "Off"
xdebug.profiler_enable = "On"
xdebug.profiler_output_dir = "/tmp"
xdebug.idekey="PHPSTORM"

and using "remote debugging" with the Xdebug toggler plugin for safari.

But in PHPStorm it always breaks on the first line even though I have no breakpoint set there. I have looked in the settings of and found a setting related to this. But I have unchecked those. But even after a restart it still breaks on the first line of the first file.

How can I disable this behaviour?


问:
how to calculate height of Iframe?
I want to insert Iframe between the header component and footer component, how shall I calculate the height of that Iframe screen?
Note: (the content of header and footer may change)</p>

```<code>    <div dangerouslySetInnerHTML={{
         __html: `<iframe
          class="iFrame-screen"
          src="${dynamic-website-inserted-here}" />`
          }}
         />
    </div>

css:
.iFrame-screen {
    position: absolute;
    right: 0;
    top: -100px;
    z-index: 1;
    height: 110%;
    width: 100%;
    border: none;
    overflow-y: auto;
    overflow-x: hidden;
}
</code>```

答:
Not tested but you may give this a try. Note that this will fail if you have not a fixed height on the header and footer. The calc() calculates the view-height minus the header-height minus the footer-height.

```<code><body>
  <div id="page">
    <header id="pageHeader">
    </header>
    <main id="pageMain">
      <iframe src="..."></iframe>
    </main>
    <footer id="pageFooter">
    </footer>
  </div>
</body>
</code>```

with this css.

```<code>html, body {
  height: 100%;
  margin: 0;
}
header, footer, main {
  display: block;
}
#page {
  min-height: 100%;
}
#pageHeader {
  height: 70px; /* or something else */
}
#pageFooter {
  height: 90px; /* or something else */
}
#pageMain {
  position: relative;
  height: calc(100vh - 160px); /* 100vh minus (header + footer) */
}
#pageMain iframe {
  position: absolute;
  top: 0; left: 0; bottom: 0;
  width: 100%;
  border: 0;
}
</code>```

Title: how to calculate height of Iframe?

Body:
I want to insert Iframe between the header component and footer component, how shall I calculate the height of that Iframe screen?
Note: (the content of header and footer may change)

    <div dangerouslySetInnerHTML={{
         __html: ``
          }}
         />

css:
.iFrame-screen {
    position: absolute;
    right: 0;
    top: -100px;
    z-index: 1;
    height: 110%;
    width: 100%;
    border: none;
    overflow-y: auto;
    overflow-x: hidden;
}

Body:
Not tested but you may give this a try. Note that this will fail if you have not a fixed height on the header and footer. The calc() calculates the view-height minus the header-height minus the footer-height.

<body>
  <div id="page">
    <header id="pageHeader">
    </header>
    <main id="pageMain">
      <iframe src="..."></iframe>
    </main>
    <footer id="pageFooter">
    </footer>
  </div>
</body>

with this css.

html, body {
  height: 100%;
  margin: 0;
}
header, footer, main {
  display: block;
}
#page {
  min-height: 100%;
}
#pageHeader {
  height: 70px; /* or something else */
}
#pageFooter {
  height: 90px; /* or something else */
}
#pageMain {
  position: relative;
  height: calc(100vh - 160px); /* 100vh minus (header + footer) */
}
#pageMain iframe {
  position: absolute;
  top: 0; left: 0; bottom: 0;
  width: 100%;
  border: 0;
}


问:
How to update dynamically an object in Javascript?
I've got an object and I want to update it with new data. But, if one of the keys has a value of undefined, I want it to have the same value it was priorly defined.

```<code>let obj

obj = {
  name: 'Bill'
  job: 'dev'
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

Object.keys(obj).forEach(key => {
  obj[key] = newObj[key];
});

</code>```

I want obj to return:

```<code>{
  name: "Sam"
  job:'dev',
  age: 33,

}
</code>```

But it returns:

```<code>{
  age: 33,
  job: undefined,
  name: "Sam"
}
</code>```

Also, it would help to return in the same order as the original.

答:
You can simply merge the objects using spread syntax like:

let obj

obj = {
  name: 'Bill',
  job: 'dev',
  age: 22,
}

const newObj = {
  name: 'Sam',
  age: 33,
}

obj= {...obj, ...newObj}
console.log( obj )```

Body:
I've got an object and I want to update it with new data. But, if one of the keys has a value of undefined, I want it to have the same value it was priorly defined.

let obj

obj = {
  name: 'Bill'
  job: 'dev'
  age: 22
}

const newObj = {
  name: 'Sam',
  age: 33
}

Object.keys(obj).forEach(key => {
  obj[key] = newObj[key];
});

I want obj to return:

{
  name: "Sam"
  job:'dev',
  age: 33,

}

But it returns:

{
  age: 33,
  job: undefined,
  name: "Sam"
}

Also, it would help to return in the same order as the original.


问:
DB and java time date comparison and conversion
I am getting a variable newValue in java as

```<code>public void reTrigger() {
    Date date1 = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH.mm.ss");

    squery: "select newValue from SAVE_TXN WHERE ROWID = 1"
(newValue is of type nvarchar2)

    String vidtime = sdf.format(parser.getValueOf("newValue")); //parser is another method which parses the squery
String currentDate = sdf.format(date1);
}
</code>```

Now newvalue contains date and time like: '2020/05/17 18.30.44' in DB, which I am fetching into vidtime.

Now I want to subtract this vidtime with currentDate  in java and check whether it is greater than or equals to 120 hours or not. How to proceed ?

答:
Maybe something like this :</p>

```<code>import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        final LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final LocalDateTime dateToCompare = LocalDateTime.parse("2020-05-28 02:05:45",formatter);
        final long hours = Duration.between(now, dateToCompare).toHours();
        System.out.print(hours);
    }
}
</code>```

Body:
I am getting a variable newValue in java as

public void reTrigger() {
    Date date1 = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH.mm.ss");

    squery: "select newValue from SAVE_TXN WHERE ROWID = 1"
(newValue is of type nvarchar2)

    String vidtime = sdf.format(parser.getValueOf("newValue")); //parser is another method which parses the squery
String currentDate = sdf.format(date1);
}

Now newvalue contains date and time like: '2020/05/17 18.30.44' in DB, which I am fetching into vidtime.

Now I want to subtract this vidtime with currentDate  in java and check whether it is greater than or equals to 120 hours or not. How to proceed ?

Body:
Maybe something like this :

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        final LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final LocalDateTime dateToCompare = LocalDateTime.parse("2020-05-28 02:05:45",formatter);
        final long hours = Duration.between(now, dateToCompare).toHours();
        System.out.print(hours);
    }
}


问:
How to delete print
Here's the problem. In the following code, I wish to produce a 'moving cursor' effect. Here's the code:

```<code>sys.stdout.write('\033[2K\033[1G')
time.sleep(2)
print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.viru|s.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print('virus_prevention.fix.vir|us.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vi|rus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.v|irus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.|virus.attempt.enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix|virus.attempt.enter')
</code>```

And this is the output:

```<code>[2K[1Gvirus_prevention.fix.virus.|attempt_enter
[2K[1Gvirus_prevention.fix.virus|.attempt_enter
[2K[1Gvirus_prevention.fix.viru|s.attempt.enter
[2K[1Gvirus_prevention.fix.vir|us.attempt.enter
[2K[1Gvirus_prevention.fix.vi|rus.attempt.enter
[2K[1Gvirus_prevention.fix.v|irus.attempt.enter
[2K[1Gvirus_prevention.fix.|virus.attempt.enter
</code>```

And the sys.stdout.write doesn't really help. It just ends up with added text on the front of the current text. So if there are solutions anyone is willing to share (Python 3) please do. (I did have a solution which used repeatedly clearing the screen via os.system('clear'), which I don't really want to use.)

答:
This is similar to what you wish to achieve, you will need to adjust it to work with where you want the 'cursor' to show

```<code>import time

displayText = "Python"
character = '|'

for i in range(len(displayText)+1):
    print(displayText[:i] + character + displayText[i:], end='\r')
    time.sleep(.2)
input()
</code>```

This will give the desired effect when executed via console/command prompt; but not through Python's IDLE Shell.

Title: How to delete print

Body:
Here's the problem. In the following code, I wish to produce a 'moving cursor' effect. Here's the code:

sys.stdout.write('\033[2K\033[1G')
time.sleep(2)
print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.viru|s.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print('virus_prevention.fix.vir|us.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vi|rus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.v|irus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.|virus.attempt.enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix|virus.attempt.enter')

And this is the output:

[2K[1Gvirus_prevention.fix.virus.|attempt_enter
[2K[1Gvirus_prevention.fix.virus|.attempt_enter
[2K[1Gvirus_prevention.fix.viru|s.attempt.enter
[2K[1Gvirus_prevention.fix.vir|us.attempt.enter
[2K[1Gvirus_prevention.fix.vi|rus.attempt.enter
[2K[1Gvirus_prevention.fix.v|irus.attempt.enter
[2K[1Gvirus_prevention.fix.|virus.attempt.enter

And the sys.stdout.write doesn't really help. It just ends up with added text on the front of the current text. So if there are solutions anyone is willing to share (Python 3) please do. (I did have a solution which used repeatedly clearing the screen via os.system('clear'), which I don't really want to use.)

Body:
This is similar to what you wish to achieve, you will need to adjust it to work with where you want the 'cursor' to show

import time

displayText = "Python"
character = '|'

for i in range(len(displayText)+1):
    print(displayText[:i] + character + displayText[i:], end='\r')
    time.sleep(.2)
input()

This will give the desired effect when executed via console/command prompt; but not through Python's IDLE Shell.


问:
Verify the date exits between dates and pick the specific row based on type
TableA

```<code>id        dtchk
1001    3/31/2018
1002    9/30/2018
1004    3/31/2019
1003    5/25/2018
1005    9/30/2019
1006    3/31/2020
</code>```

TableB

```<code>id     type  startdate  endate      name
1001    1    4/5/2018   12/31/2025  akshi
1002    100  4/27/2015  12/31/2023  polard
1004    100  4/1/2017   12/31/2019  kathi
1003    1    1/25/2018  5/25/2019   smoth
1005    1    3/21/2017  12/31/2020  sumi
1005    100  3/26/2019  12/31/2021  chechi
1006    1    2/28/2019  3/31/2021   paul
1006    100  2/28/2017  3/31/2019   rand
</code>```

First we need to verify dtchk is between startdate and endate based on id
if date eists between those dates then we need check the types
if types 1 & 100 both fits then pick row with  type 100
else pick as is if the date fits in those dates

output

```<code>id      name
1002    polard
1004    kathi
1003    smoth
1005    chechi
1006    paul
</code>```

答:
I think you want apply:

```<code>select a.*, b.*
from a cross apply
     (select top (1) with ties b.*
      from b
      where b.id = a.id and
            a.dtchk between b.startdate and b.endate and
            b.type in (1, 100)
      order by b.type desc
     ) b;
</code>```

Body:
TableA

id        dtchk
1001    3/31/2018
1002    9/30/2018
1004    3/31/2019
1003    5/25/2018
1005    9/30/2019
1006    3/31/2020

TableB

id     type  startdate  endate      name
1001    1    4/5/2018   12/31/2025  akshi
1002    100  4/27/2015  12/31/2023  polard
1004    100  4/1/2017   12/31/2019  kathi
1003    1    1/25/2018  5/25/2019   smoth
1005    1    3/21/2017  12/31/2020  sumi
1005    100  3/26/2019  12/31/2021  chechi
1006    1    2/28/2019  3/31/2021   paul
1006    100  2/28/2017  3/31/2019   rand

First we need to verify dtchk is between startdate and endate based on id
if date eists between those dates then we need check the types
if types 1 & 100 both fits then pick row with  type 100
else pick as is if the date fits in those dates

output

id      name
1002    polard
1004    kathi
1003    smoth
1005    chechi
1006    paul

Body:
I think you want apply:

select a.*, b.*
from a cross apply
     (select top (1) with ties b.*
      from b
      where b.id = a.id and
            a.dtchk between b.startdate and b.endate and
            b.type in (1, 100)
      order by b.type desc
     ) b;


问:
Java version of matlab's linspace
Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.

For example to get all integers from 1 to 30, in matlab I would type:

```<code>1:30
</code>```

or

```<code>linspace(1,30)
</code>```

答:
Do you want to do this?

```<code>for( int number = 1; number <= 30; ++number )
</code>```

If you need them spaced by a fixed amount, i.e. 3 you can write it this way:

```<code>for( int number = 1; number <= 30; number += 3 )
</code>```

The left part of the for loop initializes the variable, the middle part is the condition that gets evaluated before each iteration and the right part gets executed after each iteration.

Title: Java version of matlab's linspace

Body:
Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.

For example to get all integers from 1 to 30, in matlab I would type:

1:30

or

linspace(1,30)

Body:
Do you want to do this?

for( int number = 1; number <= 30; ++number )

If you need them spaced by a fixed amount, i.e. 3 you can write it this way:

for( int number = 1; number <= 30; number += 3 )

The left part of the for loop initializes the variable, the middle part is the condition that gets evaluated before each iteration and the right part gets executed after each iteration.


答:
you can do this:</p>

```<code>Object.keys(obj).forEach(key => {
 obj[key] = newObj[key] ? newObj[key] : obj[key];
});
</code>```

Title: How to update dynamically an object in Javascript?

Body:
you can do this:

Object.keys(obj).forEach(key => {
 obj[key] = newObj[key] ? newObj[key] : obj[key];
});


问:
Passing variable args from macro to a function that expects va_list
```<code>#define exampleA(buf, args...) \
        exampleB(buf, ##args); \
    }

#endif
</code>```

works where the exampleB function declaration is exampleB(char* buf, ...).
But I need to change the declaration as exampleB(char* buf, va_list args). How can change the marco accordingly?

答:
You cannot. In order to create a va_list, you need to have a variadic function. There is no portable facility to create a va_list object from a list of arguments.

It is quite common to write variadic functions in pairs: the outer function uses the facilities in <stdarg.h> to construct a va_list, and it passes that list directly to the function which does the work. You see that in the standarid I/O library, for example: printf/vprintf, fprintf/vfprintf, snprintf/vsnprintf, scanf/vscanf, etc.

And that's what you should do for your problem: write exampleB as the va_list form of exampleA.

Here, for example, is the entire implementation of the fprintf function extrated from the FreeBSD library, which can serve as a model of this style:

```<code>int
fprintf(FILE * __restrict fp, const char * __restrict fmt, ...)
{
    int ret;
    va_list ap;

    va_start(ap, fmt);
    ret = vfprintf_l(fp, __get_locale(), fmt, ap);
    va_end(ap);
    return (ret);
}
</code>```

As you can see from that snippet, vfprintf_l (which takes a locale argument) is actually the implementation; all the other *printf functions are simple wrappers. (printf, for examples, calls vfprintf_l passing stdin and the locale argument.) That avoids having to traverse multiple wrappers in a single call, although modern optimising compilers are usually able to do that elimination automatically.

(See lib/libc/stdio/fprintf.c for the full file in the FreeBSD source repository mirror on Github.)

Speaking of portability, #define exampleA(buf, args...) is a GCC extension which is not portable to most C implementations (although Clang implements it as well). You should use __VA_ARGS__ as per standard C:

```<code>#define exampleA(buf, ...) \
        exampleB(buf, ## __VA_ARGS__)
</code>```

Even better, if you can, replace the other GCC extension (, ##) with the newer standard __VA_OPT__:

```<code>#define exampleA(buf, ...) \
        exampleB(buf __VA_OPT__(,) __VA_ARGS__)
</code>```

Body:
#define exampleA(buf, args...) \
        exampleB(buf, ##args); \
    }

#endif

works where the exampleB function declaration is exampleB(char* buf, ...).
But I need to change the declaration as exampleB(char* buf, va_list args). How can change the marco accordingly?

Body:
You cannot. In order to create a va_list, you need to have a variadic function. There is no portable facility to create a va_list object from a list of arguments.

It is quite common to write variadic functions in pairs: the outer function uses the facilities in <stdarg.h> to construct a va_list, and it passes that list directly to the function which does the work. You see that in the standarid I/O library, for example: printf/vprintf, fprintf/vfprintf, snprintf/vsnprintf, scanf/vscanf, etc.

And that's what you should do for your problem: write exampleB as the va_list form of exampleA.

Here, for example, is the entire implementation of the fprintf function extrated from the FreeBSD library, which can serve as a model of this style:

int
fprintf(FILE * __restrict fp, const char * __restrict fmt, ...)
{
    int ret;
    va_list ap;

    va_start(ap, fmt);
    ret = vfprintf_l(fp, __get_locale(), fmt, ap);
    va_end(ap);
    return (ret);
}

As you can see from that snippet, vfprintf_l (which takes a locale argument) is actually the implementation; all the other *printf functions are simple wrappers. (printf, for examples, calls vfprintf_l passing stdin and the locale argument.) That avoids having to traverse multiple wrappers in a single call, although modern optimising compilers are usually able to do that elimination automatically.

(See lib/libc/stdio/fprintf.c for the full file in the FreeBSD source repository mirror on Github.)

Speaking of portability, #define exampleA(buf, args...) is a GCC extension which is not portable to most C implementations (although Clang implements it as well). You should use __VA_ARGS__ as per standard C:

#define exampleA(buf, ...) \
        exampleB(buf, ## __VA_ARGS__)

Even better, if you can, replace the other GCC extension (, ##) with the newer standard __VA_OPT__:

#define exampleA(buf, ...) \
        exampleB(buf __VA_OPT__(,) __VA_ARGS__)


问:
Pytorch select tensor
I want to know if Pytorch have a slice function (same as tf). In particular, I want to select the orange color rows.

答:
This is not currently supported by PyTorch. Slicing that tensor would produce another tensor were each subtensor will have different dimensions.

One way to solve this is by iterating by each subtensor and indexing:

```<code>sliced_tensors = []
tensor = [tensor with data]
slices_idx = [[first slices], [second slices] ... [n slices]]
for subtensor, slice_idx in map(tensor, slices_idx):
    sliced_tensors.append(subtensor[slices_idx, :])
</code>```

Title: Pytorch select tensor

Body:
This is not currently supported by PyTorch. Slicing that tensor would produce another tensor were each subtensor will have different dimensions.

One way to solve this is by iterating by each subtensor and indexing:

sliced_tensors = []
tensor = [tensor with data]
slices_idx = [[first slices], [second slices] ... [n slices]]
for subtensor, slice_idx in map(tensor, slices_idx):
    sliced_tensors.append(subtensor[slices_idx, :])


问:
boost::asio::streambuf -- linker error
I'm having trouble getting a boost program to compile.  The example I'm trying to compile is here:  http://rosettacode.org/wiki/Web_scraping#C.2B.2B

This is what happens when I try to compile:

```<code>  % g++ -Wall test.c -lboost_regex  -lboost_system -lboost_thread
    /tmp/ccJSxOji.o: In function `boost::exception_detail::error_info_injector<std::length_error>::error_info_injector(boost::exception_detail::error_info_injector<std::length_error> const&)':
    test.c:(.text._ZN5boost16exception_detail19error_info_injectorISt12length_errorEC2ERKS3_[_ZN5boost16exception_detail19error_info_injectorISt12length_errorEC5ERKS3_]+0x53): undefined reference to `std::length_error::~length_error()'
    /tmp/ccJSxOji.o: In function `boost::exception_detail::error_info_injector<std::length_error>::~error_info_injector()':
    test.c:(.text._ZN5boost16exception_detail19error_info_injectorISt12length_errorED2Ev[_ZN5boost16exception_detail19error_info_injectorISt12length_errorED5Ev]+0x2e): undefined reference to `std::length_error::~length_error()'
    collect2: ld returned 1 exit status
</code>```

I think I've narrowed the problem down to this line:

```<code>boost::asio::streambuf response ;
</code>```

I'm using gcc 4.6.0, linux of course:

```<code>% gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-pc-linux-gnu/4.6.0/lto-wrapper
Target: i686-pc-linux-gnu
Configured with: /build/src/gcc-4.6-20110429/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --enable-gnu-unique-object --enable-linker-build-id --with-ppl --enable-cloog-backend=isl --enable-lto --enable-gold --enable-ld=default --enable-plugin --with-plugin-ld=ld.gold --disable-multilib --disable-libstdcxx-pch --enable-checking=release
Thread model: posix
gcc version 4.6.0 20110429 (prerelease) (GCC)
</code>```

Possibly related thread:

Code using boost::asio::streambuf causes segfault

答:
I hate to answer my own question, but as it turns out, I was bitten by this:  /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I did some more digging:

```<code> % ldd /usr/lib/libboost_regex.so
/usr/lib/libboost_regex.so: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/libboost_regex.so)
        linux-gate.so.1 =>  (0xb77b3000)
        libicuuc.so.46 => /usr/lib/libicuuc.so.46 (0xb7553000)
        libicui18n.so.46 => /usr/lib/libicui18n.so.46 (0xb7389000)
        libicudata.so.46 => /usr/lib/libicudata.so.46 (0xb650a000)
        librt.so.1 => /lib/librt.so.1 (0xb6501000)
        libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb6412000)
        libm.so.6 => /lib/libm.so.6 (0xb63e8000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb63cc000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb63b1000)
        libc.so.6 => /lib/libc.so.6 (0xb624b000)
        libdl.so.2 => /lib/libdl.so.2 (0xb6246000)
        /lib/ld-linux.so.2 (0xb77b4000)

% ldd /usr/lib/libboost_date_time.so
/usr/lib/libboost_date_time.so: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/libboost_date_time.so)
        linux-gate.so.1 =>  (0xb78cf000)
        librt.so.1 => /lib/librt.so.1 (0xb788f000)
        libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb77a1000)
        libm.so.6 => /lib/libm.so.6 (0xb7777000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb775b000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb773f000)
        libc.so.6 => /lib/libc.so.6 (0xb75d9000)
        /lib/ld-linux.so.2 (0xb78d0000)
</code>```

In sum, my gcc-libs were out of date.  To fix it, I did:

```<code># pacman -Q -o /usr/lib/libstdc++.so.6
/usr/lib/libstdc++.so.6 is owned by gcc-libs 4.6.0-5

# pacman -S gcc-libs
</code>```

Thanks to everyone who commented, you got me thinking in the right direction.

Title: boost::asio::streambuf -- linker error

Body:
I'm having trouble getting a boost program to compile.  The example I'm trying to compile is here:  http://rosettacode.org/wiki/Web_scraping#C.2B.2B

This is what happens when I try to compile:

  % g++ -Wall test.c -lboost_regex  -lboost_system -lboost_thread
    /tmp/ccJSxOji.o: In function `boost::exception_detail::error_info_injector<std::length_error>::error_info_injector(boost::exception_detail::error_info_injector<std::length_error> const&)':
    test.c:(.text._ZN5boost16exception_detail19error_info_injectorISt12length_errorEC2ERKS3_[_ZN5boost16exception_detail19error_info_injectorISt12length_errorEC5ERKS3_]+0x53): undefined reference to `std::length_error::~length_error()'
    /tmp/ccJSxOji.o: In function `boost::exception_detail::error_info_injector<std::length_error>::~error_info_injector()':
    test.c:(.text._ZN5boost16exception_detail19error_info_injectorISt12length_errorED2Ev[_ZN5boost16exception_detail19error_info_injectorISt12length_errorED5Ev]+0x2e): undefined reference to `std::length_error::~length_error()'
    collect2: ld returned 1 exit status

I think I've narrowed the problem down to this line:

boost::asio::streambuf response ;

I'm using gcc 4.6.0, linux of course:

% gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-pc-linux-gnu/4.6.0/lto-wrapper
Target: i686-pc-linux-gnu
Configured with: /build/src/gcc-4.6-20110429/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --enable-gnu-unique-object --enable-linker-build-id --with-ppl --enable-cloog-backend=isl --enable-lto --enable-gold --enable-ld=default --enable-plugin --with-plugin-ld=ld.gold --disable-multilib --disable-libstdcxx-pch --enable-checking=release
Thread model: posix
gcc version 4.6.0 20110429 (prerelease) (GCC)

Possibly related thread:

Code using boost::asio::streambuf causes segfault

Body:
I hate to answer my own question, but as it turns out, I was bitten by this:  /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I did some more digging:

 % ldd /usr/lib/libboost_regex.so
/usr/lib/libboost_regex.so: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/libboost_regex.so)
        linux-gate.so.1 =>  (0xb77b3000)
        libicuuc.so.46 => /usr/lib/libicuuc.so.46 (0xb7553000)
        libicui18n.so.46 => /usr/lib/libicui18n.so.46 (0xb7389000)
        libicudata.so.46 => /usr/lib/libicudata.so.46 (0xb650a000)
        librt.so.1 => /lib/librt.so.1 (0xb6501000)
        libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb6412000)
        libm.so.6 => /lib/libm.so.6 (0xb63e8000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb63cc000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb63b1000)
        libc.so.6 => /lib/libc.so.6 (0xb624b000)
        libdl.so.2 => /lib/libdl.so.2 (0xb6246000)
        /lib/ld-linux.so.2 (0xb77b4000)

% ldd /usr/lib/libboost_date_time.so
/usr/lib/libboost_date_time.so: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/libboost_date_time.so)
        linux-gate.so.1 =>  (0xb78cf000)
        librt.so.1 => /lib/librt.so.1 (0xb788f000)
        libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb77a1000)
        libm.so.6 => /lib/libm.so.6 (0xb7777000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb775b000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb773f000)
        libc.so.6 => /lib/libc.so.6 (0xb75d9000)
        /lib/ld-linux.so.2 (0xb78d0000)

In sum, my gcc-libs were out of date.  To fix it, I did:

# pacman -Q -o /usr/lib/libstdc++.so.6
/usr/lib/libstdc++.so.6 is owned by gcc-libs 4.6.0-5

# pacman -S gcc-libs

Thanks to everyone who commented, you got me thinking in the right direction.


问:
How to decompress LZ4 JSON in Spark 2
I have downloaded a xxxx.json.lz4 file from https://censys.io/ however when I try to read the file using the following line I get no data out/count of 0.

```<code>metadata_lz4 = spark.read.json("s3n://file.json.lz4")
</code>```

it returns no results although decompressing manually works fine and can be imported into Spark.

I have also tried

```<code>val metadata_lz4_2 = spark.sparkContext.newAPIHadoopFile("s3n://file.json.lz4", classOf[TextInputFormat], classOf[LongWritable], classOf[Text])
</code>```

Which also returns no results.

I have multiple of these files which are 100GBs each so really keen on not having to decompress each one manually.

Any ideas?

答:
I achieved to parse lz4 compression in Pyspark in this way:

```<code>import lz4.frame
import pyspark.sql.functions as F
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").getOrCreate()
sc = spark.sparkContext

list_paths = ['/my/file.json.lz4', '/my/beautiful/file.json.lz4']

rdd = sc.binaryFiles(','.join(list_paths))
df = rdd.map(lambda x: lz4.frame.decompress(x[1])).map(lambda x: str(x)).map(lambda x:  (x, )).toDF()
</code>```

this is usually enough for non complex objects. But if the compressed JSON you are
 parsing has nested structures, then it is necessary to do extra cleaning on the parsed file before calling the function F.from_json():

```<code>schema = spark.read.json("/my/uncompressed_file.json").schema

df = df.select(F.regexp_replace(F.regexp_replace(F.regexp_replace(F.regexp_replace(F.regexp_replace("_1", "None", "null"), "False", "false"), "True", "true"), "b'", ""), "'", "").alias("json_notation"))
result_df = df.select(F.from_json("json_notation", schema)
</code>```

where /my/uncompressed_file.json is the /my/file.json.lz4 that you have previously decompressed (unless you want to provide the schema manually if not too complex, it will work anyway)

Title: How to decompress LZ4 JSON in Spark 2

Body:
I have downloaded a xxxx.json.lz4 file from https://censys.io/ however when I try to read the file using the following line I get no data out/count of 0.

metadata_lz4 = spark.read.json("s3n://file.json.lz4")

it returns no results although decompressing manually works fine and can be imported into Spark.

I have also tried

val metadata_lz4_2 = spark.sparkContext.newAPIHadoopFile("s3n://file.json.lz4", classOf[TextInputFormat], classOf[LongWritable], classOf[Text])

Which also returns no results.

I have multiple of these files which are 100GBs each so really keen on not having to decompress each one manually.

Any ideas?

Body:
I achieved to parse lz4 compression in Pyspark in this way:

import lz4.frame
import pyspark.sql.functions as F
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").getOrCreate()
sc = spark.sparkContext

list_paths = ['/my/file.json.lz4', '/my/beautiful/file.json.lz4']

rdd = sc.binaryFiles(','.join(list_paths))
df = rdd.map(lambda x: lz4.frame.decompress(x[1])).map(lambda x: str(x)).map(lambda x:  (x, )).toDF()

this is usually enough for non complex objects. But if the compressed JSON you are
 parsing has nested structures, then it is necessary to do extra cleaning on the parsed file before calling the function F.from_json():

schema = spark.read.json("/my/uncompressed_file.json").schema

df = df.select(F.regexp_replace(F.regexp_replace(F.regexp_replace(F.regexp_replace(F.regexp_replace("_1", "None", "null"), "False", "false"), "True", "true"), "b'", ""), "'", "").alias("json_notation"))
result_df = df.select(F.from_json("json_notation", schema)

where /my/uncompressed_file.json is the /my/file.json.lz4 that you have previously decompressed (unless you want to provide the schema manually if not too complex, it will work anyway)


问:
Wordpress has detected that your site is running on a insecure version of php
I have just finished setting up WordPress installation and my WordPress theme on my Cpanel, but after everything was set up and I logged in to wp-admin I receive a warning that "Wordpress has detected that your site is running on an insecure version of PHP" but it did not give a possible fix to the problem, I am pretty sure am using the latest version of PHP but could anything else cause that?</p>

答:
I would recommend checking the PHP version first. Starting with WordPress 5.2 there is a tool named "Health Check" (in the administration under Tools) where you can check the PHP version (click the Info tab and expand the Server section).

If the PHP version is lower than 7.1 I would definitely recommend upgrading (in the hosting control panel or by contacting your hosting provider directly). Using an outdated PHP version can be a security risk for your websites (see this link for supported PHP versions).

Just ensure to test your website thoroughly after upgrading PHP as some plugins or the theme might not support the new version and trough some errors, or even prevent you from logging in to your website.


问:
How to take SQL Server database backup using Jenkins daily?
I've tried to take backup using Windows batch command. It's working, but I need to take automatic backups with different name for 7 days as day1.bak, day2.bak, ...

```<code>SQLCMD -S xx.xx.xxx.xx -U test -P xxxx
       -Q "BACKUP  DATABASE test TO DISK='C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\test4.bak'"
</code>```

Is there is a Jenkins plugin to do this automatically?

答:
```<code>set mydate=%date:~10%%date:~4,2%%date:~7,2%
set mytime=%time:~0,2%%time:~3,2%%time:~6,2%

forfiles /P 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\'  /S /M *.bak /D -7 /C "cmd /c del @PATH"  // Delete all file less than 7 days

sqlcmd -S .\sqlexpress -Q "BACKUP DATABASE [YourDataBaseName] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\%mydate%_%mytime%.bak' WITH NOFORMAT, NOINIT,  NAME = N'YourDataBaseName-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10"
</code>```

Note: filename equals date-time now by using both variable mydate & mytime

Body:
I've tried to take backup using Windows batch command. It's working, but I need to take automatic backups with different name for 7 days as day1.bak, day2.bak, ...

SQLCMD -S xx.xx.xxx.xx -U test -P xxxx
       -Q "BACKUP  DATABASE test TO DISK='C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\test4.bak'"

Is there is a Jenkins plugin to do this automatically?

Body:
set mydate=%date:~10%%date:~4,2%%date:~7,2%
set mytime=%time:~0,2%%time:~3,2%%time:~6,2%

forfiles /P 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\'  /S /M *.bak /D -7 /C "cmd /c del @PATH"  // Delete all file less than 7 days

sqlcmd -S .\sqlexpress -Q "BACKUP DATABASE [YourDataBaseName] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\%mydate%_%mytime%.bak' WITH NOFORMAT, NOINIT,  NAME = N'YourDataBaseName-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10"

Note: filename equals date-time now by using both variable mydate & mytime


问:
Pip install from private Git repo, with Personal access token in Git URL
I am trying to install a package from a private repository on Git.

I am using Personal Access Token in my Git URL in order to bypass the manual authentication step. (You can read about Personal Access Tokens here)

If I add this git URL in requirements file and then use the requirements file in pip to install build it works.

```<code>requirements.txt
<package name> @ git+https://<Personal Access Token>@<git server address>/<username>/<repository name>.git@<branch name>#egg=<package name>
</code>```

But, if I use the same URL directly it asks for password, how do I avoid this password prompt (as mentioned below):

```<code>pip install git+https://<Personal Access Token>@<git server address>/<username>/<repository name>.git@<branch name>#egg=<package name>
</code>```

This issue is not observed on all machines that i tested on. It worked on Win 10 x64 and Win 10 x86. But it didn't work on Ubuntu x64. I made sure all the 3 systems has same Python version (3.8.0) and same Pip version (19.3.1).

答:
I just had the same issue. In the end, I could install the package as follows.

from the command line:

pip install mypackagename --no-deps --index-url https://gitlab+deploy-token-mytokenname:tokenpassword@gitlab.mycompany.com/api/v4/projects/123456789/packages/pypi/simple

by specifying it in the requirements.txt file:

(Note that the flask and flask-cors package requirements in the example below are just an example, because it may seem really weird to a reader that the other lines in the example are really content that can be written in a requirements.txt.)

```<code>flask==1.1.1
flask-cors==3.0.8
--index-url https://pypi.org/simple --extra-index-url https://gitlab+deploy-token-mytokenname:tokenpassword@gitlab.mycompany.com/api/v4/projects/123456789/packages/pypi/simple
mypackagename
</code>```

Then of course run pip install -r requirements.txt.

Note that both fragments above show how to provide your password, as you asked.

Body:
I am trying to install a package from a private repository on Git.

I am using Personal Access Token in my Git URL in order to bypass the manual authentication step. (You can read about Personal Access Tokens here)

If I add this git URL in requirements file and then use the requirements file in pip to install build it works.

requirements.txt
<package name> @ git+https://<Personal Access Token>@<git server address>/<username>/<repository name>.git@<branch name>#egg=<package name>

But, if I use the same URL directly it asks for password, how do I avoid this password prompt (as mentioned below):

pip install git+https://<Personal Access Token>@<git server address>/<username>/<repository name>.git@<branch name>#egg=<package name>

This issue is not observed on all machines that i tested on. It worked on Win 10 x64 and Win 10 x86. But it didn't work on Ubuntu x64. I made sure all the 3 systems has same Python version (3.8.0) and same Pip version (19.3.1).

Body:
I just had the same issue. In the end, I could install the package as follows.

from the command line:

pip install mypackagename --no-deps --index-url https://gitlab+deploy-token-mytokenname:tokenpassword@gitlab.mycompany.com/api/v4/projects/123456789/packages/pypi/simple

by specifying it in the requirements.txt file:

(Note that the flask and flask-cors package requirements in the example below are just an example, because it may seem really weird to a reader that the other lines in the example are really content that can be written in a requirements.txt.)

flask==1.1.1
flask-cors==3.0.8
--index-url https://pypi.org/simple --extra-index-url https://gitlab+deploy-token-mytokenname:tokenpassword@gitlab.mycompany.com/api/v4/projects/123456789/packages/pypi/simple
mypackagename

Then of course run pip install -r requirements.txt.

Note that both fragments above show how to provide your password, as you asked.


问:
Display images from sqlite3 database to a column in QTableWidget with Python
After looking at various examples here and elswhere, I have not been able to show images in 'mydb.db' which is my SQlite3 database to my table QTableWidget in python. Here is my code

```<code>def fetch_all_learner_data(self):
    connection= sqlite3.connect("mydb.db")
    query = "SELECT NAME,ADM,CLASS,STREAM,CATEGORY,GENDER,COUNTY,PARENT,PARENT_CONTACT,PHOTO   FROM learner_data"
    result = connection.execute(query)
    self.classes_table.setRowCount(0)
    for row_number,row_data in enumerate(result):
        self.classes_table.insertRow(row_number)
        for column_number,data in enumerate(row_data):
            self.classes_table.setItem(row_number,column_number,QTableWidgetItem(str(data)))
    connection.commit()
    connection.close()
</code>```

This is what  end up getting on the image column in the qtable and which have also really slowed my system.

How can I solve this?

答:
You have to build a QIcon based on the data using a QPixmap:</p>

```<code>def fetch_all_learner_data(self):
    connection = sqlite3.connect("mydb.db")
    query = "SELECT NAME,ADM,CLASS,STREAM,CATEGORY,GENDER,COUNTY,PARENT,PARENT_CONTACT,PHOTO   FROM learner_data"
    result = connection.execute(query)
    self.classes_table.setRowCount(0)
    for row_number, row_data in enumerate(result):
        self.classes_table.insertRow(row_number)
        for column_number, data in enumerate(row_data):
            it = QTableWidgetItem()
            if column_number == 9:
                pixmap = QPixmap()
                pixmap.loadFromData(data)
                it.setIcon(QIcon(pixmap))
            else:
                it.setText(str(data))
            self.classes_table.setItem(row_number, column_number, it)
    connection.commit()
    connection.close()
</code>```

Body:
After looking at various examples here and elswhere, I have not been able to show images in 'mydb.db' which is my SQlite3 database to my table QTableWidget in python. Here is my code

def fetch_all_learner_data(self):
    connection= sqlite3.connect("mydb.db")
    query = "SELECT NAME,ADM,CLASS,STREAM,CATEGORY,GENDER,COUNTY,PARENT,PARENT_CONTACT,PHOTO   FROM learner_data"
    result = connection.execute(query)
    self.classes_table.setRowCount(0)
    for row_number,row_data in enumerate(result):
        self.classes_table.insertRow(row_number)
        for column_number,data in enumerate(row_data):
            self.classes_table.setItem(row_number,column_number,QTableWidgetItem(str(data)))
    connection.commit()
    connection.close()

This is what  end up getting on the image column in the qtable and which have also really slowed my system.

How can I solve this?

Body:
You have to build a QIcon based on the data using a QPixmap:

def fetch_all_learner_data(self):
    connection = sqlite3.connect("mydb.db")
    query = "SELECT NAME,ADM,CLASS,STREAM,CATEGORY,GENDER,COUNTY,PARENT,PARENT_CONTACT,PHOTO   FROM learner_data"
    result = connection.execute(query)
    self.classes_table.setRowCount(0)
    for row_number, row_data in enumerate(result):
        self.classes_table.insertRow(row_number)
        for column_number, data in enumerate(row_data):
            it = QTableWidgetItem()
            if column_number == 9:
                pixmap = QPixmap()
                pixmap.loadFromData(data)
                it.setIcon(QIcon(pixmap))
            else:
                it.setText(str(data))
            self.classes_table.setItem(row_number, column_number, it)
    connection.commit()
    connection.close()