问:
Python os.rename with datetime keeps saving multiple file same name
I have a timelapse running with gphoto2 but it seems to be renaming all files to the same date and time

```<code>shot_date = datetime.now().strftime("%Y-%m-%d")
shot_time = datetime.now().strftime("%Y-%m-%d %H%M%S")
</code>```

```<code>def renameFiles(ID):
    for filename in os.listdir("."):
        if len(filename) < 14:
            if filename.endswith(".JPG"):
                os.rename (filename, (shot_time + ID + ".JPG"))
                print ("Renamed the jpeg boy")
            elif filename.endswith(".CR2"):
                os.rename (filename, (shot_time + ID + ".CR2"))
                print ("renamed cr2!")
</code>```

Any ideas why it's taking the files and renaming them all to the same date & time as the script started? How can I call it to get the latest datetime?

答:
The problem is that you created the shot_time before and you use it for all files. Try to generate the shot_time inside the loop.

For example:

```<code>def renameFiles(ID):
    for filename in os.listdir("."):
        if len(filename) < 14:
            shot_time = datetime.now().strftime("%Y-%m-%d %H%M%S")
            if filename.endswith(".JPG"):
                os.rename (filename, (shot_time + ID + ".JPG"))
                print ("Renamed the jpeg boy")
            elif filename.endswith(".CR2"):
                os.rename (filename, (shot_time + ID + ".CR2"))
                print ("renamed cr2!")
</code>```

Body:
I have a timelapse running with gphoto2 but it seems to be renaming all files to the same date and time

shot_date = datetime.now().strftime("%Y-%m-%d")
shot_time = datetime.now().strftime("%Y-%m-%d %H%M%S")

def renameFiles(ID):
    for filename in os.listdir("."):
        if len(filename) < 14:
            if filename.endswith(".JPG"):
                os.rename (filename, (shot_time + ID + ".JPG"))
                print ("Renamed the jpeg boy")
            elif filename.endswith(".CR2"):
                os.rename (filename, (shot_time + ID + ".CR2"))
                print ("renamed cr2!")

Any ideas why it's taking the files and renaming them all to the same date & time as the script started? How can I call it to get the latest datetime?

Body:
The problem is that you created the shot_time before and you use it for all files. Try to generate the shot_time inside the loop.

For example:

def renameFiles(ID):
    for filename in os.listdir("."):
        if len(filename) < 14:
            shot_time = datetime.now().strftime("%Y-%m-%d %H%M%S")
            if filename.endswith(".JPG"):
                os.rename (filename, (shot_time + ID + ".JPG"))
                print ("Renamed the jpeg boy")
            elif filename.endswith(".CR2"):
                os.rename (filename, (shot_time + ID + ".CR2"))
                print ("renamed cr2!")


来源: stackexchange

问:
Center a text inside an spinning element
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slide-loader">
    <div class="loader-text">Loading...</div>
  </div></code>```

答:
try this code:

  .slide-loader {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .spinner {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    border: 6px solid #f3f3f3;
    border-radius: 50%;
    border-top: 6px solid #3498db;
    width: 100px;
    height: 100px;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;

  }

  @-webkit-keyframes spin {
    0% {
      -webkit-transform: rotate(0deg);
    }

    100% {
      -webkit-transform: rotate(360deg);
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slide-loader">
    <div class="spinner"></div>
    <div class="loader-text">Loading...</div>
  </div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

Loading...

Body:
try this code:

  .slide-loader {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .spinner {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    border: 6px solid #f3f3f3;
    border-radius: 50%;
    border-top: 6px solid #3498db;
    width: 100px;
    height: 100px;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;

  }

  @-webkit-keyframes spin {
    0% {
      -webkit-transform: rotate(0deg);
    }

    100% {
      -webkit-transform: rotate(360deg);
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

<div class="slide-loader">
    <div class="spinner"></div>
    <div class="loader-text">Loading...</div>
  </div>


问:
npm ERR! code ENOLOCAL
after making a software to my laptop I installed all the programs includes node js
my OS windows

```<code>$ node -v
v8.11.1
</code>```

and the npm

```<code>$ npm -v
v5.6.0
</code>```

when I tried to install npm globally it's gave me this error :

```<code>$ npm install -g
npm ERR! code ENOLOCAL
npm ERR! Could not install from "" as it does not contain a package.json
file.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Aroma\AppData\Roaming\npm-cache\_logs\2018-04-
07T11_10_29_184Z-debug.log
</code>```

or even when I tried to install it locally to a repository it's gave me:

```<code>$ npm install
npm WARN saveError ENOENT: no such file or directory, open
'C:\Users\Aroma\Desktop\app\package.json'
npm notice created a lockfile as package-lock.json. You should commit this
file.
npm WARN enoent ENOENT: no such file or directory, open
'C:\Users\Aroma\Desktop\app\package.json'
npm WARN app No description
npm WARN app No repository field.
npm WARN app No README data
npm WARN app No license field.

up to date in 0.11s
</code>```

any help would be appreciated

答:
I had same problem. I solved in this way.

Step 1: Open the command prompt as an Administrator and run npm install -g create-react-app to solve the npx issue.

Step 2:  run  npx create-react-app your-app-name

ContentLicense: CC BY-SA 3.0

Title: npm ERR! code ENOLOCAL

Body:
after making a software to my laptop I installed all the programs includes node js
my OS windows

$ node -v
v8.11.1

and the npm

$ npm -v
v5.6.0

when I tried to install npm globally it's gave me this error :

$ npm install -g
npm ERR! code ENOLOCAL
npm ERR! Could not install from "" as it does not contain a package.json
file.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Aroma\AppData\Roaming\npm-cache\_logs\2018-04-
07T11_10_29_184Z-debug.log

or even when I tried to install it locally to a repository it's gave me:

$ npm install
npm WARN saveError ENOENT: no such file or directory, open
'C:\Users\Aroma\Desktop\app\package.json'
npm notice created a lockfile as package-lock.json. You should commit this
file.
npm WARN enoent ENOENT: no such file or directory, open
'C:\Users\Aroma\Desktop\app\package.json'
npm WARN app No description
npm WARN app No repository field.
npm WARN app No README data
npm WARN app No license field.

up to date in 0.11s

any help would be appreciated


问:
Summation of series 1 + (1+2+1) + (1+2+1+3+1+2+1)
The function is : F(n-1) n F(n-1)

Its a type of palindrome function called Zimmer Series.

The values would be : 1, 121, 1213121, ...

I want to figure the summation of the individual digits.

1 + (1+2+1) + (1+2+1+3+1+2+1) + ...

Any help is welcome.

答:
EDIT: Mark Dickinson is right, I misinterpreted the question, this solution is incorrect.

I think after the second term the sequence is of the form difference in Arithmetic Progression.

Let me show you how

```<code>Second Term = 1+2+1
Third Term  = 1+2+1+3 + 1+2+1
Difference  = 1+2+1+3 = 7

Third Term  = 1+2+1+3+1+2+1
Fourth Term = 1+2+1+3+  1+4+1+3 +1+2+1
Difference  = 1+4+1+3 = 9

Fourth Term = 1+2+1+3+1+4+1+3+1+2+1
Fifth Term  = 1+2+1+3+1+4+  1+5+1+4  +1+3+1+2+1
Difference  = 1+5+1+4 = 11
</code>```

So as you can see the difference is in the arithmetic progression and you find the sum of the terms using the formula for the sum of numbers whose different are in Arithmetic Progression

Body:
EDIT: Mark Dickinson is right, I misinterpreted the question, this solution is incorrect.

I think after the second term the sequence is of the form difference in Arithmetic Progression.

Let me show you how

Second Term = 1+2+1
Third Term  = 1+2+1+3 + 1+2+1
Difference  = 1+2+1+3 = 7

Third Term  = 1+2+1+3+1+2+1
Fourth Term = 1+2+1+3+  1+4+1+3 +1+2+1
Difference  = 1+4+1+3 = 9

Fourth Term = 1+2+1+3+1+4+1+3+1+2+1
Fifth Term  = 1+2+1+3+1+4+  1+5+1+4  +1+3+1+2+1
Difference  = 1+5+1+4 = 11

So as you can see the difference is in the arithmetic progression and you find the sum of the terms using the formula for the sum of numbers whose different are in Arithmetic Progression


问:
Sorting a list of RGB triplets into a spectrum
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum.

I've converted them to HSV, which people seem to recommend.

```<code>from PIL import Image, ImageDraw
import colorsys

def make_rainbow_rgb(colors, width, height):
    """colors is an array of RGB tuples, with values between 0 and 255"""

    img = Image.new("RGBA", (width, height))
    canvas = ImageDraw.Draw(img)

    def hsl(x):
        to_float = lambda x : x / 255.0
        (r, g, b) = map(to_float, x)
        h, s, l = colorsys.rgb_to_hsv(r,g,b)
        h = h if 0 < h else 1 # 0 -> 1
        return h, s, l

    rainbow = sorted(colors, key=hsl)

    dx = width / float(len(colors))
    x = 0
    y = height / 2.0
    for rgb in rainbow:
        canvas.line((x, y, x + dx, y), width=height, fill=rgb)
        x += dx
    img.show()
</code>```

However, the result doesn't look very much like a nice rainbow-y spectrum. I suspect I need to either convert to a different color space or handle the HSL triplet differently.

Does anyone know what I need to do to make this data look roughly like a rainbow?

Update:

I was playing around with Hilbert curves and revisited this problem. Sorting the RGB values (same colors in both images) by their position along a Hilbert curve yields an interesting (if still not entirely satisfying) result:

答:
This seems incorrect.

```<code>canvas.line((x, y, x + dx, y), width=height, fill=rgb)
</code>```

Try this.

```<code>canvas.rectangle([(x, y), (x+dx, y+height)], fill=rgb)
</code>```

Body:
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum.

I've converted them to HSV, which people seem to recommend.

from PIL import Image, ImageDraw
import colorsys

def make_rainbow_rgb(colors, width, height):
    """colors is an array of RGB tuples, with values between 0 and 255"""

    img = Image.new("RGBA", (width, height))
    canvas = ImageDraw.Draw(img)

    def hsl(x):
        to_float = lambda x : x / 255.0
        (r, g, b) = map(to_float, x)
        h, s, l = colorsys.rgb_to_hsv(r,g,b)
        h = h if 0 < h else 1 # 0 -> 1
        return h, s, l

    rainbow = sorted(colors, key=hsl)

    dx = width / float(len(colors))
    x = 0
    y = height / 2.0
    for rgb in rainbow:
        canvas.line((x, y, x + dx, y), width=height, fill=rgb)
        x += dx
    img.show()

However, the result doesn't look very much like a nice rainbow-y spectrum. I suspect I need to either convert to a different color space or handle the HSL triplet differently.

Does anyone know what I need to do to make this data look roughly like a rainbow?

Update:

I was playing around with Hilbert curves and revisited this problem. Sorting the RGB values (same colors in both images) by their position along a Hilbert curve yields an interesting (if still not entirely satisfying) result:

Body:
This seems incorrect.

canvas.line((x, y, x + dx, y), width=height, fill=rgb)

Try this.

canvas.rectangle([(x, y), (x+dx, y+height)], fill=rgb)


问:
why dose debug break point not hitting on my lamda function (java8 use idea)?
Version:IDEA 2019.3
        JDK8

Tried methods :

I'm trying to wrap it in curly braces

Globally, only one breakpoint is hit,None of them took effect

The program goes directly to the saving method,

```<code>    public <V0 extends Rmap> Output<V0> prior(Trans<V0, Rmap> conv) {
        return saving(ds0 -> {
            enqueue((DSdream) ds0.map((Function<Rmap, Rmap>) row -> {
                Rmap r = conv.apply((V0) row);
                return Rec.of(r, tds.get(r.table().toString()));
            }, f));
        });
    }
</code>```

How do I stop at the lambda break point?

Thanks

答:
I tried to use an anonymous inner class that would normally stop at the breakpoint,

```<code>    @Override
    public <V0 extends Rmap> Output<V0> prior(Trans<V0, Rmap> conv) {
        Output<Rmap> saving = saving(new Consumer<DSdream>() {
            @Override
            public void accept(DSdream dSdream) {
                enqueue((DSdream)
                        dSdream.map((Function<Rmap, Rmap>) row -> {
                            Rmap r = conv.apply((V0) row);
                            return Rec.of(r, tds.get(r.table().toString()));
                        }, f));
            }
        });
        return (Output<V0>) saving;
    }
</code>```

Presumably, after decompiling, lambda is compiled into inner class,
So the break point cannot be located .
It should be the disadvantage of lambda

Body:
Version:IDEA 2019.3
        JDK8

Tried methods :

I'm trying to wrap it in curly braces

Globally, only one breakpoint is hit,None of them took effect

The program goes directly to the saving method,

    public <V0 extends Rmap> Output<V0> prior(Trans<V0, Rmap> conv) {
        return saving(ds0 -> {
            enqueue((DSdream) ds0.map((Function<Rmap, Rmap>) row -> {
                Rmap r = conv.apply((V0) row);
                return Rec.of(r, tds.get(r.table().toString()));
            }, f));
        });
    }

How do I stop at the lambda break point?

Thanks

Body:
I tried to use an anonymous inner class that would normally stop at the breakpoint,

    @Override
    public <V0 extends Rmap> Output<V0> prior(Trans<V0, Rmap> conv) {
        Output<Rmap> saving = saving(new Consumer<DSdream>() {
            @Override
            public void accept(DSdream dSdream) {
                enqueue((DSdream)
                        dSdream.map((Function<Rmap, Rmap>) row -> {
                            Rmap r = conv.apply((V0) row);
                            return Rec.of(r, tds.get(r.table().toString()));
                        }, f));
            }
        });
        return (Output<V0>) saving;
    }

Presumably, after decompiling, lambda is compiled into inner class,
So the break point cannot be located .
It should be the disadvantage of lambda


问:
How to clear the interval in React
I am building a stopwatch by using useState hooks in react.js but while implementing pause functionality I have noticed that I am not able to clear the interval. I am new and I have tried many things but still it doesn't work. If anyone can help me fix the code or suggest me other way.

Here is my code:

```<code>function App() {
  const [stopwatch, setStopwatch] = useState({
    hour: 0,
    min: 0,
    sec: 0,
    secElapsed: 0,
    minElapsed: 0,
  });

  const [buttonState, setButtonState] = useState({
    start: true,
    stop: false,
    pause: false,
    resume: false,
  });

  var interval = null;

  function onStart() {
    // i want to clear this interval when the onPause function is called
    var clrInt = setInterval(() => {
      setStopwatch(prevValue => {
        prevValue.secElapsed++;
        return {
          hour: Math.floor(prevValue.secElapsed / 3600),
          minElapsed: Math.floor((prevValue.secElapsed + 1) / 60),
          min: prevValue.minElapsed % 60,
          sec: prevValue.secElapsed % 60,
          secElapsed: prevValue.secElapsed,
        };
      });
    }, 1000);

    setButtonState(prevValue => {
      return {
        ...prevValue,
        start: false,
        pause: true,
        stop: true,
      };
    });
    interval = clrInt;
  }

  function onPause() {
    setButtonState(prevValue => {
      return {
        ...prevValue,
        pause: false,
        resume: true,
      };
    });

    // i want to clear the interval in onStart function here
    clearInterval(interval);
  }

  return (
    <div>
      <h1>
        {stopwatch.hour < 10 ? '0' + stopwatch.hour : stopwatch.hour}:
        {stopwatch.min < 10 ? '0' + stopwatch.min : stopwatch.min}:
        {stopwatch.sec < 10 ? '0' + stopwatch.sec : stopwatch.sec}
      </h1>
      {buttonState.start ? <button onClick={onStart}>Start</button> : null}
      {buttonState.pause ? <button onClick={onPause}>Pause</button> : null}
      {buttonState.stop ? <button>Stop</button> : null}
      {buttonState.resume ? <button>Resume</button> : null}
    </div>
  );
}

</code>```

答:
I don't think the interval fits into the component's state. Instead, I would use the useRef hook to keep it through the component's lifetime.

Anyways, it's good that you start thinking in hooks :)

A cleaner way is to implement something like useInterval:

```<code>const [isRunning, setIsRunning] = useState(true)

useInterval(() => {
    // Your custom logic here
}, isRunning ? 1000 : null)

const onPause = () => {
    // ...
    setIsRunning(false)
}
</code>```

Here's a demo with an actual implementation of the hook.

Title: How to clear the interval in React

Body:
I am building a stopwatch by using useState hooks in react.js but while implementing pause functionality I have noticed that I am not able to clear the interval. I am new and I have tried many things but still it doesn't work. If anyone can help me fix the code or suggest me other way.

Here is my code:

function App() {
  const [stopwatch, setStopwatch] = useState({
    hour: 0,
    min: 0,
    sec: 0,
    secElapsed: 0,
    minElapsed: 0,
  });

  const [buttonState, setButtonState] = useState({
    start: true,
    stop: false,
    pause: false,
    resume: false,
  });

  var interval = null;

  function onStart() {
    // i want to clear this interval when the onPause function is called
    var clrInt = setInterval(() => {
      setStopwatch(prevValue => {
        prevValue.secElapsed++;
        return {
          hour: Math.floor(prevValue.secElapsed / 3600),
          minElapsed: Math.floor((prevValue.secElapsed + 1) / 60),
          min: prevValue.minElapsed % 60,
          sec: prevValue.secElapsed % 60,
          secElapsed: prevValue.secElapsed,
        };
      });
    }, 1000);

    setButtonState(prevValue => {
      return {
        ...prevValue,
        start: false,
        pause: true,
        stop: true,
      };
    });
    interval = clrInt;
  }

  function onPause() {
    setButtonState(prevValue => {
      return {
        ...prevValue,
        pause: false,
        resume: true,
      };
    });

    // i want to clear the interval in onStart function here
    clearInterval(interval);
  }

  return (

        {stopwatch.hour < 10 ? '0' + stopwatch.hour : stopwatch.hour}:
        {stopwatch.min < 10 ? '0' + stopwatch.min : stopwatch.min}:
        {stopwatch.sec < 10 ? '0' + stopwatch.sec : stopwatch.sec}

      {buttonState.start ? <button onClick={onStart}>Start</button> : null}
      {buttonState.pause ? <button onClick={onPause}>Pause</button> : null}
      {buttonState.stop ? <button>Stop</button> : null}
      {buttonState.resume ? <button>Resume</button> : null}

  );
}

Body:
I don't think the interval fits into the component's state. Instead, I would use the useRef hook to keep it through the component's lifetime.

Anyways, it's good that you start thinking in hooks :)

A cleaner way is to implement something like useInterval:

const [isRunning, setIsRunning] = useState(true)

useInterval(() => {
    // Your custom logic here
}, isRunning ? 1000 : null)

const onPause = () => {
    // ...
    setIsRunning(false)
}

Here's a demo with an actual implementation of the hook.


问:
Transparent navigation bar iOS 13
Can't create transparent NavigationBar iOS 13.

I have custom UINavigationBar, where I configure UINavigationBarAppearance in

```<code>override init(frame: CGRect) {
    super.init(frame: frame)
    self.configure()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.configure()
}
</code>```

Configuration code:

```<code>let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.shadowColor = .clear
appearance.backgroundColor = .clear
</code>```

And set it to:

```<code>self.compactAppearance = appearance
self.standardAppearance = appearance
self.scrollEdgeAppearance = appearance
</code>```

And by the result I have this:

Expected result: NavigationBar should be transparent

答:
Modify the appearance code to this :-</p>

```<code>let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.shadowColor = .clear
appearance.backgroundColor = .clear
appearance.backgroundImage = nil
appearance.shadowImage = nil
</code>```

Title: Transparent navigation bar iOS 13

Body:
Can't create transparent NavigationBar iOS 13.

I have custom UINavigationBar, where I configure UINavigationBarAppearance in

override init(frame: CGRect) {
    super.init(frame: frame)
    self.configure()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.configure()
}

Configuration code:

let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.shadowColor = .clear
appearance.backgroundColor = .clear

And set it to:

self.compactAppearance = appearance
self.standardAppearance = appearance
self.scrollEdgeAppearance = appearance

And by the result I have this:

Expected result: NavigationBar should be transparent

Body:
Modify the appearance code to this :-

let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.shadowColor = .clear
appearance.backgroundColor = .clear
appearance.backgroundImage = nil
appearance.shadowImage = nil


问:
Duplicate element of tensor while perserving gradient values
So I have a vector that I computed somehow with size k

```<code>x = torch.FloatTensor([0.5, 0.3, 0.1, 0.7])
x = x + 2
</code>```

I want to take its first element x[0] and create a vector of size k-1 filled with the value x[0] so that the gradients that come along with this element are present in the new vector.

I tried using torch.full and filling it up with x[0] but that does not preserve gradients.

Using pytorch 1.4

答:
You could also use .repeat like this (IMO cleaner and more verbose):

```<code># type deduction is automatic
x = torch.tensor([0.5, 0.3, 0.1, 0.7])
x = x + 2
y = x[0].repeat(50)
</code>```

Gradient will be preserved (gradient history will be copied).

Body:
So I have a vector that I computed somehow with size k

x = torch.FloatTensor([0.5, 0.3, 0.1, 0.7])
x = x + 2

I want to take its first element x[0] and create a vector of size k-1 filled with the value x[0] so that the gradients that come along with this element are present in the new vector.

I tried using torch.full and filling it up with x[0] but that does not preserve gradients.

Using pytorch 1.4

Body:
You could also use .repeat like this (IMO cleaner and more verbose):

# type deduction is automatic
x = torch.tensor([0.5, 0.3, 0.1, 0.7])
x = x + 2
y = x[0].repeat(50)

Gradient will be preserved (gradient history will be copied).


问:
NuxtJS/VueJS: How to know if page was rendered on client-side only?
Currently I create a html5 video player component for an universal nuxtjs/vuejs app.
There is an autoplay attribute for the video tag to start videos after navigate to them.
Usually browsers don't do that directly after page load, it's prohibited.
I need a variable in my component to know if autoplay will be possible to style elements based on this information.
In other words: The variable should be true if the current page was only rendered on client-side, but false if it was rendered on server-side first.

It's not possible to work with "window.history.length" because the autoplay will also not be possible after refresh, although this would not have an effect on the history length.

Also it's not possible to set a variable in the "created" method since it will be called on server- and client-side too.

答:
One possible solution would be to get the length of the Vue router entries. This seems currently not to be possible without manually tracking. So I ended with this code in my layout component:

```<code>watch: {
  $route () {
    Vue.prototype.$navigated = true
  }
}
</code>```

The value of $navigated is undefined or true and so I know in the layout children components if video autoplay is possible or not.

Body:
One possible solution would be to get the length of the Vue router entries. This seems currently not to be possible without manually tracking. So I ended with this code in my layout component:

watch: {
  $route () {
    Vue.prototype.$navigated = true
  }
}

The value of $navigated is undefined or true and so I know in the layout children components if video autoplay is possible or not.


问:
Using Dapper with Oracle
We use Oracle as our database provider and have looked into replacing some of our data access layer (hard to maintain, harder to merge XSD's) with a saner repository based pattern using Dapper at the bottom layer. However, we have hit a number of issues when using it with oracle.

Named Parameters: these seem to be ignored, whenever they are used in a query Oracle seems to interpret them in any order it fancies. The SqlMapper returns correctly named parameters, they just aren't interpreted correctly in Oracle

The "@" naming convention for variables is incompatible with oracle named parameters. It expects to see ":" in front of any parameters

Has anybody previously encountered this and have any workarounds?

答:
Resolution of the named parameter issue turned out to be because Oracle commands require the BindByName property set to true. To resolve this required a tweak to the SqlMapper itself. This is a bit nasty as the tweak isnt portable (it relies on a type check for a specific Oracle Command) but it works for our needs for the moment. The change involves updating the SetupCommand method, after creating the command form the connection object we type check and set the flag like so (~ln 635):

```<code>var cmd = cnn.CreateCommand();
if (cmd is OracleCommand)
{
    ((OracleCommand)cmd).BindByName = true; // Oracle Command Only
}
</code>```

Finally to address the issue of the "@" to ":" problem in parameter names involved altering the CreateParamInfoGenerator method. I added a static string - DefaultParameterCharacter setting its value to ":" then modified ln 530 from:

```<code>il.Emit(OpCodes.Ldstr, "@" + prop.Name); // stack is now [parameters] [c
</code>```

to

```<code>il.Emit(OpCodes.Ldstr, DefaultParameterCharacter + prop.Name); // stack is now [parameters] [command] [name] (Changed @ to : for oracle)
</code>```

and ln 546 from:

```<code>il.Emit(OpCodes.Ldstr, "@" + prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name] (Changed @ to : for oracle)
</code>```

to:

```<code>il.Emit(OpCodes.Ldstr, DefaultParameterCharacter + prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name] (Changed @ to : for oracle)
</code>```

This made dapper work flawlessly with Oracle commands

Title: Using Dapper with Oracle

Body:
Resolution of the named parameter issue turned out to be because Oracle commands require the BindByName property set to true. To resolve this required a tweak to the SqlMapper itself. This is a bit nasty as the tweak isnt portable (it relies on a type check for a specific Oracle Command) but it works for our needs for the moment. The change involves updating the SetupCommand method, after creating the command form the connection object we type check and set the flag like so (~ln 635):

var cmd = cnn.CreateCommand();
if (cmd is OracleCommand)
{
    ((OracleCommand)cmd).BindByName = true; // Oracle Command Only
}

Finally to address the issue of the "@" to ":" problem in parameter names involved altering the CreateParamInfoGenerator method. I added a static string - DefaultParameterCharacter setting its value to ":" then modified ln 530 from:

il.Emit(OpCodes.Ldstr, "@" + prop.Name); // stack is now [parameters] [c

to

il.Emit(OpCodes.Ldstr, DefaultParameterCharacter + prop.Name); // stack is now [parameters] [command] [name] (Changed @ to : for oracle)

and ln 546 from:

il.Emit(OpCodes.Ldstr, "@" + prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name] (Changed @ to : for oracle)

to:

il.Emit(OpCodes.Ldstr, DefaultParameterCharacter + prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name] (Changed @ to : for oracle)

This made dapper work flawlessly with Oracle commands


问:
ReactJS unit test says TypeError: Cannot read property 'apply' of undefined
My project works fine, but when I type the command yarn test to run the test, then it shows this error:

I think this error happened because of REDUX_DEVTOOLS in store, here is my store setup with REDUX_DEVTOOLS_EXTENSION:

```<code>const persistConfig = {
    key: 'root',
    storage,
};

const persistedReducer = persistReducer(persistConfig, UserReducer);

const reducers = combineReducers({
    persistedStore: persistedReducer,
    aoiStore: AoiReducer,
    aoi: AoiEventReducer,
    opticalDataStore: OpticalDataReducer,
    loaderStore: LoaderReducer,
});

export const store = createStore(
    reducers,
    compose(
        applyMiddleware(thunk),
        (window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
            (window as any).__REDUX_DEVTOOLS_EXTENSION__(),
    ),
);

export const persistor = persistStore(store);
</code>```

For your info, if I remove this line from the store then it works fine:

```<code>(window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
    (window as any).__REDUX_DEVTOOLS_EXTENSION__()
</code>```

Can anyone tell me where I made the mistake?

答: You should never import the actual store file in your test. redux-mock-store is a wonderful package which gives you the capability to mock the store according to you test file requirement.

Body:
My project works fine, but when I type the command yarn test to run the test, then it shows this error:

I think this error happened because of REDUX_DEVTOOLS in store, here is my store setup with REDUX_DEVTOOLS_EXTENSION:

const persistConfig = {
    key: 'root',
    storage,
};

const persistedReducer = persistReducer(persistConfig, UserReducer);

const reducers = combineReducers({
    persistedStore: persistedReducer,
    aoiStore: AoiReducer,
    aoi: AoiEventReducer,
    opticalDataStore: OpticalDataReducer,
    loaderStore: LoaderReducer,
});

export const store = createStore(
    reducers,
    compose(
        applyMiddleware(thunk),
        (window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
            (window as any).__REDUX_DEVTOOLS_EXTENSION__(),
    ),
);

export const persistor = persistStore(store);

For your info, if I remove this line from the store then it works fine:

(window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
    (window as any).__REDUX_DEVTOOLS_EXTENSION__()

Can anyone tell me where I made the mistake?


问:
How do you delete or change the display on the last print on perl?
What I'm trying to do it print out a string and then after a few background checks, change the previously said string?

So here is what it will initially look like:

```<code>#
Loading design modules....please wait.
</code>```

Then after a few background checks it will remove "Loading design modules....please wait." then change it to something like this without clearing the whole CLI Screen:

```<code>#
Design module loaded!
</code>```

This is my code so far:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

use feature 'say';
use feature 'switch';

use IO::Socket;
use Scalar::Util qw(looks_like_number);
use Term::ANSIScreen qw/:cursor :screen/;

$| = 1;
print "Loading design modules....please wait";
sleep(5);
say "Design module loaded!";
</code>```

答:
Use savepos() to save the position of the cursor and loadpos() to go back to that saved position.

Here's a first attempt:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Term::ANSIScreen ':cursor';

$| = 1;

savepos;

print "Loading design modules....please wait";
sleep 5;
loadpos;
say "Design module loaded!";
</code>```

But as the second string is shorter than the first, we'll end up seeing bits of both string:

```<code>Design module loaded!s....please wait
</code>```

The easiest solution is probably to just print a string of spaces to overwrite the first string before printing the second.

```<code>#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Term::ANSIScreen ':cursor';

$| = 1;

savepos;

print "Loading design modules....please wait";
sleep 5;
loadpos;
print ' ' x 37;
loadpos;
say "Design module loaded!";
</code>```

Body:
What I'm trying to do it print out a string and then after a few background checks, change the previously said string?

So here is what it will initially look like:

#
Loading design modules....please wait.

Then after a few background checks it will remove "Loading design modules....please wait." then change it to something like this without clearing the whole CLI Screen:

#
Design module loaded!

This is my code so far:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

use feature 'say';
use feature 'switch';

use IO::Socket;
use Scalar::Util qw(looks_like_number);
use Term::ANSIScreen qw/:cursor :screen/;

$| = 1;
print "Loading design modules....please wait";
sleep(5);
say "Design module loaded!";

Body:
Use savepos() to save the position of the cursor and loadpos() to go back to that saved position.

Here's a first attempt:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Term::ANSIScreen ':cursor';

$| = 1;

savepos;

print "Loading design modules....please wait";
sleep 5;
loadpos;
say "Design module loaded!";

But as the second string is shorter than the first, we'll end up seeing bits of both string:

Design module loaded!s....please wait

The easiest solution is probably to just print a string of spaces to overwrite the first string before printing the second.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Term::ANSIScreen ':cursor';

$| = 1;

savepos;

print "Loading design modules....please wait";
sleep 5;
loadpos;
print ' ' x 37;
loadpos;
say "Design module loaded!";


问:
read function problem (not read all fields) in cakephp
i want to edit row. view file contains dropwons with Ajax.
i used $this->data = $this->CourseBuilding->read(null, $id); but it cant read all fields of that id.

Can U help me.

答:
```<code>$this->CourseBuilding->read('*',$id);
</code>```

By using * as the first argument of the read method will return all the fields of that model.

ContentLicense: CC BY-SA 2.5

Body:
$this->CourseBuilding->read('*',$id);

By using * as the first argument of the read method will return all the fields of that model.


问:
Weird machine code bytes order when using Rust inline assembly
I'm currently trying to write a program in Rust (Windows 32-bits) which will basically extract some specific part machine code from it's own .text section.

Basically, if I define and call a function test1 as:

```<code>unsafe fn test1(){
    asm!("
        pushad
        .byte 0x90, 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90

        inc eax
        mov eax, ebx
        xor eax, eax

        .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90
        popad
    "
    :
    :
    :
    :"intel");
}
</code>```

It will output:

```<code>inc eax
mov eax, ebx
xor eax, eax
</code>```

The program uses .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90 and .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90 to recognize the code to retrieve (those opcode represent some nop and or reg, reg which basically does nothing).

Everything was working fine until I tried to do the following thing:

```<code>unsafe fn test2(){
    asm!("
        .byte 0x90, 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90
    "
    :
    :
    :
    :"intel");
    while a < 10{
        a += 1;
    }
    asm!("
        inc eax
        dec eax
        .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90
    "
    :
    :
    :
    :"intel");
}
</code>```

It only detects the inc/dec instructions, which means that I can't see anything which could be the assembly equivalent of the Rust code between the two usage of inline assembly (while loop that increments a).

I don't really know how the Rust compiler process inline assembly, but I logically thought that it would respect the order in which the code has to be executed...

I hope my question was clear enough.

答:
In optimized output there are basically no guarantees other than the assembly executed in between will have the same observable effects. This means no guarantees about ordering or that the assembly will look at all like the input. (The compiler is known to convert certain loops calculating series into their equivalent sum functions).

If you want to locate the assembly associated with a piece of code in optimized assembly, put that code in its own function, and mark that function and all functions it calls as no_inline. And make sure that all code you want to see has an observable effect, or use benchmark::black_box to pretend it does.

Body:
I'm currently trying to write a program in Rust (Windows 32-bits) which will basically extract some specific part machine code from it's own .text section.

Basically, if I define and call a function test1 as:

unsafe fn test1(){
    asm!("
        pushad
        .byte 0x90, 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90

        inc eax
        mov eax, ebx
        xor eax, eax

        .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90
        popad
    "
    :
    :
    :
    :"intel");
}

It will output:

inc eax
mov eax, ebx
xor eax, eax

The program uses .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90 and .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90 to recognize the code to retrieve (those opcode represent some nop and or reg, reg which basically does nothing).

Everything was working fine until I tried to do the following thing:

unsafe fn test2(){
    asm!("
        .byte 0x90, 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90
    "
    :
    :
    :
    :"intel");
    while a < 10{
        a += 1;
    }
    asm!("
        inc eax
        dec eax
        .byte 0x90, 0x09, 0xC0, 0x09, 0xDB, 0x09, 0xC9, 0x90, 0x90
    "
    :
    :
    :
    :"intel");
}

It only detects the inc/dec instructions, which means that I can't see anything which could be the assembly equivalent of the Rust code between the two usage of inline assembly (while loop that increments a).

I don't really know how the Rust compiler process inline assembly, but I logically thought that it would respect the order in which the code has to be executed...

I hope my question was clear enough.


问:
Matplotlib axes confused
I'm trying to figure out where I went wrong with this plot, I'm trying to get the axes to go from 0-1 but this one is going from 0.1-0-1, and I'm not too sure where I'm going wrong.
the csv file is in the following format:

dishwasher,60,1,1,0,1,0,0.1

```<code>import matplotlib.pyplot as plt
import numpy as np
import csv

x = np.array([1,2,3,4,5,6])
with open('Test 5.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=rows[0][2:]
y2=rows[1][2:]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.legend()
plt.show()
</code>```

the plot comes out as followed:

The only solution I could think of was to invert the axes or to outline the scale for the y-axis but neither worked

答:
Trying using pandas to import CSV files.

You don't have to explicitly pass x = [1,2,3,...] by default x-axis will take those labels.

sample code:

```<code>import pandas as pd
df = pd.read_csv("Test 5.csv")
print(df.columns)
</code>```

Let's assume your data frame df has two columns (washing_machine & dishwasher). To plot these columns using matplotlib.

```<code>plt.plot(df.washing_machine.values, label='Washing Machine')
plt.plot(df.dishwasher.values, label='Dishwasher')
plt.legend()
plt.show()
</code>```

Hope, this helps. Enjoy coding.

Title: Matplotlib axes confused

Body:
I'm trying to figure out where I went wrong with this plot, I'm trying to get the axes to go from 0-1 but this one is going from 0.1-0-1, and I'm not too sure where I'm going wrong.
the csv file is in the following format:

dishwasher,60,1,1,0,1,0,0.1

import matplotlib.pyplot as plt
import numpy as np
import csv

x = np.array([1,2,3,4,5,6])
with open('Test 5.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=rows[0][2:]
y2=rows[1][2:]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.legend()
plt.show()

the plot comes out as followed:

The only solution I could think of was to invert the axes or to outline the scale for the y-axis but neither worked

Body:
Trying using pandas to import CSV files.

You don't have to explicitly pass x = [1,2,3,...] by default x-axis will take those labels.

sample code:

import pandas as pd
df = pd.read_csv("Test 5.csv")
print(df.columns)

Let's assume your data frame df has two columns (washing_machine & dishwasher). To plot these columns using matplotlib.

plt.plot(df.washing_machine.values, label='Washing Machine')
plt.plot(df.dishwasher.values, label='Dishwasher')
plt.legend()
plt.show()

Hope, this helps. Enjoy coding.


问:
Three (almost?) identical functions return different results
I am doing simple challenges on LeetCode trying to make the fastest solution possible. The challenge I did is:

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]

The following code shows 3 different outputs in console:

```<code>const smallerNumbersThanCurrent = (nums) => {
  console.log(nums.map((num) => [...nums].sort((a, b) => a - b).indexOf(num)));
  console.log(nums.map((num) => nums.sort((a, b) => a - b).indexOf(num)));
  return nums.map((num) => [...nums].sort((a, b) => a - b).indexOf(num));
};

console.log(smallerNumbersThanCurrent([2, 5, 1, 3]));
</code>```

The output is:

```<code>[ 1, 3, 0, 2 ]
[ 1, 1, 2, 3 ]
[ 0, 1, 2, 3 ]
</code>```

If there is no console.log, the output of the function is always correct, but now only the first output is correct. Why does it behave this way?

答: The sort() method sorts the elements of an array in place and returns the sorted array.

Body:
I am doing simple challenges on LeetCode trying to make the fastest solution possible. The challenge I did is:

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]

The following code shows 3 different outputs in console:

const smallerNumbersThanCurrent = (nums) => {
  console.log(nums.map((num) => [...nums].sort((a, b) => a - b).indexOf(num)));
  console.log(nums.map((num) => nums.sort((a, b) => a - b).indexOf(num)));
  return nums.map((num) => [...nums].sort((a, b) => a - b).indexOf(num));
};

console.log(smallerNumbersThanCurrent([2, 5, 1, 3]));

The output is:

[ 1, 3, 0, 2 ]
[ 1, 1, 2, 3 ]
[ 0, 1, 2, 3 ]

If there is no console.log, the output of the function is always correct, but now only the first output is correct. Why does it behave this way?


问:
Android Studio/Kotlin - findViewById crash my app
The program stop when it reach the findViewById and I can't figure out why :

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.splash_screen)

    handler.postDelayed({ setContentView(R.layout.activity_main) }, 500) // 5 seconds
    val imageView: ImageView = findViewById(R.id.splashScreenIMG)
    Glide.with(this).load(R.drawable.sligames_waiting).into(imageView)
}

    fun showButtons()
{
    val view: View = findViewById(R.id.boutonOui)
    val cx = view.width / 2
    val cy = view.height / 2
    val finalRadius = hypot(cx.toDouble(), cy.toDouble()).toFloat()
    val anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0f, finalRadius)
    // make the view visible and start the animation
    view.visibility = View.VISIBLE
    anim.duration = 1500
    anim.start()
}
</code>```

I execute this function from another file with this line :

```<code>MainActivity().showButtons()
</code>```

Here's the stack trace :

```<code>2020-06-01 12:55:02.783 22557-22557/com.example.yourmajesty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yourmajesty, PID: 22557
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
    at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
    at android.content.Context.obtainStyledAttributes(Context.java:738)
    at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
    at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
    at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
    at com.example.yourmajesty.MainActivity.showButtons(MainActivity.kt:122)
    at com.example.yourmajesty.Dialog.dialogChanger(Dialog.kt:26)
    at com.example.yourmajesty.MainActivity$dialogBoxDiseappear$2.run(MainActivity.kt:190)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7695)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
</code>```

Thanks in advance

答:
```<code>MainActivity().showButtons()
</code>```

You can't initiate an object from your activity. You can only launch it and bundle data with its Intent

Please refere to this thread If you're trying to communicate with MainActvitiy from a fragment

Body:
The program stop when it reach the findViewById and I can't figure out why :

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.splash_screen)

    handler.postDelayed({ setContentView(R.layout.activity_main) }, 500) // 5 seconds
    val imageView: ImageView = findViewById(R.id.splashScreenIMG)
    Glide.with(this).load(R.drawable.sligames_waiting).into(imageView)
}

    fun showButtons()
{
    val view: View = findViewById(R.id.boutonOui)
    val cx = view.width / 2
    val cy = view.height / 2
    val finalRadius = hypot(cx.toDouble(), cy.toDouble()).toFloat()
    val anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0f, finalRadius)
    // make the view visible and start the animation
    view.visibility = View.VISIBLE
    anim.duration = 1500
    anim.start()
}

I execute this function from another file with this line :

MainActivity().showButtons()

Here's the stack trace :

2020-06-01 12:55:02.783 22557-22557/com.example.yourmajesty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yourmajesty, PID: 22557
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
    at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
    at android.content.Context.obtainStyledAttributes(Context.java:738)
    at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
    at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
    at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
    at com.example.yourmajesty.MainActivity.showButtons(MainActivity.kt:122)
    at com.example.yourmajesty.Dialog.dialogChanger(Dialog.kt:26)
    at com.example.yourmajesty.MainActivity$dialogBoxDiseappear$2.run(MainActivity.kt:190)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7695)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Thanks in advance

Body:
MainActivity().showButtons()

You can't initiate an object from your activity. You can only launch it and bundle data with its Intent

Please refere to this thread If you're trying to communicate with MainActvitiy from a fragment


问:
Use of Curve25519 in ECDSA
I'm currently investigating the use of curve25519 for signing. Original distribution and a C implementation (and a second C implementation).

Bernstein suggests to use ECDSA for this but I could not find any code.

答:
To use Curve25519 for this, you'd have to implement a lot of functions that AFAIK aren't currently implemented anywhere for this curve, which would mean getting very substantially into the mathematics of elliptic curve cryptography.  The reason is that the existing functions throw away the "y" coordinate of the point and work only with the "x" coordinate.  Without the "y" coordinate, the points P and -P look the same.  That's fine for ECDH which Curve25519 is designed for, because |x(yG)| = |x(-yG)|.  But for ECDSA you need to calculate aG + bP, and |aG + bP| does not in general equal |aG - bP|. I've looked into what would be involved in extending curve25519-donna to support such calculations; it's doable, but far from trivial.

Since what you need most of all is fast verification, I recommend Bernstein's Rabin-Williams scheme.

Title: Use of Curve25519 in ECDSA


问:
Switch statement with two arguments
I have a question related to switch statement with 2 arguments. I do not understand which value to look for. I've read somewhere that comma(,) is equal to AND,but that is not helping me much since when debugging it goes to case 1,case 1,and then default,so I  really don't get it.

Any help would be appreaciated,Thanks!

```<code>#define ADD(x, y) x+y
#define MUL(x, y) x*y
void main() {
    int arr[6] = { 012, -2, 7 - 011, 0x1F, 3 }, res = 0;
    int n = sizeof(arr) / sizeof(int), i, j;
    for (i = -1, j = n; i <= n / 2;) {
        switch (--j, ++i) {
        case 0: res += MUL(arr[i], arr[j]);
        case 1: res += ADD(arr[i], arr[j]); break;
        case 4: res += MUL(ADD(arr[i], arr[j]), ADD(arr[i + 1], res));
        default: res++; break;
        }
    }
    printf("%d", res);
} ```
```

答:
Operator comma is not equal to  AND. Operator comma evaluates operands from left to right, and returns the last result. Thus,

```<code>switch (--j, ++i) {
</code>```

i = 0;
it goes to the case 0, you don`t have break statement so you go to the case 1

Title: Switch statement with two arguments

Body:
I have a question related to switch statement with 2 arguments. I do not understand which value to look for. I've read somewhere that comma(,) is equal to AND,but that is not helping me much since when debugging it goes to case 1,case 1,and then default,so I  really don't get it.

Any help would be appreaciated,Thanks!

#define ADD(x, y) x+y
#define MUL(x, y) x*y
void main() {
    int arr[6] = { 012, -2, 7 - 011, 0x1F, 3 }, res = 0;
    int n = sizeof(arr) / sizeof(int), i, j;
    for (i = -1, j = n; i <= n / 2;) {
        switch (--j, ++i) {
        case 0: res += MUL(arr[i], arr[j]);
        case 1: res += ADD(arr[i], arr[j]); break;
        case 4: res += MUL(ADD(arr[i], arr[j]), ADD(arr[i + 1], res));
        default: res++; break;
        }
    }
    printf("%d", res);
} ```

Body:
Operator comma is not equal to  AND. Operator comma evaluates operands from left to right, and returns the last result. Thus,

switch (--j, ++i) {

i = 0;
it goes to the case 0, you don`t have break statement so you go to the case 1


问:
How to change color of options under select tag on mouse hover?
Hi I have refered a lot of website but i dint found the solution that how can we change the option background color on hover as by default it is blue but I want to change the color to green. Please refer the screenshot below so it may give more clearity on what i m asking for.

I tried using this css code but its not having any effect :  option:hover{background:green;}

答:
Select option form element designs can't be updated with CSS. If you are not using it inside a form, I would suggest you to use custom Dropdown with even listeners from javascript as -

```<code><div class="dropdown-wrap" id="dropdown-wrap">
    <div class="dropdown-head pointerCursor" id="dropdown-head">
        <span class="sel-option" id="sel-option">DIsplay header</span>
    </div>

    <ul class="list-ul pointerCursor hide" id="list-ul">
        <li class="list-li" data-val="1">1</li>
        <li class="list-li" data-val="2">2</li>
        <li class="list-li" data-val="3">3</li>
    </ul>
</div>
</code>```

Add 2 event listener at least as -

```<code>document.getElementById('dropdown-head').addEventListener('click', (e) => this.showTeamsList(e));

document.getElementById('dropdown-wrap').addEventListener('mouseleave', (e) => this.hideTeamsList(e));
</code>```

Add event listener functions add and remove hide class from list-ul. For hide class you can simply use max-height property as -

```<code>.hide {
    max-height: 0 !important;
}
</code>```

and overflow: hidden property in css property of list-ul.

Body:
Select option form element designs can't be updated with CSS. If you are not using it inside a form, I would suggest you to use custom Dropdown with even listeners from javascript as -

<div class="dropdown-wrap" id="dropdown-wrap">
    <div class="dropdown-head pointerCursor" id="dropdown-head">
        <span class="sel-option" id="sel-option">DIsplay header</span>
    </div>

    <ul class="list-ul pointerCursor hide" id="list-ul">
        <li class="list-li" data-val="1">1</li>
        <li class="list-li" data-val="2">2</li>
        <li class="list-li" data-val="3">3</li>
    </ul>
</div>

Add 2 event listener at least as -

document.getElementById('dropdown-head').addEventListener('click', (e) => this.showTeamsList(e));

document.getElementById('dropdown-wrap').addEventListener('mouseleave', (e) => this.hideTeamsList(e));

Add event listener functions add and remove hide class from list-ul. For hide class you can simply use max-height property as -

.hide {
    max-height: 0 !important;
}

and overflow: hidden property in css property of list-ul.


问:
t-sql loop through all rows and sum amount from column until value is reached
I have a table containing the below test data:

I now would like to fill a restaurant with 12 seating spaces.

This should result in:

Basically, I need to loop from top to bottom through all rows and add the AmountPersons until I have filled the restaurant.

In this example:

(first few rows: AmountPersons) 3+1+2+4 = 10

UserId 52 can't be added because they reserved for 3 persons, which would result in 13 occupied places and there are only 12 available.

In the next row it notices a reservation for 1. This can be added to the previous 10 we already found.

NewTotal is now 11.

UserId 79 and 82 can't be added because we'd exceed the capacity again.

UserId 95 reserved for 1, this one can be added and we now have all places filled.

This is the result I get from the cursor I use, but I'm stuck now. Please help.

The while loop I have in the cursor basically stops when the next value would be higher than 12. But that is not correct.

答:
Because you want to skip rows, you need a recursive CTE.  But it is tricky -- because you may not have a group following your rules that adds up to exactly 12.

So:

```<code>with tn as (
         select t.*, row_number() over (order by userid) as seqnum
         from t
        ),
       cte as (
        select userId, name, amountPersons as total, 1 as is_included, seqnum
        from tn
        where seqnum = 1
        union all
        select tn.userId, tn.name,
               (case when tn.amountPersons + cte.total <= 12
                     then tn.amountPersons + cte.total
                     else cte.total
                end),
               (case when tn.amountPersons + cte.total <= 12
                     then 1
                     else 0
                end) as is_included,
               tn.seqnum
        from cte join
             tn
             on tn.seqnum = cte.seqnum + 1
        where cte.total < 12
    )
select cte.*
from cte
where is_included = 1;
</code>```

Here is a db<>fiddle.

Note that if you change "I" to a larger value, then it is not included and the number of occupied seats is 11, not 12.

Body:
Because you want to skip rows, you need a recursive CTE.  But it is tricky -- because you may not have a group following your rules that adds up to exactly 12.

So:

with tn as (
         select t.*, row_number() over (order by userid) as seqnum
         from t
        ),
       cte as (
        select userId, name, amountPersons as total, 1 as is_included, seqnum
        from tn
        where seqnum = 1
        union all
        select tn.userId, tn.name,
               (case when tn.amountPersons + cte.total <= 12
                     then tn.amountPersons + cte.total
                     else cte.total
                end),
               (case when tn.amountPersons + cte.total <= 12
                     then 1
                     else 0
                end) as is_included,
               tn.seqnum
        from cte join
             tn
             on tn.seqnum = cte.seqnum + 1
        where cte.total < 12
    )
select cte.*
from cte
where is_included = 1;

Here is a db<>fiddle.

Note that if you change "I" to a larger value, then it is not included and the number of occupied seats is 11, not 12.


问:
How to tweet using Android app?
In my application, I need to post tweets, how can I do this? I have found a jar but it's constructor is deprecated.</p>

答: You can send the appropriate Intent: request for ACTION_SENDand then limit the eligible intents based on a list of known applications packages.

Title: How to tweet using Android app?


问:
F# Downcasting arrays without reflection
I am working on a program where the user can send me all sort of objects at runtime, and I do not know their type in advance (at compile time). When the object can be down-cast to an (F#) array, of any element type, I would like to perform some usual operations on the underlying array. E.g. Array.Length,  Array.sub...

The objects I can get from the users will be of things like box [| 1; 2; 3 |] or box [| "a"; "b"; "c" |], or any 'a[], but I do not know 'a at compile time.

The following does not work :

```<code>let arrCount (oarr: obj) : int =
    match oarr with
    | :? array<_> as a -> a.Length
    | :? (obj[]) as a -> a.Length
 // | :? (int[]) as a -> a.Length     // not an option for me here
 // | :? (string[]) as a -> a.Length  // not an option for me here
 // | ...
    | _ -> failwith "Cannot recognize an array"
</code>```

E.g both arrCount (box [| 1; 2; 3 |]) and arrCount (box [| "a"; "b"; "c" |]) fail here.

The only solution I found so far is to use reflection, e.g. :

```<code>type ArrayOps =
     static member count<'a> (arr: 'a[]) : int = arr.Length
     static member sub<'a> (arr: 'a[]) start len : 'a[] = Array.sub arr start len
     // ...

let tryCount (oarr: obj) =
    let ty = oarr.GetType()
    if ty.HasElementType  && ty.BaseType = typeof<System.Array> then
        let ety = ty.GetElementType()
        let meth = typeof<ArrayOps>.GetMethod("count").MakeGenericMethod([| ety |])
        let count = meth.Invoke(null, [| oarr |]) :?> int
        Some count
    else
        None
</code>```

My question: is there a way to use functions such as Array.count, Array.sub, etc... on arguments of the form box [| some elements of some unknown type |] without using reflection?

答:
Since F# is statically type-safe it tries to prevent you from doing this, which is why it isn't trivial. Casting it to an array<_> will not work because from an F# standpoint, array<obj> is not equal to array<int> etc, meaning you would have to check for every covariant type.

However, you can exploit the fact that an array is also a System.Array, and use the BCL methods on it. This doesn't give you Array.length etc, because they need type-safety, but you can essentially do any operation with a little bit of work.

If you do have a limited set of known types that the obj can be when it is an array, I suggest you create a DU with these known types and create a simple converter that matches on array<int>, array<string> etc, so that you get your type-safety back.

Without any type safety you can so something like this:

let arrCount (x: obj) =
    match x with
    | null -> nullArg "x cannot be null"
    | :? System.Array as arr -> arr.GetLength(0)  // must give the rank
    | _ -> -1  // or failwith
```

<p>Usage:</p>

<pre class="lang-ml prettyprint-override"><code>> arrCount (box [|1;2;3|]);;
val it : int = 3

> arrCount (box [|"one"|]);;
val it : int = 1
</code>```

This other answer on SO has a good way of explaining why allowing such casts makes the .NET type system unsound, and why it isn't allowed in F#: https://stackoverflow.com/a/7917466/111575

EDIT: 2nd alternative

If you don't mind boxing your entire array, you can expand on the above solution by converting the whole array, once you know it is an array. However, the first approach (with System.Array) has O(1) performance, while this approach is, necessarily, O(n):

open System.Collections

let makeBoxedArray (x: obj) =
    match x with
    | null -> nullArg "x cannot be null"
    | :? System.Array as arr ->
        arr :> IEnumerable
        |> Seq.cast<obj>
        |> Seq.toArray

    | _ -> failwith "Not an array"
```

<p>Usage:</p>

<pre class="lang-ml prettyprint-override"><code>> makeBoxedArray (box [|1;2;3|]);;  // it accepts untyped arrays
val it : obj [] = [|1; 2; 3|]

> makeBoxedArray [|"one"|];;  // or typed arrays
val it : obj [] = [|"one"|]

> makeBoxedArray [|"one"|] |> Array.length;;  // and you can do array-ish operations
val it : int = 1

> makeBoxedArray (box [|1;2;3;4;5;6|]) |> (fun a -> Array.sub a 3 2);;
val it : obj [] = [|4; 5|]
</code>```

Body:
I am working on a program where the user can send me all sort of objects at runtime, and I do not know their type in advance (at compile time). When the object can be down-cast to an (F#) array, of any element type, I would like to perform some usual operations on the underlying array. E.g. Array.Length,  Array.sub...

The objects I can get from the users will be of things like box [| 1; 2; 3 |] or box [| "a"; "b"; "c" |], or any 'a[], but I do not know 'a at compile time.

The following does not work :

let arrCount (oarr: obj) : int =
    match oarr with
    | :? array<_> as a -> a.Length
    | :? (obj[]) as a -> a.Length
 // | :? (int[]) as a -> a.Length     // not an option for me here
 // | :? (string[]) as a -> a.Length  // not an option for me here
 // | ...
    | _ -> failwith "Cannot recognize an array"

E.g both arrCount (box [| 1; 2; 3 |]) and arrCount (box [| "a"; "b"; "c" |]) fail here.

The only solution I found so far is to use reflection, e.g. :

type ArrayOps =
     static member count<'a> (arr: 'a[]) : int = arr.Length
     static member sub<'a> (arr: 'a[]) start len : 'a[] = Array.sub arr start len
     // ...

let tryCount (oarr: obj) =
    let ty = oarr.GetType()
    if ty.HasElementType  && ty.BaseType = typeof<System.Array> then
        let ety = ty.GetElementType()
        let meth = typeof<ArrayOps>.GetMethod("count").MakeGenericMethod([| ety |])
        let count = meth.Invoke(null, [| oarr |]) :?> int
        Some count
    else
        None

My question: is there a way to use functions such as Array.count, Array.sub, etc... on arguments of the form box [| some elements of some unknown type |] without using reflection?

Body:
Since F# is statically type-safe it tries to prevent you from doing this, which is why it isn't trivial. Casting it to an array<_> will not work because from an F# standpoint, array<obj> is not equal to array<int> etc, meaning you would have to check for every covariant type.

However, you can exploit the fact that an array is also a System.Array, and use the BCL methods on it. This doesn't give you Array.length etc, because they need type-safety, but you can essentially do any operation with a little bit of work.

If you do have a limited set of known types that the obj can be when it is an array, I suggest you create a DU with these known types and create a simple converter that matches on array<int>, array<string> etc, so that you get your type-safety back.

Without any type safety you can so something like this:

let arrCount (x: obj) =
    match x with
    | null -> nullArg "x cannot be null"
    | :? System.Array as arr -> arr.GetLength(0)  // must give the rank
    | _ -> -1  // or failwith

Usage:

> arrCount (box [|1;2;3|]);;
val it : int = 3

> arrCount (box [|"one"|]);;
val it : int = 1

This other answer on SO has a good way of explaining why allowing such casts makes the .NET type system unsound, and why it isn't allowed in F#: https://stackoverflow.com/a/7917466/111575

EDIT: 2nd alternative

If you don't mind boxing your entire array, you can expand on the above solution by converting the whole array, once you know it is an array. However, the first approach (with System.Array) has O(1) performance, while this approach is, necessarily, O(n):

open System.Collections

let makeBoxedArray (x: obj) =
    match x with
    | null -> nullArg "x cannot be null"
    | :? System.Array as arr ->
        arr :> IEnumerable
        |> Seq.cast<obj>
        |> Seq.toArray

    | _ -> failwith "Not an array"

Usage:

> makeBoxedArray (box [|1;2;3|]);;  // it accepts untyped arrays
val it : obj [] = [|1; 2; 3|]

> makeBoxedArray [|"one"|];;  // or typed arrays
val it : obj [] = [|"one"|]

> makeBoxedArray [|"one"|] |> Array.length;;  // and you can do array-ish operations
val it : int = 1

> makeBoxedArray (box [|1;2;3;4;5;6|]) |> (fun a -> Array.sub a 3 2);;
val it : obj [] = [|4; 5|]


问:
Center a text inside an spinning element
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slide-loader">
    <div class="loader-text">Loading...</div>
  </div></code>```

答:
Hi I made this work around and works perfectly.</p>
```<code><div class="container">
   <div class="slide-loader"></div>
   <div class="loader-text">Loading...</div>
</div>
</code>```
```<code>

       .slide-loader{
      grid-row: 1/-1;
      grid-column: 1/-1;
      margin: auto;
      border: 6px solid #f3f3f3;
      border-radius: 50%;
      border-top: 6px solid #3498db;
      width: 100px;
      height: 100px;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }
    .container{
      width: 200px;
      display: grid;
      grid-template-rows: 1fr 20px 1fr;
      grid-template-columns: auto 60px auto;
    }
    .loader-text{
      grid-row: 2;
      grid-column: 2;
    }
    @-webkit-keyframes spin {
      0% { -webkit-transform: rotate(0deg); }
      100% { -webkit-transform: rotate(360deg); }
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
</code>```

Body:
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

Loading...

Body:
Hi I made this work around and works perfectly.

<div class="container">
   <div class="slide-loader"></div>
   <div class="loader-text">Loading...</div>
</div>

       .slide-loader{
      grid-row: 1/-1;
      grid-column: 1/-1;
      margin: auto;
      border: 6px solid #f3f3f3;
      border-radius: 50%;
      border-top: 6px solid #3498db;
      width: 100px;
      height: 100px;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }
    .container{
      width: 200px;
      display: grid;
      grid-template-rows: 1fr 20px 1fr;
      grid-template-columns: auto 60px auto;
    }
    .loader-text{
      grid-row: 2;
      grid-column: 2;
    }
    @-webkit-keyframes spin {
      0% { -webkit-transform: rotate(0deg); }
      100% { -webkit-transform: rotate(360deg); }
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }


问:
does keeping kafka consumer poll to MAX_VALUE delay the group rebalance?
consumer.poll(Long.MAX_VALUE);

This is to allow the processing (high latency) to complete. Are there any side effects for keeping this high value?

Does it block other messages in the partition being read? Does it adversely affect rebalancing?

答:
There are two configurations that you should understand for this.

timeout that you specify to the poll method.

MAX_POLL_INTERVAL_MS_CONFIG while creating the Kafka consumer.

1. timeout:
From the Kafka documentation for the poll method:

This method returns immediately if there are records available.
Otherwise, it will await the passed timeout. If the timeout
expires, an empty record set will be returned.

@param timeout: The maximum time to block (must not be greater than
{@link Long#MAX_VALUE} milliseconds)

So what if I keep this value higher?

Each iteration of the poll method would wait for this higher value that you set if the records are not available to be consumed.

Does it adversely affect rebalancing?

No, this config does not have a relation to the rebalancing that gets triggered if the consumer in the group is found to be dead by the Kafka consumer group management.

2. MAX_POLL_INTERVAL_MS_CONFIG

From the Kafka documentation for this config

The maximum delay between invocations of poll() when using consumer
group management. This places an upper bound on the amount of time
that the consumer can be idle before fetching more records. If poll()
is not called before expiration of this timeout, then the consumer is
considered failed and the group will rebalance in order to reassign
the partitions to another member.

So what if I keep this value higher?

Sometimes it is known that the message would not be available for consumption during a certain time period. And this is the nature of the application, the producer of the topic might not produce messages in a certain time period.

In that case, we want to stop polling from Kafka. We Know that poll is stopped intentionally and the consumer is not failed. Setting this to a high value like 8 hours will ensure that re-balance simply does not happen.

Does it adversely affect rebalancing?

Yes, this config decides when the rebalancing would be triggered. If you set this to high value, rebalancing would be postponed until that amount of time.


答:
You can't..as such, if you rotate the parent you rotate the child. You need to rotate the text the other way at the same time.

Then center the text any way you wish, perhaps with flexbox....

.slide-loader {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  display: flex;
  justify-content: center;
  align-items: center;
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loader-text {
  animation: spin 2s linear infinite reverse;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slide-loader">
  <div class="loader-text">Loading...</div>
</div></code>```

Title: Center a text inside an spinning element

Body:
You can't..as such, if you rotate the parent you rotate the child. You need to rotate the text the other way at the same time.

Then center the text any way you wish, perhaps with flexbox....

.slide-loader {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  display: flex;
  justify-content: center;
  align-items: center;
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loader-text {
  animation: spin 2s linear infinite reverse;
}

<div class="slide-loader">
  <div class="loader-text">Loading...</div>
</div>


问:
Spring boot 1.5.8 with jakson 2.10.0 object mapping issue
i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.

when i am passing request body on springboot controller having propertyname cityCode
sample json

```<code>{
cityCode:DEL
}
</code>```

when adding jsonproperty mapping works fine

```<code>@JsonProperty("cityCode")
private String cityCode;
</code>```

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is

```<code>{
cityCode:DEL
}
</code>```

it assing

```<code>object{cityCode=null}
</code>```

please let me know if there is any property which i need to add on spring boot

because in most of my scenario i don't want to add @JsonProperty annotation to class fields

EDIT:

I enable log.level to trace i saw some message related to jackson

POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.

EDIT2:

Adding Sample Model Class

```<code>import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}
</code>```

on the controller method is being passed as

```<code>@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest
</code>```

答:
I have used one java api on spring-boot application where object mapper naming strategy is being set to upper_camel_case.

since that class imported on App.java(@SpringBootApplication) upper_camel_case strategy being applied globally.

to fix this globally imposed upper_camel_case strategy i have override the object mapper configuration on App.java and removed

```<code>objectMapper.setPropertyNamingStrategy(new UpperCamelCaseStrategy());
</code>```

now i am able to use default naming strategy on application.

Body:
i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.

when i am passing request body on springboot controller having propertyname cityCode
sample json

{
cityCode:DEL
}

when adding jsonproperty mapping works fine

@JsonProperty("cityCode")
private String cityCode;

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is

{
cityCode:DEL
}

it assing

object{cityCode=null}

please let me know if there is any property which i need to add on spring boot

because in most of my scenario i don't want to add @JsonProperty annotation to class fields

EDIT:

I enable log.level to trace i saw some message related to jackson

POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.

EDIT2:

Adding Sample Model Class

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}

on the controller method is being passed as

@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest

Body:
I have used one java api on spring-boot application where object mapper naming strategy is being set to upper_camel_case.

since that class imported on App.java(@SpringBootApplication) upper_camel_case strategy being applied globally.

to fix this globally imposed upper_camel_case strategy i have override the object mapper configuration on App.java and removed

objectMapper.setPropertyNamingStrategy(new UpperCamelCaseStrategy());

now i am able to use default naming strategy on application.


问:
Google Cloud VideoIntelligence - Is there a way to only call AnnotateVideo for a particular section of a video?
Currently I am using the AnnotateVideo function to analyse videos. Is there any way to analyse only a section of a video, such as providing start_time and end_time as an argument to the function ?</p>

```<code>gs_video_path ='gs://'+bucket_name+'/'+videodata.video.path+videodata.video.name
print(gs_video_path)

video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(gs_video_path, features=features)
</code>```

答:
What you can do is to analyse the full video and then retrieve the annotations for the specified times or frames, see this code.

If this doesn't fit your requirements because the videos are too long and you want to process only a specific part, I suggest you to use an external tool to cut the video locally and then perform the annotation of that fragment. For example you can use the following code to cut the video (there are many others).

```<code>from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
ffmpeg_extract_subclip("video1.mp4", start_time, end_time, targetname="test.mp4")
</code>```

And then you will have to process the video from a local file

Body:
Currently I am using the AnnotateVideo function to analyse videos. Is there any way to analyse only a section of a video, such as providing start_time and end_time as an argument to the function ?

gs_video_path ='gs://'+bucket_name+'/'+videodata.video.path+videodata.video.name
print(gs_video_path)

video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(gs_video_path, features=features)

Body:
What you can do is to analyse the full video and then retrieve the annotations for the specified times or frames, see this code.

If this doesn't fit your requirements because the videos are too long and you want to process only a specific part, I suggest you to use an external tool to cut the video locally and then perform the annotation of that fragment. For example you can use the following code to cut the video (there are many others).

from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
ffmpeg_extract_subclip("video1.mp4", start_time, end_time, targetname="test.mp4")

And then you will have to process the video from a local file


问:
How to use TScrollbar to richedit;
How to use Tscrollbar to Richedit.

My purpose is to separate the scrollbar in a deferent panel.

is it possible?

答:
You can try this:

```<code>procedure TForm1.ScrollBar1Scroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
var
  WParam: longint;

begin
  case ScrollCode of
    scLineUp: WParam := SB_LINEUP;
    scLineDown: WParam := SB_LINEDOWN;
    scPageUp: WParam := SB_PAGEUP;
    scPageDown: WParam := SB_PAGEDOWN;
    scEndScroll: WParam := SB_ENDSCROLL;
    scPosition: WParam := SB_THUMBPOSITION;
    scTrack: WParam := SB_THUMBTRACK;
    else
      exit;
  end;
  WParam := WParam or word(ScrollPos) shl 16;

  RichEdit1.Perform(WM_VSCROLL, WParam, 0);
end;

procedure TForm1.RichEdit1Change(Sender: TObject);
var
  ScrollInfo: TScrollInfo;

begin
  FillChar(ScrollInfo, SizeOF(ScrollInfo), 0);
  ScrollInfo.cbSize := SizeOf(ScrollInfo);
  ScrollInfo.fMask := SIF_RANGE or SIF_PAGE or SIF_POS;
  if GetScrollInfo(RichEdit1.Handle, SB_VERT, ScrollInfo) then
  begin
    ScrollBar1.Max := ScrollInfo.nMax;
    ScrollBar1.Min := ScrollInfo.nMin;
    ScrollBar1.PageSize := ScrollInfo.nPage;
    ScrollBar1.Position := ScrollInfo.nPos;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  RichEdit1Change(self);
end;
</code>```

It synchronizes Scrollbar1: TScrollBar with the scroll info of the RichEdit upon any change in it and simulates WM_VSCROLL messages coming from the scrollbar. However, it requires the RichEdit to have its own vertical scrollbar visible, because the scroll info is not updated, if it is not visible.

There is AFAIK no other way to get the scroll data, simply because the RichEdit control doesn't create them if not needed (ssNone in ScrollBars property).

Title: How to use TScrollbar to richedit;

Body:
You can try this:

procedure TForm1.ScrollBar1Scroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
var
  WParam: longint;

begin
  case ScrollCode of
    scLineUp: WParam := SB_LINEUP;
    scLineDown: WParam := SB_LINEDOWN;
    scPageUp: WParam := SB_PAGEUP;
    scPageDown: WParam := SB_PAGEDOWN;
    scEndScroll: WParam := SB_ENDSCROLL;
    scPosition: WParam := SB_THUMBPOSITION;
    scTrack: WParam := SB_THUMBTRACK;
    else
      exit;
  end;
  WParam := WParam or word(ScrollPos) shl 16;

  RichEdit1.Perform(WM_VSCROLL, WParam, 0);
end;

procedure TForm1.RichEdit1Change(Sender: TObject);
var
  ScrollInfo: TScrollInfo;

begin
  FillChar(ScrollInfo, SizeOF(ScrollInfo), 0);
  ScrollInfo.cbSize := SizeOf(ScrollInfo);
  ScrollInfo.fMask := SIF_RANGE or SIF_PAGE or SIF_POS;
  if GetScrollInfo(RichEdit1.Handle, SB_VERT, ScrollInfo) then
  begin
    ScrollBar1.Max := ScrollInfo.nMax;
    ScrollBar1.Min := ScrollInfo.nMin;
    ScrollBar1.PageSize := ScrollInfo.nPage;
    ScrollBar1.Position := ScrollInfo.nPos;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  RichEdit1Change(self);
end;

It synchronizes Scrollbar1: TScrollBar with the scroll info of the RichEdit upon any change in it and simulates WM_VSCROLL messages coming from the scrollbar. However, it requires the RichEdit to have its own vertical scrollbar visible, because the scroll info is not updated, if it is not visible.

There is AFAIK no other way to get the scroll data, simply because the RichEdit control doesn't create them if not needed (ssNone in ScrollBars property).


问:
Apply javascript (add row) to 2 different form fields
This is all new to me and i don't have that much (or even none) knowledge of javascript. I hoped someone could help me out? I have 2 different form fields and i would like to apply a script to the 2 different form fields.
The thing is to add an extra form row. I found this script on-line and hoped to get it work for both fields.

These are the forms:

```<code><div class="card" style="width: 100%;" id="card-elements">
                <h5 class="card-header">Ingredients</h5>
                <div class="card-body">
                    <div class="ingredients-contents">
                        <form method="post" action="">
                            <div class="row">
                                <div class="col-lg-12">
                                    <div id="inputFormRow-ingredients">
                                        <div class="input-group mb-3">
                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">
                                            <div class="input-group-append">
                                                <button id="removeRow" type="button" class="btn btn-danger"><i class="fas fa-times-circle"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="newRow"></div>
                                    <button id="addRow" type="button" class="btn btn-info">Add Ingredient</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="card" style="width: 100%;" id="card-elements">
                <h5 class="card-header">Steps</h5>
                <div class="card-body">
                    <div class="steps-contents">
                        <form method="post" action="">
                            <div class="row">
                                <div class="col-lg-12">
                                    <div id="inputFormRow-steps">
                                        <div class="input-group mb-3">
                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add Step" autocomplete="off">
                                            <div class="input-group-append">
                                                <button id="removeRow" type="button" class="btn btn-danger"><i class="fas fa-times-circle"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="newRow"></div>
                                    <button id="addRow" type="button" class="btn btn-info">Add Step</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
</code>```

This is the script i'm using:

```<code> // add row
$("#addRow").click(function () {
    var html = '';
    html += '<div id="inputFormRow">';
    html += '<div class="input-group mb-3">';
    html += '<input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">';
    html += '<div class="input-group-append">';
    html += '<button id="removeRow" type="button" class="btn btn-danger"><i class="fas fa-times-circle"></i></button>';
    html += '</div>';
    html += '</div>';

    $('#newRow').append(html);
});

// remove row
$(document).on('click', '#removeRow', function () {
    $(this).closest('#inputFormRow').remove();
});
</code>```

答:
in 2 places you have

 I don't think this is what you want. first one should be

 and the other one

and then you would have

```<code>$('#newRow-ingredients').append(html);
</code>```

and adding the other field would be: (with other html)

```<code>$('#newRow-steps').append(html);
</code>```

also don't use ID's unless you really need them. Always use classes 99% of the time, in your situation that would also be a problem because ID's have to be unique and you are using them multiple times

Body:
This is all new to me and i don't have that much (or even none) knowledge of javascript. I hoped someone could help me out? I have 2 different form fields and i would like to apply a script to the 2 different form fields.
The thing is to add an extra form row. I found this script on-line and hoped to get it work for both fields.

These are the forms:

Ingredients

                        <form method="post" action="">

                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">

                                                <button id="removeRow" type="button" class="btn btn-danger"></button>

                                    <button id="addRow" type="button" class="btn btn-info">Add Ingredient</button>

                        </form>

Steps

                        <form method="post" action="">

                                            <input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add Step" autocomplete="off">

                                                <button id="removeRow" type="button" class="btn btn-danger"></button>

                                    <button id="addRow" type="button" class="btn btn-info">Add Step</button>

                        </form>

This is the script i'm using:

 // add row
$("#addRow").click(function () {
    var html = '';
    html += '
';
    html += '
';
    html += '<input type="text" name="ingredient[]" class="form-control m-input" placeholder="Add ingredient" autocomplete="off">';
    html += '
';
    html += '<button id="removeRow" type="button" class="btn btn-danger"></button>';
    html += '
';
    html += '
';

    $('#newRow').append(html);
});

// remove row
$(document).on('click', '#removeRow', function () {
    $(this).closest('#inputFormRow').remove();
});

Body:
in 2 places you have <div id="newRow"></div> I don't think this is what you want. first one should be <div id="newRow-ingredients"></div> and the other one <div id="newRow-steps"></div>

and then you would have

$('#newRow-ingredients').append(html);

and adding the other field would be: (with other html)

$('#newRow-steps').append(html);

also don't use ID's unless you really need them. Always use classes 99% of the time, in your situation that would also be a problem because ID's have to be unique and you are using them multiple times