问:
Error check user input with integers in C
I am trying to take RGB codes entered by a user in the format #1, #2, #3. I error check the input to make sure it matches the ', ' format and can extract the numbers from the string. However, I am having trouble checking if the input is a number after that.

Ex: If the user enters: 255, 0, 0f the program still runs.

Any help would be appreciated!

```<code>char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);

//function to error check ', ' format

int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);
</code>```

I just need to check if these are in fact integers

答:
Ok. So you need to check if the input values inside the character array input are in fact numbers before putting them in c1, c2 and c3 integer variables. Good idea.

There is a function in C which helps you do that unless you want to write your own one (Which I will not venture into here but you may want to research the Ascii table if this appeals to you). It is called isdigit and you can learn more about it here: https://www.tutorialspoint.com/c_standard_library/c_function_isdigit.htm. It has the following form int isdigit (int c) and it returns a non-zero value if the argument passed is a digit. You can pass it the character value inside the input array as for example isdigit(input[x]);
where x is the position of the character in the character array input. Hope this helps.

Body:
I am trying to take RGB codes entered by a user in the format #1, #2, #3. I error check the input to make sure it matches the ', ' format and can extract the numbers from the string. However, I am having trouble checking if the input is a number after that.

Ex: If the user enters: 255, 0, 0f the program still runs.

Any help would be appreciated!

char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);

//function to error check ', ' format

int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);

I just need to check if these are in fact integers


来源: stackexchange

问:
Changing exists rule based on choosen option
So i have this simple code to input value based on database value in registration form and it's work great,

The code below located at register.blade.php

This for selecting branch

```<code><div class="form-group form-material floating">
  <select class="form-control" name="branch" id="branch">
      <option value="1">Option A</option>
      <option value="2">Option B</option>
  </select>
  <label class="floating-label" for="inputStatus">Branch</label>
</div>
</code>```

This one for inputing reference

```<code><div class="form-group form-material floating {{ $errors->has('reference') ? ' has-error' : '' }}">
        <input type="text" class="form-control empty" id="reference" name="reference">
          <label class="floating-label" for="inputStatus">Reference</label>
          @if ($errors->has('reference'))
              <span class="help-block">
                  <strong>{{ $errors->first('reference') }}</strong>
              </span>
          @endif
      </div>
</code>```

the code below located atRegisterController.php

And this one for validation

```<code>protected function validator(array $data)
 {

 return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'phone' => 'required|string|min:5|max:20',
'rate' => 'required',
'product' => 'required',
'branch' => 'required',
'reference' => [
    'required',
        Rule::exists('references')->where(function ($query) {
            if( 'branch' == 1 ){
                $query->where('references.type', '=', "TOP");
            }
            else{
                $query->where('references.type', '=', "BOTTOM");
            }
        }),
    ],
   ]
  );
 }
</code>```

In registration form when user choose the first option on branch, the user can only write (Example : 'ABC', 'DEF', 'GHI') if the user write another value it will return Error Message : 'Wrong reference code', but when the user choose second option on branch, the user can only write (Example : '123', '456', '789'), , does anyone have and idea how to do it? Thanks

Edit 1 :
The code above works fine, but the exists rule for reference is not working, user still able to input 'ABC', 'DEF', or 'GHI' when choosing second option.

Edit 2 :
I also have this custom validation inside register.blade.php

```<code>fields: {
        reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Max 8 character'
                }
            }
        }
    }
</code>```

答:
You can make custom validation. So you can move this extra validation inside your custom validation. May be it can solve your problem.

Refer this for more on custom validation: Laravel custom validation

Hope it helps:)

ContentLicense: CC BY-SA 4.0

Body:
So i have this simple code to input value based on database value in registration form and it's work great,

The code below located at register.blade.php

This for selecting branch

  <select class="form-control" name="branch" id="branch">
      <option value="1">Option A</option>
      <option value="2">Option B</option>
  </select>
  Branch

This one for inputing reference

has('reference') ? ' has-error' : '' }}">
        <input type="text" class="form-control empty" id="reference" name="reference">
          Reference
          @if ($errors->has('reference'))

                  {{ $errors->first('reference') }}

          @endif

the code below located atRegisterController.php

And this one for validation

protected function validator(array $data)
 {

 return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'phone' => 'required|string|min:5|max:20',
'rate' => 'required',
'product' => 'required',
'branch' => 'required',
'reference' => [
    'required',
        Rule::exists('references')->where(function ($query) {
            if( 'branch' == 1 ){
                $query->where('references.type', '=', "TOP");
            }
            else{
                $query->where('references.type', '=', "BOTTOM");
            }
        }),
    ],
   ]
  );
 }

In registration form when user choose the first option on branch, the user can only write (Example : 'ABC', 'DEF', 'GHI') if the user write another value it will return Error Message : 'Wrong reference code', but when the user choose second option on branch, the user can only write (Example : '123', '456', '789'), , does anyone have and idea how to do it? Thanks

Edit 1 :
The code above works fine, but the exists rule for reference is not working, user still able to input 'ABC', 'DEF', or 'GHI' when choosing second option.

Edit 2 :
I also have this custom validation inside register.blade.php

fields: {
        reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Max 8 character'
                }
            }
        }
    }


问:
How to create an object based on filtering two arrays with a filter criteria from one array in Javascript/ES6?
Let's assume I have two arrays of the same length:

```<code>const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];
</code>```

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

```<code>const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}
</code>```

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

```<code>let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};
</code>```

How can I achieve this with a minimal number of code lines?

答:
Use lodash zipObject utility
Here is a reference: https://lodash.com/docs/4.17.15#zipObject</p>

Body:
Let's assume I have two arrays of the same length:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};

How can I achieve this with a minimal number of code lines?


问:
JavaScript `reduce` performance
I've spent some time recently plying around with transducers (tool in functional programming meant to improve performance without losing readability/flexibility of code) and when I came to testing their actual speed, I got some quite disappointing results. Consider:

const inc = x => x + 1;

const isEven = x => x % 2 === 0;

// simplest, shortest way I would be comfortable with if performance wasn't an issue

const mapFilter = xs => xs.filter(isEven).map(inc);

// transducers way

// function composition
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);

const map = f => step => (a, c) => step(a, f(c));
const filter = p => step => (a, c) => (p(c) ? step(a, c) : a);

// basic reducer for building array
const build = (acc, x) => {
  acc.push(x);
  return acc;
};

// transducer, it doesn't create intermediate arrays hence should theoretically be faster
const transducers = xs =>
  xs.reduce(compose(filter(isEven), map(inc))(build), []);

// native loop for comparison
const nativeLoop = data => {
  const result = [];
  const l = data.length;
  for (let i = 0; i < l; i++) {
    const x = data[i];
    if (isEven(x)) result.push(inc(x));
  }
  return result;
};

const data = Array(1000).fill(1);

const base = ["simplest, chained map and filter", () => mapFilter(data)];
const alternative = ["composed transducers", () => transducers(data)];
const alternative2 = ["native loop", () => nativeLoop(data)];

/* console.log(Benchmark) */
console.log("Running benchmarks....");

const suite = new Benchmark.Suite();
suite
  .add(...base)
  .add(...alternative)
  .add(...alternative2)
  .on("cycle", function(event) {
  console.log(String(event.target));
})
  .on("complete", function() {
  console.log("Fastest is " + this.filter("fastest").map("name").join(", "));
})
// run async
  .run({ async: true });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script></code>```

I would expect that the order of performance will be

native loop > transducers > chained map/filter

Meanwhile, besides native approach which is way faster than any other, it turned out, to my great astonishment, that reduce/transduce way is much slower than using map/filter and creating intermediate arrays (slower, like an order of magnitude in Chrome). Could someone explain to me the origin of this result?

答:
Your benchmark is wrong because you're building a new transducer chain on each run.

const inc = x => x + 1;

const isEven = x => x % 2 === 0;

// simplest, shortest way I would be comfortable with if performance wasn't an issue

const mapFilter = xs => xs.filter(isEven).map(inc);

// transducers way

// function composition
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);

const map = f => step => (a, c) => step(a, f(c));
const filter = p => step => (a, c) => (p(c) ? step(a, c) : a);

// basic reducer for building array
const build = (acc, x) => {
  acc.push(x);
  return acc;
};

// transducer, it doesn't create intermediate arrays hence should theoretically be faster
const reducer = compose(filter(isEven), map(inc))(build);
const transducers = xs => xs.reduce(reducer, []);

// native loop for comparison
const nativeLoop = data => {
  const result = [];
  const l = data.length;
  for (let i = 0; i < l; i++) {
    const x = data[i];
    if (isEven(x)) result.push(inc(x));
  }
  return result;
};

const data = Array(1000).fill(1);

const base = ["simplest, chained map and filter", () => mapFilter(data)];
const alternative = ["composed transducers", () => transducers(data)];
const alternative2 = ["native loop", () => nativeLoop(data)];

/* console.log(Benchmark) */
console.log("Running benchmarks....");

const suite = new Benchmark.Suite();
suite
  .add(...base)
  .add(...alternative)
  .add(...alternative2)
  .on("cycle", function(event) {
  console.log(String(event.target));
})
  .on("complete", function() {
  console.log("Fastest is " + this.filter("fastest").map("name").join(", "));
})
// run async
  .run({ async: true });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script></code>```

As you can see, transducers are indeed faster than chained map and filter methods.

Title: JavaScript `reduce` performance

Body:
I've spent some time recently plying around with transducers (tool in functional programming meant to improve performance without losing readability/flexibility of code) and when I came to testing their actual speed, I got some quite disappointing results. Consider:

const inc = x => x + 1;

const isEven = x => x % 2 === 0;

// simplest, shortest way I would be comfortable with if performance wasn't an issue

const mapFilter = xs => xs.filter(isEven).map(inc);

// transducers way

// function composition
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);

const map = f => step => (a, c) => step(a, f(c));
const filter = p => step => (a, c) => (p(c) ? step(a, c) : a);

// basic reducer for building array
const build = (acc, x) => {
  acc.push(x);
  return acc;
};

// transducer, it doesn't create intermediate arrays hence should theoretically be faster
const transducers = xs =>
  xs.reduce(compose(filter(isEven), map(inc))(build), []);

// native loop for comparison
const nativeLoop = data => {
  const result = [];
  const l = data.length;
  for (let i = 0; i < l; i++) {
    const x = data[i];
    if (isEven(x)) result.push(inc(x));
  }
  return result;
};

const data = Array(1000).fill(1);

const base = ["simplest, chained map and filter", () => mapFilter(data)];
const alternative = ["composed transducers", () => transducers(data)];
const alternative2 = ["native loop", () => nativeLoop(data)];

/* console.log(Benchmark) */
console.log("Running benchmarks....");

const suite = new Benchmark.Suite();
suite
  .add(...base)
  .add(...alternative)
  .add(...alternative2)
  .on("cycle", function(event) {
  console.log(String(event.target));
})
  .on("complete", function() {
  console.log("Fastest is " + this.filter("fastest").map("name").join(", "));
})
// run async
  .run({ async: true });

I would expect that the order of performance will be

native loop > transducers > chained map/filter

Meanwhile, besides native approach which is way faster than any other, it turned out, to my great astonishment, that reduce/transduce way is much slower than using map/filter and creating intermediate arrays (slower, like an order of magnitude in Chrome). Could someone explain to me the origin of this result?

Body:
Your benchmark is wrong because you're building a new transducer chain on each run.

const inc = x => x + 1;

const isEven = x => x % 2 === 0;

// simplest, shortest way I would be comfortable with if performance wasn't an issue

const mapFilter = xs => xs.filter(isEven).map(inc);

// transducers way

// function composition
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);

const map = f => step => (a, c) => step(a, f(c));
const filter = p => step => (a, c) => (p(c) ? step(a, c) : a);

// basic reducer for building array
const build = (acc, x) => {
  acc.push(x);
  return acc;
};

// transducer, it doesn't create intermediate arrays hence should theoretically be faster
const reducer = compose(filter(isEven), map(inc))(build);
const transducers = xs => xs.reduce(reducer, []);

// native loop for comparison
const nativeLoop = data => {
  const result = [];
  const l = data.length;
  for (let i = 0; i < l; i++) {
    const x = data[i];
    if (isEven(x)) result.push(inc(x));
  }
  return result;
};

const data = Array(1000).fill(1);

const base = ["simplest, chained map and filter", () => mapFilter(data)];
const alternative = ["composed transducers", () => transducers(data)];
const alternative2 = ["native loop", () => nativeLoop(data)];

/* console.log(Benchmark) */
console.log("Running benchmarks....");

const suite = new Benchmark.Suite();
suite
  .add(...base)
  .add(...alternative)
  .add(...alternative2)
  .on("cycle", function(event) {
  console.log(String(event.target));
})
  .on("complete", function() {
  console.log("Fastest is " + this.filter("fastest").map("name").join(", "));
})
// run async
  .run({ async: true });

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script>

As you can see, transducers are indeed faster than chained map and filter methods.


问:
How to evenly distributed margin with flex?

I want to display the UI as the picture, and I use a loop to creat the div , so I think flex is the most convince way to do it . each row displays four elements and I want set the margin(top left right bottom) of each flex-item the same 10px. I tried justify-content:space-between / space-around. and neither of these is what I want.

class App extends Component {
  constructor() {
    super();
    this.arr = [1, 2, 3, 4, 5];
  }

  createDiv = () => {
    // return  div className="child" />
  };

  render() {
    return (

        {this.arr.map((item, index) => (

        ))}

    );
  }
}

```

<pre class="lang-css prettyprint-override"><code>.contianer{
   /* width: calc(100%-20px); */
  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between
  /* flex:1; */
}

.child{
  background-color: yellow;
  width: calc((100% - 50px) / 4);
  height: 100px;
  margin: 10px 5px

}
</code>```

online demo : https://stackblitz.com/edit/react-fapbff

so it's there a way to achive what I want?

答:
Here is an example for this. You can try this code. It is fully tested. I hope it will help you.

CSS:

```<code>.contianer {
  display: grid;
  background-color:red;
  grid-column-gap: 10px;
  grid-template-columns: auto auto auto auto;
  grid-row-gap: 10px;
  padding: 10px;
}
.child {
  background-color: yellow;
  height: 100px;
}
</code>```

By using grid, you can achieve this. I tested this code in your demo "https://stackblitz.com/edit/react-fapbff". It is working fine.

Body:
I want to display the UI as the picture, and I use a loop to creat the div , so I think flex is the most convince way to do it . each row displays four elements and I want set the margin(top left right bottom) of each flex-item the same 10px. I tried justify-content:space-between / space-around. and neither of these is what I want.

class App extends Component {
  constructor() {
    super();
    this.arr = [1, 2, 3, 4, 5];
  }

  createDiv = () => {
    // return  div className="child" />
  };

  render() {
    return (

        {this.arr.map((item, index) => (

        ))}

    );
  }
}

.contianer{
   /* width: calc(100%-20px); */
  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between
  /* flex:1; */
}

.child{
  background-color: yellow;
  width: calc((100% - 50px) / 4);
  height: 100px;
  margin: 10px 5px

}

online demo : https://stackblitz.com/edit/react-fapbff

so it's there a way to achive what I want?

Body:
Here is an example for this. You can try this code. It is fully tested. I hope it will help you.

CSS:

.contianer {
  display: grid;
  background-color:red;
  grid-column-gap: 10px;
  grid-template-columns: auto auto auto auto;
  grid-row-gap: 10px;
  padding: 10px;
}
.child {
  background-color: yellow;
  height: 100px;
}

By using grid, you can achieve this. I tested this code in your demo "https://stackblitz.com/edit/react-fapbff". It is working fine.


问:
How to insert href URL to Javascript var?
I am trying to create a script for autoreply in google apps and would love to have that reply to have some formatting. I've been getting a syntax error due to the quotes closing with the opening of the href tag. Is there a way to insert the URL into the html message? My scribbles below.

function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var message = "We are out of the office until Monday morning and will reply to your email then. If you are having an emergency, please text (800) 590-2508, we'll do our best to reply as soon as possible.";
  var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([6,0].indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply(message, {htmlBody: htmlMessage});
      threads[i].markRead();
      threads[i].star();
      }
    }
  }
}```
</div>
</div>
</p>

<p>The error is on line 4</p>

``` var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";
```

The quotes after htmlMessage = open the message, and the quotes after the first href= close it, so the rest of the message breaks the syntax.

Any insight on how to include the whole html under the var statement?

Thanks!

答:
Replace " from the beginning and end with tild  `

Check the documentation Here

```<code>var htmlMessage = `<p>Hi,</p><p>Thanks for your message.</p><p>We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:</p><p><a href="https://sampleurl.com" target="_blank" rel="noopener">Link text</a></p><p><a href="https://anothersammple.com" target="_blank" rel="noopener">Link text</a></p><p>If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.</p><p>Have a pleasant weekend,</p><p>My Signature</p>`;
</code>```

function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var message = "We are out of the office until Monday morning and will reply to your email then. If you are having an emergency, please text (800) 590-2508, we'll do our best to reply as soon as possible.";
  var htmlMessage = `
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
`;
  document.write(htmlMessage)
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([6,0].indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply(message, {htmlBody: htmlMessage});
      threads[i].markRead();
      threads[i].star();
      }
    }
  }
}
autoReply()```

Body:
I am trying to create a script for autoreply in google apps and would love to have that reply to have some formatting. I've been getting a syntax error due to the quotes closing with the opening of the href tag. Is there a way to insert the URL into the html message? My scribbles below.

function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var message = "We are out of the office until Monday morning and will reply to your email then. If you are having an emergency, please text (800) 590-2508, we'll do our best to reply as soon as possible.";
  var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([6,0].indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply(message, {htmlBody: htmlMessage});
      threads[i].markRead();
      threads[i].star();
      }
    }
  }
}

The error is on line 4

 var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";

The quotes after htmlMessage = open the message, and the quotes after the first href= close it, so the rest of the message breaks the syntax.

Any insight on how to include the whole html under the var statement?

Thanks!

Body:
Replace " from the beginning and end with tild  `

Check the documentation Here

var htmlMessage = `<p>Hi,</p><p>Thanks for your message.</p><p>We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:</p><p><a href="https://sampleurl.com" target="_blank" rel="noopener">Link text</a></p><p><a href="https://anothersammple.com" target="_blank" rel="noopener">Link text</a></p><p>If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.</p><p>Have a pleasant weekend,</p><p>My Signature</p>`;

function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var message = "We are out of the office until Monday morning and will reply to your email then. If you are having an emergency, please text (800) 590-2508, we'll do our best to reply as soon as possible.";
  var htmlMessage = `<p>Hi,</p><p>Thanks for your message.</p><p>We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:</p><p><a href="https://sampleurl.com" target="_blank" rel="noopener">Link text</a></p><p><a href="https://anothersammple.com" target="_blank" rel="noopener">Link text</a></p><p>If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.</p><p>Have a pleasant weekend,</p><p>My Signature</p>`;
  document.write(htmlMessage)
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([6,0].indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply(message, {htmlBody: htmlMessage});
      threads[i].markRead();
      threads[i].star();
      }
    }
  }
}
autoReply()


问:
How do I extract a certain amount of lines after a pattern in perl?
Lets say I have a text file:

```<code>Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

So far all I have is code to find the target and print it out:

```<code>use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}
</code>```

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

答:
Skip lines until you reach the target line, then output that line. Inside the loop, read the number of lines you want and output those. Here's one way to do that:</p>

```<code>while( <> ) {
    next unless /\ATarget\s+\S+/;  # skip until you find the start line
    print;                         # output the current line

    print scalar <> for 1 .. 3;    # output the next lines
    print "\n";                    # separate groups
    }
</code>```

Body:
Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

Body:
Skip lines until you reach the target line, then output that line. Inside the loop, read the number of lines you want and output those. Here's one way to do that:

while( <> ) {
    next unless /\ATarget\s+\S+/;  # skip until you find the start line
    print;                         # output the current line

    print scalar <> for 1 .. 3;    # output the next lines
    print "\n";                    # separate groups
    }


问:
changing the substr functionality with java 8 style
In the below method I am reading the invoice id and remove the first three initial characters and then after checking if it contains dollar I am also removing them. My question is if I can do the same in java 8? </p>

```<code>public static String removID(String invoiceId) {
    String deviceSerialNo = null;
    if(invoiceId != null && invoiceId.length() == 15) {
        invoiceIdSerialNo = invoiceId.substring(3);
        if(invoiceIdSerialNo.contains("$")) {
            invoiceIdSerialNo = invoiceIdSerialNo.replace("$", "");
        }
    }
    return invoiceIdSerialNo;

}
</code>```

答:
Assuming you mean "lambda expressions" when you say "Java 8 style", you can do it using Optional.

```<code>public static String shrinkDeviceID(String deviceId) {
    return Optional.ofNullable(deviceId)
            .filter(s -> s.length() == 15)
            .map(s -> s.substring(3).replace("$", ""))
            .orElse(null);
}
</code>```

Body:
In the below method I am reading the invoice id and remove the first three initial characters and then after checking if it contains dollar I am also removing them. My question is if I can do the same in java 8?

public static String removID(String invoiceId) {
    String deviceSerialNo = null;
    if(invoiceId != null && invoiceId.length() == 15) {
        invoiceIdSerialNo = invoiceId.substring(3);
        if(invoiceIdSerialNo.contains("$")) {
            invoiceIdSerialNo = invoiceIdSerialNo.replace("$", "");
        }
    }
    return invoiceIdSerialNo;

}

Body:
Assuming you mean "lambda expressions" when you say "Java 8 style", you can do it using Optional.

public static String shrinkDeviceID(String deviceId) {
    return Optional.ofNullable(deviceId)
            .filter(s -> s.length() == 15)
            .map(s -> s.substring(3).replace("$", ""))
            .orElse(null);
}


问:
Java: NullPointerException from class.getResource( ... )
I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

```<code>prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));
</code>```

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

```<code>System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);
</code>```

Prints true.

答:
As far as I know getResource() will look into locations of known resources, in other words if the folder /icons/ is not seen as a resource folder it will not as you had expected. There are two ways of going around this as far as I know:

1) Set icons folder as a resource to the application, then you can use getResource() for instance
URL css_url = getClass().getResource("/resource/style.css");

For more info on this option, see http://lj4newbies.blogspot.com/2008/03/using-classgetresource-load-resource.html

2) Get the icon as a regular file without using getResource() method. This is actually adviced in Swing tutorials on Sun/Oracle own documentation .

Generally, applications provide their own set of images used as part
  of the application, as is the case
  with the images used by many of our
  demos. You should use the Class
  getResource method to obtain the path
  to the image. This allows the
  application to verify that the image
  is available and to provide sensible
  error handling if it is not. When the
  image is not part of the application,
  getResource should not be used and the
  ImageIcon constructor is used
  directly. For example:

ImageIcon icon = new
  ImageIcon("images/middle.gif",
                                 "a pretty but meaningless splat");

Hope this helps, good luck!

ContentLicense: CC BY-SA 3.0

Body:
I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);

Prints true.


问:
mp4 Vj Animation video lagging hi res video
I am trying to get a video to play inside a video tag at the top left hand corner of my page, it loads ok, the resolution is good and it seems to be looping but it is lagging very much, definatly not achieving 60fps it is in mp4 format and the resolution on the original mp4 is 1920x1080 it is a hi resolution vj free loop called GlassVein, you can see it if you search on youtube. On right clicking properties it comes up with the following inforamtion;

Bitrate:127kbs
  Data rate:11270kbps
  Total bitrate:11398kbs
  Audio sample rate is: 44khz
  filetype is:VLC media file(.mp4)
    (but i do not want or need the audio)

& it also says 30fps, but I'm not sure i believe this as it runs smooth as butter on vlc media player no lagging, just smooth loop animation

I have searched on :https://trac.ffmpeg.org/wiki/Encode/AAC for encoding information but it is complete gobbldygook to me, I don't understand a word its saying

My code is so far as follows;

```<code>    <video src="GlassVeinColorful.mp4" autoplay="1" preload="auto"
      -movflags class="Vid" width="640" height="360" loop="1" viewport=""
      faststart mpeg4 -s 320x240 -r 1080 -b 128k>
    </video>
</code>```

Does anyone know why this is lagging so much, or what I could do about it.
it is a quality animation and I don't really want to loose an of its resolution or crispness.. the -s section was originally set to 1920x1080 as this is what the original file is but i have changed it to try and render it quicker...

Any helpful sites, articles or answers would be great..

2020 Update

The Solution to this problem was to convert the Video to WebM, then use Javascript & a Html5 Canvas Element to render the Video to the page instead of using the video tag to embed the video.

Html

```<code><section id="Theater">
        <video src="Imgs/Vid/PurpGlassVein.webm" type="video/webm"
               width="684" height="auto"
               muted loop autoplay>
               <source>
               <source>
               <source>
        </video>
        <canvas style="filter:opacity(0);"></canvas>
</section><!-- Closing Section for the Header -->
</code>```

Css

```<code>video{
   display:none !important;
   visibility:hidden;
}
</code>```

Javascript

```<code>    const Canv = document.querySelector("canvas");
    const Video = document.querySelector("video");
    const Ctx = Canv.getContext("2d");

    Video.addEventListener('play',()=>{
      function step() {
        Ctx.drawImage(Video, 0, 0, Canv.width, Canv.height)
        requestAnimationFrame(step)
      }
      requestAnimationFrame(step);
    })

    Canv.animate({
        filter: ['opacity(0) blur(5.28px)','opacity(1) blur(8.20px)']
    },{
        duration: 7288,
        fill: 'forwards',
        easing: 'ease-in',
        iterations: 1,
        delay: 728
    })
</code>```

I've Also Used the Vanilla Javascript .animate() API to fade the element into the page when the page loads. But one Caveat is that both the Canvas and the off-screen Video Tag must match the original videos resolution otherwise it starts to lag again, however you can use Css to scale it down via transform:scale(0.5); which doesn't seem to effect performance at all.

runs smooth as butter, and doesn't loose any of the high resolution image.
Added a slight blur 0.34px onto it aswell to smooth it even more.

Possibly could of still used ffmpeg to get a better[Smaller File Size] WebM Output file but thats something I'll have to look into at a later date.

答:
I recently went back to this project,
and went back over the Code,

Found that Converting the Video to WebM
& Using the html Canvas element to display the Vj loop
has made the performance 10x better, I will Upload the code for writing the data to the canvas when I can find it, my projects folder is kinda messy and un organised.

The main Idea though is having an Offscreen canvas with display none, and then reading that data into another Canvas that is displayed on the screen.
Seems to have fixed the issue that I was facing.

See the above edit[in the question] if you are facing any of the same issues or problems.

Body:
I am trying to get a video to play inside a video tag at the top left hand corner of my page, it loads ok, the resolution is good and it seems to be looping but it is lagging very much, definatly not achieving 60fps it is in mp4 format and the resolution on the original mp4 is 1920x1080 it is a hi resolution vj free loop called GlassVein, you can see it if you search on youtube. On right clicking properties it comes up with the following inforamtion;

Bitrate:127kbs
  Data rate:11270kbps
  Total bitrate:11398kbs
  Audio sample rate is: 44khz
  filetype is:VLC media file(.mp4)
    (but i do not want or need the audio)

& it also says 30fps, but I'm not sure i believe this as it runs smooth as butter on vlc media player no lagging, just smooth loop animation

I have searched on :https://trac.ffmpeg.org/wiki/Encode/AAC for encoding information but it is complete gobbldygook to me, I don't understand a word its saying

My code is so far as follows;

    <video src="GlassVeinColorful.mp4" autoplay="1" preload="auto"
      -movflags class="Vid" width="640" height="360" loop="1" viewport=""
      faststart mpeg4 -s 320x240 -r 1080 -b 128k>
    </video>

Does anyone know why this is lagging so much, or what I could do about it.
it is a quality animation and I don't really want to loose an of its resolution or crispness.. the -s section was originally set to 1920x1080 as this is what the original file is but i have changed it to try and render it quicker...

Any helpful sites, articles or answers would be great..

2020 Update

The Solution to this problem was to convert the Video to WebM, then use Javascript & a Html5 Canvas Element to render the Video to the page instead of using the video tag to embed the video.

Html

        <video src="Imgs/Vid/PurpGlassVein.webm" type="video/webm"
               width="684" height="auto"
               muted loop autoplay>
               <source>
               <source>
               <source>
        </video>
        <canvas style="filter:opacity(0);"></canvas>

Css

video{
   display:none !important;
   visibility:hidden;
}

Javascript

    const Canv = document.querySelector("canvas");
    const Video = document.querySelector("video");
    const Ctx = Canv.getContext("2d");

    Video.addEventListener('play',()=>{
      function step() {
        Ctx.drawImage(Video, 0, 0, Canv.width, Canv.height)
        requestAnimationFrame(step)
      }
      requestAnimationFrame(step);
    })

    Canv.animate({
        filter: ['opacity(0) blur(5.28px)','opacity(1) blur(8.20px)']
    },{
        duration: 7288,
        fill: 'forwards',
        easing: 'ease-in',
        iterations: 1,
        delay: 728
    })

I've Also Used the Vanilla Javascript .animate() API to fade the element into the page when the page loads. But one Caveat is that both the Canvas and the off-screen Video Tag must match the original videos resolution otherwise it starts to lag again, however you can use Css to scale it down via transform:scale(0.5); which doesn't seem to effect performance at all.

runs smooth as butter, and doesn't loose any of the high resolution image.
Added a slight blur 0.34px onto it aswell to smooth it even more.

Possibly could of still used ffmpeg to get a better[Smaller File Size] WebM Output file but thats something I'll have to look into at a later date.


问:
JavaScript - issue about figure out console.log return on longest subsequence algorithm
I have this complex algorithm exercise. At this moment, I have some difficulty understanding it at all. So I decided to split the code into small parts. At this moment I want to understand only the console.log's return. In the future, I will post other doubts.

Below, here is solution came from this youtube video:

https://www.youtube.com/watch?v=10WnvBk9sZc

```<code>longestSubseq("ABAZDC", "BACBAD") //ABAD
longestSubseq("AGGTAB", "GXTXAYB") //GTAB
longestSubseq("aaaa", "aa") //aa
longestSubseq("", "...") //""
longestSubseq("ABBA", "ABCABA")//ABBA

function longestSubseq(s1, s2, s1StartIdx = 0, s2StartIdx = 0) {
  const results = []

  for(let s1Idx = s1StartIdx; s1Idx < s1.length; s1Idx++) {
    const s1Char = s1[s1Idx]
    const s2Idx = s2.indexOf(s1Char, s2StartIdx)
    let result = []

    //Here is the highlight of my doubt
    console.log('s1Idx: ' + s1Idx)
    console.log('s2Idx: ' + s2Idx)
    console.log('s1Char: ' + s1Char)

    if(s2Idx !== -1) {
      result.push(s1Char, ...longestSubseq(s1,s2,s1Idx + 1, s2Idx + 1))
    }

    results.push(result)
  }

  const longest = findLongest(results)
    return longest.join('')
}

function findLongest(arr) {
  let longest = []

  for (let candidate of arr ) {
    if(candidate.length > longest.length) {
      longest = candidate
    }
  }

  return longest
}
</code>```

Let do it based on this example:

```<code> longestSubseq("ABAZDC", "BACBAD") //ABAD
</code>```

In this code above, into of the for of longestSubseq function...

```<code> console.log('s1Idx: ' + s1Idx)
 console.log('s2Idx: ' + s2Idx)
 console.log('s1Char: ' + s1Char)
</code>```

It returns in the console:

```<code>s1Idx: 0
s2Idx: 1
s1Char: A
s1Idx: 1
s2Idx: 3
s1Char: B
s1Idx: 2
s2Idx: 4
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 2
s2Idx: 4
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 1
s2Idx: 0
s1Char: B
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
</code>```

I did understand the begin of the return involving these lines below, with the loop passing throught these letters: 'ABAZDC'

```<code> s1Idx: 0
 s2Idx: 1
 s1Char: A
 s1Idx: 1
 s2Idx: 3
 s1Char: B
 s1Idx: 2
 s2Idx: 4
 s1Char: A
 s1Idx: 3
 s2Idx: -1
 s1Char: Z
 s1Idx: 4
 s2Idx: 5
 s1Char: D
 s1Idx: 5
 s2Idx: -1
 s1Char: C
 s1Idx: 5
 s2Idx: -1
</code>```

I did NOT understand the loop continues, resulting these returns below printing the repeated letters
C,Z,D,C,C,A,Z,C,C,Z,D,C,C,B,A,Z...

```<code>s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 2
s2Idx: 4
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 1
s2Idx: 0
s1Char: B
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
</code>```

答:
How code execute you can check here step by step

python-tutor

First try to understand how indexOf works

second Spread_syntax

so  result.push(s1Char, ...longestSubseq(s1,s2,s1Idx + 1, s2Idx + 1))

this function call recursively  longestSubseq(s1,s2,s1Idx + 1, s2Idx + 1)

Body:
I have this complex algorithm exercise. At this moment, I have some difficulty understanding it at all. So I decided to split the code into small parts. At this moment I want to understand only the console.log's return. In the future, I will post other doubts.

Below, here is solution came from this youtube video:

https://www.youtube.com/watch?v=10WnvBk9sZc

longestSubseq("ABAZDC", "BACBAD") //ABAD
longestSubseq("AGGTAB", "GXTXAYB") //GTAB
longestSubseq("aaaa", "aa") //aa
longestSubseq("", "...") //""
longestSubseq("ABBA", "ABCABA")//ABBA

function longestSubseq(s1, s2, s1StartIdx = 0, s2StartIdx = 0) {
  const results = []

  for(let s1Idx = s1StartIdx; s1Idx < s1.length; s1Idx++) {
    const s1Char = s1[s1Idx]
    const s2Idx = s2.indexOf(s1Char, s2StartIdx)
    let result = []

    //Here is the highlight of my doubt
    console.log('s1Idx: ' + s1Idx)
    console.log('s2Idx: ' + s2Idx)
    console.log('s1Char: ' + s1Char)

    if(s2Idx !== -1) {
      result.push(s1Char, ...longestSubseq(s1,s2,s1Idx + 1, s2Idx + 1))
    }

    results.push(result)
  }

  const longest = findLongest(results)
    return longest.join('')
}

function findLongest(arr) {
  let longest = []

  for (let candidate of arr ) {
    if(candidate.length > longest.length) {
      longest = candidate
    }
  }

  return longest
}

Let do it based on this example:

 longestSubseq("ABAZDC", "BACBAD") //ABAD

In this code above, into of the for of longestSubseq function...

 console.log('s1Idx: ' + s1Idx)
 console.log('s2Idx: ' + s2Idx)
 console.log('s1Char: ' + s1Char)

It returns in the console:

s1Idx: 0
s2Idx: 1
s1Char: A
s1Idx: 1
s2Idx: 3
s1Char: B
s1Idx: 2
s2Idx: 4
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 2
s2Idx: 4
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 1
s2Idx: 0
s1Char: B
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C

I did understand the begin of the return involving these lines below, with the loop passing throught these letters: 'ABAZDC'

 s1Idx: 0
 s2Idx: 1
 s1Char: A
 s1Idx: 1
 s2Idx: 3
 s1Char: B
 s1Idx: 2
 s2Idx: 4
 s1Char: A
 s1Idx: 3
 s2Idx: -1
 s1Char: Z
 s1Idx: 4
 s2Idx: 5
 s1Char: D
 s1Idx: 5
 s2Idx: -1
 s1Char: C
 s1Idx: 5
 s2Idx: -1

I did NOT understand the loop continues, resulting these returns below printing the repeated letters
C,Z,D,C,C,A,Z,C,C,Z,D,C,C,B,A,Z...

s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 2
s2Idx: 4
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 1
s2Idx: 0
s1Char: B
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 2
s2Idx: 1
s1Char: A
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C
s1Idx: 3
s2Idx: -1
s1Char: Z
s1Idx: 4
s2Idx: 5
s1Char: D
s1Idx: 5
s2Idx: -1
s1Char: C
s1Idx: 5
s2Idx: 2
s1Char: C

Body:
How code execute you can check here step by step

<a href="http://www.pythontutor.com/live.html#code=function%20longestSubseq%28s1,%20s2,%20s1StartIdx%20%3D%200,%20s2StartIdx%20%3D%200%29%20%7B%0A%20%20const%20results%20%3D%20%5B%5D%20%20%0A%0A%20%20for%28let%20s1Idx%20%3D%20s1StartIdx%3B%20s1Idx%20%3C%20s1.length%3B%20s1Idx%2B%2B%29%20%7B%0A%20%20%20%20const%20s1Char%20%3D%20s1%5Bs1Idx%5D%0A%20%20%20%20const%20s2Idx%20%3D%20s2.indexOf%28s1Char,%20s2StartIdx%29%20%20%20%20%0A%20%20%20%20let%20result%20%3D%20%5B%5D%0A%0A%20%20%20%20if%28s2Idx%20!%3D%3D%20-1%29%20%7B%0A%20%20%20%20%20%20result.push%28s1Char,%20...longestSubseq%28s1,s2,s1Idx%20%2B%201,%20s2Idx%20%2B%201%29%29%0A%20%20%20%20%7D%0A%0A%20%20%20%20results.push%28result%29%20%20%20%0A%20%20%7D%0A%0A%20%20const%20longest%20%3D%20findLongest%28results%29%0A%20%20%20%20return%20longest.join%28''%29%20%20%0A%7D%0A%0A%0Afunction%20findLongest%28arr%29%20%7B%0A%20%20let%20longest%20%3D%20%5B%5D%0A%0A%20%20for%20%28let%20candidate%20of%20arr%20%29%20%7B%0A%20%20%20%20if%28candidate.length%20%3E%20longest.length%29%20%7B%0A%20%20%20%20%20%20longest%20%3D%20candidate%0A%20%20%20%20%7D%0A%20%20%7D%0A%0A%20%20return%20longest%0A%7D%0A%0AlongestSubseq%28%22ABAZDC%22,%20%22BACBAD%22%29%20//ABAD&cumulative=false&curInstr=12&heapPrimitives=nevernest&mode=display&origin=opt-live.js&py=js&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow noreferrer">python-tutor

First try to understand how indexOf works

second Spread_syntax

so  result.push(s1Char, ...longestSubseq(s1,s2,s1Idx + 1, s2Idx + 1))

this function call recursively  longestSubseq(s1,s2,s1Idx + 1, s2Idx + 1)


问:
is this json file? and if yes, how can I read it back to java?

Possible Duplicate:

  A better Java JSON library?

Hi,

I have a json file like this:

```<code>workloads = [
  {
    total: 5,
    attributes:
    {
      taskA:1,
      taskB:2
    }
  }
]
</code>```

Thanks in advance

答:
This is not a valid JSon object.

to validate your json you can use for example jsonlint.

Have a look at the Json grammar here

To know which library you can use to read json from java look here A better Java JSON library?

Body:
Possible Duplicate:

  A better Java JSON library?

Hi,

I have a json file like this:

workloads = [
  {
    total: 5,
    attributes:
    {
      taskA:1,
      taskB:2
    }
  }
]

Thanks in advance


问:
How to get the respective value from a multiple column based on the given value in mysql
I have a table in mysql as follows

```
id  slab1     slab2     slab3
1   200-500   600-800   900-100
```

my given value for search is 250

how to find the corresponding column value, based on the given no. in mysql

My expected output will be is 200-500

答:
Try this:

```<code>select case when (select 250) > 200 and (select 250) < 500 then slab1
when (select 250) > 600 and (select 250) < 800 then slab2
when (select 250) > 900 and (select 250) < 1000 then slab3 end as slab from test;
</code>```

Replace 250 with given value.

Body:
I have a table in mysql as follows

id  slab1     slab2     slab3
1   200-500   600-800   900-100

my given value for search is 250

how to find the corresponding column value, based on the given no. in mysql

My expected output will be is 200-500

Body:
Try this:

select case when (select 250) > 200 and (select 250) < 500 then slab1
when (select 250) > 600 and (select 250) < 800 then slab2
when (select 250) > 900 and (select 250) < 1000 then slab3 end as slab from test;

Replace 250 with given value.


问:
Electron Pakaging issue for Windows in Mac Os 10.11.6
I am using mac OS 10.11.6. My elecron build for mac OS is successful but for Windows it is giving the following error

⨯ cannot execute  cause=exit status 1 errorOut=wine: failed to initialize: dlopen(/tmp/wine-stage/wine/usr/lib/wine/ntdll.dll.so, 258): image not found

I am using     "electron-builder": "22.3.2" in package.json

I have seen various post on this issue but no proper solutions. Please help

答:
The Only Option for me to make it work is to upgrade MacOs(OSX EI Captain) to macOS Mojave( 10.14.6).

Somewhere I read some packaging tools have issues with macOS catalina , So I did not opt for it for upgrade and considered Mojave.

Note: The upgrade experience was not that smooth.
a) Upgrade Process itself took more than 8hrs and I had to leave the laptop for overnight after waiting for 3hrs. But luckily , when I checked in the morning , the laptop was booted up to login screen
b) When I tried to login, it stuck for hrs there, but I realised after googling it is a common issue and many people faced it. Then I had to follow safe mode booting clearing of NVM etc process . But finally it is thru
c) Finally  npm install of my app which was working before , broke and the solution was to do

```<code>xcode-select --install
</code>```

d) Subsequently the windows build was done without any issue and app is working fine now.

So in short, unless you have at least one day to keep aside , do not attempt the OS upgrade.

Body:
The Only Option for me to make it work is to upgrade MacOs(OSX EI Captain) to macOS Mojave( 10.14.6).

Somewhere I read some packaging tools have issues with macOS catalina , So I did not opt for it for upgrade and considered Mojave.

Note: The upgrade experience was not that smooth.
a) Upgrade Process itself took more than 8hrs and I had to leave the laptop for overnight after waiting for 3hrs. But luckily , when I checked in the morning , the laptop was booted up to login screen
b) When I tried to login, it stuck for hrs there, but I realised after googling it is a common issue and many people faced it. Then I had to follow safe mode booting clearing of NVM etc process . But finally it is thru
c) Finally  npm install of my app which was working before , broke and the solution was to do

xcode-select --install

d) Subsequently the windows build was done without any issue and app is working fine now.

So in short, unless you have at least one day to keep aside , do not attempt the OS upgrade.


问:
material design not recognize
Here is my folder:

```<code>-app
     -content
     -footer
     -header
       -main-header
         {other services - shortcut} <- I just shortcut this bec. it is too long.
         main-header.component.html
         main-header.component.scss
         main-header.component.spec.ts
         main-header.module.ts
         main-header.routing.ts
     app.component.html
     etc..
</code>```

main-header module

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MainHeaderComponent } from './main-header.component';
import { MainHeaderRouteModule } from './main-header.routing';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatCardModule } from '@angular/material/card';
import { MatSidenavModule } from '@angular/material/sidenav';
import { FormsModule } from '@angular/forms';
import { LayoutModule } from '@angular/cdk/layout';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';

@NgModule({
  declarations: [
    MainHeaderComponent
  ],
  imports: [
    MatCardModule,
    MatCheckboxModule,
    MatSidenavModule,
    FormsModule,
    LayoutModule,
    MatToolbarModule,
    MatButtonModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MainHeaderRouteModule,
    CommonModule
  ]
})
export class MainHeaderModule {}
</code>```

main-header.routing

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainHeaderComponent } from './main-header.component';

const routes: Routes = [
  {path: '', component: MainHeaderComponent}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MainHeaderRouteModule {}
</code>```

app module

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MainHeaderComponent } from './header/main-header/main-header.component';

@NgModule({
  declarations: [
    AppComponent,
    MainHeaderComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  exports: [
    MainHeaderComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.routing.module

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {path: '', redirectTo: 'main-header', pathMatch: 'full'},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

Since I am using a lazyloading route, it seems that the main-module doesn't recognize angular material:

'mat-sidenav-container' is not a known element:
1. If 'mat-sidenav-container' is an Angular component, then verify that it is part of this module.
2. If 'mat-sidenav-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]

答:
According to the comments for Lys's answer, you need to import MainHeaderModule in app.module.ts. Then you will get the error you mentioned

```<code> ERROR in Type MainHeaderComponent in D:/Angular/proj/src/app/header/main-header/main-header.component.ts is part of the declarations of 2 modules
</code>```

The error is because, in both modules you have declared MainHeaderComponent. Remove MainHeaderComponent from app.module.ts. Since it's already declared in main header module. Importing main header module in app.module.ts will take care of MainHeaderComponent.

Title: material design not recognize

Body:
Here is my folder:

-app
     -content
     -footer
     -header
       -main-header
         {other services - shortcut} <- I just shortcut this bec. it is too long.
         main-header.component.html
         main-header.component.scss
         main-header.component.spec.ts
         main-header.module.ts
         main-header.routing.ts
     app.component.html
     etc..

main-header module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MainHeaderComponent } from './main-header.component';
import { MainHeaderRouteModule } from './main-header.routing';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatCardModule } from '@angular/material/card';
import { MatSidenavModule } from '@angular/material/sidenav';
import { FormsModule } from '@angular/forms';
import { LayoutModule } from '@angular/cdk/layout';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';

@NgModule({
  declarations: [
    MainHeaderComponent
  ],
  imports: [
    MatCardModule,
    MatCheckboxModule,
    MatSidenavModule,
    FormsModule,
    LayoutModule,
    MatToolbarModule,
    MatButtonModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MainHeaderRouteModule,
    CommonModule
  ]
})
export class MainHeaderModule {}

main-header.routing

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainHeaderComponent } from './main-header.component';

const routes: Routes = [
  {path: '', component: MainHeaderComponent}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MainHeaderRouteModule {}

app module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MainHeaderComponent } from './header/main-header/main-header.component';

@NgModule({
  declarations: [
    AppComponent,
    MainHeaderComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  exports: [
    MainHeaderComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.routing.module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {path: '', redirectTo: 'main-header', pathMatch: 'full'},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Since I am using a lazyloading route, it seems that the main-module doesn't recognize angular material:

'mat-sidenav-container' is not a known element:
1. If 'mat-sidenav-container' is an Angular component, then verify that it is part of this module.
2. If 'mat-sidenav-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]

Body:
According to the comments for Lys's answer, you need to import MainHeaderModule in app.module.ts. Then you will get the error you mentioned

 ERROR in Type MainHeaderComponent in D:/Angular/proj/src/app/header/main-header/main-header.component.ts is part of the declarations of 2 modules

The error is because, in both modules you have declared MainHeaderComponent. Remove MainHeaderComponent from app.module.ts. Since it's already declared in main header module. Importing main header module in app.module.ts will take care of MainHeaderComponent.


问:
TypeError during extracting bigrams with Gensim(Python)
I want to extract and print bigrams using Gensim. For this purpose I used that code in GoogleColab:

```<code>import gensim.downloader as api
from gensim.models import Word2Vec
from gensim.corpora import WikiCorpus, Dictionary
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from collections import Counter

data = api.load("text8") # wikipedia corpus
bigram = Phrases(data, min_count=3, threshold=10)

cntr = Counter()
for key in bigram.vocab.keys():
  if len(key.split('_')) > 1:
    cntr[key] += bigram.vocab[key]

for key, counts in cntr.most_common(50):
  print(key, " - ", counts)
</code>```

But there's an error:

Then I tried this:

```<code>cntr = Counter()
for key in bigram.vocab.keys():
  if len(key.split(b'_')) > 1:
    cntr[key] += bigram.vocab[key]

for key, counts in cntr.most_common(50):
  print(key, " - ", counts)
</code>```

And then:

What is wrong?

答:
```<code> bigram_token  = list(bigram.vocab.keys())
 type(bigram_token[0])

 #op
 bytes
</code>```

convert this into string and it will solve problem, in your code just while splitting do

```<code>cntr = Counter()
for key in bigram.vocab.keys():
    if len(key.decode('utf-8').split(b'_')) > 1: # here added .decode('utf-8')
       cntr[key] += bigram.vocab[key]
</code>```

Body:
I want to extract and print bigrams using Gensim. For this purpose I used that code in GoogleColab:

import gensim.downloader as api
from gensim.models import Word2Vec
from gensim.corpora import WikiCorpus, Dictionary
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from collections import Counter

data = api.load("text8") # wikipedia corpus
bigram = Phrases(data, min_count=3, threshold=10)

cntr = Counter()
for key in bigram.vocab.keys():
  if len(key.split('_')) > 1:
    cntr[key] += bigram.vocab[key]

for key, counts in cntr.most_common(50):
  print(key, " - ", counts)

But there's an error:

Then I tried this:

cntr = Counter()
for key in bigram.vocab.keys():
  if len(key.split(b'_')) > 1:
    cntr[key] += bigram.vocab[key]

for key, counts in cntr.most_common(50):
  print(key, " - ", counts)

And then:

What is wrong?

Body:
 bigram_token  = list(bigram.vocab.keys())
 type(bigram_token[0])

 #op
 bytes

convert this into string and it will solve problem, in your code just while splitting do

cntr = Counter()
for key in bigram.vocab.keys():
    if len(key.decode('utf-8').split(b'_')) > 1: # here added .decode('utf-8')
       cntr[key] += bigram.vocab[key]


问:
Perl: sending zip as base64-encoded attachment corrupts archive
I'm using perl to assemble a multipart-MIME email, which I'm then sending using sendmail, on a Windows environment.  Not ideal, I know.

Part of this is collecting files, zipping them up, then encoding the zip file as Base64 and writing it into the email as an attachment.  My problem is that whenever I send files over a certain size (I don't know exactly what size that is; somewhere between 20 KB and 2 MB) the zip file ends up corrupted on receipt.  (When opened in WinRAR it complains "unexpected end of archive", and the CRC values are all zero-valued, if that's any clue).

I suspect I might just be writing it into the email in such a way that I'm letting garbage or duplication in, but I can't see where it's happening.  Here's the snippet I'm using to do the reading/encoding/writing; it's using MIME::Base64, and obviously has an open Sendmail handle.

```<code>    open(FILE, "c:\\temp\\$uid.zip") or die "$!";
    while (read(FILE, $buffer, 60*57))
    {
        printf SENDMAIL encode_base64($buffer);
    }
</code>```

Even when I read it in without any kind of buffering (I should certainly have enough memory for a paltry 2mb file), I still end up receiving a corrupted zip file.  Size is definitely the confounding factor, but I'm struggling to figure out why or how to remedy it.

答:
I think on Windows you need to binmode your file

```<code>open(FILE, "c:\\temp\\$uid.zip") or die "$!";
binmode FILE;
while (read(FILE, $buffer, 60*57))
{
    printf SENDMAIL encode_base64($buffer);
}
</code>```

Also, use MIME::Lite for sending emails.

Body:
I'm using perl to assemble a multipart-MIME email, which I'm then sending using sendmail, on a Windows environment.  Not ideal, I know.

Part of this is collecting files, zipping them up, then encoding the zip file as Base64 and writing it into the email as an attachment.  My problem is that whenever I send files over a certain size (I don't know exactly what size that is; somewhere between 20 KB and 2 MB) the zip file ends up corrupted on receipt.  (When opened in WinRAR it complains "unexpected end of archive", and the CRC values are all zero-valued, if that's any clue).

I suspect I might just be writing it into the email in such a way that I'm letting garbage or duplication in, but I can't see where it's happening.  Here's the snippet I'm using to do the reading/encoding/writing; it's using MIME::Base64, and obviously has an open Sendmail handle.

    open(FILE, "c:\\temp\\$uid.zip") or die "$!";
    while (read(FILE, $buffer, 60*57))
    {
        printf SENDMAIL encode_base64($buffer);
    }

Even when I read it in without any kind of buffering (I should certainly have enough memory for a paltry 2mb file), I still end up receiving a corrupted zip file.  Size is definitely the confounding factor, but I'm struggling to figure out why or how to remedy it.

Body:
I think on Windows you need to binmode your file

open(FILE, "c:\\temp\\$uid.zip") or die "$!";
binmode FILE;
while (read(FILE, $buffer, 60*57))
{
    printf SENDMAIL encode_base64($buffer);
}

Also, use MIME::Lite for sending emails.


答:
Try this query:

```<code>SELECT CASE WHEN 250 BETWEEN SUBSTRING_INDEX(slab1,'-',1) AND SUBSTRING_INDEX(slab1,'-',-1) THEN slab1
            WHEN 250 BETWEEN SUBSTRING_INDEX(slab2,'-',1) AND SUBSTRING_INDEX(slab2,'-',-1) THEN slab2
            WHEN 250 BETWEEN SUBSTRING_INDEX(slab3,'-',1) AND SUBSTRING_INDEX(slab3,'-',-1) THEN slab3
            ELSE 'None' END AS checking
FROM mytable;
</code>```

Fiddle: https://www.db-fiddle.com/f/dsFBJb5tzHTTv4rSG5LGuw/1

Or maybe you can set the search value in a variable so you only need to chage the value in one place:

```<code>SET @val := 250;

SELECT CASE WHEN @val BETWEEN SUBSTRING_INDEX(slab1,'-',1) AND SUBSTRING_INDEX(slab1,'-',-1) THEN slab1
            WHEN @val BETWEEN SUBSTRING_INDEX(slab2,'-',1) AND SUBSTRING_INDEX(slab2,'-',-1) THEN slab2
            WHEN @val BETWEEN SUBSTRING_INDEX(slab3,'-',1) AND SUBSTRING_INDEX(slab3,'-',-1) THEN slab3
            ELSE 'None' END AS checking
FROM mytable;
</code>```

Title: How to get the respective value from a multiple column based on the given value in mysql

Body:
Try this query:

SELECT CASE WHEN 250 BETWEEN SUBSTRING_INDEX(slab1,'-',1) AND SUBSTRING_INDEX(slab1,'-',-1) THEN slab1
            WHEN 250 BETWEEN SUBSTRING_INDEX(slab2,'-',1) AND SUBSTRING_INDEX(slab2,'-',-1) THEN slab2
            WHEN 250 BETWEEN SUBSTRING_INDEX(slab3,'-',1) AND SUBSTRING_INDEX(slab3,'-',-1) THEN slab3
            ELSE 'None' END AS checking
FROM mytable;

Fiddle: https://www.db-fiddle.com/f/dsFBJb5tzHTTv4rSG5LGuw/1

Or maybe you can set the search value in a variable so you only need to chage the value in one place:

SET @val := 250;

SELECT CASE WHEN @val BETWEEN SUBSTRING_INDEX(slab1,'-',1) AND SUBSTRING_INDEX(slab1,'-',-1) THEN slab1
            WHEN @val BETWEEN SUBSTRING_INDEX(slab2,'-',1) AND SUBSTRING_INDEX(slab2,'-',-1) THEN slab2
            WHEN @val BETWEEN SUBSTRING_INDEX(slab3,'-',1) AND SUBSTRING_INDEX(slab3,'-',-1) THEN slab3
            ELSE 'None' END AS checking
FROM mytable;


问:
action upon selecting cell in segmented control
I am using below code for getting the action done upon selecting the cell in segmented control to perform the segue and pass the information accordingly, but it is not performing as expect, it is not doing anything upon the cell being tapped.

below code is implemented through extension

```<code> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) -> UITableViewCell {
        print("hello1")
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyWsPostCell
        switch segmentControl.selectedSegmentIndex{
        case 0:
            print("hello2")
            cell.section1 = section1list[indexPath.row]
            cell.commentbutton.tag = indexPath.row
            cell.commentbutton.addTarget(self, action: #selector(todetailview(_:)), for: .touchUpInside)

            break
        case 1:
            print("hello4")
            cell.section2 = section2list[indexPath.row]
            cell.commentbutton.tag = indexPath.row
            cell.commentbutton.addTarget(self, action: #selector(todetailview(_:)), for: .touchUpInside)

            break

        default:
            break
        }

        return cell
    }
</code>```

function called

```<code>    @objc func todetailview(_ sender: AnyObject) {

              performSegue(withIdentifier: "myWtoDetail", sender: self)

          }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            var vc = segue.destination as! DetailViewController
            vc.infopassed = infokey

     }
</code>```

if anymore information is required, please let me know

答:
Because you are tapping on Button not on your cell, possible that didSelect not being called because Button cover your cell. You can use closer.

Your Table View Cell Class

```<code>class XYZ : UITableViewCell {

  var btn1:(()->())?

  //Create Action For Button
  @IBAction func btnAction(_ sender: Any) {
     btn1?()
   }
}
</code>```

In your tableView : cellForRowAt method

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier:.....

     cell.btn1 = {
            ()in
         // You can Perform your action here. No need to maintain any tag or index

      }
    }
</code>```

Body:
I am using below code for getting the action done upon selecting the cell in segmented control to perform the segue and pass the information accordingly, but it is not performing as expect, it is not doing anything upon the cell being tapped.

below code is implemented through extension

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) -> UITableViewCell {
        print("hello1")
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyWsPostCell
        switch segmentControl.selectedSegmentIndex{
        case 0:
            print("hello2")
            cell.section1 = section1list[indexPath.row]
            cell.commentbutton.tag = indexPath.row
            cell.commentbutton.addTarget(self, action: #selector(todetailview(_:)), for: .touchUpInside)

            break
        case 1:
            print("hello4")
            cell.section2 = section2list[indexPath.row]
            cell.commentbutton.tag = indexPath.row
            cell.commentbutton.addTarget(self, action: #selector(todetailview(_:)), for: .touchUpInside)

            break

        default:
            break
        }

        return cell
    }

function called

    @objc func todetailview(_ sender: AnyObject) {

              performSegue(withIdentifier: "myWtoDetail", sender: self)

          }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            var vc = segue.destination as! DetailViewController
            vc.infopassed = infokey

     }

if anymore information is required, please let me know

Body:
Because you are tapping on Button not on your cell, possible that didSelect not being called because Button cover your cell. You can use closer.

Your Table View Cell Class

class XYZ : UITableViewCell {

  var btn1:(()->())?

  //Create Action For Button
  @IBAction func btnAction(_ sender: Any) {
     btn1?()
   }
}

In your tableView : cellForRowAt method

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier:.....

     cell.btn1 = {
            ()in
         // You can Perform your action here. No need to maintain any tag or index

      }
    }


问:
React-Testing-Library(RTL): Animation causing TypeError with React Pose
I have a React application with an animation using React Pose (https://popmotion.io/pose/).

This works fine, but when I write an integration test for the component (using react-testing-library), the test fails.

The error I get when running the test is:

```<code>Error: Uncaught [TypeError: Cannot read property '1' of null]
          at reportException (/app/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
          at invokeEventListeners (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:209:9)
          at HTMLUnknownElementImpl._dispatch (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
          at HTMLUnknownElement.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
          at Object.invokeGuardedCallbackDev (/app/node_modules/react-dom/cjs/react-dom.development.js:199:16)
          at invokeGuardedCallback (/app/node_modules/react-dom/cjs/react-dom.development.js:256:31)
          at commitRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:18427:7)
          at completeRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:19884:3) TypeError: Cannot read property '1' of null
          at Object.x (/app/node_modules/popmotion-pose/lib/index.js:526:64)
          at /app/node_modules/popmotion-pose/lib/index.js:593:51
          at Array.forEach (<anonymous>)
          at convertPositionalUnits (/app/node_modules/popmotion-pose/lib/index.js:592:27)
          at transformPose (/app/node_modules/popmotion-pose/lib/index.js:647:20)
          at getParentAnimations (/app/node_modules/pose-core/lib/index.js:113:28)
          at Object.set (/app/node_modules/pose-core/lib/index.js:167:28)
          at /app/node_modules/react-pose/lib/index.js:203:77
          at Array.map (<anonymous>)
          at PoseElement.Object.<anonymous>.PoseElement.setPose (/app/node_modules/react-pose/lib/index.js:203:30)
          at PoseElement.Object.<anonymous>.PoseElement.initPoser (/app/node_modules/react-pose/lib/index.js:197:18)
          at PoseElement.Object.<anonymous>.PoseElement.componentDidMount (/app/node_modules/react-pose/lib/index.js:157:18)
          at commitLifeCycles (/app/node_modules/react-dom/cjs/react-dom.development.js:16864:22)
          at commitAllLifeCycles (/app/node_modules/react-dom/cjs/react-dom.development.js:18219:7)
          at HTMLUnknownElement.callCallback (/app/node_modules/react-dom/cjs/react-dom.development.js:149:14)
          at invokeEventListeners (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:193:27)
          at HTMLUnknownElementImpl._dispatch (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
          at HTMLUnknownElement.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
          at Object.invokeGuardedCallbackDev (/app/node_modules/react-dom/cjs/react-dom.development.js:199:16)
          at invokeGuardedCallback (/app/node_modules/react-dom/cjs/react-dom.development.js:256:31)
          at commitRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:18427:7)
          at completeRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:19884:3)
          at performWorkOnRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:19813:9)
          at performWork (/app/node_modules/react-dom/cjs/react-dom.development.js:19721:7)
          at performSyncWork (/app/node_modules/react-dom/cjs/react-dom.development.js:19695:3)
          at Object.batchedUpdates$1 [as unstable_batchedUpdates] (/app/node_modules/react-dom/cjs/react-dom.development.js:19908:7)
          at act (/app/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1161:27)
          at rtlAct (/app/node_modules/react-testing-library/dist/act-compat.js:29:10)
          at Function.fireEvent.(anonymous function).args [as click] (/app/node_modules/react-testing-library/dist/index.js:175:28)
</code>```

This looks to be caused by the regular expression here: https://github.com/Popmotion/popmotion/blob/1b181ee1673003cb7239a2696623da3f494217be/packages/popmotion-pose/src/dom/unit-conversion.ts#L28

The transform variable contains translateX(-100%) translateZ(0), so this check returns null.

I presume the problem I'm having is due to something not being implemented in jsdom (similar to this issue: https://github.com/Popmotion/popmotion/issues/402), but I'm not sure what's missing or why the method above (GetActualMeasurementInPixels) is being called because it looks like it will never work.

答:
I think this was caused by a bug with mixed units (% and px) - I had the following config:

```<code>posed.div({
  enter: {
    x: '0%'
  },
  exit: {
    x: '-400px'
  }
})
</code>```

And when I changed enter.x to 0px the exception disappeared.

Body:
I have a React application with an animation using React Pose (https://popmotion.io/pose/).

This works fine, but when I write an integration test for the component (using react-testing-library), the test fails.

The error I get when running the test is:

Error: Uncaught [TypeError: Cannot read property '1' of null]
          at reportException (/app/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
          at invokeEventListeners (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:209:9)
          at HTMLUnknownElementImpl._dispatch (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
          at HTMLUnknownElement.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
          at Object.invokeGuardedCallbackDev (/app/node_modules/react-dom/cjs/react-dom.development.js:199:16)
          at invokeGuardedCallback (/app/node_modules/react-dom/cjs/react-dom.development.js:256:31)
          at commitRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:18427:7)
          at completeRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:19884:3) TypeError: Cannot read property '1' of null
          at Object.x (/app/node_modules/popmotion-pose/lib/index.js:526:64)
          at /app/node_modules/popmotion-pose/lib/index.js:593:51
          at Array.forEach (<anonymous>)
          at convertPositionalUnits (/app/node_modules/popmotion-pose/lib/index.js:592:27)
          at transformPose (/app/node_modules/popmotion-pose/lib/index.js:647:20)
          at getParentAnimations (/app/node_modules/pose-core/lib/index.js:113:28)
          at Object.set (/app/node_modules/pose-core/lib/index.js:167:28)
          at /app/node_modules/react-pose/lib/index.js:203:77
          at Array.map (<anonymous>)
          at PoseElement.Object.<anonymous>.PoseElement.setPose (/app/node_modules/react-pose/lib/index.js:203:30)
          at PoseElement.Object.<anonymous>.PoseElement.initPoser (/app/node_modules/react-pose/lib/index.js:197:18)
          at PoseElement.Object.<anonymous>.PoseElement.componentDidMount (/app/node_modules/react-pose/lib/index.js:157:18)
          at commitLifeCycles (/app/node_modules/react-dom/cjs/react-dom.development.js:16864:22)
          at commitAllLifeCycles (/app/node_modules/react-dom/cjs/react-dom.development.js:18219:7)
          at HTMLUnknownElement.callCallback (/app/node_modules/react-dom/cjs/react-dom.development.js:149:14)
          at invokeEventListeners (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:193:27)
          at HTMLUnknownElementImpl._dispatch (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
          at HTMLUnknownElementImpl.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
          at HTMLUnknownElement.dispatchEvent (/app/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
          at Object.invokeGuardedCallbackDev (/app/node_modules/react-dom/cjs/react-dom.development.js:199:16)
          at invokeGuardedCallback (/app/node_modules/react-dom/cjs/react-dom.development.js:256:31)
          at commitRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:18427:7)
          at completeRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:19884:3)
          at performWorkOnRoot (/app/node_modules/react-dom/cjs/react-dom.development.js:19813:9)
          at performWork (/app/node_modules/react-dom/cjs/react-dom.development.js:19721:7)
          at performSyncWork (/app/node_modules/react-dom/cjs/react-dom.development.js:19695:3)
          at Object.batchedUpdates$1 [as unstable_batchedUpdates] (/app/node_modules/react-dom/cjs/react-dom.development.js:19908:7)
          at act (/app/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1161:27)
          at rtlAct (/app/node_modules/react-testing-library/dist/act-compat.js:29:10)
          at Function.fireEvent.(anonymous function).args [as click] (/app/node_modules/react-testing-library/dist/index.js:175:28)

This looks to be caused by the regular expression here: https://github.com/Popmotion/popmotion/blob/1b181ee1673003cb7239a2696623da3f494217be/packages/popmotion-pose/src/dom/unit-conversion.ts#L28

The transform variable contains translateX(-100%) translateZ(0), so this check returns null.

I presume the problem I'm having is due to something not being implemented in jsdom (similar to this issue: https://github.com/Popmotion/popmotion/issues/402), but I'm not sure what's missing or why the method above (GetActualMeasurementInPixels) is being called because it looks like it will never work.

Body:
I think this was caused by a bug with mixed units (% and px) - I had the following config:

posed.div({
  enter: {
    x: '0%'
  },
  exit: {
    x: '-400px'
  }
})

And when I changed enter.x to 0px the exception disappeared.


问:
Android Spinner Dropdown arrow not displaying
my background for my fragment is white, and the arrow for the spinner does not display unless I click on it.

This is the snippet from my Java file:

```<code>    spinner = (Spinner)v.findViewById(R.id.spinner);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.accounts,R.layout.spinner_item);
    adapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
    spinner.setAdapter(adapter);
    spinner.setPrompt("Select an account");
</code>```

This is my XMLfor the spinner_item

```<code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="inherit"
android:textSize="16dp"
android:background="#FFFFFFFF"
android:textColor="#ff252525"/>
</code>```

And this is my layout for my spinner_dropdown_items.

```<code><?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="inherit"
android:textSize="16dp"
android:background="#FFFFFFFF"
android:textColor="#ff252525"/>
</code>```

This is how my spinner looks with a white background to my fragment:
White Colour Background - Spinner
And this is how it looks when I change my background colour to purple:
Purple background - Spinner

答: remove background color for your spinner like may be you have set white background which will not display drop down icon</p>

Body:
my background for my fragment is white, and the arrow for the spinner does not display unless I click on it.

This is the snippet from my Java file:

    spinner = (Spinner)v.findViewById(R.id.spinner);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.accounts,R.layout.spinner_item);
    adapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
    spinner.setAdapter(adapter);
    spinner.setPrompt("Select an account");

This is my XMLfor the spinner_item

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="inherit"
android:textSize="16dp"
android:background="#FFFFFFFF"
android:textColor="#ff252525"/>

And this is my layout for my spinner_dropdown_items.

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textAlignment="inherit"
android:textSize="16dp"
android:background="#FFFFFFFF"
android:textColor="#ff252525"/>

This is how my spinner looks with a white background to my fragment:
White Colour Background - Spinner
And this is how it looks when I change my background colour to purple:
Purple background - Spinner


问:
How to allow only lower case as input arguments in Bash
I want to allow only lower case in my input. I've tried [a-z], [a-z^A-Z] and also [:lower:]. But it doesn't help.

All the expressions are going to else loop only if the whole string in uppercase.

Example:

If 1. Demo --- It says syntax valid
   2. demo --- It says syntax valid
   3. DEMO --- It says syntax invalid

But I need the syntax invalid even if the input is similar to example 1.

```<code>#!/bin/bash
client_name=$1

if [[ "$client_name" =~ [:lower:] ]]
        then
        echo " CLIENT Name Syntax is Valid"
        else
        echo -e "CLIENT Name Syntax is Invalid"
        exit 01
fi
</code>```

Any suggestion would be much appreciated. Thanks

答:
[:lower:] check if lowercase exist use [:upper:] instead</p>

```<code>client_name="Demo"

if [[ "$client_name" =~ [[:upper:]] ]]; then
  echo "uppercase character found"
else
  echo "all lowercase"
fi
</code>```

Body:
I want to allow only lower case in my input. I've tried [a-z], [a-z^A-Z] and also [:lower:]. But it doesn't help.

All the expressions are going to else loop only if the whole string in uppercase.

Example:

If 1. Demo --- It says syntax valid
   2. demo --- It says syntax valid
   3. DEMO --- It says syntax invalid

But I need the syntax invalid even if the input is similar to example 1.

#!/bin/bash
client_name=$1

if [[ "$client_name" =~ [:lower:] ]]
        then
        echo " CLIENT Name Syntax is Valid"
        else
        echo -e "CLIENT Name Syntax is Invalid"
        exit 01
fi

Any suggestion would be much appreciated. Thanks

Body:
[:lower:] check if lowercase exist use [:upper:] instead

client_name="Demo"

if [[ "$client_name" =~ [[:upper:]] ]]; then
  echo "uppercase character found"
else
  echo "all lowercase"
fi