问:
Multiple Declarations of [variable name]
I am working on a header file that does a couple of functions for me. I include the header file in two seperate files, the c file and the main file.

I use #ifndef and #def but it looks like it still gets compiled twice, because during the linking process I get serveral

multiple declarations of ...

errors.

PLL header file

#ifndef PLL_HEADER
#define PLL_HEADER

/********************************************************************
 * includes
 ********************************************************************/
#include "board.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "PITDriver.h"

// Some more stuff

#endif
```

<h2>Here is the relevant log data</h2>

```[compiling stuff]

Building target: PLL Function.axf
Invoking: MCU Linker

[other linker stuff]

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:45: multiple definition of `accumulateVal'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:45: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:46: multiple definition of `getValOne'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:46: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:47: multiple definition of `getValTwo'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:47: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:48: multiple definition of `countTo'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:48: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:49: multiple definition of `runUntil'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:49: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:50: multiple definition of `currentValue'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:50: first defined here

collect2.exe: error: ld returned 1 exit status
make: *** [makefile:39: PLL Function.axf] Error 1
```

答:
Correction made according to the comment of @Peter

In C you can only put variable definitions in a header if it is only included in one compilation unit.

You seem to have two compilation unit :

one that compiles your PLL.h and PLL.c to create PLL.o

one that compiles your main.c and PLL.h to create main.o

Both of your objects files contain the variables that you have defined in PLL.h and therefore when you hit the linker it throws an error because the variables have been declared twice (once in each object file).

To correct this error you can either change the way you compile to merge your two compilation unit. Or (if you use an IDE that handles automatically your compilation) you can apply the following changes to avoid defining the variable in your header.

In the header : (change the definition to a declaration)

```<code>extern int x;
</code>```

In a source file : (define the variable)

```<code>int x;
</code>```

Body:
I am working on a header file that does a couple of functions for me. I include the header file in two seperate files, the c file and the main file.

I use #ifndef and #def but it looks like it still gets compiled twice, because during the linking process I get serveral

multiple declarations of ...

errors.

PLL header file

#ifndef PLL_HEADER
#define PLL_HEADER

/********************************************************************
 * includes
 ********************************************************************/
#include "board.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "PITDriver.h"

// Some more stuff

#endif

Here is the relevant log data

[compiling stuff]

Building target: PLL Function.axf
Invoking: MCU Linker

[other linker stuff]

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:45: multiple definition of `accumulateVal'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:45: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:46: multiple definition of `getValOne'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:46: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:47: multiple definition of `getValTwo'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:47: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:48: multiple definition of `countTo'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:48: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:49: multiple definition of `runUntil'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:49: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:50: multiple definition of `currentValue'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:50: first defined here

collect2.exe: error: ld returned 1 exit status
make: *** [makefile:39: PLL Function.axf] Error 1

Body:
Correction made according to the comment of @Peter

In C you can only put variable definitions in a header if it is only included in one compilation unit.

You seem to have two compilation unit :

one that compiles your PLL.h and PLL.c to create PLL.o

one that compiles your main.c and PLL.h to create main.o

Both of your objects files contain the variables that you have defined in PLL.h and therefore when you hit the linker it throws an error because the variables have been declared twice (once in each object file).

To correct this error you can either change the way you compile to merge your two compilation unit. Or (if you use an IDE that handles automatically your compilation) you can apply the following changes to avoid defining the variable in your header.

In the header : (change the definition to a declaration)

extern int x;

In a source file : (define the variable)

int x;


来源: stackexchange

问:
Change div background-image on a click
I have a button-based menu that refers to content of the page. It is animated by some jquery I found on the net.
My goal is to change the background-image to certain image while clicking certain button (ex. when I click "historia" button the background image changes to historia.png) but at the same time keep the scrolling down to referring section working.

* {
 margin: 0;
 padding: 0;
 scroll-behavior: smooth;
 z-index: 2;
}

body {
 background-size: cover;
}

/* tło */
.background {
 position: fixed;
  left: 0;
  right: 0;
  z-index: -1;
  display: block;
  width: 100vw;
  height: 100vh;
 background-image: url(mainback.png);
 background-repeat: no-repeat;
 background-size: cover;
 background-position: center;
 filter: blur(2px;);
 -webkit-filter: blur(2px);
}

.undefinedheader {
  width: 50vw;
  height: 65px;
  background-color: grey;
  margin: auto;
 top: 8vh;
 margin-left: auto;
 margin-right: auto;
 left: 0;
 right: 0;
  box-shadow: 0px 0px 40px -2px rgba(0,0,0,0.63);
  border-radius: 5px;
  font-family: 'Merriweather', serif;
  font-size: 20px;
 text-align: center;
 position: absolute;
}
.container {
 height: 420px;
 background-color: blue;
  top: 30vh;
  width:100%;
  background-image: linear-gradient(to right top, #a62a71, #963680, #83408c, #6d4993, #565096, #4560a6, #2e70b2, #007fba, #009ed0, #00bee0, #1cddeb, #5ffbf1);
  box-shadow: 0px 0px 40px -2px rgba(0,0,0,0.63);
  transform: translateY(50%);
 display: block;
}

.internal-width {
 padding: 0;
  width: 90vmin;
  margin-left: auto;
  margin-right: auto;
 display:flex;
  flex-wrap: wrap;
  justify-content:space-between;
}

.box
{
 width: 220px;
 height: 100px;
 background-color: #22584F;
 margin:1%;
 flex-basis:calc(94% / 3);
 float: left;
 margin-bottom: 50px;
 margin-top: 50px;
 transition: all 0.2s ease-in-out;
  border-radius: 20px;
 position: relative;
 font-family: fantasy;
 font-size: 4vw;
 text-align: center;
 color: black;
 text-decoration: none;
}
.box:hover
{
 box-shadow: 0px 0px 20px 5px rgba(0,0,0,0.4);
 cursor: pointer;
 transform: scale(1.1);
}

/* zawartość indeksu */

section {
 height: 100vh;
 padding: 0;
}

section:nth-child(2){
 display: flex;
}
section:before{
 content: attr(data-text);

}

.starttext {
 padding: 0;
 margin: 0;
 font-size: 0;
}
.internal-box1{

 position: relative;
 width: 90vw;
 top: 45%;
  margin-left: auto;
  margin-right: auto;
 display:flex;
  flex-wrap: wrap;
  justify-content:space-between;
}

.contentbox {
 width: 250px;
 height: 80px;
 background-color: #22584F;
 margin:1%;
 flex-basis:calc(110% / 5);
 float: left;
 margin-bottom: 50px;
 margin-top: 50px;
 transition: all 0.2s ease-in-out;
  border-radius: 20px;
 position: relative;
 text-align: center;
 vertical-align: middle;
 font-size: 2.4vw;
 line-height: 80px;
 text-decoration: none;
 color: black;
}

.contenttitle{
 position: relative;
 background-color: grey;
 width: 70vw;
 height: 80px;
 margin-top: 10px;
 left: 0;
 right: 0;
 margin-left: auto;
 margin-right: auto;
 text-align: center;
 vertical-align: middle;
 font-size: 5vw;
 line-height: 80px;
}

.description {
 position: absolute;
 margin-top: 20px;
 width: 75vw;
 right: 0;
 left: 0;
 margin-left: auto;
 margin-right: auto;
 font-size: 40px;
 line-height: 35px;
 vertical-align: middle;
 font-family: monospace;
}

.contentbox:hover
{
 box-shadow: 0px 0px 20px 5px rgba(0,0,0,0.4);
 cursor: pointer;
 transform: scale(1.1);
}

/* zmiana tła */

#history:hover .background {
 background-image: url(1back.png);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<link rel = "stylesheet" type = "text/css" href = "stylei.css" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
<script>
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $(id).offset().top;

    // animated top scrolling
    $('body, html').animate({
        scrollTop: pos
    });
});

</script>
</head>

<div class="background" id="back"></div>

<body>

<section id="top">
<div class="starttext" id="start">1</div>
<div class="undefinedheader">
tu może być tytuł
</div>
<div class="container">
 <div class="internal-width">
 Historia

 </div>
</div>
</section>

<section  id="1">
<div class="starttext">pisanie</div>
  <div class="container">
    <div class="contenttitle">Historia gier planszowych</div>
    <div class="description">
    Gry planszowe jak się okazuje, są dużo starsze niż większości z nas się wydaje, bowiem już około 5000 lat temu ludzie zaczęli tworzyć pierwsze gry planszowe.
    </div>
    <div class="internal-box1">

      starożytność
      średniowiecze
      czasy nowożytne
      do gory

    </div>
</div>
</section>

<section id="2">
<div class="starttext">pisanie</div>
<div class="container">tekst
  <div class="internal-box1">
    <div class="contentlink"></div>
    <div class="contentbox"></div>
    <div class="contentbox"></div>
    <div class="contentbox"></div>
  </div>
</div>
</section>

<section id="3">
<div class="starttext">pisanie</div>
<div class="container">tekst</div>
</section>

<section id="4">
<div class="starttext">pisanie</div>
<div class="container">tekst</div>
</section>

<section id="5">
<div class="starttext">pisanie</div>
<div class="container">tekst</div>
</section>

<section id="6">
<div class="starttext">pisanie</div>
<div class="container">tekst</div>
</section>

</body></code>```

答:
Target the button with the click event after that in the function target the element with the background-image and change it's url. </p>

<p>$(btn).click(function(){ elementWithBackgroundImage.css('background-image', 'url')}); </p>

ContentLicense: CC BY-SA 4.0

Title: Change div background-image on a click

Body:
I have a button-based menu that refers to content of the page. It is animated by some jquery I found on the net.
My goal is to change the background-image to certain image while clicking certain button (ex. when I click "historia" button the background image changes to historia.png) but at the same time keep the scrolling down to referring section working.

* {
 margin: 0;
 padding: 0;
 scroll-behavior: smooth;
 z-index: 2;
}

body {
 background-size: cover;
}

/* tło */
.background {
 position: fixed;
  left: 0;
  right: 0;
  z-index: -1;
  display: block;
  width: 100vw;
  height: 100vh;
 background-image: url(mainback.png);
 background-repeat: no-repeat;
 background-size: cover;
 background-position: center;
 filter: blur(2px;);
 -webkit-filter: blur(2px);
}

.undefinedheader {
  width: 50vw;
  height: 65px;
  background-color: grey;
  margin: auto;
 top: 8vh;
 margin-left: auto;
 margin-right: auto;
 left: 0;
 right: 0;
  box-shadow: 0px 0px 40px -2px rgba(0,0,0,0.63);
  border-radius: 5px;
  font-family: 'Merriweather', serif;
  font-size: 20px;
 text-align: center;
 position: absolute;
}
.container {
 height: 420px;
 background-color: blue;
  top: 30vh;
  width:100%;
  background-image: linear-gradient(to right top, #a62a71, #963680, #83408c, #6d4993, #565096, #4560a6, #2e70b2, #007fba, #009ed0, #00bee0, #1cddeb, #5ffbf1);
  box-shadow: 0px 0px 40px -2px rgba(0,0,0,0.63);
  transform: translateY(50%);
 display: block;
}

.internal-width {
 padding: 0;
  width: 90vmin;
  margin-left: auto;
  margin-right: auto;
 display:flex;
  flex-wrap: wrap;
  justify-content:space-between;
}

.box
{
 width: 220px;
 height: 100px;
 background-color: #22584F;
 margin:1%;
 flex-basis:calc(94% / 3);
 float: left;
 margin-bottom: 50px;
 margin-top: 50px;
 transition: all 0.2s ease-in-out;
  border-radius: 20px;
 position: relative;
 font-family: fantasy;
 font-size: 4vw;
 text-align: center;
 color: black;
 text-decoration: none;
}
.box:hover
{
 box-shadow: 0px 0px 20px 5px rgba(0,0,0,0.4);
 cursor: pointer;
 transform: scale(1.1);
}

/* zawartość indeksu */

section {
 height: 100vh;
 padding: 0;
}

section:nth-child(2){
 display: flex;
}
section:before{
 content: attr(data-text);

}

.starttext {
 padding: 0;
 margin: 0;
 font-size: 0;
}
.internal-box1{

 position: relative;
 width: 90vw;
 top: 45%;
  margin-left: auto;
  margin-right: auto;
 display:flex;
  flex-wrap: wrap;
  justify-content:space-between;
}

.contentbox {
 width: 250px;
 height: 80px;
 background-color: #22584F;
 margin:1%;
 flex-basis:calc(110% / 5);
 float: left;
 margin-bottom: 50px;
 margin-top: 50px;
 transition: all 0.2s ease-in-out;
  border-radius: 20px;
 position: relative;
 text-align: center;
 vertical-align: middle;
 font-size: 2.4vw;
 line-height: 80px;
 text-decoration: none;
 color: black;
}

.contenttitle{
 position: relative;
 background-color: grey;
 width: 70vw;
 height: 80px;
 margin-top: 10px;
 left: 0;
 right: 0;
 margin-left: auto;
 margin-right: auto;
 text-align: center;
 vertical-align: middle;
 font-size: 5vw;
 line-height: 80px;
}

.description {
 position: absolute;
 margin-top: 20px;
 width: 75vw;
 right: 0;
 left: 0;
 margin-left: auto;
 margin-right: auto;
 font-size: 40px;
 line-height: 35px;
 vertical-align: middle;
 font-family: monospace;
}

.contentbox:hover
{
 box-shadow: 0px 0px 20px 5px rgba(0,0,0,0.4);
 cursor: pointer;
 transform: scale(1.1);
}

/* zmiana tła */

#history:hover .background {
 background-image: url(1back.png);
}

<link rel = "stylesheet" type = "text/css" href = "stylei.css" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">

1

tu może być tytuł

 Historia

pisanie

Historia gier planszowych

    Gry planszowe jak się okazuje, są dużo starsze niż większości z nas się wydaje, bowiem już około 5000 lat temu ludzie zaczęli tworzyć pierwsze gry planszowe.

      starożytność
      średniowiecze
      czasy nowożytne
      do gory

pisanie

tekst

pisanie

tekst

pisanie

tekst

pisanie

tekst

pisanie

tekst

Body:
Target the button with the click event after that in the function target the element with the background-image and change it's url.

$(btn).click(function(){ elementWithBackgroundImage.css('background-image', 'url')});


问:
Spreadsheet::Workbook.new creates .xls instead of xlsx
I want to generate  xlsx file
but Spreadsheet genrates  xls

How to generate the  xlsx file using the same gem ?

答: You may want to use the roo gem instead as it supports XLSX format. It's also more well supported as the spreadsheet gem has not been updated in 5 years, and spreadsheet gem does NOT support XLS format.</p>


问:
return last word in a file that starts with capital letter
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "
</code>```

but this isn't working.

I also tried this:

```<code>    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "
</code>```

Any help?

答:
I did something like this.

import re
pattern = "[A-Z][a-zA-Z]+"

with open('input.txt', 'r') as file:
  for el in reversed(file.readlines()):
    res = re.findall(pattern, el)
    if res:
      print(res[-1])

```

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?


问:
Adding/Viewing/Deleting Data from HBase using PHP and Mapreduce in Java?
Hi friends

i am generating a web crawler, i like to know some things about that,

1)Can i use Map reduce to Fetch the Data from the NET

2)Can i able to save the Fetched data to HBase?

3)Can i able to Write an App in PHP for Fetch the Data from HBase?if yes can u gave me a code snippet??How can i Adding/Viewing/Deleting Data from HBase using PHP

答: Can be done easily via REST using Stargate.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How can we reduce the size of HOG descriptor changing the size of cells and bloks
I have a question about reducing the size of HOG descriptor i would like without using methods such as PCA .. to reduce the size of this descriptor and obtain a 16 elements in this vector using a specific number of cells and blocks. Idf you have any idea i will be thankfull.
Thanks a lot </p>

答: By using the extractHOGfeatures method given by matlab we can specify the number of blocks and cells so automatically the size of the characteristic vector will be changed </p>


问:
Get value based on input in two dimensional array
I have a 2 dimensional array

```<code>var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
</code>```

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.

答:
You can use the find() method.

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

let input = +prompt('enter the index');
console.log(years.find(x => x[0] === input)[1])```

Body:
I have a 2 dimensional array

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.


问:
Converting from alpha to numeric with decimals fails
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

```<code>dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;
</code>```

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

答:
Just for completeness, you could use a data structure to do the conversion as well. But, the conversion is not as explicit when you do that.

```<code>**free
dcl-ds *n;
  charfld     char(6);
  numfld      zoned(6: 2) Pos(1);
end-ds;

evalr charfld = '6000';
dsply %char(numfld);
return;
</code>```

```<code>                      Display Program Messages

Job 499369/XXXXXXX/QPADEV0011 started on 05/29/19 at 08:31:13 in subsystem Q
DSPLY  60.00
</code>```

Body:
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

Body:
Just for completeness, you could use a data structure to do the conversion as well. But, the conversion is not as explicit when you do that.

**free
dcl-ds *n;
  charfld     char(6);
  numfld      zoned(6: 2) Pos(1);
end-ds;

evalr charfld = '6000';
dsply %char(numfld);
return;

                      Display Program Messages

Job 499369/XXXXXXX/QPADEV0011 started on 05/29/19 at 08:31:13 in subsystem Q
DSPLY  60.00


问:
How to extract the key values from a function within a function using list comprehension?
I have the data on movies, which looks like this for one of the movies, Bridesmaids.

```<code>{'Similar': {'Info': [{'Name': 'Bridesmaids', 'Type': 'movie'}], 'Results': [{'Name': 'Baby Mama', 'Type': 'movie'}, {'Name': 'The Five-Year Engagement', 'Type': 'movie'}, {'Name': 'Bachelorette', 'Type': 'movie'}, {'Name': 'The Heat', 'Type': 'movie'}, {'Name': 'Date Night', 'Type': 'movie'}]}}
</code>```

I want to create a list[] which contains the names of movies only (so, I want to descend into 'Similar', then 'Info', within the dictionary, find the value for the 'Name' key, extract this value, e.g.'Bridesmaids') and iterate for all of the movies.

first I created the function get_movies_from_tastedive(name), to have my data on movies (Part 1).

Then I am trying to define a second function, extract_movie_titles, which hopefully will return a list of movie titles.  I'm using list comprehension here.
When I try to invoke it by printing (line 22 and line 23), it does not work..

Part 1.

```<code>def get_movies_from_tastedive(name):
    baseurl = 'https://tastedive.com/api/similar'
    pdict = {'q': name,'type': 'movies','limit': '5'}
    movie_resp = requests.get(baseurl, params = pdict)
    return movie_resp.json()
</code>```

Part 2.

```<code>def extract_movie_titles(name):
p = get_movies_from_tastedive(name)
return[d['Name'] for d in p['Similar']['Info']]

print(extract_movie_titles(get_movies_from_tastedive("Tony Bennett"))) #line 22
print(extract_movie_titles(get_movies_from_tastedive("Bridesmaids"))) #line 23
</code>```

SyntaxError: bad input on line 22

答:
A compacted version of the code plus a short testing code.

```<code>import requests

def get_movies_from_tastedive(name):
    r = requests.get('https://tastedive.com/api/similar', params={'q': name, 'type': 'movies', 'limit': '5'})
    if r.status_code == 200:
        return [m['Name'] for m in r.json()['Similar']['Results'] if m['Type'] == 'movie']

movies = get_movies_from_tastedive('Tony Bennett')
if movies:
    print(movies)
else:
    print('ERR.Cant read movies')
</code>```

Output

```<code>['The Startup Kids', 'The Englishman Who Went Up A Hill But Came Down A Mountain', 'A Place In The Sun', 'Last Tango In Paris', 'Charlie Chaplin']
</code>```

Body:
I have the data on movies, which looks like this for one of the movies, Bridesmaids.

{'Similar': {'Info': [{'Name': 'Bridesmaids', 'Type': 'movie'}], 'Results': [{'Name': 'Baby Mama', 'Type': 'movie'}, {'Name': 'The Five-Year Engagement', 'Type': 'movie'}, {'Name': 'Bachelorette', 'Type': 'movie'}, {'Name': 'The Heat', 'Type': 'movie'}, {'Name': 'Date Night', 'Type': 'movie'}]}}

I want to create a list[] which contains the names of movies only (so, I want to descend into 'Similar', then 'Info', within the dictionary, find the value for the 'Name' key, extract this value, e.g.'Bridesmaids') and iterate for all of the movies.

first I created the function get_movies_from_tastedive(name), to have my data on movies (Part 1).

Then I am trying to define a second function, extract_movie_titles, which hopefully will return a list of movie titles.  I'm using list comprehension here.
When I try to invoke it by printing (line 22 and line 23), it does not work..

Part 1.

def get_movies_from_tastedive(name):
    baseurl = 'https://tastedive.com/api/similar'
    pdict = {'q': name,'type': 'movies','limit': '5'}
    movie_resp = requests.get(baseurl, params = pdict)
    return movie_resp.json()

Part 2.

def extract_movie_titles(name):
p = get_movies_from_tastedive(name)
return[d['Name'] for d in p['Similar']['Info']]

print(extract_movie_titles(get_movies_from_tastedive("Tony Bennett"))) #line 22
print(extract_movie_titles(get_movies_from_tastedive("Bridesmaids"))) #line 23

SyntaxError: bad input on line 22

Body:
A compacted version of the code plus a short testing code.

import requests

def get_movies_from_tastedive(name):
    r = requests.get('https://tastedive.com/api/similar', params={'q': name, 'type': 'movies', 'limit': '5'})
    if r.status_code == 200:
        return [m['Name'] for m in r.json()['Similar']['Results'] if m['Type'] == 'movie']

movies = get_movies_from_tastedive('Tony Bennett')
if movies:
    print(movies)
else:
    print('ERR.Cant read movies')

Output

['The Startup Kids', 'The Englishman Who Went Up A Hill But Came Down A Mountain', 'A Place In The Sun', 'Last Tango In Paris', 'Charlie Chaplin']


问:
When should i use @android:id/?
I've found some code examples with the @android:id/xyz attribute set instead of @+id/xyz.

When and why is it necessary to use Android ids instead of the user's id?

答: @android:id indicates that the id is in the Android.r.id namespace. So this is useful for ListActivities where they look for Android.r.id.list by default.

Title: When should i use @android:id/?


问:
JS prevent flickered input border on focus
I'm trying to build a custom input number. The only problem I have is that when I click on the button multiple times (increment), I'm getting a flickered input border.

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus {
 border: 1px solid red;
 outline: none;
}</code>```

<input type="text">

<button>Increment</button>```

There is a way to getting around it?

答:
The problem is that your button is taking focus when it is clicked. To prevent this happening, you can intercept the mousedown event on your button and call preventDefault().

However, forcing focus like this is a strange thing to do and best avoided.

const input = document.querySelector('input');

const buttonEl = document.querySelector('button');
buttonEl.addEventListener('mousedown', ev => ev.preventDefault())
buttonEl.addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus, input:active {
 border: 1px solid red;
 outline: none;
}</code>```

<input type="text">

<button>Increment</button>```

Body:
I'm trying to build a custom input number. The only problem I have is that when I click on the button multiple times (increment), I'm getting a flickered input border.

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus {
 border: 1px solid red;
 outline: none;
}

<input type="text">

<button>Increment</button>

There is a way to getting around it?

Body:
The problem is that your button is taking focus when it is clicked. To prevent this happening, you can intercept the mousedown event on your button and call preventDefault().

However, forcing focus like this is a strange thing to do and best avoided.

const input = document.querySelector('input');

const buttonEl = document.querySelector('button');
buttonEl.addEventListener('mousedown', ev => ev.preventDefault())
buttonEl.addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus, input:active {
 border: 1px solid red;
 outline: none;
}

<input type="text">

<button>Increment</button>


问:
Is it necessary to save a downloaded file from an URL before sending it through another REST API?
I have a problem regarding handling files using java. In my program i'll have to download a certain file from a URL (this works fine), but then i need to send the same file via a REST API to save it into a cloud storage.

My question now is whether it's necessary to save the downloaded file locally before sending it via the REST API?

答: Ask from yourself - is it OK to loose the file when something happens to your program and it restarts. When saving it locally (in temporary location) then you can continue processing it after your program is again up and running.</p>


问:
Start Quartz Scheduler without firing the triggers
I have got q requirement where I need to start the scheduler but the existing triggers should not run. I have spring boot application, I want to implement a case where I will start the application but it should not run the existing triggers into the system.

It can be any flag or parameter base. Is there any way to achieve this? I have been checking on web related to this but could not find anything related to this.

答:
Possibly what you can do, create the scheduler instance, but do not set autostart to true. Then application will be started, but no triggers will be executed.

The code fragment is on kotlin, but it should be similar on java

```<code>@Bean
open fun quartzScheduler(springBeanJobFactory: SpringBeanJobFactory): SchedulerFactoryBean {
    val quartzSchedulerFactory = SchedulerFactoryBean()
    quartzSchedulerFactory.setJobFactory(springBeanJobFactory)
    quartzSchedulerFactory.setConfigLocation(ClassPathResource("quartz.properties"))
    quartzSchedulerFactory.setOverwriteExistingJobs(true)
    quartzSchedulerFactory.isAutoStartup = false

    return quartzSchedulerFactory
}
</code>```

Then you can create some simple controller to start the scheduler

```<code>schedulerFactory.scheduler.start()
</code>```

Body:
Possibly what you can do, create the scheduler instance, but do not set autostart to true. Then application will be started, but no triggers will be executed.

The code fragment is on kotlin, but it should be similar on java

@Bean
open fun quartzScheduler(springBeanJobFactory: SpringBeanJobFactory): SchedulerFactoryBean {
    val quartzSchedulerFactory = SchedulerFactoryBean()
    quartzSchedulerFactory.setJobFactory(springBeanJobFactory)
    quartzSchedulerFactory.setConfigLocation(ClassPathResource("quartz.properties"))
    quartzSchedulerFactory.setOverwriteExistingJobs(true)
    quartzSchedulerFactory.isAutoStartup = false

    return quartzSchedulerFactory
}

Then you can create some simple controller to start the scheduler

schedulerFactory.scheduler.start()


问:
How to display a page only, if certain parameters are provided in the URL?
I want to create a page in Spring, which has the url

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password is a one-time password that the user receives via e-mail every time they want to sign in.

Whenever the user visits this page, I want two things to happen:

Check whether or not the provided credentials are correct.

If they are, display the HTML content of the page.

I've done the first part:

```<code>    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }
</code>```

How do I need to change the code in order to display the main page (HTML file in src/main/resources/static), but only if the authentication checks are passed?

Update 1: Using return ClassPathResource("main.html") as recommended here did not help.

答:
@RobScully is right, you should not handle authorization like this . What you can do is enable spring-security and use spring security annotations to handle this scenario.
Use the following dependencies and setup a basic spring security setup.

Annotations like @PreAuthorize() can then be used to validate the user privileges before executing a method. You can even add this annotation to controller methods to validate before serving each request if you insist.

You can setup and LDAP server or Oauth or even use database for authentication (if you working on a demo or something).

```<code>        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring-security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring-security.version}</version>
        </dependency>
</code>```

Use a configuration class like below to configure the security :

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
            "select username,password, enabled from users where username=?")
        .authoritiesByUsernameQuery(
            "select username, role from user_roles where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") //To check admin role permission
        .and()
          .formLogin().loginPage("/login").failureUrl("/login?error") //provide failure url
          .usernameParameter("username").passwordParameter("password")
        .and()
          .logout().logoutSuccessUrl("/login?logout")
        .and()
          .exceptionHandling().accessDeniedPage("/403")
        .and()
        .csrf();
    }
}
</code>```

This sample project in github gives a basic setup where you can use spring security:

https://github.com/mohchi/spring-security-request-mapping

Reference use:
https://www.mkyong.com/spring-security/spring-security-form-login-using-database/

Body:
I want to create a page in Spring, which has the url

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password is a one-time password that the user receives via e-mail every time they want to sign in.

Whenever the user visits this page, I want two things to happen:

Check whether or not the provided credentials are correct.

If they are, display the HTML content of the page.

I've done the first part:

    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }

How do I need to change the code in order to display the main page (HTML file in src/main/resources/static), but only if the authentication checks are passed?

Update 1: Using return ClassPathResource("main.html") as recommended here did not help.

Body:
@RobScully is right, you should not handle authorization like this . What you can do is enable spring-security and use spring security annotations to handle this scenario.
Use the following dependencies and setup a basic spring security setup.

Annotations like @PreAuthorize() can then be used to validate the user privileges before executing a method. You can even add this annotation to controller methods to validate before serving each request if you insist.

You can setup and LDAP server or Oauth or even use database for authentication (if you working on a demo or something).

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring-security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring-security.version}</version>
        </dependency>

Use a configuration class like below to configure the security :

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
            "select username,password, enabled from users where username=?")
        .authoritiesByUsernameQuery(
            "select username, role from user_roles where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") //To check admin role permission
        .and()
          .formLogin().loginPage("/login").failureUrl("/login?error") //provide failure url
          .usernameParameter("username").passwordParameter("password")
        .and()
          .logout().logoutSuccessUrl("/login?logout")
        .and()
          .exceptionHandling().accessDeniedPage("/403")
        .and()
        .csrf();
    }
}

This sample project in github gives a basic setup where you can use spring security:

https://github.com/mohchi/spring-security-request-mapping

Reference use:
https://www.mkyong.com/spring-security/spring-security-form-login-using-database/


问:
Regional Settings for MS Reporting Services
My reports are showing decimals like this 10,000,000.00, and I would like tho show like this 10.000.000,00

The Windows regional settings are OK, but I don't know from where MS Reporting Services is getting from.

Anyone knows where do I need to configure?

答:
By default, the settings come from the local server settings.

In each report you can customise this to pull in the browser settings. You need to set the "Language" property to =User!Language


问:
shiny Display HTML entities like Δ
How can I use HTML entities in shiny?

The following code shows Δ, Δ and Δ respectively instead of Δ:

```<code>shinyApp(fluidPage(span("Δ", "Δ", "Δ")), function(...) {})
</code>```

答:
The shiny package does not render everything as HTML since it is basically a R package. It takes many features from the htmltools package. An example of this would be shiny's tags list of function which are the same as the one you can find in the htmltools package.
Try the following:

shinyApp(
  fluidPage(
    span(HTML("Δ", "Δ", "Δ")) # the HTML() function missed
  ),
  function(...) {}
)
```

Title: shiny Display HTML entities like Δ

Body:
How can I use HTML entities in shiny?

The following code shows Δ, Δ and Δ respectively instead of Δ:

shinyApp(fluidPage(span("Δ", "Δ", "Δ")), function(...) {})

Body:
The shiny package does not render everything as HTML since it is basically a R package. It takes many features from the htmltools package. An example of this would be shiny's tags list of function which are the same as the one you can find in the htmltools package.
Try the following:

shinyApp(
  fluidPage(
    span(HTML("&Delta;", "&#916;", "&#x0394;")) # the HTML() function missed
  ),
  function(...) {}
)


问:
Proper way of reading messages from Kafka topic and then closing
I am building a simple node.js API using express and kafka-node that returns unread messages from requested Kafka topic and consumer group when HTTP request is received and then closes the connection. I don't need or want the consumer to keep waiting for new messages.

In kafka-node, what is the proper way of checking if the end of the topic has been reached and if yes, close the connection to broker and exit the application in order to prevent new messages being read?

Here's my consumer.js. It's pretty much the same as example given in kafka-node documentation.

```<code>"use strict";

const kafka = require("kafka-node");

let topicName = "testTopic-01",
  groupName = "testGroup-01",
  consumerOptions = {
    kafkaHost: "localhost: 9092",
    groupId: groupName,
    sessionTimeout: 15000,
    protocol: ["roundrobin"],
    fromOffset: "earliest",
    encoding: "utf8"
  };

const consumerGroup = new kafka.ConsumerGroup(consumerOptions, topicName);

consumerGroup.on("message", message => {
  console.log(`Message: ${message.value}`);
});
consumerGroup.on("error", error => {
  console.error(error);
});

console.log(`Consumer started on topic ${topicName} on group ${groupName}`);
</code>```

答:
You can fetch the current offset of a topic partition by using #Offset. By comparing the so fetched offset of your assigned topic partition, you then know what the last message in the corresponding topic partition is.

Keep in mind, that, if you have multiple consumers in parallel, you should keep track of the topic partition that your consumer inside the consumer group was assigned to (#fetchCommits).

Body:
I am building a simple node.js API using express and kafka-node that returns unread messages from requested Kafka topic and consumer group when HTTP request is received and then closes the connection. I don't need or want the consumer to keep waiting for new messages.

In kafka-node, what is the proper way of checking if the end of the topic has been reached and if yes, close the connection to broker and exit the application in order to prevent new messages being read?

Here's my consumer.js. It's pretty much the same as example given in kafka-node documentation.

"use strict";

const kafka = require("kafka-node");

let topicName = "testTopic-01",
  groupName = "testGroup-01",
  consumerOptions = {
    kafkaHost: "localhost: 9092",
    groupId: groupName,
    sessionTimeout: 15000,
    protocol: ["roundrobin"],
    fromOffset: "earliest",
    encoding: "utf8"
  };

const consumerGroup = new kafka.ConsumerGroup(consumerOptions, topicName);

consumerGroup.on("message", message => {
  console.log(`Message: ${message.value}`);
});
consumerGroup.on("error", error => {
  console.error(error);
});

console.log(`Consumer started on topic ${topicName} on group ${groupName}`);


问:
Create a new array from the csv file
I have imported a CSV file using D3, the 'University', 'State', 'Salary' and the 'Type' are the values that I need to do more visualization.
Now I am trying to create a new array that imports the above four attributes.

I create a new array using
    var SalaryArray = []

I have imported the CSV file, by returning the attributes that I need using

```<code>d3.csv("Median Salary Integration 2018.csv")
    .row(function (d) {
        return {University: String(d.University), State: String(d.State),Salary: String(d.Median), Type: String(d.Type)}
</code>```

I tried

```<code>SalaryData = d3.csv("Median Salary Integration 2018.csv")
    .row(function (d) {
        return {
            University: String(d.University), State: String(d.State),
            Salary: String(d.Median), Type: String(d.Type)
        }
    })
</code>```

but by console.log(SalaryData), the result doesn't show.

答:
The documentation shows that you get the value in a callback, not as a return value:

```<code>d3.csv("Median Salary Integration 2018.csv")
.row(function (d) {
    return {
        University: String(d.University), State: String(d.State),
        Salary: String(d.Median), Type: String(d.Type)
    }
})
.then(salaryData => {
    // ***Use salaryData here***
    // It will be an array, so for instance
    for (const entry of salaryData) { // Loop through the array
        // Use `entry.University`, etc., here
    }
})
.catch(error => {
    // Handle/report error
});
</code>```

The documentation says:

This module provides convenient parsing on top of Fetch.

...so what you get back from csv is a promise, not the actual data, because the process is asynchronous. Hence the then and catch above.

Title: Create a new array from the csv file

Body:
I have imported a CSV file using D3, the 'University', 'State', 'Salary' and the 'Type' are the values that I need to do more visualization.
Now I am trying to create a new array that imports the above four attributes.

I create a new array using
    var SalaryArray = []

I have imported the CSV file, by returning the attributes that I need using

d3.csv("Median Salary Integration 2018.csv")
    .row(function (d) {
        return {University: String(d.University), State: String(d.State),Salary: String(d.Median), Type: String(d.Type)}

I tried

SalaryData = d3.csv("Median Salary Integration 2018.csv")
    .row(function (d) {
        return {
            University: String(d.University), State: String(d.State),
            Salary: String(d.Median), Type: String(d.Type)
        }
    })

but by console.log(SalaryData), the result doesn't show.

Body:
The documentation shows that you get the value in a callback, not as a return value:

d3.csv("Median Salary Integration 2018.csv")
.row(function (d) {
    return {
        University: String(d.University), State: String(d.State),
        Salary: String(d.Median), Type: String(d.Type)
    }
})
.then(salaryData => {
    // ***Use salaryData here***
    // It will be an array, so for instance
    for (const entry of salaryData) { // Loop through the array
        // Use `entry.University`, etc., here
    }
})
.catch(error => {
    // Handle/report error
});

The documentation says:

This module provides convenient parsing on top of Fetch.

...so what you get back from csv is a promise, not the actual data, because the process is asynchronous. Hence the then and catch above.


问:
Ignore scrollbar on mousedown event
I'm trying to build a code which will exit a modal when user clicks outside of the modal. The problem is when i click on vertical scrollbar it triggers the event for some reason.
Here's my code

```<code>  $(document).mouseup(function(e) {
      var popup = $(".ui-dialog");

      if (!$('.ui-dialog').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
        popup.fadeOut(100);
        $('#remove').fadeOut(100, function() {
          $('#remove').remove();
        });
        $('#csbox').fadeOut(100, function() {
          $('#csbox').remove;
        });
        $('body').removeClass('custombox-lock');
      }
    });
</code>```

Is there a way to not trigger the event when scrollbar is clicked or being used?

Here's the HTML, the entire content is stripped because its too long. I am on drupal 8

```<code><div id="remove" class="js-modal-window custombox-content custombox-x-center custombox-y-center custombox-fadein custombox-open">
<div id="remove" class="js-modal-window custombox-content custombox-x-center custombox-y-center custombox-fadein custombox-open">
<div style="position: relative; height: auto; width: 700px; display: block; z-index: 601;" tabindex="-1" role="dialog" class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front js-signup-modal u-modal-window p-5" aria-describedby="drupal-modal" aria-labelledby="ui-id-2">
<div class="ui-dialog-titlebar ui-corner-all ui-widget-header ui-helper-clearfix">
<span id="ui-id-2" class="ui-dialog-title">Modal Title</span>
<button type="button" class="ui-dialog-titlebar-close btn btn-sm btn-icon btn-text-secondary u-modal-window__close" id="close">
<span class="fas fa-times"></span>
</button></div>
<div id="drupal-modal" class="ui-front ui-dialog-content ui-widget-content" style="width: auto; min-height: 50px; max-height: 249px; height: auto;"></article></div></div></div></div>
<div class="custombox-overlay custombox-fadein custombox-open" style="z-index: 600;" id="csbox"></div>
</code>```

答:
Spend too much time trying to figure out the way. Eventually did this

```<code>    $(document).mouseup(function(e) {
      var container = $(".ui-dialog");
      console.log(e.target);
      var len = $(window).width() - 50;
      if (!container.is(e.target) && (container.has(e.target).length === 0) && (e.target != $('html').get(0)) &&
        len > e.originalEvent.screenX) {
        if (!$('.ui-dialog').is(e.target) && !container.is(e.target) && container.has(e.target).length == 0) {
          container.fadeOut(100);
          $('#remove').fadeOut(100, function() {
            $('#remove').remove();
          });
          $('#csbox').fadeOut(100, function() {
            $('#csbox').remove();
          });
          $('body').removeClass('custombox-lock');
        }
      }
    });
</code>```

I got the coordinates of user's browser window and assigned a variable, then i subtracted 50 out of it, it means if user clicks within 50 pixels of right side of the window it wont trigger.
If you guys have other ways to solve this problem leave an answer.

Title: Ignore scrollbar on mousedown event

Body:
I'm trying to build a code which will exit a modal when user clicks outside of the modal. The problem is when i click on vertical scrollbar it triggers the event for some reason.
Here's my code

  $(document).mouseup(function(e) {
      var popup = $(".ui-dialog");

      if (!$('.ui-dialog').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
        popup.fadeOut(100);
        $('#remove').fadeOut(100, function() {
          $('#remove').remove();
        });
        $('#csbox').fadeOut(100, function() {
          $('#csbox').remove;
        });
        $('body').removeClass('custombox-lock');
      }
    });

Is there a way to not trigger the event when scrollbar is clicked or being used?

Here's the HTML, the entire content is stripped because its too long. I am on drupal 8

Modal Title
<button type="button" class="ui-dialog-titlebar-close btn btn-sm btn-icon btn-text-secondary u-modal-window__close" id="close">

</button>

Body:
Spend too much time trying to figure out the way. Eventually did this

    $(document).mouseup(function(e) {
      var container = $(".ui-dialog");
      console.log(e.target);
      var len = $(window).width() - 50;
      if (!container.is(e.target) && (container.has(e.target).length === 0) && (e.target != $('html').get(0)) &&
        len > e.originalEvent.screenX) {
        if (!$('.ui-dialog').is(e.target) && !container.is(e.target) && container.has(e.target).length == 0) {
          container.fadeOut(100);
          $('#remove').fadeOut(100, function() {
            $('#remove').remove();
          });
          $('#csbox').fadeOut(100, function() {
            $('#csbox').remove();
          });
          $('body').removeClass('custombox-lock');
        }
      }
    });

I got the coordinates of user's browser window and assigned a variable, then i subtracted 50 out of it, it means if user clicks within 50 pixels of right side of the window it wont trigger.
If you guys have other ways to solve this problem leave an answer.


问:
store XMLHttpRequest.responseText as variable :(
```<code><script language="javascript" type="text/javascript">
</code>```

<p>

```<code>try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
var result = ajaxRequest.responseText;
    }
}
ajaxRequest.open("GET", "vartest.php", true);
document.getElementById('span').innerHTML = result;
ajaxRequest.send(null);
</code>```

<p>}

</p>

答:
```<code><script language="javascript" type="text/javascript">

//this is in the global scope
//so it's available anywhere

**var result;**

function ajaxFunction(){

    var path = 'http://localhost/php/';
    var fileName = 'yourCode.php';

    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
                       **result = ajaxRequest.responseText;**
        }
    }

    ajaxRequest.open("GET", path+fileName, true);
    ajaxRequest.send(null);
}

</script>
</code>```


问:
How to extract number suffix from a filename
In Java I have a filename example ABC.12.txt.gz, I want to extract number 12 from the filename. Currently I am using last index method and extracting substring multiple times.</p>

答:
You can just separate every numeric part from alphanumeric ones by using a regular expression:

```<code>public static void main(String args[]) {
    String str = "ABC.12.txt.gz";
    String[] parts = str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

    // view the resulting parts
    for (String s : parts) {
        System.out.println(s);
    }

    // do what you want with those values...
}
</code>```

This will output

```<code>ABC.
12
.txt.gz
</code>```

Then take the parts you need and do what you have to do with them.

Body:
You can just separate every numeric part from alphanumeric ones by using a regular expression:

public static void main(String args[]) {
    String str = "ABC.12.txt.gz";
    String[] parts = str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

    // view the resulting parts
    for (String s : parts) {
        System.out.println(s);
    }

    // do what you want with those values...
}

This will output

ABC.
12
.txt.gz

Then take the parts you need and do what you have to do with them.


答:
Just change border and padding for input

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input {
  border:1px solid #777777;
  padding:2px 0px;
}

input:focus {
  border:1px solid red;
  outline: none;
}</code>```

<input type="text">

<button>Increment</button>```

Title: JS prevent flickered input border on focus

Body:
Just change border and padding for input

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input {
  border:1px solid #777777;
  padding:2px 0px;
}

input:focus {
  border:1px solid red;
  outline: none;
}

<input type="text">

<button>Increment</button>


问:
VB.net Fill Listview with images in a folder
I have some ini files with the imagenames for the ini files in it.
I have this function:

```<code>Public Function GetAllSongs()
    Try
        While Me.ListView3.Items.Count > 0
            Me.ListView3.Items.Remove(Me.ListView3.Items(0))
            Me.ListView3.Columns.Remove(Me.ListView3.Columns(0))
        End While
    Catch
    End Try

    If Directory.GetFiles(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\").Length = 0 Then
        ListView3.Columns.Add("Cover", 53, HorizontalAlignment.Left)
        ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
        ListView3.Columns.Add("Views", 245, HorizontalAlignment.Left) '163
        ListView3.AllowColumnReorder = True
        ListView3.Columns(1).DisplayIndex = 1

        Dim index As Integer = 0
        Dim lvi As New ListViewItem
        lvi.ImageIndex = index
        lvi.SubItems.Add("Not songs")
        lvi.SubItems.Add("Not songs")
        ListView3.Items.Add(lvi)
    Else

        ListView3.Columns.Add("Cover", 100, HorizontalAlignment.Left)
        ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
        ListView3.Columns.Add("Views", 145, HorizontalAlignment.Left) '163
        Dim di As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\")
        Dim fiArr As FileInfo() = di.GetFiles()
        Dim fri As FileInfo
        For Each fri In fiArr

            Dim Covername As String = My.Computer.FileSystem.CurrentDirectory & "\Files\Covers\" & Inireader.WertLesen("Details", "ID", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
            Dim Trackname As String = Inireader.WertLesen("Details", "TrackName", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
            Dim Views As String = Inireader.WertLesen("Details", "Views", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)

            Dim imgList As New ImageList

            ListView3.AllowColumnReorder = True
            ListView3.Columns(1).DisplayIndex = 1
            imgList.ImageSize = New Size(70, 70)
            imgList.Images.Add("Cover", Image.FromFile(Covername & ".jpg"))
            ListView3.SmallImageList = imgList

            Dim index As Integer = 0
            Dim lvi As New ListViewItem
            lvi.ImageIndex = index
            lvi.SubItems.Add(Trackname)
            lvi.SubItems.Add(Views)
            ListView3.Items.Add(lvi)

        Next fri
    End If
End Function
</code>```

The problem: It only shows one cover, instead of the different covers for each file.

My ini file structure:

```<code> [Details] ID=6W6H3BCUZ5s5wZlKWdICOc
 URL=https://open.spotify.com/track/6W6H3BCUZ5s5wZlKWdICOc?si=5ehoney8QoC-q9FGqeY_ew
 TrackName=Shortcut
</code>```

It´s looking like this right now:

I think it has something to do with the index. But when I change it from 0 to 1 for example, there are no covers anymore.

Do you have an idea, where the problem is?

Thank you :)
Best regards

答:
Declare the ImageList out side the for loop and increase a count value after each iteration. </p>

```<code>Try
    While Me.ListView3.Items.Count > 0
        Me.ListView3.Items.Remove(Me.ListView3.Items(0))
        Me.ListView3.Columns.Remove(Me.ListView3.Columns(0))
    End While
Catch
End Try

If Directory.GetFiles(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\").Length = 0 Then
    ListView3.Columns.Add("Cover", 53, HorizontalAlignment.Left)
    ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
    ListView3.Columns.Add("Views", 245, HorizontalAlignment.Left) '163
    ListView3.AllowColumnReorder = True
    ListView3.Columns(1).DisplayIndex = 1

    Dim index As Integer = 0
    Dim lvi As New ListViewItem
    lvi.ImageIndex = index
    lvi.SubItems.Add("Not songs")
    lvi.SubItems.Add("Not songs")
    ListView3.Items.Add(lvi)
Else

    ListView3.Columns.Add("Cover", 100, HorizontalAlignment.Left)
    ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
    ListView3.Columns.Add("Views", 145, HorizontalAlignment.Left) '163
    Dim di As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\")
    Dim fiArr As FileInfo() = di.GetFiles()
    Dim fri As FileInfo

    Dim imgList As New ImageList

    ListView3.AllowColumnReorder = True
    ListView3.Columns(1).DisplayIndex = 1
    imgList.ImageSize = New Size(70, 70)
    ListView3.SmallImageList = imgList
    Dim index As Integer = 0

    For Each fri In fiArr
        Dim Covername As String = My.Computer.FileSystem.CurrentDirectory & "\Files\Covers\" & Inireader.WertLesen("Details", "ID", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
        Dim Trackname As String = Inireader.WertLesen("Details", "TrackName", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
        Dim Views As String = Inireader.WertLesen("Details", "Views", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)

           imgList.Images.Add("Cover", Image.FromFile(Covername & ".jpg"))

        Dim lvi As New ListViewItem
        lvi.ImageIndex = index

        'Increase the index
        index += 1

        lvi.SubItems.Add(Trackname)
        lvi.SubItems.Add(Views)
        ListView3.Items.Add(lvi)
    Next fri
End If
</code>```

Body:
I have some ini files with the imagenames for the ini files in it.
I have this function:

Public Function GetAllSongs()
    Try
        While Me.ListView3.Items.Count > 0
            Me.ListView3.Items.Remove(Me.ListView3.Items(0))
            Me.ListView3.Columns.Remove(Me.ListView3.Columns(0))
        End While
    Catch
    End Try

    If Directory.GetFiles(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\").Length = 0 Then
        ListView3.Columns.Add("Cover", 53, HorizontalAlignment.Left)
        ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
        ListView3.Columns.Add("Views", 245, HorizontalAlignment.Left) '163
        ListView3.AllowColumnReorder = True
        ListView3.Columns(1).DisplayIndex = 1

        Dim index As Integer = 0
        Dim lvi As New ListViewItem
        lvi.ImageIndex = index
        lvi.SubItems.Add("Not songs")
        lvi.SubItems.Add("Not songs")
        ListView3.Items.Add(lvi)
    Else

        ListView3.Columns.Add("Cover", 100, HorizontalAlignment.Left)
        ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
        ListView3.Columns.Add("Views", 145, HorizontalAlignment.Left) '163
        Dim di As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\")
        Dim fiArr As FileInfo() = di.GetFiles()
        Dim fri As FileInfo
        For Each fri In fiArr

            Dim Covername As String = My.Computer.FileSystem.CurrentDirectory & "\Files\Covers\" & Inireader.WertLesen("Details", "ID", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
            Dim Trackname As String = Inireader.WertLesen("Details", "TrackName", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
            Dim Views As String = Inireader.WertLesen("Details", "Views", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)

            Dim imgList As New ImageList

            ListView3.AllowColumnReorder = True
            ListView3.Columns(1).DisplayIndex = 1
            imgList.ImageSize = New Size(70, 70)
            imgList.Images.Add("Cover", Image.FromFile(Covername & ".jpg"))
            ListView3.SmallImageList = imgList

            Dim index As Integer = 0
            Dim lvi As New ListViewItem
            lvi.ImageIndex = index
            lvi.SubItems.Add(Trackname)
            lvi.SubItems.Add(Views)
            ListView3.Items.Add(lvi)

        Next fri
    End If
End Function

The problem: It only shows one cover, instead of the different covers for each file.

My ini file structure:

 [Details] ID=6W6H3BCUZ5s5wZlKWdICOc
 URL=https://open.spotify.com/track/6W6H3BCUZ5s5wZlKWdICOc?si=5ehoney8QoC-q9FGqeY_ew
 TrackName=Shortcut

It´s looking like this right now:

I think it has something to do with the index. But when I change it from 0 to 1 for example, there are no covers anymore.

Do you have an idea, where the problem is?

Thank you :)
Best regards

Body:
Declare the ImageList out side the for loop and increase a count value after each iteration.

Try
    While Me.ListView3.Items.Count > 0
        Me.ListView3.Items.Remove(Me.ListView3.Items(0))
        Me.ListView3.Columns.Remove(Me.ListView3.Columns(0))
    End While
Catch
End Try

If Directory.GetFiles(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\").Length = 0 Then
    ListView3.Columns.Add("Cover", 53, HorizontalAlignment.Left)
    ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
    ListView3.Columns.Add("Views", 245, HorizontalAlignment.Left) '163
    ListView3.AllowColumnReorder = True
    ListView3.Columns(1).DisplayIndex = 1

    Dim index As Integer = 0
    Dim lvi As New ListViewItem
    lvi.ImageIndex = index
    lvi.SubItems.Add("Not songs")
    lvi.SubItems.Add("Not songs")
    ListView3.Items.Add(lvi)
Else

    ListView3.Columns.Add("Cover", 100, HorizontalAlignment.Left)
    ListView3.Columns.Add("Title", 145, HorizontalAlignment.Left) '163
    ListView3.Columns.Add("Views", 145, HorizontalAlignment.Left) '163
    Dim di As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\")
    Dim fiArr As FileInfo() = di.GetFiles()
    Dim fri As FileInfo

    Dim imgList As New ImageList

    ListView3.AllowColumnReorder = True
    ListView3.Columns(1).DisplayIndex = 1
    imgList.ImageSize = New Size(70, 70)
    ListView3.SmallImageList = imgList
    Dim index As Integer = 0

    For Each fri In fiArr
        Dim Covername As String = My.Computer.FileSystem.CurrentDirectory & "\Files\Covers\" & Inireader.WertLesen("Details", "ID", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
        Dim Trackname As String = Inireader.WertLesen("Details", "TrackName", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)
        Dim Views As String = Inireader.WertLesen("Details", "Views", My.Computer.FileSystem.CurrentDirectory & "\Files\Songs\" & fri.Name)

           imgList.Images.Add("Cover", Image.FromFile(Covername & ".jpg"))

        Dim lvi As New ListViewItem
        lvi.ImageIndex = index

        'Increase the index
        index += 1

        lvi.SubItems.Add(Trackname)
        lvi.SubItems.Add(Views)
        ListView3.Items.Add(lvi)
    Next fri
End If


问:
consuming a weblogic datasource options in a web application
I have a web application with plain old JDBC being used .
Using weblogic 12c and Java 1.7

Have configured a Generic datasource in weblogic.

For now I am deploying it as a WAR - in future I would need to deploy it as an EAR.

So here are the three options I tried :
Have configured 4 JNDI names for this datasource : 'abc' 'lmn' 'pqr' 'xyz'

1

```<code>public static DataSource dataSource1 = null;
Context initContext1 = new InitialContext();
dataSource1 = (DataSource)initContext1.lookup("abc");
</code>```

This works.

2

```<code>Defined the datasource in web.xml:

<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>lmn</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
</code>```

In java code:

```<code> public static DataSource dataSource2 = null;
 Context initContext2 = new InitialContext();
 dataSource2 = (DataSource)initContext2.lookup("lmn");
</code>```

This also works fine

3

```<code>@Resource(name = "pqr")
public static DataSource dataSource3 = null;

conn = dataSource3.getConnection();
</code>```

This does NOT work .

Not sure what is wrong here ?
also what is the better option to use ?

Will test with an EAR file separately and test a second question around it.

答:
With

```<code>@Resource(mappedName="pqr")
</code>```

it works on my weblogic.

See SO: Mapped name

Body:
I have a web application with plain old JDBC being used .
Using weblogic 12c and Java 1.7

Have configured a Generic datasource in weblogic.

For now I am deploying it as a WAR - in future I would need to deploy it as an EAR.

So here are the three options I tried :
Have configured 4 JNDI names for this datasource : 'abc' 'lmn' 'pqr' 'xyz'

1

public static DataSource dataSource1 = null;
Context initContext1 = new InitialContext();
dataSource1 = (DataSource)initContext1.lookup("abc");

This works.

2

Defined the datasource in web.xml:

<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>lmn</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

In java code:

 public static DataSource dataSource2 = null;
 Context initContext2 = new InitialContext();
 dataSource2 = (DataSource)initContext2.lookup("lmn");

This also works fine

3

@Resource(name = "pqr")
public static DataSource dataSource3 = null;

conn = dataSource3.getConnection();

This does NOT work .

Not sure what is wrong here ?
also what is the better option to use ?

Will test with an EAR file separately and test a second question around it.

Body:
With

@Resource(mappedName="pqr")

it works on my weblogic.

See SO: Mapped name


问:
Cannot play sound in iOS Safari
I cannot play sound in iOS Safari. I've looked into similar issues on StackOverflow, most suggested that it could only work with user interactions(onclick, ontouchstart, etc.). But my code doesn't work even if the playing is initiated by onclick. Here is my code.

  <button onclick="playSound()">Play Sound</button>

```

The above code works in desktop browsers but failed in iOS Safari. Why? I'm using iOS 12.0.1

答: As @obscure suggested in the comment, iOS Safari doesn't work with wav files by default. I converted all the wav files to mp3 and it works now.</p>

Title: Cannot play sound in iOS Safari

Body:
I cannot play sound in iOS Safari. I've looked into similar issues on StackOverflow, most suggested that it could only work with user interactions(onclick, ontouchstart, etc.). But my code doesn't work even if the playing is initiated by onclick. Here is my code.

  <button onclick="playSound()">Play Sound</button>

The above code works in desktop browsers but failed in iOS Safari. Why? I'm using iOS 12.0.1


问:
How to handle two different times if they are not in the same day?
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .</p>

```<code>   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

</code>```

答:
What I do for such problems is actually say that the restaurant is open twice. Once from 00:00 to 01:00 and once from 09:00 to 00:00. This way, if the time validates either of those intervals, the restaurant must be open.

This approach is very similar to how you would handle, for example, lunch breaks where a store or restaurant is closed between 12:00 and 14:00 in the afternoon.

Body:
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .

   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }


问:
How to sample from delayed geometric distribution in matlab
What is the best and correct way to sample from a delayed geometric distribution (geometric distribution for positive integers greater 0) in matlab?

To my understanding the delayed geometric distribution is defined as follows, where f is the probability mass function:

```<code>f(k)= (1-p)*p^(k-1) for k=1,2,3... and 0<p<1
</code>```

My current approach to sample from that distribution is to first solve for k and defining a function that returns a random value:

```<code>function k = georndDel(p)
    f = rand;
    k = log(-(f*p)./(p-1))./log(p); %for log(p)<>0, 0<p<1
end
</code>```

However, this returns a continuous value, sometimes negative, where I require only positive integers to be returned.

Is there amn obvious error in inverting the probability mass function? And how do I restrict the random values to positive ingegers?

答:
You can generate the numbers manually:

```<code>cdf_val = rand();

k = log(1-cdf_val)/log(1-p);
k = round(k+0.5);
</code>```

Or as Luis already mentioned using the geornd() plus 1.

Here is an example:

```<code>p = 0.1;

n = 20000;

arr1=zeros(n, 1);
arr2=zeros(n, 1);

for i=1:n
    % manual approach
    cdf_val = rand();

    k = log(1-cdf_val)/log(1-p);
    arr1(i) = round(k+0.5);

    % using geornd
    arr2(i) = geornd(p)+1;
end

histogram(arr1, 0:60);
hold on;
histogram(arr2, 0:60);
hold off;
legend('manual', 'geornd+1')
</code>```

Body:
What is the best and correct way to sample from a delayed geometric distribution (geometric distribution for positive integers greater 0) in matlab?

To my understanding the delayed geometric distribution is defined as follows, where f is the probability mass function:

f(k)= (1-p)*p^(k-1) for k=1,2,3... and 0<p<1

My current approach to sample from that distribution is to first solve for k and defining a function that returns a random value:

function k = georndDel(p)
    f = rand;
    k = log(-(f*p)./(p-1))./log(p); %for log(p)<>0, 0<p<1
end

However, this returns a continuous value, sometimes negative, where I require only positive integers to be returned.

Is there amn obvious error in inverting the probability mass function? And how do I restrict the random values to positive ingegers?

Body:
You can generate the numbers manually:

cdf_val = rand();

k = log(1-cdf_val)/log(1-p);
k = round(k+0.5);

Or as Luis already mentioned using the geornd() plus 1.

Here is an example:

p = 0.1;

n = 20000;

arr1=zeros(n, 1);
arr2=zeros(n, 1);

for i=1:n
    % manual approach
    cdf_val = rand();

    k = log(1-cdf_val)/log(1-p);
    arr1(i) = round(k+0.5);

    % using geornd
    arr2(i) = geornd(p)+1;
end

histogram(arr1, 0:60);
hold on;
histogram(arr2, 0:60);
hold off;
legend('manual', 'geornd+1')


答:
If you reverse the elements you can use the adjacent sibling selector button:active + input to select the input styles while the button is being pressed. However to re-align things you will need to use a container and grid (or I'm sure you can pull this off with flex or just floats)

CSS Grid: https://developer.mozilla.org/en-US/docs/Web/CSS/grid

Adjacent Sibling Selector: https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

button:active + input,
input:focus {
 border: 1px solid red;
 outline: none;
}

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
.container input {
  order: 1;
}
.container button {
  order: 2;
}</code>```

  <button>Increment</button>
  <input type="text">

```

Body:
I'm trying to build a custom input number. The only problem I have is that when I click on the button multiple times (increment), I'm getting a flickered input border.

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus {
 border: 1px solid red;
 outline: none;
}

<input type="text">

<button>Increment</button>

There is a way to getting around it?

Body:
If you reverse the elements you can use the adjacent sibling selector button:active + input to select the input styles while the button is being pressed. However to re-align things you will need to use a container and grid (or I'm sure you can pull this off with flex or just floats)

CSS Grid: https://developer.mozilla.org/en-US/docs/Web/CSS/grid

Adjacent Sibling Selector: https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

button:active + input,
input:focus {
 border: 1px solid red;
 outline: none;
}

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
.container input {
  order: 1;
}
.container button {
  order: 2;
}

<div class='container'>
  <button>Increment</button>
  <input type="text">
</div>


问:
Google Ads : tracking events
I'm little confused with Google services.
I want to track conversion events.

I've already configured the script like that :

```<code><!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
</code>```

My Google Tag Manager account is configured with deux services : Analytics and Ads

I've configured conversion event on Google Ads and I try to push it through Javascript calls, but maybe I'm wrong somewhere.

Here is my Javascript code :

```<code>gtag('send', <event_action>, {
  'event_category': <event_category>,
  'event_label': <event_label>,
  'value': <event_value
});
</code>```

At the end of the day, I have no conversion on my dashboard on Google Ads.

Can someone helps with to figure out what's wrong ?

答:
Do you also include the gtag.js?</p>

```<code><script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>
</code>```

Title: Google Ads : tracking events

Body:
I'm little confused with Google services.
I want to track conversion events.

I've already configured the script like that :

My Google Tag Manager account is configured with deux services : Analytics and Ads

I've configured conversion event on Google Ads and I try to push it through Javascript calls, but maybe I'm wrong somewhere.

Here is my Javascript code :

gtag('send', <event_action>, {
  'event_category': <event_category>,
  'event_label': <event_label>,
  'value': <event_value
});

At the end of the day, I have no conversion on my dashboard on Google Ads.

Can someone helps with to figure out what's wrong ?

Body:
Do you also include the gtag.js?

<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>


问:
How to convert JSON data into table and store into Postgres DB using Node JS?
I need help in converting json data into datatable and store inside postgresql DB.

For example,

```<code>[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]
</code>```

I'd like to convert the above data or lets say store the data as a table with rows and columns.

I think we do have a datatype called "json" but it's to store the entire json right? But I want to convert as real table what we see in DB, like below,

```<code>   name   |  role
--------------+-------
"abc"     | "swe"
"xyz"     | "Tester
</code>```

Could you please help me how to parse them please? I'm using Node JS.

Any pointers will be helpful. Thanks a lot for your time.

答:
I think it will work, convert your json into object and prepare and insert it  using npm package node-postgres(np) and node-sql(sql || sql string builder for node), Take reference from the following the code.

```<code>const pg = require('pg');
const sql = require('sql');

let usersToInsert = JSON.parse(`[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]`);

let User = sql.define({
  name: 'users',
  columns: [
    'name',
    'role'
  ]
});

async function run() {
  let client;
  try {
    client = new pg.Client({
      connectionString: 'postgresql://localhost/node_example'
    });
    await client.connect();
    let query = User.insert(usersToInsert).toQuery();
    console.log(query);
    let {rows} = await client.query(query);
    console.log(rows);
  } catch (e) {
    console.error(e);
  } finally {
    client.end();
  }
}

run();
</code>```

Body:
I need help in converting json data into datatable and store inside postgresql DB.

For example,

[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]

I'd like to convert the above data or lets say store the data as a table with rows and columns.

I think we do have a datatype called "json" but it's to store the entire json right? But I want to convert as real table what we see in DB, like below,

   name   |  role
--------------+-------
"abc"     | "swe"
"xyz"     | "Tester

Could you please help me how to parse them please? I'm using Node JS.

Any pointers will be helpful. Thanks a lot for your time.

Body:
I think it will work, convert your json into object and prepare and insert it  using npm package node-postgres(np) and node-sql(sql || sql string builder for node), Take reference from the following the code.

const pg = require('pg');
const sql = require('sql');

let usersToInsert = JSON.parse(`[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]`);

let User = sql.define({
  name: 'users',
  columns: [
    'name',
    'role'
  ]
});

async function run() {
  let client;
  try {
    client = new pg.Client({
      connectionString: 'postgresql://localhost/node_example'
    });
    await client.connect();
    let query = User.insert(usersToInsert).toQuery();
    console.log(query);
    let {rows} = await client.query(query);
    console.log(rows);
  } catch (e) {
    console.error(e);
  } finally {
    client.end();
  }
}

run();


问:
Argument passing in R to functions of several real variables
I'm a newcomer to R and need to solve a multi-objective optimization problem (MOOP). I've imported the mco package, defined my functions and checked the nsga2 function. The thing is that I have not found the proper way to bind the parameters in the function definitions (formal parameters) and those in the invocations (actual parameters) when the former match with a numeric variable.

I have the following code:

```<code>funct_set <- function (x1,x2,x3) {
  f <- numeric(2)
  f[1] <- min(-5*x1 - 2*x2 - 8*x3)
  f[2] <- min(1000*x1 + 8000*x2 + 12000*x3)
  return (f);
}

restrictions <- function (x1,x2,x3) {
  restrictions <- numeric(3)
  restrictions[1] <- (x1 + x2 + x3 <= 30)
  restrictions[2] <- (x1 + x2 + x3 > 0)
  restrictions[3] <- (2*x1 + 3*x2 + 1.5*x3 <= 45)
  return (restrictions);
}

optimization <- nsga2(funct_set('x1', 'x2', 'x3'),
                      constraints = restrictions('x1', 'x2', 'x3'),
                      2, 2,
                      NULL,
                      generations=150,
                      popsize=100,
                      cprob=0.7,
                      cdist=20,
                      mprob=0.2,
                      mdist=20,
                      lower.bounds=rep(-5, 2),
                      upper.bounds=rep(10, 2)
                      );
</code>```

However, this led to R considering that 'x1','x2' and 'x3' are not numbers:
Error in x1 + x2 : non-numeric argument to binary operator

What is the correct way to pass those parameters?

答:
Several problems with your code:

the function to be minimized and the constraints function must take a vector as argument, and you just have to pass their names in nsga2

you have to set idim to 3, the number of parameters

lower.bounds and upper.bounds must have length idim

you have to set cdim to 3, the number of constraints

I don't know why you set a NULL argument

Below is the corrected code, it works.

```<code>library(mco)

funct_set <- function (x) {
  x1 <- x[1]; x2 <- x[2]; x3 <- x[3]
  f <- numeric(2)
  f[1] <- min(-5*x1 - 2*x2 - 8*x3)
  f[2] <- min(1000*x1 + 8000*x2 + 12000*x3)
  return (f);
}

restrictions <- function (x) {
  x1 <- x[1]; x2 <- x[2]; x3 <- x[3]
  restrictions <- logical(3)
  restrictions[1] <- (x1 + x2 + x3 <= 30)
  restrictions[2] <- (x1 + x2 + x3 > 0)
  restrictions[3] <- (2*x1 + 3*x2 + 1.5*x3 <= 45)
  return (restrictions);
}

optimization <- nsga2(funct_set, idim = 3, odim = 2,
                      constraints = restrictions, cdim = 3,
                      generations=150,
                      popsize=100,
                      cprob=0.7,
                      cdist=20,
                      mprob=0.2,
                      mdist=20,
                      lower.bounds=rep(-5, 3),
                      upper.bounds=rep(10, 3)
)
</code>```

Body:
I'm a newcomer to R and need to solve a multi-objective optimization problem (MOOP). I've imported the mco package, defined my functions and checked the nsga2 function. The thing is that I have not found the proper way to bind the parameters in the function definitions (formal parameters) and those in the invocations (actual parameters) when the former match with a numeric variable.

I have the following code:

funct_set <- function (x1,x2,x3) {
  f <- numeric(2)
  f[1] <- min(-5*x1 - 2*x2 - 8*x3)
  f[2] <- min(1000*x1 + 8000*x2 + 12000*x3)
  return (f);
}

restrictions <- function (x1,x2,x3) {
  restrictions <- numeric(3)
  restrictions[1] <- (x1 + x2 + x3 <= 30)
  restrictions[2] <- (x1 + x2 + x3 > 0)
  restrictions[3] <- (2*x1 + 3*x2 + 1.5*x3 <= 45)
  return (restrictions);
}

optimization <- nsga2(funct_set('x1', 'x2', 'x3'),
                      constraints = restrictions('x1', 'x2', 'x3'),
                      2, 2,
                      NULL,
                      generations=150,
                      popsize=100,
                      cprob=0.7,
                      cdist=20,
                      mprob=0.2,
                      mdist=20,
                      lower.bounds=rep(-5, 2),
                      upper.bounds=rep(10, 2)
                      );

However, this led to R considering that 'x1','x2' and 'x3' are not numbers:
Error in x1 + x2 : non-numeric argument to binary operator

What is the correct way to pass those parameters?

Body:
Several problems with your code:

the function to be minimized and the constraints function must take a vector as argument, and you just have to pass their names in nsga2

you have to set idim to 3, the number of parameters

lower.bounds and upper.bounds must have length idim

you have to set cdim to 3, the number of constraints

I don't know why you set a NULL argument

Below is the corrected code, it works.

library(mco)

funct_set <- function (x) {
  x1 <- x[1]; x2 <- x[2]; x3 <- x[3]
  f <- numeric(2)
  f[1] <- min(-5*x1 - 2*x2 - 8*x3)
  f[2] <- min(1000*x1 + 8000*x2 + 12000*x3)
  return (f);
}

restrictions <- function (x) {
  x1 <- x[1]; x2 <- x[2]; x3 <- x[3]
  restrictions <- logical(3)
  restrictions[1] <- (x1 + x2 + x3 <= 30)
  restrictions[2] <- (x1 + x2 + x3 > 0)
  restrictions[3] <- (2*x1 + 3*x2 + 1.5*x3 <= 45)
  return (restrictions);
}

optimization <- nsga2(funct_set, idim = 3, odim = 2,
                      constraints = restrictions, cdim = 3,
                      generations=150,
                      popsize=100,
                      cprob=0.7,
                      cdist=20,
                      mprob=0.2,
                      mdist=20,
                      lower.bounds=rep(-5, 3),
                      upper.bounds=rep(10, 3)
)


问:
repeating input
I want to program it like that so while taking input of num1,num2 and operation if user doesn't give input in appropriate type it ask the user again for input.</p>

```<code>operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if operation == "add" or operation == '1' :
   print(num1,"+",num2,"=", (num1+num2))
elif operation =="subtract" or operation == '2':
   print(num1,"-",num2,"=", (num1-num2))
elif operation =="multiply" or operation == '3':
   print(num1,"*",num2,"=", (num1*num2))
elif operation =="divide" or operation == '4':
   print(num1,"/",num2,"=", (num1/num2))
</code>```

答:
You can use in keyword.

Ex:

```<code>>>> "1" in ["1","add"]
True
>>> "add" in ["1","add"]
True
</code>```

Modify code like:

```<code> operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if operation in ["1","add"] :
       print(num1,"+",num2,"=", (num1+num2))
    elif operationi in ["2", "subtract"]:
       print(num1,"-",num2,"=", (num1-num2))
    elif operation in ["3", "multiply"]:
       print(num1,"*",num2,"=", (num1*num2))
    elif operation in ["4", "divide"]:
       print(num1,"/",num2,"=", (num1/num2))
    else:
        print("Invalid Input")
</code>```

Title: repeating input

Body:
I want to program it like that so while taking input of num1,num2 and operation if user doesn't give input in appropriate type it ask the user again for input.

operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if operation == "add" or operation == '1' :
   print(num1,"+",num2,"=", (num1+num2))
elif operation =="subtract" or operation == '2':
   print(num1,"-",num2,"=", (num1-num2))
elif operation =="multiply" or operation == '3':
   print(num1,"*",num2,"=", (num1*num2))
elif operation =="divide" or operation == '4':
   print(num1,"/",num2,"=", (num1/num2))

Body:
You can use in keyword.

Ex:

>>> "1" in ["1","add"]
True
>>> "add" in ["1","add"]
True

Modify code like:

 operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if operation in ["1","add"] :
       print(num1,"+",num2,"=", (num1+num2))
    elif operationi in ["2", "subtract"]:
       print(num1,"-",num2,"=", (num1-num2))
    elif operation in ["3", "multiply"]:
       print(num1,"*",num2,"=", (num1*num2))
    elif operation in ["4", "divide"]:
       print(num1,"/",num2,"=", (num1/num2))
    else:
        print("Invalid Input")


答:
Try this,

```<code> operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if operation == "1" or operation == "add" :
       print(num1,"+",num2,"=", (num1+num2))
    elif operation == "2" or operation == "subtract":
       print(num1,"-",num2,"=", (num1-num2))
    elif operation == "3" or operation == "multiply":
       print(num1,"*",num2,"=", (num1*num2))
    elif operation == "4" or operation == "divide":
       print(num1,"/",num2,"=", (num1/num2))
    else:
        print("Invalid Input")
</code>```

Explanation:

In your code, IF will check condition-1 or condition-2 are True or False

```<code>if operation == "1" or operation == "add"
</code>```

here,

condition-1: operation == "1"

condition-2: operation == "add"

```<code>if operation == "1" or operation == "add"
</code>```

here,

condition-1: operation == "1"

condition-2: "add"  # Always True as string contains elements.

Title: repeating input

Body:
Try this,

 operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if operation == "1" or operation == "add" :
       print(num1,"+",num2,"=", (num1+num2))
    elif operation == "2" or operation == "subtract":
       print(num1,"-",num2,"=", (num1-num2))
    elif operation == "3" or operation == "multiply":
       print(num1,"*",num2,"=", (num1*num2))
    elif operation == "4" or operation == "divide":
       print(num1,"/",num2,"=", (num1/num2))
    else:
        print("Invalid Input")

Explanation:

In your code, IF will check condition-1 or condition-2 are True or False

if operation == "1" or operation == "add"

here,

condition-1: operation == "1"

condition-2: operation == "add"

if operation == "1" or operation == "add"

here,

condition-1: operation == "1"

condition-2: "add"  # Always True as string contains elements.


问:
Cannot step into .NET framework source with VS2008 SP1
Somehow my VS2008 SP1 has lost the ability to step into .NET framework sources. I've played around with checkboxes to no end; I've re-deleted the Symbol cache folder a dozen times; and I've tried all kinds of debug symbol servers.

All it does is download some .PDB files, but when I try to select a stack frame in .NET, I always get the message about no source available and "do you want to view disassembly".

What gives?

Added: Web application; Windows Vista Business x32; .NET 3.5 SP1.

答:
I believe your problem is a mismatched version of .Net running on your System compared to the image version in the pdb that downloads from the symbol server.  I've had the same problem on 64 bit Vista and Win7.  I have yet to find a reference for how to get the assembly to 2.0.5.xxxx as indicated in the instructions.  SP1 with all service packs on the two OSs I indacated are show the assemblies at 2.0.0.xxxx

EDIT: Start debugging any app you have and Hit CTRL+ALT+U to get the module list.  It shows which assembly in the GAC is being used for the application

I blogged what I think is a better description of the problem.
Blog of problem

OwnerDisplayName: Vilx-

LastEditorDisplayName: moocha

OwnerDisplayName: jmcecil

LastEditorDisplayName: jmcecil