问:
Is it wise to disable a Task by using an expression evaluation?
I have an SSIS Package that is scheduled to export data on a daily basis.  I have a few Tasks that I'd like to execute only on the first day of the month.  It is important that these Tasks are skipped, and that the Package continue to execute if it is not the first of the month.

After doing a bit of searching, I've found numerous references to solve this problem by using the method posted in the following blog post:
http://bi-polar23.blogspot.com/2007/05/conditional-task-execution.html

I think, however, there is a simpler solution.  Why can't I just add an expression to each of my 1st-day-of-the-month Tasks which checks the day of the month and sets the "Disabled" property on the Task accordingly?

Using expressions and disabling the Task seems a lot simpler than adding a dummy script before each Task.  Does anyone else see or know of a problem with my method for solving this problem?  Preliminary tests appear to work, however, I've found SSIS to be finicky.  I'd rather not do something that is "unconventional" if it might cause problems in the future.

Thanks for any thoughts.

答:
I don't think there is anything unconventional about setting expressions to disable tasks on conditional basis. I have done the same thing in a package that I developed. I would prefer to set the conditions directly on the Disable property on the task using Expressions rather than using Script Task. Refer screenshot #1. In other words, I agree with your approach.

A note of caution with this approach would be that the next person looking into the package may not be aware why a particular task didn't execute on a given date (in your case first day of the month). To prevent that, you can add an Annotation stating that there is an Expression set on the Disable property of the task.

One other thing I would suggest is to calculate the first day of the month value and store it in a variable that has the property EvaluateAsExpression set to true and use this variable in the Expressions of a given task to disable\enable it. This would prevent calculating the value in each of the tasks' expressions. Screenshot #1 displays that the Disable property is set to assume the value stored in the variable IsFirstDayOfMonth. Expression on this variable can be set to calculate the first day of the month.

Hope that helps.

Screenshot #1:


来源: stackexchange

问:
How to create a switch/case statement with div id as the case parameter?
I'm trying to create a dropdown list that will show different results based on the dropdown selected. Here's my minimal example for reproduction:

let elem = document.getElementById("dropdown");
elem.onchange = function(){
  if /*this is where I'm stuck. And on the following code. I want to say if the dropdown id = 1,
  then show div option1_result*/
    let hiddenDiv = document.getElementById("option1_result");
    hiddenDiv.style.display = (this.value == "") ? "none":"block";
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
Please select the dropdown:
</p>
<select id = "dropdown">
  <option id = "1" class = "selected"> option 1</option>
  <option id = "2" class = "selected"> option 2</option>
</select>

<div class = "result">
  <div class = "option1_result" style="display:none;">
    <p>
      Option 1 Result!
      <button href="#">
      See More
      </button>
    </p>
  </div>
  <div class = "option2_result" style = "display:none;">
    <p>
      Option 2 result
      <button href="#">
      More about opt 2
      </button>
    </p>
  </div>
</div></code>```

Ideally I'd like to do this where

```<code>case (1):
  hiddenDiv.style.display = "block";
</code>```

But I'm not sure that will work in this instance.

JSFiddle

答:
In addition to @Jacob's answer, it seems you should also give id not class to the result options.

ID can be used to identify one element, whereas a class can be used to
  identify more than one

and to clear your options whenever you select other options, in onchange

```<code>Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")
</code>```

otherwise options would pileup.

Also you can avoid the using if statement in your case. Use template literals.

const elem = document.getElementById("dropdown");
elem.addEventListener("change", () => {
  Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")
  const hiddenDiv = document.getElementById(`option${elem.value}_result`);
  hiddenDiv.style.display = "block"
})
const hiddenDiv = document.getElementById(`option${elem.value}_result`);
  hiddenDiv.style.display = "block"```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  Please select the dropdown:
</p>
<select id="dropdown">
  <option value="1" class="selected"> option 1</option>
  <option value="2" class="selected"> option 2</option>
</select>

<div class="result">
  <div id="option1_result" style="display:none;">
    <p>
      Option 1 Result!
      <button href="#">
      See More
      </button>
    </p>
  </div>
  <div id="option2_result" style="display:none;">
    <p>
      Option 2 result
      <button href="#">
      More about opt 2
      </button>
    </p>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a dropdown list that will show different results based on the dropdown selected. Here's my minimal example for reproduction:

let elem = document.getElementById("dropdown");
elem.onchange = function(){
  if /*this is where I'm stuck. And on the following code. I want to say if the dropdown id = 1,
  then show div option1_result*/
    let hiddenDiv = document.getElementById("option1_result");
    hiddenDiv.style.display = (this.value == "") ? "none":"block";
};

Please select the dropdown:

<select id = "dropdown">
  <option id = "1" class = "selected"> option 1</option>
  <option id = "2" class = "selected"> option 2</option>
</select>

      Option 1 Result!
      <button href="#">
      See More
      </button>

      Option 2 result
      <button href="#">
      More about opt 2
      </button>

Ideally I'd like to do this where

case (1):
  hiddenDiv.style.display = "block";

But I'm not sure that will work in this instance.

JSFiddle

Body:
In addition to @Jacob's answer, it seems you should also give id not class to the result options.

ID can be used to identify one element, whereas a class can be used to
  identify more than one

and to clear your options whenever you select other options, in onchange

Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")

otherwise options would pileup.

Also you can avoid the using if statement in your case. Use template literals.

const elem = document.getElementById("dropdown");
elem.addEventListener("change", () => {
  Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")
  const hiddenDiv = document.getElementById(`option${elem.value}_result`);
  hiddenDiv.style.display = "block"
})
const hiddenDiv = document.getElementById(`option${elem.value}_result`);
  hiddenDiv.style.display = "block"

<p>
  Please select the dropdown:
</p>
<select id="dropdown">
  <option value="1" class="selected"> option 1</option>
  <option value="2" class="selected"> option 2</option>
</select>

<div class="result">
  <div id="option1_result" style="display:none;">
    <p>
      Option 1 Result!
      <button href="#">
      See More
      </button>
    </p>
  </div>
  <div id="option2_result" style="display:none;">
    <p>
      Option 2 result
      <button href="#">
      More about opt 2
      </button>
    </p>
  </div>
</div>


问:
Credentials are required to create a TwilioClient
I want to send whatsapp messages using python using the Twilio module. I got a code from youtube and when ran the code ,it came with an error as

```<code>Traceback (most recent call last):
  File "whatsapp.py", line 4, in <module>
    client = Client()
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\twilio\rest\__init__.py", line
54, in __init__
    raise TwilioException("Credentials are required to create a TwilioClient")
twilio.base.exceptions.TwilioException: Credentials are required to create a TwilioClient
</code>```

Here is my code:

```<code>from twilio.rest import Client

client = Client()

from_whatsapp_number = 'whatsapp: +60***86744'
to_whatsapp_number = 'whatsapp: +8134***727'

client.messages.create(body='Testing message using python',
                       from_ = from_whatsapp_number,
                       to = to_whatsapp_number)
</code>```

答:
From the docs, a Client should be declared as follows:

```<code>from twilio.rest import Client

# Your Account SID from twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# Your Auth Token from twilio.com/console
auth_token  = "your_auth_token"

client = Client(account_sid, auth_token)
</code>```

You were missing your account_sid and auth_token when you declared your Client.

As @Alan pointed out, if account_sid and auth_token are not declared in the Client, Twilio looks for them as environment variables, TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN respectively.

Body:
I want to send whatsapp messages using python using the Twilio module. I got a code from youtube and when ran the code ,it came with an error as

Traceback (most recent call last):
  File "whatsapp.py", line 4, in <module>
    client = Client()
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\twilio\rest\__init__.py", line
54, in __init__
    raise TwilioException("Credentials are required to create a TwilioClient")
twilio.base.exceptions.TwilioException: Credentials are required to create a TwilioClient

Here is my code:

from twilio.rest import Client

client = Client()

from_whatsapp_number = 'whatsapp: +60***86744'
to_whatsapp_number = 'whatsapp: +8134***727'

client.messages.create(body='Testing message using python',
                       from_ = from_whatsapp_number,
                       to = to_whatsapp_number)

Body:
From the docs, a Client should be declared as follows:

from twilio.rest import Client

# Your Account SID from twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# Your Auth Token from twilio.com/console
auth_token  = "your_auth_token"

client = Client(account_sid, auth_token)

You were missing your account_sid and auth_token when you declared your Client.

As @Alan pointed out, if account_sid and auth_token are not declared in the Client, Twilio looks for them as environment variables, TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN respectively.


问:
Should I use async/await or promise in react-redux env?
I'm working on a project with Express as backend and React as front. I'm using react-redux with redux-thunk in React app and I was wondering what's the difference (in terms of exec time, etc..) between using async/await function or promise. I know there's some threads about it but I didn't find a good answer why I should use one rather than other. From my pov async/await maybe is more readable but is the only reason to choose this approach? Is there any substantial difference? Here both examples:

ASYNC/AWAIT EXAMPLE:

```<code>export const fetchAllUsers = () => {
 return async dispatch => {
   try {
    fetchTokenFunc();
    dispatch({type: FETCH_START});
    const response = await axios.get('/users/list');
    if (response.data.result) {
      dispatch({type: FETCH_SUCCESS});
      dispatch({type: FETCH_ALL_USERS, payload: response.data.result});
    }  else {
        dispatch({type: FETCH_ERROR, payload: response.data.error});
     }
 } catch (error) {
   dispatch({type: FETCH_ERROR, payload: error.message});
 }
  return 'done';
  };
};
</code>```

PROMISE EXAMPLE:

```<code>export const fetchAllUsers = () => {
 return (dispatch) => {
  dispatch({type: FETCH_START});
   axiosTokenHeader();
   axios.get('/users/list').then(({data}) => {
   if (data.result) {
    dispatch({type: FETCH_SUCCESS});
    dispatch({type: FETCH_ALL_USERS, payload: data.result});
   } else {
     dispatch({type: FETCH_ERROR, payload: data.error});
   }
    }).catch((error) => {
      dispatch({type: FETCH_ERROR, payload: error.message});
  });
 };
};
</code>```

答: The only difference between your two examples is the asynchronous syntax you chose to express dispatch code. dispatch does not care so much whether it is called within a promise chain or within an async/await block, so you can even use callbacks if you really wanted. Readability is a fine reason to choose a particular syntax. You are good to use async and await for that reason.

Body:
I'm working on a project with Express as backend and React as front. I'm using react-redux with redux-thunk in React app and I was wondering what's the difference (in terms of exec time, etc..) between using async/await function or promise. I know there's some threads about it but I didn't find a good answer why I should use one rather than other. From my pov async/await maybe is more readable but is the only reason to choose this approach? Is there any substantial difference? Here both examples:

ASYNC/AWAIT EXAMPLE:

export const fetchAllUsers = () => {
 return async dispatch => {
   try {
    fetchTokenFunc();
    dispatch({type: FETCH_START});
    const response = await axios.get('/users/list');
    if (response.data.result) {
      dispatch({type: FETCH_SUCCESS});
      dispatch({type: FETCH_ALL_USERS, payload: response.data.result});
    }  else {
        dispatch({type: FETCH_ERROR, payload: response.data.error});
     }
 } catch (error) {
   dispatch({type: FETCH_ERROR, payload: error.message});
 }
  return 'done';
  };
};

PROMISE EXAMPLE:

export const fetchAllUsers = () => {
 return (dispatch) => {
  dispatch({type: FETCH_START});
   axiosTokenHeader();
   axios.get('/users/list').then(({data}) => {
   if (data.result) {
    dispatch({type: FETCH_SUCCESS});
    dispatch({type: FETCH_ALL_USERS, payload: data.result});
   } else {
     dispatch({type: FETCH_ERROR, payload: data.error});
   }
    }).catch((error) => {
      dispatch({type: FETCH_ERROR, payload: error.message});
  });
 };
};


问:
Get the duration of audio blob stored in azure container using C#
Problem Statement:

I am reaching out to people in community after searching a lot on how to get the duration of audio blob stored in Azure container using C# program.

Research Work:

I have seen a lot many libraries in C# (eg. NAudio, MediaInfo, WindowsAPICodePack-Shell etc. ) which help in getting the duration of media file , but that only support the media files stored in the local system path and not the audios placed in cloud.

Talking from blob perspective, it does give length property of blob which returns the size in bytes , which does not suffice my requirement.

Please suggest if there is any way to get the duration of audio blob.
Thanks in Advance!

答:
The tool ffprobe (from the FFmpeg family) would do the trick. This tool is designed to inspect a media file and return all of the information you require from it.

It can take input as a URL so you can feed it your blob file (assuming the URL is open and doesn't require authentication).

This website (https://trac.ffmpeg.org/wiki/FFprobeTips) has some great tips on how to use ffprobe.

From C#, you can simply invoke the .exe using Process.Start([pathToFFProbe], [Arguments]). If you're on a Mac, use Homebrew brew install FFmpeg to get the tools. Should be just as easy on other platforms.

Arguments such as -o JSON will output the data in a JSON format that you can parse in your own application to perform any further calculations.


问:
How to add commas to CountUp JS package
I am using CountUp package for JS in React. You can find it here. The problem is that when a number is greater than 1000 it doesn't show it like this: 1,000 which would be my ideal solution.

This is code I have at the moment

```<code>$<CountUp decimal="," end={todaysStats.money_earned} duration={3} />
</code>```

As you can see I tried adding decimal="," but it is not working.

In this case, I am counting up currency but it should work on any other number greater than 1000.

How do I approach this issue?

答:
As per the documentation you need to use separator instead of decimal

separator: string Specifies character of thousands separator.

https://github.com/glennreyes/react-countup#separator-string

Title: How to add commas to CountUp JS package

Body:
I am using CountUp package for JS in React. You can find it here. The problem is that when a number is greater than 1000 it doesn't show it like this: 1,000 which would be my ideal solution.

This is code I have at the moment

$<CountUp decimal="," end={todaysStats.money_earned} duration={3} />

As you can see I tried adding decimal="," but it is not working.

In this case, I am counting up currency but it should work on any other number greater than 1000.

How do I approach this issue?


问:
PHP String replace on certain lines only
I currently have a file such as this.

```<code>[Line 1] Hello
[Line 2] World
[Line 3] Hello World
</code>```

I wish to look for all lines containing "Hello" which would be Line 1 and 3.

Then I would like to change on that line all cases of "Line" to "Changed" so the output would be

```<code>[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
</code>```

With line two being untouched. I currently have code to locate all lines with Hello in them, but am unsure how to edit those lines alone and no other.

For example the code below does find all the lines, but also deletes everything in the process with the str_replace, so I know it's not str_replace I'm seeking.

```<code>$lines = file("lines.html");
$find = "Hello";
$repl = "Changed";
foreach($lines as $key => $line)
  if(stristr($line, $find)){$line = str_replace("$find","$repl",$line);}
</code>```

答:
Here's a quick way if $find = "Hello"; and $repl = "Changed";:

```<code>$result = preg_replace("/\[Line (\d+\].*?$find.*)/", "[$repl $1", file("lines.html"));
file_put_contents("lines.html", $result);
</code>```

Match [Line and capture () digits \d one or more +

Followed by anything .*? then the $find string then anything .* capturing all

Replace with [ $repl and what was captured $1

Body:
I currently have a file such as this.

[Line 1] Hello
[Line 2] World
[Line 3] Hello World

I wish to look for all lines containing "Hello" which would be Line 1 and 3.

Then I would like to change on that line all cases of "Line" to "Changed" so the output would be

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World

With line two being untouched. I currently have code to locate all lines with Hello in them, but am unsure how to edit those lines alone and no other.

For example the code below does find all the lines, but also deletes everything in the process with the str_replace, so I know it's not str_replace I'm seeking.

$lines = file("lines.html");
$find = "Hello";
$repl = "Changed";
foreach($lines as $key => $line)
  if(stristr($line, $find)){$line = str_replace("$find","$repl",$line);}

Body:
Here's a quick way if $find = "Hello"; and $repl = "Changed";:

$result = preg_replace("/\[Line (\d+\].*?$find.*)/", "[$repl $1", file("lines.html"));
file_put_contents("lines.html", $result);

Match [Line and capture () digits \d one or more +

Followed by anything .*? then the $find string then anything .* capturing all

Replace with [ $repl and what was captured $1


问:
echoing text field value in a while loop
```<code>echo " <table bgcolor='#d3fcfe'   align='center'>  ";

while ($row = mysql_fetch_array($result)) {

echo '</div> <tr onmouseout="this.bgColor=\'#d3fcfe\';"  onmouseover= "this   .bgColor=\'#fffdcd\';" >  ';
 $numq2=$row['username'] ;

{
echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
}

echo '  </table>';
}
</code>```

<p>i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script? </p>

答:
This

```<code>echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
</code>```

should become

```<code>echo '<td ><div class="iddiv"> <input name="" type="text" value="'.$numq2.'" />   <div>    </td> ';
</code>```

Notice the '. and .' around your $numq2

ContentLicense: CC BY-SA 3.0

Body:
echo "
  ";

while ($row = mysql_fetch_array($result)) {

echo '

  ';
 $numq2=$row['username'] ;

{
echo '
 <input name="" type="text" value="$numq2" />
    	 ';
}

echo '
';
}

i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script?

Body:
This

echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';

should become

echo '<td ><div class="iddiv"> <input name="" type="text" value="'.$numq2.'" />   <div>    </td> ';

Notice the '. and .' around your $numq2


问:
Image not rendering in md format file in Gitlab
I have a directory called "features" in the root and inside this directory has image "state_transitation.JPG" and document "myMdc_features.md"

I am trying to add an image "state_transitation.JPG" to the md extension document "myMdc_features.md"  in my repository by using markdown below:

```<code>![alt text](./state_transitation.JPG)

![alt text](/state_transitation.JPG)

![alt text](state_transitation.JPG)

<p>
<img src="state_transitation.JPG" />
</p>
</code>```

I tried all above options but this is giving page could not be found error. 404

Both myMdc_features.md and image file are in same path/directory.

What is the correct way to display an image in gitlab myMdc_features.md?

答:
I think that the first option should work, assuming they are in the same folder.  I made an example repostiory here that works.

Source of the file:

```<code> Hello World

![](./i-have-no-idea-what-im-doing.jpg)
</code>```

Output in GitLab:

Body:
I have a directory called "features" in the root and inside this directory has image "state_transitation.JPG" and document "myMdc_features.md"

I am trying to add an image "state_transitation.JPG" to the md extension document "myMdc_features.md"  in my repository by using markdown below:

![alt text](./state_transitation.JPG)

![alt text](/state_transitation.JPG)

![alt text](state_transitation.JPG)

I tried all above options but this is giving page could not be found error. 404

Both myMdc_features.md and image file are in same path/directory.

What is the correct way to display an image in gitlab myMdc_features.md?

Body:
I think that the first option should work, assuming they are in the same folder.  I made an example repostiory here that works.

Source of the file:

 Hello World

![](./i-have-no-idea-what-im-doing.jpg)

Output in GitLab:


问:
React-Native Constructor
Please help me find what is wrong in the following React-Native code?

It says after constructor (props) should have ';' semicolon. I don't know if I declared it in the right way.

```<code>import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';

export default function App() {
  constructor (props){
    this.state = {
      text: 'HI'
    }
  }
  render () {
  return (
    <View style={styles.container}>
      <TextInput style={styles.input}
      placeholder = 'Enter Value...'
      placeholderTextColor ='#E74292'
      onChangeText = {(text) => {
        this.setState({text})
      }}
      />
    </View>
  );
}
const styles = StyleSheet.create({
  container:{
    flex:1,
    backgroundColor:'#F4C724',

  },
  input :{
marginTop:30,
height:30,
width:30,
borderWidth:2,
padding:10,
borderRadius: 5,
borderColor:'#1287A5'
  }
}
);
</code>```

答:
you can use useState , the dynamic function value loads to the initial variable on load</p>

```<code>import React,{ useState } from 'react';
import { View, Text, Button, ImageBackground} from 'react-native';
export default function Home({navigation}){

   //function getversion onload

    const [initval,setInitval] = useState(()=>{ return '123456'});

    return(
        <View  style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text> {initval} </Text>
        </View>
    );
}
</code>```

Title: React-Native Constructor

Body:
Please help me find what is wrong in the following React-Native code?

It says after constructor (props) should have ';' semicolon. I don't know if I declared it in the right way.

import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';

export default function App() {
  constructor (props){
    this.state = {
      text: 'HI'
    }
  }
  render () {
  return (
    <View style={styles.container}>
      <TextInput style={styles.input}
      placeholder = 'Enter Value...'
      placeholderTextColor ='#E74292'
      onChangeText = {(text) => {
        this.setState({text})
      }}
      />
    </View>
  );
}
const styles = StyleSheet.create({
  container:{
    flex:1,
    backgroundColor:'#F4C724',

  },
  input :{
marginTop:30,
height:30,
width:30,
borderWidth:2,
padding:10,
borderRadius: 5,
borderColor:'#1287A5'
  }
}
);

Body:
you can use useState , the dynamic function value loads to the initial variable on load

import React,{ useState } from 'react';
import { View, Text, Button, ImageBackground} from 'react-native';
export default function Home({navigation}){

   //function getversion onload

    const [initval,setInitval] = useState(()=>{ return '123456'});

    return(
        <View  style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text> {initval} </Text>
        </View>
    );
}


问:
Can't build an Android Cordova project (Ionic 5)
I'm making an app in Ionic 5 (with Angular as my framework of choice), which uses Cordova for compiling the final hybrid app.

As the final development period is coming, I'm trying to put some ads into the app. For that, I used the Cordova's plugin "AdMobFree", and integrated it with ionic-native/admob-free NPM package for using the plugin from my codebase.

Thing is, I'm not being able to compile anything. The error I'm getting seems to be related with the Google Play Services package. This error starts giving me the following warning:

```<code>WARNING in ./node_modules/parse/node_modules/crypto-js/core.js
Module not found: Error: Can't resolve 'crypto' in 'D:\Dev\bygymapp\node_modules\parse\node_modules\crypto-js'
</code>```

As it is only a warning, I don't give it too much credit, but I add it in case it's related. The big chunk of the problem seems to be here:

```<code>    BUILD FAILED in 14s
D:\Dev\bygymapp\platforms\android\gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[17.0.
  0]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown.

  Dependency failing: com.google.android.gms:play-services-measurement-api:17.0.0 -> com.google.android.gms:play-services-
  measurement-sdk-api@[17.0.0], but play-services-measurement-sdk-api version was 17.1.0.

  The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art
  ifact with the issue.
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@11.0.4
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@19.0.1
  -- Project 'app' depends onto com.google.android.gms:play-services-gass@19.0.1
  -- Project 'app' depends onto com.google.firebase:firebase-core@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@16.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager-api@17.0.0
  -- Project 'app' depends onto com.google.firebase:firebase-analytics@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-api@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk-api@17.1.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads-lite@19.0.1

  For extended debugging info execute Gradle from the command line with ./gradlew --info :app:assembleDebug to see the dep
  endency paths to the artifact. This error message came from the google-services Gradle plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding "googleServices { disableVersionCheck = false }" to your b
  uild.gradle file.
</code>```

I tried declaring different versions of the Google Play Service in my package.json, but I couldn't manage to get this error off. The app works well when I use it with ionic serve (even if the AdMobFree plugin doesn't work because it's on a browser instead of a mobile device), so I guess it's not a problem of my codebase nor the plugin itself, but rather, a problem with my Android SDK versions and so.

Anybody got any idea on how to fix this annoying error?

Thank you a lot!

edit: my environment looks like this:

```<code>Windows 10
Node Version: 14.1
Ionic Version: 5.4.14
Cordova Android: ^8.1.0
</code>```

This is my build.gradle:

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath 'com.android.tools.build:gradle:3.3.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }

    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="28.0.3" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=28 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=28 //Integer - We ALWAYS compile with the latest by default
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

edit 2:
After many attempts and two answers, this is still not working. I'm getting the same error over and over, with the mention to the Google Play Services dependency error, especially with the com.google.android.gms:play-services-measurement-api package.

This is getting out of hand since I already tried every solution and nothing seems to yield results. I can't stress enough how much I need help with this.

答:
This seems like some google dependencies are conflicting with each other and the ones included in the ionic framework.

Check the following thread cuz it could fix your problem.

Also, try adding the following to your build.gradle file and build your app again to see if gradle gives you any more details.

```<code>googleServices {
    disableVersionCheck = false
}
</code>```

Body:
I'm making an app in Ionic 5 (with Angular as my framework of choice), which uses Cordova for compiling the final hybrid app.

As the final development period is coming, I'm trying to put some ads into the app. For that, I used the Cordova's plugin "AdMobFree", and integrated it with ionic-native/admob-free NPM package for using the plugin from my codebase.

Thing is, I'm not being able to compile anything. The error I'm getting seems to be related with the Google Play Services package. This error starts giving me the following warning:

WARNING in ./node_modules/parse/node_modules/crypto-js/core.js
Module not found: Error: Can't resolve 'crypto' in 'D:\Dev\bygymapp\node_modules\parse\node_modules\crypto-js'

As it is only a warning, I don't give it too much credit, but I add it in case it's related. The big chunk of the problem seems to be here:

    BUILD FAILED in 14s
D:\Dev\bygymapp\platforms\android\gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[17.0.
  0]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown.

  Dependency failing: com.google.android.gms:play-services-measurement-api:17.0.0 -> com.google.android.gms:play-services-
  measurement-sdk-api@[17.0.0], but play-services-measurement-sdk-api version was 17.1.0.

  The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art
  ifact with the issue.
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@11.0.4
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@19.0.1
  -- Project 'app' depends onto com.google.android.gms:play-services-gass@19.0.1
  -- Project 'app' depends onto com.google.firebase:firebase-core@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@16.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager-api@17.0.0
  -- Project 'app' depends onto com.google.firebase:firebase-analytics@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-api@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk-api@17.1.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads-lite@19.0.1

  For extended debugging info execute Gradle from the command line with ./gradlew --info :app:assembleDebug to see the dep
  endency paths to the artifact. This error message came from the google-services Gradle plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding "googleServices { disableVersionCheck = false }" to your b
  uild.gradle file.

I tried declaring different versions of the Google Play Service in my package.json, but I couldn't manage to get this error off. The app works well when I use it with ionic serve (even if the AdMobFree plugin doesn't work because it's on a browser instead of a mobile device), so I guess it's not a problem of my codebase nor the plugin itself, but rather, a problem with my Android SDK versions and so.

Anybody got any idea on how to fix this annoying error?

Thank you a lot!

edit: my environment looks like this:

Windows 10
Node Version: 14.1
Ionic Version: 5.4.14
Cordova Android: ^8.1.0

This is my build.gradle:

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath 'com.android.tools.build:gradle:3.3.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }

    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="28.0.3" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=28 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=28 //Integer - We ALWAYS compile with the latest by default
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

edit 2:
After many attempts and two answers, this is still not working. I'm getting the same error over and over, with the mention to the Google Play Services dependency error, especially with the com.google.android.gms:play-services-measurement-api package.

This is getting out of hand since I already tried every solution and nothing seems to yield results. I can't stress enough how much I need help with this.

Body:
This seems like some google dependencies are conflicting with each other and the ones included in the ionic framework.

Check the following thread cuz it could fix your problem.

Also, try adding the following to your build.gradle file and build your app again to see if gradle gives you any more details.

googleServices {
    disableVersionCheck = false
}


问:
Replace everything from a string when it reaches a match
Given:

```<code>path = 'abc/dfg/zxc'
</code>```

Is there a way to replace the string before the first '/' with '.' ?

Expected result:

```<code>'./dfg/zxc'
</code>```

What i have tried, this approah is messy and i am wondering if there is a cleaner one to solving this issue?:

```<code> lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str
</code>```

答:
How about using a regex match/substitution?</p>

```<code>import re

path = 'abc/dfg/zxc'

print(re.sub(r'^\w+/', './', path))
'./dfg/zxc'
</code>```

Body:
Given:

path = 'abc/dfg/zxc'

Is there a way to replace the string before the first '/' with '.' ?

Expected result:

'./dfg/zxc'

What i have tried, this approah is messy and i am wondering if there is a cleaner one to solving this issue?:

 lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str

Body:
How about using a regex match/substitution?

import re

path = 'abc/dfg/zxc'

print(re.sub(r'^\w+/', './', path))
'./dfg/zxc'


问:
How do you dynamically set the value for the MaterialUI grid size prop in TypeScript?
When using the Grid size props, such as XL, how can you pass a value dynamically to it in TypeScript ?

For example,
*Update for example clarification

```<code>import Grid, { GridSize } from "@material-ui/core/Grid";
let value: GridSize = 12/4;
xl={value}
</code>```

Type 'number' is not assignable to type 'GridSize'

If I setup a type such as,

```<code>type gridSize = boolean | "auto" | 1 | 2 | 12 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined
</code>```

Type 'number' is not assignable to type 'boolean | "auto" | 1 | 2 | 12
  | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined'.ts(2769)

Its the same  issue, how do I convert a number to this type?

** Answer Marked Below that helped, In the end I cast it as GridSize and added some unit tests around it for edgecases.

let value = 12/4 as GridSize

答:
There is already defined GridSize type which you can use in code

export type GridSize = 'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
```

<p><strong>Example</strong></p>

<pre class="lang-js prettyprint-override"><code>import Grid, { GridSize } from "@material-ui/core/Grid";

const App = () => {
  let size: GridSize = 1;

  return <Grid xl={size}>
  </Grid>
}

render(<App />, document.getElementById("root"));
</code>```

--Edit

I see that xl prop also accepts boolean and undefined

You can also extend GridSize type to include these two.

type NewGridSize = GridSize | boolean | undefined;

let size: NewGridSize  = undefined;
```

<p>--Edit</p>

<p>Typescript doesn't have such advanced flow control analysis to assume this is <code>3</code></p>

<p>In such case you have to do dirty trick to cast it to any.</p>

<pre class="lang-js prettyprint-override"><code>let value: GridSize = 12/4 as any;
</code>```

Or you can make typesguard ( that would be overkill though )

function compute(value: any): value is 3 {
  return value;
}
```

Body:
When using the Grid size props, such as XL, how can you pass a value dynamically to it in TypeScript ?

For example,
*Update for example clarification

import Grid, { GridSize } from "@material-ui/core/Grid";
let value: GridSize = 12/4;
xl={value}

Type 'number' is not assignable to type 'GridSize'

If I setup a type such as,

type gridSize = boolean | "auto" | 1 | 2 | 12 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined

Type 'number' is not assignable to type 'boolean | "auto" | 1 | 2 | 12
  | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined'.ts(2769)

Its the same  issue, how do I convert a number to this type?

** Answer Marked Below that helped, In the end I cast it as GridSize and added some unit tests around it for edgecases.

let value = 12/4 as GridSize

Body:
There is already defined GridSize type which you can use in code

export type GridSize = 'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;

Example

import Grid, { GridSize } from "@material-ui/core/Grid";

const App = () => {
  let size: GridSize = 1;

  return <Grid xl={size}>
  </Grid>
}

render(<App />, document.getElementById("root"));

--Edit

I see that xl prop also accepts boolean and undefined

You can also extend GridSize type to include these two.

type NewGridSize = GridSize | boolean | undefined;

let size: NewGridSize  = undefined;

--Edit

Typescript doesn't have such advanced flow control analysis to assume this is 3

In such case you have to do dirty trick to cast it to any.

let value: GridSize = 12/4 as any;

Or you can make typesguard ( that would be overkill though )

function compute(value: any): value is 3 {
  return value;
}


问:
Share scripts and profiles with Dropbox
I'm new to bash, but eager to learn.
Right now I'm stealing useful scripts from other ppl and are wondering where I should put them. So I have a bunch of *.sh files, but don't know where they should go. To make it even more useful I would like a way to share them with my other puter with Dropbox. Is it as simple as linking the dropbox folder to the right place?

Sincerly
R

答:
Since you mentioned Dropbox, you might consider making a bin folder there and adding that directory to your PATH. You could also make a universal bash_profile file and put it on Dropbox. That's what I do. Not to be self-promoting, but I blogged about it here: https://blog.iharder.net/2011/03/17/bash-profile-sharing-and-useful-scripts/trackback/

Important lines for your ~/.bash_profile (or ~/.bashrc on some systems) file:

test -r ~/Dropbox/bin/bash_profile && . ~/Dropbox/bin/bash_profile

export PATH=~/Dropbox/bin:$PATH

-Rob

Title: Share scripts and profiles with Dropbox


问:
How to get number of rows with Advantage PHP Extension?
How can I get the number of rows from a SELECT statement result set using the Advantage Database PHP Extension?</p>

答: In Version 12 as far as I know you have the function ads_num_rows(). Please see in official documentation for further usage. </p>


问:
Cannot download anything with Python Selenium Chrome Ubuntu 20.04
I am having trouble getting files to download with Selenium Chrome in Python with headless mode.  I have checked a few answers on here and most of them are the same. they talk about adding prefs and experimental options.

Download with python selenium

Selenium Webdriver: How to Download a PDF File with Python?

Downloading a PDF using Selenium, Chrome and Python

Downloading with chrome headless and selenium

None of these has helped, and i am starting to wonder if it has something to do with my environment.

Ubuntu: 20.04

Python: 3.8.2

Chromeium-browser:
Chromium 80.0.3987.162 snap

Cromium-driver:
ChromeDriver 80.0.3987.162 (f2c5dd6138153bb0658091205bd1a1717f16081a-refs/branch-heads/3987@{#1034})

Here is a basic piece of sample code that is not working. it completes without any errors, but the file never downloads.

```<code>#!/usr/bin/env python3

import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

IMG_DIR = '/images/'
if not os.path.exists(IMG_DIR):
  os.makedirs(IMG_DIR)

options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-setuid-sandbox")
options.add_argument("--window-size=1920,1080")

prefs = {"download.default_directory" : IMG_DIR}
options.add_experimental_option("prefs",prefs)

driver = webdriver.Chrome(options=options, executable_path='chromedriver')

driver.get('https://www.thinkbroadband.com/download')

#Find the Extra Small file on port 80
download_button = driver.find_element_by_xpath('//*[@id="main-col"]/div/div/div[8]/p[2]/a[1]')

driver.execute_script("arguments[0].scrollIntoView();", download_button)
download_button.click()
time.sleep(10)
driver.save_screenshot('{}page.png'.format(IMG_DIR))

driver.get('chrome://downloads')
time.sleep(10)
driver.switch_to.window(driver.window_handles[-1])
driver.save_screenshot('{}downloads.png'.format(IMG_DIR))

driver.close()
driver.quit()
</code>```

I have attached both screenshots, but the downloads page always comes out as a blank white page.

Test file download site:

Chrome Download page:

Please help!

UPDATE:  I have removed the snap versions of chrome and it seems to be working better.  i can download files to a custom directory.  must be a bug with the snap version.

答:
I just filed a bug on this. As you can see from the write-up, the problem is that the download folder that the Snap uses is pointing into the Snap setup, and completely ignoring your IMG_DIR setting.

You should be able to confirm this by stopping your test at the point of the download, and looking into the browser "Downloads" directly for the folder where the download is destined.

Body:
I am having trouble getting files to download with Selenium Chrome in Python with headless mode.  I have checked a few answers on here and most of them are the same. they talk about adding prefs and experimental options.

Download with python selenium

Selenium Webdriver: How to Download a PDF File with Python?

Downloading a PDF using Selenium, Chrome and Python

Downloading with chrome headless and selenium

None of these has helped, and i am starting to wonder if it has something to do with my environment.

Ubuntu: 20.04

Python: 3.8.2

Chromeium-browser:
Chromium 80.0.3987.162 snap

Cromium-driver:
ChromeDriver 80.0.3987.162 (f2c5dd6138153bb0658091205bd1a1717f16081a-refs/branch-heads/3987@{#1034})

Here is a basic piece of sample code that is not working. it completes without any errors, but the file never downloads.

#!/usr/bin/env python3

import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

IMG_DIR = '/images/'
if not os.path.exists(IMG_DIR):
  os.makedirs(IMG_DIR)

options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-setuid-sandbox")
options.add_argument("--window-size=1920,1080")

prefs = {"download.default_directory" : IMG_DIR}
options.add_experimental_option("prefs",prefs)

driver = webdriver.Chrome(options=options, executable_path='chromedriver')

driver.get('https://www.thinkbroadband.com/download')

#Find the Extra Small file on port 80
download_button = driver.find_element_by_xpath('//*[@id="main-col"]/div/div/div[8]/p[2]/a[1]')

driver.execute_script("arguments[0].scrollIntoView();", download_button)
download_button.click()
time.sleep(10)
driver.save_screenshot('{}page.png'.format(IMG_DIR))

driver.get('chrome://downloads')
time.sleep(10)
driver.switch_to.window(driver.window_handles[-1])
driver.save_screenshot('{}downloads.png'.format(IMG_DIR))

driver.close()
driver.quit()

I have attached both screenshots, but the downloads page always comes out as a blank white page.

Test file download site:

Chrome Download page:

Please help!

UPDATE:  I have removed the snap versions of chrome and it seems to be working better.  i can download files to a custom directory.  must be a bug with the snap version.


问:
How to find beginning letters in string.I am getting errors in the program below
```<code>#include <stdio.h>
#include <string.h>
void printfletter(char *);``
int main ()
{
    char a[50]="where are you";
    printfletter(a);
    return 0;
}
void printfletter(char *p)
{
    int i;
    printf("%c",*p);
    for (i=1;*(p+i)!='\0';i++)
    {
        if (*(p+i)==32)
        {
            printf("%c",*(++p));
        }
    }
}
</code>```

Program is to print all the beginning letters in string.
I should get the output as 'way'(w-where,a-are,y-you)
But i get 'whe'
I tried to implement it using functions and pointers.

答:
First remove the last two characters in

```<code>void printfletter(char *);``
</code>```

so it will compile. Then note that *(++p) will always choose the next character in the array. You really want the (i+1)th character, so replace your printf line with

```<code>        printf("%c",p[i+1]);
</code>```

This will give you the output you want. I would recommend also making sure that you code does not exhibit undefined behaviour if you feed it the empty string.

Body:
#include <stdio.h>
#include <string.h>
void printfletter(char *);``
int main ()
{
    char a[50]="where are you";
    printfletter(a);
    return 0;
}
void printfletter(char *p)
{
    int i;
    printf("%c",*p);
    for (i=1;*(p+i)!='\0';i++)
    {
        if (*(p+i)==32)
        {
            printf("%c",*(++p));
        }
    }
}

Program is to print all the beginning letters in string.
I should get the output as 'way'(w-where,a-are,y-you)
But i get 'whe'
I tried to implement it using functions and pointers.

Body:
First remove the last two characters in

void printfletter(char *);``

so it will compile. Then note that *(++p) will always choose the next character in the array. You really want the (i+1)th character, so replace your printf line with

        printf("%c",p[i+1]);

This will give you the output you want. I would recommend also making sure that you code does not exhibit undefined behaviour if you feed it the empty string.


问:
JS - Compare individual numerical values:
I am evaluating if a condition is met between one numeric value and another, but I don't know how to add individual values.

This example works for me:

```<code>$(document).ready(function(){
  alertone();
});

$(document).on('input','#enviara',alertone);

function alertone() {
  const total = Number($("#enviara").val().replace(".",""));

  if(total >= 52001 && total <= 52006) {
    $("#alerta-melilla,.layer-melilla").show();
  }
  else{
    $("#alerta-melilla,.layer-melilla").hide();
  };
};
</code>```

But between the values 52001 & 52006, I also want to check if the individual values are written:

```<code>52009, 52012, 52019
</code>```

I've tried these snippets, but it doesn't work for me:

```<code>if (total> = 52001 && total <= 52006 && 52009 && 52012 && 52019) { ...
</code>```

```<code>if (total> = 52001 && total <= 52006 || 52009 || 52012 || 52019) { ...
</code>```

What am I doing wrong here?

Thanks in advance!

Thanks @TopWebGhost

```<code>if (total >= 52001 && total <= 52006 || total === 52009 || total === 52012 || total === 52019)
</code>```

:)

答:
You could create an Array of the exceptional values you want to accept, and check if total is within that Array:

```<code>let validValues = [ 52009, 52012, 52019 ];
if ((total >= 52001 && total <= 52006) || validValues.contains(total)) { /* ... */ }
</code>```

Body:
I am evaluating if a condition is met between one numeric value and another, but I don't know how to add individual values.

This example works for me:

$(document).ready(function(){
  alertone();
});

$(document).on('input','#enviara',alertone);

function alertone() {
  const total = Number($("#enviara").val().replace(".",""));

  if(total >= 52001 && total <= 52006) {
    $("#alerta-melilla,.layer-melilla").show();
  }
  else{
    $("#alerta-melilla,.layer-melilla").hide();
  };
};

But between the values 52001 & 52006, I also want to check if the individual values are written:

52009, 52012, 52019

I've tried these snippets, but it doesn't work for me:

if (total> = 52001 && total <= 52006 && 52009 && 52012 && 52019) { ...

if (total> = 52001 && total <= 52006 || 52009 || 52012 || 52019) { ...

What am I doing wrong here?

Thanks in advance!

Thanks @TopWebGhost

if (total >= 52001 && total <= 52006 || total === 52009 || total === 52012 || total === 52019)

:)

Body:
You could create an Array of the exceptional values you want to accept, and check if total is within that Array:

let validValues = [ 52009, 52012, 52019 ];
if ((total >= 52001 && total <= 52006) || validValues.contains(total)) { /* ... */ }


问:
Functions In CoffeeScript
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

```<code>function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}
</code>```

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

```<code><script type="text/javascript" src="../coffee/convert.js"></script>

<script type="text/javascript">
    convert(6, 3, 10);
</script>
</code>```

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?

答:
```<code>window.convert = (num1, num2, num3) ->
  num1 + num2 * num3
</code>```

Title: Functions In CoffeeScript

Body:
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?


问:
DynamoDB Query throwing exception "The query can return at most one row and cannot be restarted"
I'm seeing occurrences of this in my application log for some DynamoDB queries.  I can't find any reference to this error message via googling.

Can anyone provide insight into the cause of this exception?

Thanks.

答:
We were running into this issue when using AppSync mapping templates to issue queries to DynamoDB. AppSync encrypts/obfuscates the ExclusiveStartKey in a nextToken pagination token, making debugging this even more fun.

The error was occurring because we were re-using nextToken's generated with one set of key criteria specified via query.expression with a different set of key criteria. This likely translates to different dynamodb KeyConditionExpression under the hood, similar to @Varun's answer.


问:
HTML Content Overflowing the Page
Im working on a small site and I've encountered a problem where my website content overflows a little off the page by about 100px.

I want my content to not overflow where the user will have to always scroll to the right to see all of the content.

I have included a snippet of code here that I have made to replicate the problem. I have tried using the overflow property but it doesnt seem to change my result.

It may be the image I am using on my site (which I cant post here), but maybe thats too wide? I'm not sure why the content is overflowing all of a sudden. Thanks for any help!

.body
{
  width: 100%;
}

.flex-wrapper
{
  display: flex;
}

.image_div
{
  flex: 1;
}

.text_div
{
  flex: 1;
}

#image
{
  width: 90%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<div class="flex-wrapper">
<div class="image_div">
<img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" id="image">
</div>

<div class="text_div">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>

</body></code>```

答:
try this

```<code>#img {
    width: 90%;
    max-width: 90%;
    height: auto;
}
</code>```

or

```<code>.flex-wrapper
{
  display: flex;
  max-width: 100%;
}

</code>```

Title: HTML Content Overflowing the Page

Body:
Im working on a small site and I've encountered a problem where my website content overflows a little off the page by about 100px.

I want my content to not overflow where the user will have to always scroll to the right to see all of the content.

I have included a snippet of code here that I have made to replicate the problem. I have tried using the overflow property but it doesnt seem to change my result.

It may be the image I am using on my site (which I cant post here), but maybe thats too wide? I'm not sure why the content is overflowing all of a sudden. Thanks for any help!

.body
{
  width: 100%;
}

.flex-wrapper
{
  display: flex;
}

.image_div
{
  flex: 1;
}

.text_div
{
  flex: 1;
}

#image
{
  width: 90%;
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Body:
try this

#img {
    width: 90%;
    max-width: 90%;
    height: auto;
}

or

.flex-wrapper
{
  display: flex;
  max-width: 100%;
}


问:
AudioBuffer.copyFromChannel returns empty Float32Array
AudioBuffer.copyFromChannel returns empty Float32Array from every channel of audiobuffer....is there any way to make this work correctly?

```<code>var floatarray1 = new Float32Array();
audioBuffer.copyFromChannel(floatarray1,0);
console.log(floatarray1)
</code>```

Output of "floatarray1" which returns empty Float32Array

答:
copyFromChannel() will only copy as much data as possible. If the length of the given Float32Array is 0 it can not copy anything.

If you want to copy all the channel data you could do it like this:

```<code>const channelData = new Float32Array(audioBuffer.length);

audioBuffer.copyFromChannel(channelData, 0);
</code>```

Body:
AudioBuffer.copyFromChannel returns empty Float32Array from every channel of audiobuffer....is there any way to make this work correctly?

var floatarray1 = new Float32Array();
audioBuffer.copyFromChannel(floatarray1,0);
console.log(floatarray1)

Output of "floatarray1" which returns empty Float32Array

Body:
copyFromChannel() will only copy as much data as possible. If the length of the given Float32Array is 0 it can not copy anything.

If you want to copy all the channel data you could do it like this:

const channelData = new Float32Array(audioBuffer.length);

audioBuffer.copyFromChannel(channelData, 0);


问:
Java blinking cursor Ubuntu terminal
I want to stop the blinking cursor while running a program in Java with a Java command in Ubuntu terminal. How can I do it?</p>

答:
Your Java program doesn't exactly have control of the terminal the user ran it from. My advice would be to have your program manage its own window which you can control.

But if you don't feel like doing that then one idea is that there are codes which some terminals listen for. This is very dependent on what terminal you are using but Linux seems to mostly adhere to a spec.

Ubuntu manpages even lists its codes here: http://manpages.ubuntu.com/manpages/focal/man4/console_codes.4.html

<s>Under ECMA-48 Set Graphics Rendition section it says that ESC [ 25 m sets blink off</s>

correction, as mentioned by VGR, this controls whether printed text blinks, not the cursor blink

So search for and try some different codes for your specific terminal and remember to actually run from your terminal as your IDE terminal isn't necessarily the same:

```<code>// \u001B is ESC
public static final String ESC = "\u001B";
public static final String HIDE_CURSOR = ESC + "[?25l";

public static void main(String[] args) throws IOException {
    System.out.print(HIDE_CURSOR);
    System.out.println("Where'd your cursor go??");
}
</code>```

Title: Java blinking cursor Ubuntu terminal

Body:
Your Java program doesn't exactly have control of the terminal the user ran it from. My advice would be to have your program manage its own window which you can control.

But if you don't feel like doing that then one idea is that there are codes which some terminals listen for. This is very dependent on what terminal you are using but Linux seems to mostly adhere to a spec.

Ubuntu manpages even lists its codes here: http://manpages.ubuntu.com/manpages/focal/man4/console_codes.4.html

<s>Under ECMA-48 Set Graphics Rendition section it says that ESC [ 25 m sets blink off</s>

correction, as mentioned by VGR, this controls whether printed text blinks, not the cursor blink

So search for and try some different codes for your specific terminal and remember to actually run from your terminal as your IDE terminal isn't necessarily the same:

// \u001B is ESC
public static final String ESC = "\u001B";
public static final String HIDE_CURSOR = ESC + "[?25l";

public static void main(String[] args) throws IOException {
    System.out.print(HIDE_CURSOR);
    System.out.println("Where'd your cursor go??");
}


问:
Adding Google Custom Search to AMP site
I have my Google Custom Search Engine (GCSE) code:

```<code><script>
  (function() {
    var cx = '008589157460623253837:mhsjluzrngo';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
</code>```

However my Accelerated Mobile Pages (AMP) site does not allow me to add JavaScript to it, and I don't see any AMP components that allow for embedding GCSE into an AMP site.

How can I get GCSE on my site without breaking AMP compliance?

Thanks

答:
I added a search feature to my open source website (https://csaba.page/) with amp-form following these steps:

Create a GCSE (Google Custom Search Engine) at the CSE (Custom Search Engine) Console https://cse.google.com/ as described by https://developers.google.com/custom-search/docs/tutorial/creatingcse if you haven't already done so.

Remember your Search engine ID, it looks something like "013535696182405026577:kmxne16xdtx". You can see it on the Basics tab in the CS Console, or if you are looking at the JavaScript code it's the cx variable.

Add  to your head section where the other AMP includes are.

In the body add an amp-form where you want to position the search input and style the form as you need:

  <form method="GET" class="search-form" action="https://www.google.com/cse" target="_top">

      <input name="cx" type="hidden" value="013535696182405026577:kmxne16xdtx" />
      <input name="ie" type="hidden" value="UTF-8" />
      <input type="search" placeholder="Search..." name="q" required>
      <input type="submit" value="Go" class="search-button">

  </form>

```

Here are some blog posts as well:

https://csaba.page/blog/amp-google-custom-search-engine.html

https://gfw-blog.netlify.app/2018/05/11/cse-amp.html

And an initial commit: https://gitlab.com/MrCsabaToth/mrcsabatoth.gitlab.io/-/commit/96345716d620b916d1c61cb5b51941378ffc5dc6

Title: Adding Google Custom Search to AMP site

Body:
I have my Google Custom Search Engine (GCSE) code:

However my Accelerated Mobile Pages (AMP) site does not allow me to add JavaScript to it, and I don't see any AMP components that allow for embedding GCSE into an AMP site.

How can I get GCSE on my site without breaking AMP compliance?

Thanks

Body:
I added a search feature to my open source website (https://csaba.page/) with amp-form following these steps:

Create a GCSE (Google Custom Search Engine) at the CSE (Custom Search Engine) Console https://cse.google.com/ as described by https://developers.google.com/custom-search/docs/tutorial/creatingcse if you haven't already done so.

Remember your Search engine ID, it looks something like "013535696182405026577:kmxne16xdtx". You can see it on the Basics tab in the CS Console, or if you are looking at the JavaScript code it's the cx variable.

Add <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script> to your head section where the other AMP includes are.

In the body add an amp-form where you want to position the search input and style the form as you need:

<div>
  <form method="GET" class="search-form" action="https://www.google.com/cse" target="_top">
    <div class="search-form-inner">
      <input name="cx" type="hidden" value="013535696182405026577:kmxne16xdtx" />
      <input name="ie" type="hidden" value="UTF-8" />
      <input type="search" placeholder="Search..." name="q" required>
      <input type="submit" value="Go" class="search-button">
    </div>
  </form>
</div>

Here are some blog posts as well:

https://csaba.page/blog/amp-google-custom-search-engine.html

https://gfw-blog.netlify.app/2018/05/11/cse-amp.html

And an initial commit: https://gitlab.com/MrCsabaToth/mrcsabatoth.gitlab.io/-/commit/96345716d620b916d1c61cb5b51941378ffc5dc6


问:
looping through nested arrays and accessing elements RUBY
I want to iterate through a nested array and operate on each element, so square each number in this case. I know how to do it for a normal array but for some reason i am getting undefined map method when include deeper iteration to access the inner arrays. Am a newbie too so if you could explain how it works that would help my learning. Thanks</p>

```<code>def SquareArrayElements(n)
  n.each do |number|
    number.map do |num|
     squared_nums = num * num
  end
end
squared_nums
end
SquareArrayElements([10,[[10],10],[10]])
</code>```

答:
Since you've said in the comments that:

i want to square the 10s and return them to one array =>[100,100,100,100].

I assume that you don't need to preserve the original arrays and just want one array with the squared results. If that's the case you can #flatten the array and then square the numbers:

```<code>def square_array(arr)
  arr.flatten.map { |e| e ** 2 }
end

square_array([10,[[10],10],[10]])
#=> [100, 100, 100, 100]
</code>```

Body:
I want to iterate through a nested array and operate on each element, so square each number in this case. I know how to do it for a normal array but for some reason i am getting undefined map method when include deeper iteration to access the inner arrays. Am a newbie too so if you could explain how it works that would help my learning. Thanks

def SquareArrayElements(n)
  n.each do |number|
    number.map do |num|
     squared_nums = num * num
  end
end
squared_nums
end
SquareArrayElements([10,[[10],10],[10]])

Body:
Since you've said in the comments that:

i want to square the 10s and return them to one array =>[100,100,100,100].

I assume that you don't need to preserve the original arrays and just want one array with the squared results. If that's the case you can #flatten the array and then square the numbers:

def square_array(arr)
  arr.flatten.map { |e| e ** 2 }
end

square_array([10,[[10],10],[10]])
#=> [100, 100, 100, 100]


问:
Why am I getting Unknown error in line 1 of pom.xml?
Getting unknown error at Line 1 in pom.xml in Eclipse IDE.
It was working fine till yesterday, but all of a sudden after updating my project from master and after fixing merge conflicts getting "Unknown error" in pom.xml.
Except me, none of my teammates are facing this issue. I also changed the workspace, deleted cache but still no luck.

I am using the h2 database for this project, in spite of inserting values in data.sql, it is not picking up any values and inserting into h2 DB tables. Before this issue, it was working fine. I feel its due to the issue in pom.xml, I am not sure though. Please help

I deleted the existing project and took the latest code from master. After that deleted .m2 folder under users including the repository folder.  I did update project and enabled Forced update of snapshots/releases, maven clean and maven build. But nothing helps.

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.abc.roster</groupId>
    <artifactId>spring-boot-roster-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>spring-boot-roster-app</name>
    <description>Demo project for Spring Boot Roster</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.BUILD-SNAPSHOT</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!-- <start-class>com.infosys.roster.SpringBootRosterAppApplication</start-class> -->
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--encryption lib -->
        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt</artifactId>
            <version>1.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt-springsecurity3</artifactId>
            <version>1.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>

        </dependency>

<!--        <dependency> -->
<!--         <groupId>org.hibernate</groupId> -->
<!--         <artifactId>hibernate-core</artifactId> -->
<!--         <version>5.2.10.Final</version> -->
<!--   </dependency> -->

        <!-- <dependency> -->
        <!-- <groupId>io.springfox</groupId> -->
        <!-- <artifactId>springfox-swagger2</artifactId> -->
        <!-- <version>2.7.0</version> -->
        <!-- <scope>compile</scope> -->
        <!-- </dependency> -->

        <!-- <dependency> -->
        <!-- <groupId>io.springfox</groupId> -->
        <!-- <artifactId>springfox-swagger-ui</artifactId> -->
        <!-- <version>2.7.0</version> -->
        <!-- <scope>compile</scope> -->
        <!-- </dependency> -->

        <!-- <dependency> -->
        <!-- <groupId>io.springfox</groupId> -->
        <!-- <artifactId>springfox-data-rest</artifactId> -->
        <!-- <version>2.7.0</version> -->
        <!-- </dependency> -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

application.properties

```<code>server.port=
spring.h2.console.path=/h2
spring.h2.console.enabled=true

spring.datasource.url=

spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.platform=h2
spring.datasource.initialization-mode=always

spring.jpa.hibernate.ddl-auto=update
spring.datasource.continue-on-error=true

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=false

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
</code>```

Should remove unknown error in pom.xml and also I must be able to populate values in H2 db.

答:
whenever you facing this type of error simply change the
Release version  just like
In my case  it is showing Error in 2.2.7 I changed to 2.2.6

Problem:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
```

<p>Solution:</p>

<pre class="lang-xml prettyprint-override"><code><groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</code>```

Body:
Getting unknown error at Line 1 in pom.xml in Eclipse IDE.
It was working fine till yesterday, but all of a sudden after updating my project from master and after fixing merge conflicts getting "Unknown error" in pom.xml.
Except me, none of my teammates are facing this issue. I also changed the workspace, deleted cache but still no luck.

I am using the h2 database for this project, in spite of inserting values in data.sql, it is not picking up any values and inserting into h2 DB tables. Before this issue, it was working fine. I feel its due to the issue in pom.xml, I am not sure though. Please help

I deleted the existing project and took the latest code from master. After that deleted .m2 folder under users including the repository folder.  I did update project and enabled Forced update of snapshots/releases, maven clean and maven build. But nothing helps.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.abc.roster</groupId>
    <artifactId>spring-boot-roster-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>spring-boot-roster-app</name>
    <description>Demo project for Spring Boot Roster</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.BUILD-SNAPSHOT</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt</artifactId>
            <version>1.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt-springsecurity3</artifactId>
            <version>1.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>

        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

application.properties

server.port=
spring.h2.console.path=/h2
spring.h2.console.enabled=true

spring.datasource.url=

spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.platform=h2
spring.datasource.initialization-mode=always

spring.jpa.hibernate.ddl-auto=update
spring.datasource.continue-on-error=true

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=false

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

Should remove unknown error in pom.xml and also I must be able to populate values in H2 db.

Body:
whenever you facing this type of error simply change the
Release version  just like
In my case  it is showing Error in 2.2.7 I changed to 2.2.6

Problem:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>

Solution:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>


问:
Howto set cookie_httponly?
So i have my code where i use session

```<code>$session->start();
if (...){
...
$session->set('session', $someVar);
}
</code>```

And Ive got some problem when i try in console document.cookie. How can i set cookie_httponly, im using symfony. And where should i set it? i tried to set it in the same file where i used $session->start();

```<code>ini_set('session.cookie_httponly', 1);
class Class
{
$session->start();
if (...){
...
$session->set('session', $someVar);
}
}
</code>```

Was it right?

答:
Set PHP.ini values then set session cookie parameters before you start session.

```<code>ini_set("session.cookie_domain",".".$_SERVER['SERVER_NAME']);
ini_set("session.cookie_secure",true);
ini_set("session.cookie_httponly",true);

session_set_cookie_params(
    0,
    "/",
    ini_get("session.cookie_domain"),
    ini_get("session.cookie_secure"),
    ini_get("session.cookie_httponly")
);

session_start();
</code>```

To set cookie:

```<code>setCookie(
    $cookie_name="CookieName",
    $cookie_value="CookieValue",
    $cookie_lifetime=time()+31536000, // 1 Year
    $cookie_path="/",
    ini_get("session.cookie_domain"),
    ini_get("session.cookie_secure"),
    ini_get("session.cookie_httponly")
)
</code>```

Refer to the official PHP Manual for more details.

Title: Howto set cookie_httponly?

Body:
So i have my code where i use session

$session->start();
if (...){
...
$session->set('session', $someVar);
}

And Ive got some problem when i try in console document.cookie. How can i set cookie_httponly, im using symfony. And where should i set it? i tried to set it in the same file where i used $session->start();

ini_set('session.cookie_httponly', 1);
class Class
{
$session->start();
if (...){
...
$session->set('session', $someVar);
}
}

Was it right?

Body:
Set PHP.ini values then set session cookie parameters before you start session.

ini_set("session.cookie_domain",".".$_SERVER['SERVER_NAME']);
ini_set("session.cookie_secure",true);
ini_set("session.cookie_httponly",true);

session_set_cookie_params(
    0,
    "/",
    ini_get("session.cookie_domain"),
    ini_get("session.cookie_secure"),
    ini_get("session.cookie_httponly")
);

session_start();

To set cookie:

setCookie(
    $cookie_name="CookieName",
    $cookie_value="CookieValue",
    $cookie_lifetime=time()+31536000, // 1 Year
    $cookie_path="/",
    ini_get("session.cookie_domain"),
    ini_get("session.cookie_secure"),
    ini_get("session.cookie_httponly")
)

Refer to the official PHP Manual for more details.


问:
Personal names in a global application: What to store
Storing personal names in a structured way seems quite difficult when it comes to an application which is used by users from lots of different countries. The application I'm working on could theoretically be used by anyone from any place in the world.

Most often a given name (first name / forename) and surname seems to be used. In which case those two could simply be stored in the user database table.

Is storing "given name" and "surname" in the user table enough for a globally used application? Please give your opinion with a motivation.

Do you have any other suggestions?

Are there any good guides on how to solve this?

Some important facts:

Communication between users (who reside at the same or different companies and may be in different countries).

It's important that searching for users by name feels natural to users and that all important parts of a person name are searchable.

It would be nice if, when sending a message to someone in another country the system should be able to help by suggesting a proper greeting. It will probably be hard for arabic names, at least from what I've read as they seem to have a complex structure.

答:
In general, a name is a human-readable identifier of a person. For a given person, you will need to store one name for each use case of such an identifier. You will need a name to display as part of the postal address; you may need one to use as a "screen name"; you may need one to use in the openning of a letter to the person; you may sometimes need to include titles and honors of the person, sometimes not.

In any of these cases, what you want to display is a single string. You may or may not be able to avoid duplication of effort by storing components of these strings and putting them back together later. But in general, both in terms of national culture and professional culture, you may be better off just storing the full strings.

The same, BTW, largely occurs for postal addresses, except that there are international standards that permit the postal authority of one country to send mail to persons in another country.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: John Saunders


问:
Zend passing string containing "Zero" to form-element Description
Zend talk. I built a Zend_Form class.
I noticed that if I pass the string '0' the method setDescription of my form-element will consider it as NULL  and I can't get to echo out its value in the element description.

```<code>//this is how I set the element description in Myform class:
$element->setDescription('0');
</code>```

How can I avoid that?

Thanks

Luca

答:
According to http://php.net/manual/en/function.empty.php, php recognizes '0' as empty.

The Description decorator render() function checks to see if the description is empty(). There doesn't currently appear to be a way to display just a '0'.

I'd suggest filing a bug report at http://framework.zend.com/issues

Until that gets changed, your best bet is to create your own Description decorator which extends the Zend one and changes the behavior.

Body:
Zend talk. I built a Zend_Form class.
I noticed that if I pass the string '0' the method setDescription of my form-element will consider it as NULL  and I can't get to echo out its value in the element description.

//this is how I set the element description in Myform class:
$element->setDescription('0');

How can I avoid that?

Thanks

Luca


问:
Limit the date to today and block the previous dates
I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);

    const dayFromImputDate = inputDate.getFullYear(); // previous day

    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }

    console.log("Date is valid");
    return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html></code>```

Thank you very much for your help and your time.

答:
You can check if input date is less than today's date using < operator

const form = document.querySelector('form');
const error = document.getElementById('date_startError');

function validation(event) {
  event.preventDefault();

  const startDate = form.elements['date_start'].value;

  if (!startDate) {
    error.innerHTML = " ** date empty ! ";
    return;
  }

  const inputDate = new Date(startDate).getDate();
  const today = new Date().getDate();

  if (inputDate < today || !inputDate.valueOf()) {
    error.innerHTML = " ** Error date ! ";
    return;
  }

  error.innerHTML = "date is valid";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="validation(event)">
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

Body:
I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);

    const dayFromImputDate = inputDate.getFullYear(); // previous day

    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }

    console.log("Date is valid");
    return true;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">

<form action="#" onsubmit="return validation()" >

Date start :

<input type="date" name="date_start" id="date_start">

<input type="submit" value="ok">
</form>

Thank you very much for your help and your time.

Body:
You can check if input date is less than today's date using < operator

const form = document.querySelector('form');
const error = document.getElementById('date_startError');

function validation(event) {
  event.preventDefault();

  const startDate = form.elements['date_start'].value;

  if (!startDate) {
    error.innerHTML = " ** date empty ! ";
    return;
  }

  const inputDate = new Date(startDate).getDate();
  const today = new Date().getDate();

  if (inputDate < today || !inputDate.valueOf()) {
    error.innerHTML = " ** Error date ! ";
    return;
  }

  error.innerHTML = "date is valid";
}

<form action="#" onsubmit="validation(event)">
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>


问:
Get all points of a straight line in python
Very simply, given a point A(x,y) and another point B(m,n), I need a function that can return in any iterable object a list[k,z] of all points in between.

Am only interested in integer points, so no need for floats.

I need the best possible pythonic way because this 'little' function is going to be heavily run and is the key pillar of a larger system.

EDIT:

@roippi, thanks pointing out the gotcha concerning the integers. From my code below, you can see I try to step across the x axis and get corresponding y, then do the same for y. My set of points will not have any non-discrete co-ordinate point, so for the moment I can afford to overlook that small flaw

```<code>import itertools
#Vars
origin = {'x':0, 'y':0}

def slope(origin, target):
    if target['x'] == origin['x']:
        return 0
    else:
        m = (target['y'] - origin['y']) / (target['x'] - origin['x'])
        return m

def line_eqn(origin, target):
    x = origin['x']
    y = origin['y']
    c = -(slope(origin, target)*x - y)
    c = y - (slope(origin, target)*x)
    #return 'y = ' + str(slope(target)) + 'x + ' + str(c)
    m = slope(origin, target)
    return {'m':m, 'c':c}

def get_y(x, slope, c):
    # y = mx + c
    y = (slope*x) + c
    return y

def get_x(y, slope, c):
    #x = (y-c)/m
    if slope == 0:
        c = 0   #vertical lines never intersect with y-axis
    if slope == 0:
        slope = 1   #Do NOT divide by zero
    x = (y - c)/slope
    return x

def get_points(origin, target):
    coord_list = []
    #Step along x-axis
    for i in range(origin['x'], target['x']+1):
        eqn = line_eqn(origin, target)
        y = get_y(i, eqn['m'], eqn['c'])
        coord_list.append([i, y])

    #Step along y-axis
    for i in range(origin['y'], target['y']+1):
        eqn = line_eqn(origin, target)
        x = get_x(i, eqn['m'], eqn['c'])
        coord_list.append([x, i])

    #return unique list
    return list(k for k,_ in itertools.groupby(sorted(coord_list)))

origin = {'x':1, 'y':3}
target = {'x':1, 'y':6}

print get_points(origin, target)
</code>```

答:
```<code>def getLine(x1,y1,x2,y2):
    if x1==x2: ## Perfectly horizontal line, can be solved easily
        return [(x1,i) for i in range(y1,y2,int(abs(y2-y1)/(y2-y1)))]
    else: ## More of a problem, ratios can be used instead
        if x1>x2: ## If the line goes "backwards", flip the positions, to go "forwards" down it.
            x=x1
            x1=x2
            x2=x
            y=y1
            y1=y2
            y2=y
        slope=(y2-y1)/(x2-x1) ## Calculate the slope of the line
        line=[]
        i=0
        while x1+i < x2: ## Keep iterating until the end of the line is reached
            i+=1
            line.append((x1+i,y1+slope*i)) ## Add the next point on the line
        return line ## Finally, return the line!

</code>```

Body:
Very simply, given a point A(x,y) and another point B(m,n), I need a function that can return in any iterable object a list[k,z] of all points in between.

Am only interested in integer points, so no need for floats.

I need the best possible pythonic way because this 'little' function is going to be heavily run and is the key pillar of a larger system.

EDIT:

@roippi, thanks pointing out the gotcha concerning the integers. From my code below, you can see I try to step across the x axis and get corresponding y, then do the same for y. My set of points will not have any non-discrete co-ordinate point, so for the moment I can afford to overlook that small flaw

import itertools
#Vars
origin = {'x':0, 'y':0}

def slope(origin, target):
    if target['x'] == origin['x']:
        return 0
    else:
        m = (target['y'] - origin['y']) / (target['x'] - origin['x'])
        return m

def line_eqn(origin, target):
    x = origin['x']
    y = origin['y']
    c = -(slope(origin, target)*x - y)
    c = y - (slope(origin, target)*x)
    #return 'y = ' + str(slope(target)) + 'x + ' + str(c)
    m = slope(origin, target)
    return {'m':m, 'c':c}

def get_y(x, slope, c):
    # y = mx + c
    y = (slope*x) + c
    return y

def get_x(y, slope, c):
    #x = (y-c)/m
    if slope == 0:
        c = 0   #vertical lines never intersect with y-axis
    if slope == 0:
        slope = 1   #Do NOT divide by zero
    x = (y - c)/slope
    return x

def get_points(origin, target):
    coord_list = []
    #Step along x-axis
    for i in range(origin['x'], target['x']+1):
        eqn = line_eqn(origin, target)
        y = get_y(i, eqn['m'], eqn['c'])
        coord_list.append([i, y])

    #Step along y-axis
    for i in range(origin['y'], target['y']+1):
        eqn = line_eqn(origin, target)
        x = get_x(i, eqn['m'], eqn['c'])
        coord_list.append([x, i])

    #return unique list
    return list(k for k,_ in itertools.groupby(sorted(coord_list)))

origin = {'x':1, 'y':3}
target = {'x':1, 'y':6}

print get_points(origin, target)


问:
How to provide methods outside the Angular Library - publishing to npm
I created a simple application that needs several methods from the outside. I know that we export modules outside using public-api.ts but how to import any dependencies?

For example, I need to use the getToken() and logout() methods from src/app/auth.service.ts inside projects/my-npm-project/src/lib/services/example.service.ts how to do it?

Because when I add dependency in the traditional way (import * from ...) I get an error 'rootDir' is expected to contain all source files. when I run ng build my-npm-project ;/

```<code>Angular
|
|- projects
|   |_my-npm-project
|       |_src
|           |_lib
|               |_services
|                   |_example.service.ts
|
|- src
    |_app
        |_auth.service.ts
</code>```

答: Not sure you can use the outside functions inside the Library. You may need to pass the values inside, or you may need to have an event emitted using @Output() and call the function from the main application folder, and pass value inside.</p>

Body:
I created a simple application that needs several methods from the outside. I know that we export modules outside using public-api.ts but how to import any dependencies?

For example, I need to use the getToken() and logout() methods from src/app/auth.service.ts inside projects/my-npm-project/src/lib/services/example.service.ts how to do it?

Because when I add dependency in the traditional way (import * from ...) I get an error 'rootDir' is expected to contain all source files. when I run ng build my-npm-project ;/

Angular
|
|- projects
|   |_my-npm-project
|       |_src
|           |_lib
|               |_services
|                   |_example.service.ts
|
|- src
    |_app
        |_auth.service.ts