问:
How can you check if an array contains a duplicate? JavaScript
Start with an empty array, and add the numbers 1 - 10 RANDOMLY only allowing a number to be repeated once.
eg: when generated, the array would contain two 1's, two 2's, and so on. [1, 1, 2, 2,... 9, 9, 10, 10]

```<code>arr = []

getrandomNum() => {
  let randomNum = Math.floor(Math.random() * 10) - 1;}
  arr.push(randomNum)
</code>```

This example allows more than two of the same number to be generated and I'm not sure what the logic would be not allow more than two 1's or two 5's and so on.

The end result will be apart of a bigger picture; a numbers games like the one on Countdown https://en.wikipedia.org/wiki/Countdown_(game_show)

答:
We can create a random number and check if it is already there in the result array and push it if not. But there is a possibility here, theoretically, that random number continue to generate the same set of number and ends up with an infinity loop. So in order to overcome this, we can have a separate values array and remove each item from it after picking randomly from it.

Sample visualization of the logic:

/**
 * Start with an empty array, and add the numbers 1 - 10 RANDOMLY
 * only allowing a number to be repeated once.
 * eg: when generated, the array would contain two 1's, two 2's, and so on.
 * [1, 1, 2, 2,... 9, 9, 10, 10]
**/

// result array
const result = []

// Define an array with values from 1 to 10
const baseValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
renderBaseValues();

function updateResult() {
  if(baseValues.length == 0) {
    return;
  }
  // Generate random number between 0 to 9
  let maxRandomValue = baseValues.length;
  let currentRandomIndex = Math.floor(Math.random() * maxRandomValue);

  // push random value two time
  result.push(baseValues[currentRandomIndex]);
  result.push(baseValues[currentRandomIndex]);

  // remove this from base values to avoid adding again
  baseValues.splice(currentRandomIndex, 1);
  renderBaseValues();
  renderResult();
  setTimeout(() => {
    updateResult();
  }, 1000)
}

updateResult();

/// Render functions --
function renderBaseValues() {
  const el = document.getElementById("main");
  el.innerHTML = "";
  baseValues.forEach(val => {
    el.innerHTML += `<span class="base-val">${val}</span>`
  });
}

function renderResult() {
  const el = document.getElementById("result");
  el.innerHTML = "";
  result.forEach(val => {
    el.innerHTML += `<span class="result">${val}</span>`
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
  margin: 5px;
}

.base-val, .result {
  border: 1px solid #ccc;
  padding: 4px;
  margin: 2px;
}

.result {
  border: 1px solid #00ff00;
}</code>```

Base values

Result values

```

Body:
Start with an empty array, and add the numbers 1 - 10 RANDOMLY only allowing a number to be repeated once.
eg: when generated, the array would contain two 1's, two 2's, and so on. [1, 1, 2, 2,... 9, 9, 10, 10]

arr = []

getrandomNum() => {
  let randomNum = Math.floor(Math.random() * 10) - 1;}
  arr.push(randomNum)

This example allows more than two of the same number to be generated and I'm not sure what the logic would be not allow more than two 1's or two 5's and so on.

The end result will be apart of a bigger picture; a numbers games like the one on Countdown https://en.wikipedia.org/wiki/Countdown_(game_show)

Body:
We can create a random number and check if it is already there in the result array and push it if not. But there is a possibility here, theoretically, that random number continue to generate the same set of number and ends up with an infinity loop. So in order to overcome this, we can have a separate values array and remove each item from it after picking randomly from it.

Sample visualization of the logic:

/**
 * Start with an empty array, and add the numbers 1 - 10 RANDOMLY
 * only allowing a number to be repeated once.
 * eg: when generated, the array would contain two 1's, two 2's, and so on.
 * [1, 1, 2, 2,... 9, 9, 10, 10]
**/

// result array
const result = []

// Define an array with values from 1 to 10
const baseValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
renderBaseValues();

function updateResult() {
  if(baseValues.length == 0) {
    return;
  }
  // Generate random number between 0 to 9
  let maxRandomValue = baseValues.length;
  let currentRandomIndex = Math.floor(Math.random() * maxRandomValue);

  // push random value two time
  result.push(baseValues[currentRandomIndex]);
  result.push(baseValues[currentRandomIndex]);

  // remove this from base values to avoid adding again
  baseValues.splice(currentRandomIndex, 1);
  renderBaseValues();
  renderResult();
  setTimeout(() => {
    updateResult();
  }, 1000)
}

updateResult();

/// Render functions --
function renderBaseValues() {
  const el = document.getElementById("main");
  el.innerHTML = "";
  baseValues.forEach(val => {
    el.innerHTML += `<span class="base-val">${val}</span>`
  });
}

function renderResult() {
  const el = document.getElementById("result");
  el.innerHTML = "";
  result.forEach(val => {
    el.innerHTML += `<span class="result">${val}</span>`
  });
}

.row {
  margin: 5px;
}

.base-val, .result {
  border: 1px solid #ccc;
  padding: 4px;
  margin: 2px;
}

.result {
  border: 1px solid #00ff00;
}

<h3>Base values</h3>
<div id="main" class="row"></div>
<h3>Result values</h3>
<div id="result" class="row"></div>


来源: stackexchange

问:
How turn on flashlight using Barcode Detection in Google Play services?
I'm trying to reimplement Redlaser barcode Scanner using Google play services. And face to the problem with flashlight. Android hardware.Camera object can't be using in common with CameraSource from gms.vision.
Is there any opportunity to working with flashlight and Google barcode scanner?

答:
```<code>Add permossion on AndroidManifest file

 <uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />
 <permission android:name="android.permission.FLASHLIGHT"
        android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
        android:protectionLevel="normal"/>

Turn on torch on Android, using Kotlin.

cameraProvider.bindToLifecycle((LifecycleOwner)this,
                 cameraSelector, imageAnalysis, preview);

Get Camera for cameraProvider..

camera = cameraProvider!!.bindToLifecycle(
                    (this as LifecycleOwner),
                    cameraSelector!!, Preview
                )

to turn on/off the FlashLight
private fun navigateflash(isFlash : Boolean) {
            try {
               if(camera!= null && camera!!.cameraInfo.hasFlashUnit()){
                   if(isFlash){
                       camera!!.cameraControl.enableTorch(false); // or false
                       isFlashOn = false
                   }else{
                       camera!!.getCameraControl().enableTorch(true); // or false
                       isFlashOn = true
                   }
               }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
azcopy login not granting permissions
I want to use azcopy to download/upload to my blob storage.

Using azcopy login, opening the browser and login works fine.

```<code>$ azcopy login --tenant-id xxxx
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code xxx to authenticate.

INFO: Login succeeded.
</code>```

Now I am trying:

```<code>$ azcopy ls https://xxxx.blob.core.windows.net/xxxx

failed to obtain credential info: Login Credentials missing. No SAS token or OAuth token is present and the resource is not public
</code>```

The container access level is set to private, the authentication method set to Azure AD User Account and I am Storage Blob Data Owner and Owner.

What am I doing wrong?

答:
Please ensure that you have logged in first while you are performing the azcopy list operation .

I tested the same scenario in my environment by creating a storage account , a private container with Azure AD authentication enabled and having owner and storage blob data owner role like below :

Output:

The error only occurs when I have either logged out or haven't logged in to azcopy like below :

Update:

If the above doesn't resolve the issue the you can use keyctl session workaroundSession first and then use azcopy login and other commands as mentioned in this GitHub Issue by John Rusk

Title: azcopy login not granting permissions

Body:
I want to use azcopy to download/upload to my blob storage.

Using azcopy login, opening the browser and login works fine.

$ azcopy login --tenant-id xxxx
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code xxx to authenticate.

INFO: Login succeeded.

Now I am trying:

$ azcopy ls https://xxxx.blob.core.windows.net/xxxx

failed to obtain credential info: Login Credentials missing. No SAS token or OAuth token is present and the resource is not public

The container access level is set to private, the authentication method set to Azure AD User Account and I am Storage Blob Data Owner and Owner.

What am I doing wrong?


问:
How to pass parameters to URL from Laravel Blade file
I want to pass parameters from my blade file to the URL when the user presses the next or previous button. I want to achieve that when the user presses the button next, the parameters page will be equal to 1, and the value will keep increasing by one every time the user presses the following button. I know I have to do something in ref, but I do not know what code to put in. So the example URL after the user presses the next button will be www.example.com?page=1.

```<code><div>
    <ul class="pagination">
        <li class="">
            <a href=""><i class="fa fa-angle-left"></i> Previous</a>
        </li>
        <li class="">
            <a href="">Next <i class="fa fa-angle-right"></i></a>
        </li>
    </ul>
</div>
</code>```

答:
You can use Laravel default pagination such as

```<code>$users = User::paginate(15);
</code>```

and use them in the blade such as

```<code>{{ $users->links() }}
</code>```

There are many pagination option such as simplepaginate and other u can explore them as well
hope this would be helpfull

Body:
I want to pass parameters from my blade file to the URL when the user presses the next or previous button. I want to achieve that when the user presses the button next, the parameters page will be equal to 1, and the value will keep increasing by one every time the user presses the following button. I know I have to do something in ref, but I do not know what code to put in. So the example URL after the user presses the next button will be www.example.com?page=1.

             Previous

            Next

Body:
You can use Laravel default pagination such as

$users = User::paginate(15);

and use them in the blade such as

{{ $users->links() }}

There are many pagination option such as simplepaginate and other u can explore them as well
hope this would be helpfull


问:
Azure SQL server import export responds with Error SQL72014: .Net SqlClie
Azure SQL server import export responds with Error SQL72014: .Net SqlClie
Not able to see full stacktrace
Demo logs are as below

```<code>Additional details
Could not import package.
Warning SQL72012: The object [information_9] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Warning SQL72012: The object [stacktrace] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Error SQL72014: .Net SqlClie
</code>```

Error logs are incomplete. So, I am not able to identify MSG message number for it.

Please suggest possible solutions.

答:
The error SQL72014 is requesting to enable contained database authentication on the SQL Server instance.

In order to restore a contained database coming from Azure SQL Database into on-premise SQL Server instance the "contained database authentication" property must be enabled.

Solution:

To enable this property please try the below script:

```<code>sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO
</code>```

Body:
Azure SQL server import export responds with Error SQL72014: .Net SqlClie
Not able to see full stacktrace
Demo logs are as below

Additional details
Could not import package.
Warning SQL72012: The object [information_9] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Warning SQL72012: The object [stacktrace] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Error SQL72014: .Net SqlClie

Error logs are incomplete. So, I am not able to identify MSG message number for it.

Please suggest possible solutions.

Body:
The error SQL72014 is requesting to enable contained database authentication on the SQL Server instance.

In order to restore a contained database coming from Azure SQL Database into on-premise SQL Server instance the "contained database authentication" property must be enabled.

Solution:

To enable this property please try the below script:

sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO


问:
Datetime strptime in python
I've tried the following code :

```<code>import datetime
d = datetime.datetime.strptime("01/27/2012", "%m/%d/%Y")
print(d)
</code>```

and the output is :

```<code>2012-01-27 00:00:00
</code>```

I'am using Linux Mint :

```<code>test@testsrv ~/pythonvault $ date
Fri Jun 16 21:40:57 EEST 2017
</code>```

So,the question is why the output of python code returns a date in "%Y/%m/%d" ( 2012-01-27 ) instead of "%m/%d/%Y" format ?

Please note that I'am using python 2.7

Any help would be appreciated.

答:
The datetime.strptime() class method creates a datetime object from a
string representing a date and time and a corresponding format string.

%a

```<code>Weekday as locale’s abbreviated name.

Sun, Mon, …, Sat (en_US);
So, Mo, …, Sa (de_DE)
</code>```

%A

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```

%w

```<code>Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, …, 6
</code>```

%d

```<code>Day of the month as a zero-padded decimal number.

01, 02, …, 31
</code>```

%b

```<code>Month as locale’s abbreviated name.

Jan, Feb, …, Dec (en_US);
Jan, Feb, …, Dez (de_DE)
</code>```

%B

```<code> Month as locale’s full name.

 January, February, …, December (en_US);
 Januar, Februar, …, Dezember (de_DE)
</code>```

%m

```<code>Month as a zero-padded decimal number.

01, 02, …, 12
</code>```

%y

```<code>Year without century as a zero-padded decimal number.

00, 01, …, 99
</code>```

%Y

```<code>Year with century as a decimal number.

0001, 0002, …, 2013, 2014, …, 9998, 9999
</code>```

%H

```<code>Hour (24-hour clock) as a zero-padded decimal number.

00, 01, …, 23
</code>```

%I

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```0

%p

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```1

%M

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```2

%S

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```3

%f

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```4

%z

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```5

%Z

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```6

%j

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```7

%U

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```8

first Sunday are considered to be in week 0.

```<code>Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
</code>```9

%W

```<code>Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, …, 6
</code>```0

first Monday are considered to be in week 0.

```<code>Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, …, 6
</code>```1

%c

```<code>Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, …, 6
</code>```2

%x

```<code>Locale’s appropriate date representation.

08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
</code>```

%X

```<code>Locale’s appropriate time representation.

21:30:00 (en_US);
21:30:00 (de_DE)
</code>```

%%

```<code>A literal '%' character.

%
</code>```

for more information please visit official website for python

Example Programs for better understanding

Program 1:

```<code>from datetime import datetime

data = "2022-02-09 12:25:22"

dat = datetime.strptime(data, "%Y-%m-%d %H:%M:%S")
print(dat)
</code>```

Output:

```<code>2022-02-09 12:25:22
</code>```

Program 2:

```<code>from datetime import datetime
data = "Thursday, 10 February 2022 11:28:45 am"
dat = datetime.strptime(data, "%A, %d %B %Y %H:%M:%S %p")
print(dat)
</code>```

Output:

```<code>2022-02-10 11:28:45
</code>```

Title: Datetime strptime in python

Body:
I've tried the following code :

import datetime
d = datetime.datetime.strptime("01/27/2012", "%m/%d/%Y")
print(d)

and the output is :

2012-01-27 00:00:00

I'am using Linux Mint :

test@testsrv ~/pythonvault $ date
Fri Jun 16 21:40:57 EEST 2017

So,the question is why the output of python code returns a date in "%Y/%m/%d" ( 2012-01-27 ) instead of "%m/%d/%Y" format ?

Please note that I'am using python 2.7

Any help would be appreciated.

Body:
The datetime.strptime() class method creates a datetime object from a
string representing a date and time and a corresponding format string.

%a

Weekday as locale’s abbreviated name.

Sun, Mon, …, Sat (en_US);
So, Mo, …, Sa (de_DE)

%A

Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)

%w

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, …, 6

%d

Day of the month as a zero-padded decimal number.

01, 02, …, 31

%b

Month as locale’s abbreviated name.

Jan, Feb, …, Dec (en_US);
Jan, Feb, …, Dez (de_DE)

%B

 Month as locale’s full name.

 January, February, …, December (en_US);
 Januar, Februar, …, Dezember (de_DE)

%m

Month as a zero-padded decimal number.

01, 02, …, 12

%y

Year without century as a zero-padded decimal number.

00, 01, …, 99

%Y

Year with century as a decimal number.

0001, 0002, …, 2013, 2014, …, 9998, 9999

%H

Hour (24-hour clock) as a zero-padded decimal number.

00, 01, …, 23

%I

Hour (12-hour clock) as a zero-padded decimal number.

01, 02, …, 12

%p

Locale’s equivalent of either AM or PM.

AM, PM (en_US);
am, pm (de_DE)

%M

Minute as a zero-padded decimal number.

00, 01, …, 59

%S

Second as a zero-padded decimal number.

00, 01, …, 59

%f

Microsecond as a decimal number, zero-padded to 6 digits.

000000, 000001, …, 999999

%z

UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

(empty), +0000, -0400, +1030, +063415, -030712.345216

%Z

Time zone name (empty string if the object is naive).

(empty), UTC, GMT

%j

Day of the year as a zero-padded decimal number.

001, 002, …, 366

%U

Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the

first Sunday are considered to be in week 0.

00, 01, …, 53

%W

Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the

first Monday are considered to be in week 0.

00, 01, …, 53

%c

Locale’s appropriate date and time representation.

Tue Aug 16 21:30:00 1988 (en_US);
Di 16 Aug 21:30:00 1988 (de_DE)

%x

Locale’s appropriate date representation.

08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)

%X

Locale’s appropriate time representation.

21:30:00 (en_US);
21:30:00 (de_DE)

%%

A literal '%' character.

%

for more information please visit official website for python

Example Programs for better understanding

Program 1:

from datetime import datetime

data = "2022-02-09 12:25:22"

dat = datetime.strptime(data, "%Y-%m-%d %H:%M:%S")
print(dat)

Output:

2022-02-09 12:25:22

Program 2:

from datetime import datetime
data = "Thursday, 10 February 2022 11:28:45 am"
dat = datetime.strptime(data, "%A, %d %B %Y %H:%M:%S %p")
print(dat)

Output:

2022-02-10 11:28:45


问:
SharePoint Designer Site Configuration error while creating forms
I have configure SharePoint site in my local system, While I am going to create forms I am getting error

答:
SharePoint Designer deprecated please check these two articles:

https://microsoft365.today/microsoft-365/powerapps/sharepoint-designer-feature-deprecation/

https://learn.microsoft.com/en-us/sharepoint/what-s-new/what-s-deprecated-or-removed-from-sharepoint-...


问:
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?

We already have a WAMP stack setup on a Windows Server 2003 box to support some internal PHP applications, and I want to also setup CI Factory on that box which will try to configure IIS to support it's ASP.NET based dashboard.  I want to make sure that there isn't a big chance of fubarring the WAMP stack that is already there.  Will it be smart enough to handle *.PHP through Apache and *.aspx through IIS ?

Edit: Is there a way to get this to work on the same port?

答: As mentioned before, yes. If it helps to provide "real world examples", the GoDaddy account that I'm currently hosting my sites on gives me both stacks. I have a couple SMF forums that are PHP/MySQL based and I have a web application that is .NET 3.5/SQL Server 2005 based and they run just fine.</p>

OwnerDisplayName: aaronls

LastEditorDisplayName: aaronls

OwnerDisplayName: Dillie-O

ContentLicense: CC BY-SA 2.5


问:
How to call current temperature from openweathermap with axios
I am trying to do an axios call to get the latest temperature using openweatherapi. However for some reason I cant find out why my axios call is not working. Any help would be great, here is my code:

```<code>function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}
</code>```

Any advice on what im doing wrong would be great!

答:
You can get the data using encodeURI() function.

```<code>const getWeather = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}`;
    const response = await axios.get(encodeURI(url));
    const temp = await response.data?.main?.temp;
    setData(temp);
}
</code>```

Body:
I am trying to do an axios call to get the latest temperature using openweatherapi. However for some reason I cant find out why my axios call is not working. Any help would be great, here is my code:

function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}

Any advice on what im doing wrong would be great!

Body:
You can get the data using encodeURI() function.

const getWeather = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}`;
    const response = await axios.get(encodeURI(url));
    const temp = await response.data?.main?.temp;
    setData(temp);
}


问:
throws NoRootNodeMappingException while projecting/mapping neo4j query result to an interface or DTO class
my query is very simple and the projection I am doing is following guidelines given in [https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#projections.interfaces](Spring Data Neo4J Projection) documentation.
My Code:

```<code>@Query("MATCH (User {mobile:$mobile})-[:CONTACT]-(n:User)-[:STEPTAKER]-(s:Step) RETURN n.name AS name, s.count AS count")
    public List<StepList> findAllStepByMobile(String mobile);

interface StepList{
    String getName();
    int getCount();
}
</code>```

The error:
2021-09-10 10:36:25.180 ERROR 18088 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.neo4j.core.mapping.NoRootNodeMappingException: Could not find mappable nodes or relationships inside Record<{s.count: 400}> for org.springframework.data.neo4j.core.mapping.DefaultNeo4jPersistentEntity@305b43ca] with root cause

org.springframework.data.neo4j.core.mapping.NoRootNodeMappingException: Could not find mappable nodes or relationships inside Record<{s.count: 400}> for org.springframework.data.neo4j.core.mapping.DefaultNeo4jPersistentEntity@305b43ca

答:
https://docs.spring.io/spring-data/neo4j/docs/6.2.0/reference/html/#projections.interfaces

From the above link:

"The important bit here is that the properties defined here exactly match properties in the aggregate root"

I think that means your StepList interface has to have a subset of properties from your root class (which I assume is User).

Body:
my query is very simple and the projection I am doing is following guidelines given in [https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#projections.interfaces](Spring Data Neo4J Projection) documentation.
My Code:

@Query("MATCH (User {mobile:$mobile})-[:CONTACT]-(n:User)-[:STEPTAKER]-(s:Step) RETURN n.name AS name, s.count AS count")
    public List<StepList> findAllStepByMobile(String mobile);

interface StepList{
    String getName();
    int getCount();
}

The error:
2021-09-10 10:36:25.180 ERROR 18088 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.neo4j.core.mapping.NoRootNodeMappingException: Could not find mappable nodes or relationships inside Record<{s.count: 400}> for org.springframework.data.neo4j.core.mapping.DefaultNeo4jPersistentEntity@305b43ca] with root cause

org.springframework.data.neo4j.core.mapping.NoRootNodeMappingException: Could not find mappable nodes or relationships inside Record<{s.count: 400}> for org.springframework.data.neo4j.core.mapping.DefaultNeo4jPersistentEntity@305b43ca


问:
Blocking commits to branches with no-direct-commit policies
I work with git repos hosted in Azure Devops (AzDO). Usually the master branch has AzDO policy that you can't push directly to it, and must use pull requests. However, some folks accidentally commit locally to master, and then their master branch gets out of sync with the origin, and they need to reset it with git reset --hard origin. I want to avoid this.

I know I can prevent commits to master using pre-commit hooks, with scripts or utils that will block (See answers to this question, and also this answer to a similar question). The richest util for this - https://pre-commit.com/hooks.html - only has a manually-configured no-commit-to-branch list.

Is there a solution that will block commits to any branch with policies in AzDO?

Edit in response to comments:

I disagree it's a training issue. A tool should do its best to guard users from mistake (just like saws have hand guard/etc.). IMO git fails at it, and git/AzDO could do better.

That said, maybe the git checkout master/git checkout -b mybranch is at fault here. So git fetch/git checkout -b mybranch origin/master would be safer.

I know one can reset/rebase, and that's the workaround for folks that got into this situation. However, I'd like to avoid that, especially for people with lower git skills.

答:
However, some folks accidentally commit locally to master, and then their master branch gets out of sync with the origin, and they need to reset it with git reset --hard origin. I want to avoid this.

They don't need to do that. In Git, all ref names are local and completely, utterly arbitrary. Just rename the local branch.

```<code>git branch -M master whatIshouldhavecalledit
</code>```

is all they need, rename their branch.

Body:
However, some folks accidentally commit locally to master, and then their master branch gets out of sync with the origin, and they need to reset it with git reset --hard origin. I want to avoid this.

They don't need to do that. In Git, all ref names are local and completely, utterly arbitrary. Just rename the local branch.

git branch -M master whatIshouldhavecalledit

is all they need, rename their branch.


问:
Best way to start learning Corona?
I know I know this has been posted millions of times but I still can't find a solution.

I want to start learning Corona and taking it seriously but I don't know how to start.

I feel shame actually because I've been playing with its API for a couple of days but I still have lots of weakness and questions mostly in its basics and structure of the language.

People posted Lua online Book link but how to start with it? Do I have to download Lua compiler or I could just use Corona compiler and after a fast checking I feel there is difference between lua and corona when it comes to syntaxes.

I've never felt this way when I started learning Fortran75 and Java. Everything was easy to look for books (love books) and videos and much more.

So to all Corona expert lvls please guide me to the best road to learn.

答:
If you want to learn using the Corona SDK, have a look at http://www.learningcorona.com as proposed by jhocking.

If you want to learn Lua first, check out http://lua-users.org/. You will find tutorials and code snippets there, which should get you started.

Another good starting point to learn Lua is to look at the rosetta code site: http://rosettacode.org/wiki/Lua There you can compare Lua to one of the languages you already know.

Last but not least, I would be happy to help you myself, if you ask more specific questions.

I have written a complete tutorial on my blog http://www.cutemachine.com on how to write a complete game with the Corona SDK. It is also listed on learningcorona.com.

Title: Best way to start learning Corona?


问:
sqlalchemy relationship and classmethods and not only
I have a problem that I can't solve((( Sample code below...

```<code>from sqlalchemy import Column, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.types import Integer, String, Text

Base = declarative_base()

class Model(Base):
    __abstract__ = True

    @classmethod
    def need_run(cls):
        pass

class Profile(Model):
  __tablename__ = 'profile'

  id = Column('id', Integer, primary_key=True)
  email = Column('email', String(length=128), unique=True, index=True)
  password = Column('password', String(length=255), index=True)
  messages = relationship('Message', lazy='select')

class Message(Model):

  __tablename__ = 'message'
  id = Column('id', Integer, primary_key=True)
  profile_id = Column('profile_id', Integer, ForeignKey('profile.id', ondelete='CASCADE'))
  title = Column('title', String(length=128), unique=True, index=True)
  body = Column('text', Text, index=True)
</code>```

Through the message attribute, i want to access the Message class to run the need_run method

Through the profile_id attribute, i want to access the Profile class to run the need_run method

Is it possible?

答:
It should be possible but you probably want to change your relationship to include a backref:

class Profile(Model):
    #...
    messages = relationship('Message', lazy='select', backref="profile")
```
<p>Then you can access messages from a profile like:</p>
<pre class="lang-py prettyprint-override"><code>for msg in some_profile.messages:
    msg.need_run()
</code>```

And you can access a profile from a message like:

some_message.profile.need_run()
```

Body:
I have a problem that I can't solve((( Sample code below...

from sqlalchemy import Column, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.types import Integer, String, Text

Base = declarative_base()

class Model(Base):
    __abstract__ = True

    @classmethod
    def need_run(cls):
        pass

class Profile(Model):
  __tablename__ = 'profile'

  id = Column('id', Integer, primary_key=True)
  email = Column('email', String(length=128), unique=True, index=True)
  password = Column('password', String(length=255), index=True)
  messages = relationship('Message', lazy='select')

class Message(Model):

  __tablename__ = 'message'
  id = Column('id', Integer, primary_key=True)
  profile_id = Column('profile_id', Integer, ForeignKey('profile.id', ondelete='CASCADE'))
  title = Column('title', String(length=128), unique=True, index=True)
  body = Column('text', Text, index=True)

Through the message attribute, i want to access the Message class to run the need_run method

Through the profile_id attribute, i want to access the Profile class to run the need_run method

Is it possible?

Body:
It should be possible but you probably want to change your relationship to include a backref:

class Profile(Model):
    #...
    messages = relationship('Message', lazy='select', backref="profile")

Then you can access messages from a profile like:

for msg in some_profile.messages:
    msg.need_run()

And you can access a profile from a message like:

some_message.profile.need_run()


问:
Is there a way to turn a rectangle into a circle in pygame?
This is my code atm. It outputs a square right on top of a circle. I want to make the square sort of "turn into" the circle.</p>
```<code>import pygame

GREEN = (0,255,0)

pygame.init()
pygame.display.set_caption("Game TITLE")
screen = pygame.display.set_mode((400,400))

quitVar = True

while quitVar == True:
    screen.fill(WHITE)

    pygame.draw.rect(screen, GREEN, (100,100,200,200))
    pygame.draw.circle(screen, GREEN, (200,200),100)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            quitVar = False

    pygame.display.update()

pygame.quit()

</code>```

答:
You can draw a rectangle with round corners in Pygame (see Setting a pygame surface to have rounded corners). Animate the corner radius from 0 to the radius of the circle:

import pygame

WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

pygame.init()
pygame.display.set_caption("Game TITLE")
screen = pygame.display.set_mode((400,400))
clock = pygame.time.Clock()

radius = 0
step = 1

quitVar = True
while quitVar == True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quitVar = False

    screen.fill(WHITE)
    pygame.draw.rect(screen, GREEN, (100, 100, 200, 200), border_radius = radius)
    pygame.display.update()

    radius += step
    if radius <= 0 or radius >= 100:
        step *= -1

pygame.quit()
```

Body:
This is my code atm. It outputs a square right on top of a circle. I want to make the square sort of "turn into" the circle.

import pygame

GREEN = (0,255,0)

pygame.init()
pygame.display.set_caption("Game TITLE")
screen = pygame.display.set_mode((400,400))

quitVar = True

while quitVar == True:
    screen.fill(WHITE)

    pygame.draw.rect(screen, GREEN, (100,100,200,200))
    pygame.draw.circle(screen, GREEN, (200,200),100)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            quitVar = False

    pygame.display.update()

pygame.quit()


问:
How do I automatically redirect when the session cookie expires?
When a user is idle for ten minutes, I would like to have an automatic redirect. Below is the test code, which is not working.

The LoginPath, LogoutPath, and AccessDeniedPath do not exist. Therefore, I would expect an error after the timeout period. Instead, I can continue to successfully click "Home" and "About" without an error and without being redirected. My expectation is that I will be redirected back to the home page.

Sample code:

services.AddMemoryCache();
services.AddSession(options =>
    {
        options.Cookie.Name = "MyAppCookie";
        options.Cookie.IsEssential = true;
        options.Cookie.HttpOnly = true;
        options.IdleTimeout = TimeSpan.FromMinutes(1);
    });

services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
        options.SlidingExpiration = true;
    });
```

答:
On the server side, your code can know about the session timeout. Using it, you can set a cookie indicating when the actual session timeout occurred (no mention of whether it was an active session timeout or an idle timeout). The javascript running on the page can periodically read the cookie and redirect the user when the timeout value is exceeded.

This is one of many methods that I hope will help you.

Refer this post ：

In ASP Net Core 3.1 Expiration cookie is not redirecting to login page when using ajax


问:
Vetur can't find package.json
I was writing code for my app with Vue and everything worked perfectly. Then I started to create child components and I could not refresh the localhost anymore.

Now it says:

"Vetur can't find 'package.json"
&
"Vetur can't find 'tsconfig.json' or 'jsconfig.json"

and when I try to "npm run serve" in the cmd - then i get this:

```<code>C:\Users\cmana\Desktop\WebDeveloper\Vue app\vuetify-todo>npm run serve
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\cmana\Desktop\WebDeveloper\Vue app\vuetify-todo\package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\cmana\Desktop\WebDeveloper\Vue app\vuetify-todo\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

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

Acording to this https://vuejs.github.io/vetur/guide/setup.html#project-setup - I tried to add the jsconfig.json file with this content. (I deleted all the child components so I only have these vue files (About, Todo, App) left.)

```<code>{
  "include": [
    "./src/views/About.vue",
    "./src/views/Todo.vue",
    "./src/App.vue"
  ]
}
</code>```

Still nothing. Anybody any ideas? Thank you <3

答:
In VS Code, if the actual code is in a subfolder (e.g you have a monorepo), you can add a vetur.config.js in the root directory as per below.

```<code>module.exports = {
    projects: [
      {
        root: './frontend', // root of your vue project (should contain package.json)
        package: './package.json', // Relative to root property, don't change this.
        tsconfig: './tsconfig.json',  // Relative to root property, don't change this.
      }
    ]
  }
</code>```

Please refer to Vetur Reference for more details.

Title: Vetur can't find package.json

Body:
I was writing code for my app with Vue and everything worked perfectly. Then I started to create child components and I could not refresh the localhost anymore.

Now it says:

"Vetur can't find 'package.json"
&
"Vetur can't find 'tsconfig.json' or 'jsconfig.json"

and when I try to "npm run serve" in the cmd - then i get this:

C:\Users\cmana\Desktop\WebDeveloper\Vue app\vuetify-todo>npm run serve
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\cmana\Desktop\WebDeveloper\Vue app\vuetify-todo\package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\cmana\Desktop\WebDeveloper\Vue app\vuetify-todo\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

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

Acording to this https://vuejs.github.io/vetur/guide/setup.html#project-setup - I tried to add the jsconfig.json file with this content. (I deleted all the child components so I only have these vue files (About, Todo, App) left.)

{
  "include": [
    "./src/views/About.vue",
    "./src/views/Todo.vue",
    "./src/App.vue"
  ]
}

Still nothing. Anybody any ideas? Thank you <3

Body:
In VS Code, if the actual code is in a subfolder (e.g you have a monorepo), you can add a vetur.config.js in the root directory as per below.

module.exports = {
    projects: [
      {
        root: './frontend', // root of your vue project (should contain package.json)
        package: './package.json', // Relative to root property, don't change this.
        tsconfig: './tsconfig.json',  // Relative to root property, don't change this.
      }
    ]
  }

Please refer to Vetur Reference for more details.


问:
How to make read prompt show when redirecting stderr to a process in bash
I currently have this issue where redirecting(2>) or piping(|&) stderr somewhere will cause read prompts to not print on the terminal when input is required. Instead the text is only printed after the program returned. The problem might look similar to this one, but I am not sure how it works and if we are having the same issue.

What I am trying to do is to filter the output of pacman so that it is not cluttered with warnings that I knew would be present. This is the command I execute:

pacman -Syu --ignore="$(IFS=',';echo "${AUTOPKG[*]}")" 2> >(grep -v 'ignoring package upgrade' >&2)

Where ${AUTOPKG[*]} is expanded to a comma separated list of package I want to ignore at that moment. grep -v filters out the unnecessary warnings and redirect the output back to the terminal.

In addition, I have also tried using the read utility to narrow the problem down to stderr only as redirecting stdout alone will still let the prompt through. I have no more clues from here on though, any help is appreciated.

答:
So I have experimented with the commands and stuff and found that the line is printed to the file descriptor just that it is not printing it out because it still haven't hit a newline, so I realized I can use read -rn1 to read the input and pass that to grep with a timeout that prints the buffer out if too much time is passed. Here is the drop-in replacement function for grep:

timeoutGrep()
{
    local string  pid_sleep=0
    while IFS= read -rN1 ch ;do
        if (( $pid_sleep )) && [ -e /proc/$pid_sleep ] ;\
            then kill $pid_sleep ;\
            else string='' ;fi
        string+="$ch"

        if [ "$ch" = $'\n' ] ;then
            grep "$@" <(printf '%s' "$string")
            pid_sleep=0
        else
            sleep 0.5 && grep "$@" <(printf '%s' "$string") | tr -d '\n' &
            pid_sleep=$!
        fi
    done
}
```

The rundown of what this function does is to read a char and append it to a buffer, then depend on the character read: '\n'? then send the line to grep immediately, since we know the line is finished, then tell the next iteration it didn't call a background process; or not '\n'? then create a background grep that is delayed, tell the next iteration what the pid of it is. An iteration is advanced when a new character is read, if the background process was successfully run it will be terminated, otherwise if it is 0, no background process was created, in both cases clean the buffer. If it is neither of both cases, assume the background process still hasn't grepped the string, kill it before it does, then carry on to continue the loop.

It seems to be working for now though it has some delays and may mess up the order of the message. I also tried using the timeout option in read but it seems to stop the running process somehow which I suspect is due to closing of the file descriptor.

Body:
So I have experimented with the commands and stuff and found that the line is printed to the file descriptor just that it is not printing it out because it still haven't hit a newline, so I realized I can use read -rn1 to read the input and pass that to grep with a timeout that prints the buffer out if too much time is passed. Here is the drop-in replacement function for grep:

timeoutGrep()
{
    local string  pid_sleep=0
    while IFS= read -rN1 ch ;do
        if (( $pid_sleep )) && [ -e /proc/$pid_sleep ] ;\
            then kill $pid_sleep ;\
            else string='' ;fi
        string+="$ch"

        if [ "$ch" = $'\n' ] ;then
            grep "$@" <(printf '%s' "$string")
            pid_sleep=0
        else
            sleep 0.5 && grep "$@" <(printf '%s' "$string") | tr -d '\n' &
            pid_sleep=$!
        fi
    done
}

The rundown of what this function does is to read a char and append it to a buffer, then depend on the character read: '\n'? then send the line to grep immediately, since we know the line is finished, then tell the next iteration it didn't call a background process; or not '\n'? then create a background grep that is delayed, tell the next iteration what the pid of it is. An iteration is advanced when a new character is read, if the background process was successfully run it will be terminated, otherwise if it is 0, no background process was created, in both cases clean the buffer. If it is neither of both cases, assume the background process still hasn't grepped the string, kill it before it does, then carry on to continue the loop.

It seems to be working for now though it has some delays and may mess up the order of the message. I also tried using the timeout option in read but it seems to stop the running process somehow which I suspect is due to closing of the file descriptor.


问:
Add a "Ship To" column in Woocommerce "My Account" orders table
I am trying to add a column that displays the 'Ship to' company name to the WooCommerce > my account > orders page.

So far the code below adds a column but how do I get the 'Ship to' data to show, where am I'm I getting it wrong?

 // Add new column(s) to the "My Orders" table in the account.
function filter_woocommerce_account_orders_columns( $columns ) {
    $columns['custom-column'] = __( 'New Column 1', 'woocommerce' );
    return $columns;
}
add_filter( 'woocommerce_account_orders_columns', 'filter_woocommerce_account_orders_columns', 10, 1 );

 // Adds data to the custom column in "My Account > Orders"
function filter_woocommerce_my_account_my_orders_shipping_company_column( $order ) {
    echo 'New Column 1';
}
add_action( 'woocommerce_my_account_my_orders_column_custom-column', 'filter_woocommerce_my_account_my_orders_column_custom_column', 10, 1 );

 $order_shipping_company = $order_data['shipping']['company'];```

答:
I discovered it : FINALLY !!

function sv_wc_add_my_account_orders_column( $columns ) {

    $new_columns = array();

    foreach ( $columns as $key => $name ) {

        $new_columns[ $key ] = $name;

        // add ship-to after order status column
        if ( 'order-status' === $key ) {
            $new_columns['order-ship-to'] = __( 'Ship to', 'textdomain' );
        }
    }

    return $new_columns;
}
add_filter( 'woocommerce_my_account_my_orders_columns', 'sv_wc_add_my_account_orders_column' );

/**
 * Adds data to the custom "ship to" column in "My Account > Orders".
 *
 * @param \WC_Order $order the order object for the row
 */
function sv_wc_my_orders_ship_to_column( $order ) {

    $formatted_shipping = $order->get_formatted_shipping_address();

    echo ! empty( $formatted_shipping ) ? $formatted_shipping : '–';
}
add_action( 'woocommerce_my_account_my_orders_column_order-ship-to', 'sv_wc_my_orders_ship_to_column' );```

Body:
I discovered it : FINALLY !!

function sv_wc_add_my_account_orders_column( $columns ) {

    $new_columns = array();

    foreach ( $columns as $key => $name ) {

        $new_columns[ $key ] = $name;

        // add ship-to after order status column
        if ( 'order-status' === $key ) {
            $new_columns['order-ship-to'] = __( 'Ship to', 'textdomain' );
        }
    }

    return $new_columns;
}
add_filter( 'woocommerce_my_account_my_orders_columns', 'sv_wc_add_my_account_orders_column' );

/**
 * Adds data to the custom "ship to" column in "My Account > Orders".
 *
 * @param \WC_Order $order the order object for the row
 */
function sv_wc_my_orders_ship_to_column( $order ) {

    $formatted_shipping = $order->get_formatted_shipping_address();

    echo ! empty( $formatted_shipping ) ? $formatted_shipping : '&ndash;';
}
add_action( 'woocommerce_my_account_my_orders_column_order-ship-to', 'sv_wc_my_orders_ship_to_column' );


问:
How to change font size in Material Design TabLayout android?
I have been trying to explore online to set my font size for TabLayout TabItems
But none of them seems to be working for me. This is what I tried referring last link

below are the things which I have implemented so far,
Not sure why it's not picking textSize from style.

in xml:

```<code><com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutForgot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/header_height"
                app:layout_constraintTop_toBottomOf="@+id/imageViewLogo"
                app:tabIndicatorColor="@color/text_color"
                app:tabSelectedTextColor="@color/text_color"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyCustomTabLayout"
                app:tabMode="fixed"
                app:tabIndicatorFullWidth="false"
                app:tabTextColor="@color/text_color" />
</code>```

in themes.xml:

```<code><style name="MyCustomTabLayout" parent="@android:style/TextAppearance.Widget.TabWidget">
        <item name="textAllCaps">false</item>
        <item name="android:textSize">20sp</item>
        <item name="android:fontFamily">@font/roboto_medium</item>
        <item name="android:textColor">@color/text_color</item>
    </style>
</code>```

this does everything else like textAllCaps and fontFamily but doesn't seems to take textSize.

Appreciate any help.

答:
You should inherit your style from TextAppearance.Design.Tab
First make a style,

```<code><style name="MyStyle" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">16sp</item>
</style>
</code>```

Then use it in your Tablayout like this,

```<code><android.support.design.widget.TabLayout
            app:tabTextAppearance="@style/MyStyle"
            ...
            />
</code>```

hope it will work

Body:
I have been trying to explore online to set my font size for TabLayout TabItems
But none of them seems to be working for me. This is what I tried referring last link

below are the things which I have implemented so far,
Not sure why it's not picking textSize from style.

in xml:

<com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutForgot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/header_height"
                app:layout_constraintTop_toBottomOf="@+id/imageViewLogo"
                app:tabIndicatorColor="@color/text_color"
                app:tabSelectedTextColor="@color/text_color"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyCustomTabLayout"
                app:tabMode="fixed"
                app:tabIndicatorFullWidth="false"
                app:tabTextColor="@color/text_color" />

in themes.xml:

this does everything else like textAllCaps and fontFamily but doesn't seems to take textSize.

Appreciate any help.

Body:
You should inherit your style from TextAppearance.Design.Tab
First make a style,

<style name="MyStyle" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">16sp</item>
</style>

Then use it in your Tablayout like this,

<android.support.design.widget.TabLayout
            app:tabTextAppearance="@style/MyStyle"
            ...
            />

hope it will work


问:
Do Docker secrets provide any additional security over a bind mount?
From what I understand, Docker secrets and mounts (bind and volume) are all secure ways of managing secrets within a Docker container. I am wondering whether secrets has any security advantages?

I have an arbitrarily sized group of secrets. The secrets are kept in separate files in a folder. They periodically and automatically change. I want to make all of them available to a Docker container. Using a bind mount, I can mount their folder and they will all be accessible. Using secrets, I would have to specify each one in the Docker Compose file, increasing coupling and reducing maintainability. Is there any reason I should choose to go with secrets at the cost of maintainability?

答:
if you are not using swarm, it is of no use to you.

Docker secrets are only available to swarm services, not to standalone containers.

using secrets has the following advantages

Secrets are encrypted during transit and at rest in a Docker swarm.

you can leverage secrets in docker compose, which bring the secrets features to containers regardless of swarm. docker compose just gives a nice interface\facede for mounting a secret file and exposing it to the container with a its naming conventions.


问:
C++ vector initialization by using istream_iterator
my test.cpp:

```<code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
    vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
    // no error using std::cin
    // vector<int> vec(istream_iterator<int>(std::cin), istream_iterator<int>());
    sort(vec.begin(), vec.end());
    return 0;
}
</code>```

complile with g++ and here is what I get:

test.cpp:12:11: error: request for member ‘begin’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   12 |  sort(vec.begin(), vec.end());
```

答:
When I compiled this code with the options -Wall -Wextra -Werror, I got the following error messages:

```<code>iter-vec.cpp: In function ‘int main()’:
iter-vec.cpp:10:20: error: parentheses were disambiguated as a function declaration [-Werror=vexing-parse]
   10 |     vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
      |
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iter-vec.cpp:10:20: note: replace parentheses with braces to declare a variable
   10 |     vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
      |
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                    -
      |                    {
-
      |
}
iter-vec.cpp:13:14: error: request for member ‘begin’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   13 |     sort(vec.begin(), vec.end());
      |              ^~~~~
iter-vec.cpp:13:27: error: request for member ‘end’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   13 |     sort(vec.begin(), vec.end());
      |                           ^~~
cc1plus: all warnings being treated as errors
</code>```

From this I concluded that it was a problem of the initialization of vec being ambiguous. When I removed the using namespace std; clause and added the appropriate std:: markers, I got the following to compile cleanly:

```<code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> vec(std::istream_iterator<int>(std::cin),
                         std::istream_iterator<int>());
    std::sort(vec.begin(), vec.end());
    return 0;
}
</code>```

I may not have gotten all the details correct, but I am fairly certain that this was the cause of the problem.

Body:
my test.cpp:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
    vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
    // no error using std::cin
    // vector<int> vec(istream_iterator<int>(std::cin), istream_iterator<int>());
    sort(vec.begin(), vec.end());
    return 0;
}

complile with g++ and here is what I get:

test.cpp:12:11: error: request for member ‘begin’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   12 |  sort(vec.begin(), vec.end());

Body:
When I compiled this code with the options -Wall -Wextra -Werror, I got the following error messages:

iter-vec.cpp: In function ‘int main()’:
iter-vec.cpp:10:20: error: parentheses were disambiguated as a function declaration [-Werror=vexing-parse]
   10 |     vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
      |
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iter-vec.cpp:10:20: note: replace parentheses with braces to declare a variable
   10 |     vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
      |
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                    -
      |                    {
-
      |
}
iter-vec.cpp:13:14: error: request for member ‘begin’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   13 |     sort(vec.begin(), vec.end());
      |              ^~~~~
iter-vec.cpp:13:27: error: request for member ‘end’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   13 |     sort(vec.begin(), vec.end());
      |                           ^~~
cc1plus: all warnings being treated as errors

From this I concluded that it was a problem of the initialization of vec being ambiguous. When I removed the using namespace std; clause and added the appropriate std:: markers, I got the following to compile cleanly:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> vec(std::istream_iterator<int>(std::cin),
                         std::istream_iterator<int>());
    std::sort(vec.begin(), vec.end());
    return 0;
}

I may not have gotten all the details correct, but I am fairly certain that this was the cause of the problem.


问:
(C Programming) User name and Password Identification
Why do I get format '%s' expects argument of type 'char*'? How should I fix the problem?

Here are my codes:

```<code>char UserName[] = "iluvcake";
scanf("%s", &UserName);
printf("Please enter your password: \n");
char PassWord[] = "Chocolate";
scanf("%s", &PassWord);
    //if...else statement to test if the input is the correct username.
    if (UserName == "iluvcake")
    {
     if (PassWord == "Chocolate"){
     printf("Welcome!\n");
    }
    }else
    {
     printf("The user name or password you entered is invalid.\n");
    }
</code>```

答:
```<code>#include <stdio.h>

int main(){
int serial;
int code;

printf("Type the Serial Here: ");
scanf("%d", &serial);

if(serial== 1590){
    printf("Almost there, now type the code: ");
    scanf("%d", &code);
    if(code==2359)
    {
            printf("\nYOU ARE DONE, ENJOY");
    }
    else{
            printf("TRY AGAIN NEXT TIME");
    }

}
    else{
        printf("OPPS");
}
</code>```

Body:
Why do I get format '%s' expects argument of type 'char*'? How should I fix the problem?

Here are my codes:

char UserName[] = "iluvcake";
scanf("%s", &UserName);
printf("Please enter your password: \n");
char PassWord[] = "Chocolate";
scanf("%s", &PassWord);
    //if...else statement to test if the input is the correct username.
    if (UserName == "iluvcake")
    {
     if (PassWord == "Chocolate"){
     printf("Welcome!\n");
    }
    }else
    {
     printf("The user name or password you entered is invalid.\n");
    }


问:
Flutter: How to make a button like this?
I tried to use TextButton.Icon to make the effect as following.
But I found that the words can only be at the left or right of the icon. How can I put the words under the icon like this?

答:
I think GirdView Widget  the best way to make button like this-

```<code>GridView.count(
    crossAxisCount: 4,
    children:  List<Widget>.generate(16, (index) {
      return  GridTile(
        child:GestureDetector(
          onTap:(){
            print(index.toString());
          },
      child:    Card(
          color: Colors.blue.shade200,
          child:  Column(
            children:[  Text('tile $index'),
                         Icon(Icons.alarm)
          ])
        )),
     );
    }),
  ),

</code>```

With help of index parameter you can pass function  according to button type.

Body:
I think GirdView Widget  the best way to make button like this-

GridView.count(
    crossAxisCount: 4,
    children:  List<Widget>.generate(16, (index) {
      return  GridTile(
        child:GestureDetector(
          onTap:(){
            print(index.toString());
          },
      child:    Card(
          color: Colors.blue.shade200,
          child:  Column(
            children:[  Text('tile $index'),
                         Icon(Icons.alarm)
          ])
        )),
     );
    }),
  ),

With help of index parameter you can pass function  according to button type.


问:
How to add Row to DataGridView in Visual Basic (Visual Studio)
I want to be able to add a new row to my already existing DataGridView through the use of a button. How do I add this? (Using Visual Basic on Visual Studio)

Here is the Code Filling the DataGridView.

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim connection As New SqlConnection(PlaceHolder for String)
    Dim Table As New DataTable()

    Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)

    Adapter.Fill(Table)

    DataGridView1.DataSource = Table
    bind_data()

End Sub
</code>```

答:
bind_data() method seems to come from this reference.

If you want to add a new empty row, just edit it directly on DataGridView.
For example:

To add a new row with data, you can use DataTable:

```<code>dt.Rows.Add(...)
</code>```

Body:
I want to be able to add a new row to my already existing DataGridView through the use of a button. How do I add this? (Using Visual Basic on Visual Studio)

Here is the Code Filling the DataGridView.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim connection As New SqlConnection(PlaceHolder for String)
    Dim Table As New DataTable()

    Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)

    Adapter.Fill(Table)

    DataGridView1.DataSource = Table
    bind_data()

End Sub

Body:
bind_data() method seems to come from this reference.

If you want to add a new empty row, just edit it directly on DataGridView.
For example:

To add a new row with data, you can use DataTable:

dt.Rows.Add(...)


问:
Microsoft Graph Toolkit PeoplePicker onChange event not triggering in mobile
We are using PeoplePicker in the Teams Personal Tab, we are able to trigger onChange event in the Desktop and browser but not in the Teams Mobile App.
We are rendering the PeoplePicker in a Modal component (All are Fluent UI react components).</p>

答:
I tried the PeoplePicker selectionChanged event inside Teams IOS mobile client and it works fine.

Here is code snippet:

```<code>const handleInputChange = (e) => {
  this.setState({
    selectedPeople: e.target.selectedPeople
  });
  ...
}

...
<div className="people-picker-area">
      <PeoplePicker selectionChanged={handleInputChange} placeholder="Typing name to select people to view contact info"></PeoplePicker>
</div>
</code>```

We have a sample project which is using PeoplePicker inside teams Tab Project you can refer here:

https://github.com/OfficeDev/TeamsFx-Samples/tree/v2/graph-toolkit-contact-exporter

Simply install teams toolkit extension in your VSCode, open the sample  project, and then click F5 button, you can preview this sample.

If you want to try this sample inside mobile client, just run provision, and deploy command, then you can access this sample project in your mobile client.

Body:
I tried the PeoplePicker selectionChanged event inside Teams IOS mobile client and it works fine.

Here is code snippet:

const handleInputChange = (e) => {
  this.setState({
    selectedPeople: e.target.selectedPeople
  });
  ...
}

...
<div className="people-picker-area">
      <PeoplePicker selectionChanged={handleInputChange} placeholder="Typing name to select people to view contact info"></PeoplePicker>
</div>

We have a sample project which is using PeoplePicker inside teams Tab Project you can refer here:

https://github.com/OfficeDev/TeamsFx-Samples/tree/v2/graph-toolkit-contact-exporter

Simply install teams toolkit extension in your VSCode, open the sample  project, and then click F5 button, you can preview this sample.

If you want to try this sample inside mobile client, just run provision, and deploy command, then you can access this sample project in your mobile client.


问:
bootstrap 5 alpha 2 card deck example not showing like it is in documentation
I inserted this example for a card desk and thought it would show like its shown in the docs. But it isn't.
https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css - I am using Bootstrap 5 alpha 2. Has the card layout changed ?

It is showing as three rows instead of 1 row with 3 columns. Do we need to insert grid based HTML too wrapping the card-deck ?

```<code><div class="card-deck">
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
</div>
</code>```

答:
I was stuck in this for hours before I found out Bootstrap 5 no longer supports card-deck class, Note! This is not updated in the bootstrap documentary, by the way, yet we have practical evidence for that.

THE SOLUTION, use a  and grid format to position your cards in a single row as you want.

EXAMPLE CODE:

```<code><div class="row  row-cols-1 row-cols-md-3 mb-3 text-center">
  <div class="col">
    <div class="card">
        <div class="card-header">
              <h3>Card1 header</h3>
        </div>
        <div class="card-body">
          <p>Card1 body</p>
          <button type="button">Card1-Button</button>
        </div>
    </div>
  </div>

 <div class="col">
    <div class="card">
        <div class="card-header">
              <h3>Card2 header</h3>
        </div>
        <div class="card-body">
          <p>Card2 body</p>
          <button type="button">Card2-Button</button>
        </div>
    </div>
  </div
  <div class="col">
    <div class="card">
        <div class="card-header">
              <h3>Card3 header</h3>
        </div>
        <div class="card-body">
          <p>Card3 body</p>
          <button type="button">Card3-Button</button>
        </div>
    </div>
  </diviv>
</div>
</code>```

Body:
I inserted this example for a card desk and thought it would show like its shown in the docs. But it isn't.
https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css - I am using Bootstrap 5 alpha 2. Has the card layout changed ?

It is showing as three rows instead of 1 row with 3 columns. Do we need to insert grid based HTML too wrapping the card-deck ?

Card title

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Card title

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

Body:
I was stuck in this for hours before I found out Bootstrap 5 no longer supports card-deck class, Note! This is not updated in the bootstrap documentary, by the way, yet we have practical evidence for that.

THE SOLUTION, use a  and grid format to position your cards in a single row as you want.

EXAMPLE CODE:

<div class="row  row-cols-1 row-cols-md-3 mb-3 text-center">
  <div class="col">
    <div class="card">
        <div class="card-header">
              <h3>Card1 header</h3>
        </div>
        <div class="card-body">
          <p>Card1 body</p>
          <button type="button">Card1-Button</button>
        </div>
    </div>
  </div>

 <div class="col">
    <div class="card">
        <div class="card-header">
              <h3>Card2 header</h3>
        </div>
        <div class="card-body">
          <p>Card2 body</p>
          <button type="button">Card2-Button</button>
        </div>
    </div>
  </div
  <div class="col">
    <div class="card">
        <div class="card-header">
              <h3>Card3 header</h3>
        </div>
        <div class="card-body">
          <p>Card3 body</p>
          <button type="button">Card3-Button</button>
        </div>
    </div>
  </diviv>
</div>


问:
How to refresh the same page after select option changes in another component using ionic?
I'm new to ionic. I'm trying to refresh the same page after user selects an option from dropdown. but the my dropdown is in another component(somehow like partial view) and I used this in other components.
I tried navigating but it didn't refresh the page. I want when user selects an option that component will refresh.
the ngOnInit method works fine btw.
This is my partial view component:

```<code> navigateTo(path: string) {
localStorage.setItem('selectedapp', this.appId);
this.router.navigate([path]);
 }
</code>```

this is the html of this component:

```<code>  <ion-item *ngIf="!isPrivate">
  <ion-label>فروشگاه های من</ion-label>
  <ion-select [(ngModel)]="appId" (ionChange)="navigateTo(model[0].url)" ok-text="تایید" cancel-text="کنسل" [value]="00000000-0000-0000-0000-000000000000">
    <ion-select-option value="00000000-0000-0000-0000-000000000000">همه</ion-select-option>
    <ion-select-option value="{{item.applicationId}}" *ngFor="let item of model">{{item.applicationTitle}}</ion-select-option>
    </ion-select>
</ion-item>
</code>```

This is where I used above component's tag in another html page:

```<code> <app-user-applications returnUrl="prizePackages"></app-user-applications>
</code>```

in this case I want to refresh the prizePackages page.
what should I do?

答:
There is no reload in mobile applications. Given your scenario, what I suggest you do is add ngif to your html contents that you want to hide / show based on new data.

Thus when you get new data, you hide your html content, update it with new data and show it again.

Body:
I'm new to ionic. I'm trying to refresh the same page after user selects an option from dropdown. but the my dropdown is in another component(somehow like partial view) and I used this in other components.
I tried navigating but it didn't refresh the page. I want when user selects an option that component will refresh.
the ngOnInit method works fine btw.
This is my partial view component:

 navigateTo(path: string) {
localStorage.setItem('selectedapp', this.appId);
this.router.navigate([path]);
 }

this is the html of this component:

  <ion-item *ngIf="!isPrivate">
  <ion-label>فروشگاه های من</ion-label>
  <ion-select [(ngModel)]="appId" (ionChange)="navigateTo(model[0].url)" ok-text="تایید" cancel-text="کنسل" [value]="00000000-0000-0000-0000-000000000000">
    <ion-select-option value="00000000-0000-0000-0000-000000000000">همه</ion-select-option>
    <ion-select-option value="{{item.applicationId}}" *ngFor="let item of model">{{item.applicationTitle}}</ion-select-option>
    </ion-select>
</ion-item>

This is where I used above component's tag in another html page:

 <app-user-applications returnUrl="prizePackages"></app-user-applications>

in this case I want to refresh the prizePackages page.
what should I do?


问:
Youtube API 3.0 search videos and get video statistics at single request
I'm searching youtube videos with youtube api 3.0.

I'm using this type of example API request

```<code>https://www.googleapis.com/youtube/v3/search?part=snippet&key=[API_KEY]
</code>```

But i want to get statistics of videos with in the same api request. How to solve this problem.

Note: When I'm using statistics key with part. I got error.

I'm also tried this request

```<code>https://www.googleapis.com/youtube/v3/search?part=snippet,statistics&key=[API_KEY]
</code>```

答: Unfortunately, dislikeCount attribute has became private, in december 2021. according the youtube api docs.</p>

Body:
I'm searching youtube videos with youtube api 3.0.

I'm using this type of example API request

https://www.googleapis.com/youtube/v3/search?part=snippet&key=[API_KEY]

But i want to get statistics of videos with in the same api request. How to solve this problem.

Note: When I'm using statistics key with part. I got error.

I'm also tried this request

https://www.googleapis.com/youtube/v3/search?part=snippet,statistics&key=[API_KEY]


问:
How to fetch token from Token API using Java
I am trying to fetch token by calling token API but unable to fetch the same.
It is working in postman.
Postman details are as follows

My code

```<code>import java.io.*;
import java.net.*;
public class GetToken {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String accessToken = "";
        String tokenURL="https://test.iapsoftware.com/iap6/MobileServices/token";
        String grantType = "password";
        String userName="APITester";
        String password="password";
        String ClientCode ="iaptest1";
        String ClientInterface ="API";

                try {
                     URL url = new URL(tokenURL);
                    HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
                    // Set header
                    httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    httpConn.setRequestProperty("ClientCode", ClientCode);
                    httpConn.setRequestProperty("ClientInterface", ClientInterface);

                    //httpConn.setRequestBody();
                    httpConn.setDoOutput(true);
                    httpConn.setDoInput(true);
                    httpConn.setRequestMethod("POST");
                    //Set Request Body
                    String jsonInputString =("grant_type="+grantType+",username="+userName+",password="+password);

                    OutputStream os = httpConn.getOutputStream();
                    byte[] input = jsonInputString.getBytes("utf-8");
                    os.write(input, 0, input.length);
                     // Read the response.
                    InputStreamReader isr=null;
                        if (httpConn.getResponseCode() == 200) {
                     isr = new InputStreamReader(httpConn.getInputStream());
                    }
                            else
                         {
                                               isr = new InputStreamReader(httpConn.getErrorStream());
                   }
                    BufferedReader in = new BufferedReader(isr);
                    String responseString = "";
                    String outputString = "";
                   // Write response to a String.
                    while ((responseString = in.readLine()) != null) {
                     outputString = outputString + responseString;
                    }
                       accessToken = outputString;
                }
                catch (Exception e)
                {
                    accessToken = "Error"; //+ e.getMessage();
                }

                System.out.println(accessToken);

    }

}
</code>```

error

-As per my understanding I am not passing correct input.
Input needs to be URL encoded and I am sending it as JSON.
Kindly suggest and provide solution for the same.

答:
After setting up the body correctly it worked</p>
```<code>String urlParameters  = ("grant_type="+grantType+"&username="+userName+"&password="+password);

OutputStream os = httpConn.getOutputStream();

byte[] postData = urlParameters.getBytes("utf-8");
int postDataLength = postData.length;

os.write(postData, 0, postDataLength);

</code>```

Body:
I am trying to fetch token by calling token API but unable to fetch the same.
It is working in postman.
Postman details are as follows

My code

import java.io.*;
import java.net.*;
public class GetToken {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String accessToken = "";
        String tokenURL="https://test.iapsoftware.com/iap6/MobileServices/token";
        String grantType = "password";
        String userName="APITester";
        String password="password";
        String ClientCode ="iaptest1";
        String ClientInterface ="API";

                try {
                     URL url = new URL(tokenURL);
                    HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
                    // Set header
                    httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    httpConn.setRequestProperty("ClientCode", ClientCode);
                    httpConn.setRequestProperty("ClientInterface", ClientInterface);

                    //httpConn.setRequestBody();
                    httpConn.setDoOutput(true);
                    httpConn.setDoInput(true);
                    httpConn.setRequestMethod("POST");
                    //Set Request Body
                    String jsonInputString =("grant_type="+grantType+",username="+userName+",password="+password);

                    OutputStream os = httpConn.getOutputStream();
                    byte[] input = jsonInputString.getBytes("utf-8");
                    os.write(input, 0, input.length);
                     // Read the response.
                    InputStreamReader isr=null;
                        if (httpConn.getResponseCode() == 200) {
                     isr = new InputStreamReader(httpConn.getInputStream());
                    }
                            else
                         {
                                               isr = new InputStreamReader(httpConn.getErrorStream());
                   }
                    BufferedReader in = new BufferedReader(isr);
                    String responseString = "";
                    String outputString = "";
                   // Write response to a String.
                    while ((responseString = in.readLine()) != null) {
                     outputString = outputString + responseString;
                    }
                       accessToken = outputString;
                }
                catch (Exception e)
                {
                    accessToken = "Error"; //+ e.getMessage();
                }

                System.out.println(accessToken);

    }

}

error

-As per my understanding I am not passing correct input.
Input needs to be URL encoded and I am sending it as JSON.
Kindly suggest and provide solution for the same.

Body:
After setting up the body correctly it worked

String urlParameters  = ("grant_type="+grantType+"&username="+userName+"&password="+password);

OutputStream os = httpConn.getOutputStream();

byte[] postData = urlParameters.getBytes("utf-8");
int postDataLength = postData.length;

os.write(postData, 0, postDataLength);


问:
Moving default AVD configuration folder (.android)
After installation of Android SDK, the folder .android was created on the E:\ drive. As far as I know, this is the default folder of Android Virtual Devices for configuration files.

How can I move .android folder to a different location?

(eg. from E:\.android to E:\Android\.android)

答:
(Optional) Download Rapid Environment Editor

Add a new system variable

ANDROID_PREFS_ROOT = D:\IDE\Externals\ANDROID_PREFS_ROOT (The folder you want to move to.)

Save and you're done.


问:
On publish Entity Framework is connecting to the wrong database
I have Asp.Net Core 5.0 and Entity Framework 5.0.12. When I change the connection string I'm changing it in both appsettings.json and in ProgramContext. Then I do build and Publish in folder or Publish with FTP. Both times I make sure the publisher is using the correct connection string.

Then I deploy and I can see that on the deployed the publisher is using the old connection string. Please help how my newly published api to use the new connection string.

For those who will say put some code as example(so irrelevant) in appsettings.json I have

```<code>  "ConnectionStrings": {
    "DefaultConnection1": "Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword"

</code>```

Then in services.cs I have

```<code>services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection1")));
</code>```

in MyContext.cs I have

```<code>if (!optionsBuilder.IsConfigured)
 {
      optionsBuilder.UseSqlServer("Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword");
 }
</code>```

and again when I try to print context.Database.GetConnectionString() I'm getting

```<code>Data Source=MyOldDatabaseServer;Initial Catalog=myOldDatabaseName;MyOldUser;Password=MyPassword
</code>```

Please help

答:
Found solution

There are 2 files: appsettings.json and appsettings.production.json. The Api is taking the connection string from the second file, appsettings.production.json, so the changes need to be done there manually.

Body:
I have Asp.Net Core 5.0 and Entity Framework 5.0.12. When I change the connection string I'm changing it in both appsettings.json and in ProgramContext. Then I do build and Publish in folder or Publish with FTP. Both times I make sure the publisher is using the correct connection string.

Then I deploy and I can see that on the deployed the publisher is using the old connection string. Please help how my newly published api to use the new connection string.

For those who will say put some code as example(so irrelevant) in appsettings.json I have

  "ConnectionStrings": {
    "DefaultConnection1": "Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword"

Then in services.cs I have

services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection1")));

in MyContext.cs I have

if (!optionsBuilder.IsConfigured)
 {
      optionsBuilder.UseSqlServer("Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword");
 }

and again when I try to print context.Database.GetConnectionString() I'm getting

Data Source=MyOldDatabaseServer;Initial Catalog=myOldDatabaseName;MyOldUser;Password=MyPassword

Please help


问:
Heroku doesn't open index.html
I have deployed an application successfully but when trying to run the app on Heroku, I am getting below error:

```<code>2022-01-02T05:26:45.612777+00:00 heroku[web.1]: Starting process with command `npm start`
2022-01-02T05:26:46.989656+00:00 app[web.1]: > tic-tac-toe@1.0.0 start /app
2022-01-02T05:26:46.989657+00:00 app[web.1]: > npm run open
2022-01-02T05:26:47.536042+00:00 app[web.1]: > tic-tac-toe@1.0.0 open /app
2022-01-02T05:26:47.536043+00:00 app[web.1]: > open index.html
2022-01-02T05:26:47.539616+00:00 app[web.1]: sh: 1: open: not found
2022-01-02T05:26:47.543563+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2022-01-02T05:26:47.543721+00:00 app[web.1]: npm ERR! syscall spawn
2022-01-02T05:26:47.543782+00:00 app[web.1]: npm ERR! file sh
2022-01-02T05:26:47.543850+00:00 app[web.1]: npm ERR! errno ENOENT
2022-01-02T05:26:47.546906+00:00 app[web.1]: npm ERR! tic-tac-toe@1.0.0 open: `open index.html`
</code>```

When I am running it on my system, the node scripts run just fine. Can someone please suggest what could be wrong?

The scripts in package.json are:
 "scripts": { "start": "npm run open", "open": "open index.html" },

答:
I was able to resolve this by creating a node server and adding a script to serve the index.html.

It is kind of unnecessary but that's how Heroku expects us to work. Cheers :)

Title: Heroku doesn't open index.html

Body:
I have deployed an application successfully but when trying to run the app on Heroku, I am getting below error:

2022-01-02T05:26:45.612777+00:00 heroku[web.1]: Starting process with command `npm start`
2022-01-02T05:26:46.989656+00:00 app[web.1]: > tic-tac-toe@1.0.0 start /app
2022-01-02T05:26:46.989657+00:00 app[web.1]: > npm run open
2022-01-02T05:26:47.536042+00:00 app[web.1]: > tic-tac-toe@1.0.0 open /app
2022-01-02T05:26:47.536043+00:00 app[web.1]: > open index.html
2022-01-02T05:26:47.539616+00:00 app[web.1]: sh: 1: open: not found
2022-01-02T05:26:47.543563+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2022-01-02T05:26:47.543721+00:00 app[web.1]: npm ERR! syscall spawn
2022-01-02T05:26:47.543782+00:00 app[web.1]: npm ERR! file sh
2022-01-02T05:26:47.543850+00:00 app[web.1]: npm ERR! errno ENOENT
2022-01-02T05:26:47.546906+00:00 app[web.1]: npm ERR! tic-tac-toe@1.0.0 open: `open index.html`

When I am running it on my system, the node scripts run just fine. Can someone please suggest what could be wrong?

The scripts in package.json are:
 "scripts": { "start": "npm run open", "open": "open index.html" },


问:
how to get value of more than one text box in a loop
I have some text boxes in my page. I want to get all text box values in an array and insert in to table of database.

Is there any option to work by loop

答:
you can try something on these lines, if all the textbox are on the page directly

```<code>foreach(Control c in Page.Controls)
{
    if (c is TextBox)
    {
        //get the text
    }
}
</code>```

This will not work for child controls for that you will have to recursively iterate

Body:
you can try something on these lines, if all the textbox are on the page directly

foreach(Control c in Page.Controls)
{
    if (c is TextBox)
    {
        //get the text
    }
}

This will not work for child controls for that you will have to recursively iterate


问:
slice() on a long skinny list with multiple entries
I have a data frame in R which is comprised like this:

year
region
age
population_count
cumulative_count*
middle_value*

2001
Region x
0
10
10
50

2001
Region x
1
10
20
50

2001
Region x
2
10
30
50

2001
Region x
3
10
40
50

2001
Region x
4
10
50
50

2001
Region x
5
10
60
50

...2020
Region y
1
10
20
50

For each year and region combination I have a discrete cumulative_count (derived from population_count by age) and middle_value (derived from the cumulative_count), again discrete for each year and region combination.

I want to extract from this the row for each region and year combination where the cumulative_count is closest to the middle_value in each instance.
(in the example above this would be age 4 in region x where culmulative_count = 50 and middle_value=50).

I have tried slice from dplyr:

slice(which.min(abs(table$cumulative_count - table$middle_value)))

but this only returns the first instance of the row where there is a match, not all the subsequent year and region combinations.

group_by(year,region) doesn't return all the possible year and region combinations either.

I feel I should be looping through the data frame for all possible year and region combinations and then slicing out the rows that meet the criteria.

Any thoughts?

UPDATE
I used @Merijn van Tilborg dplyr approach, needed only the first match.

Here's a screenshot of the output table - note that variable column is the single year of age and is getting older.

答:
You could de-mean the groups and look where the value is zero. You probably will have ties, depends on what you want, you could simply use the first one by subsetting with [1, ].

```<code>by(dat, dat[c('year', 'region')], \(x)
   x[x$cumulative_count - mean(x$cumulative_count) == 0, ][1, ]) |>
  do.call(what=rbind)
#    year   region age population_count cumulative_count middle_value
# 2  2001 Region x   1               10               20           50
# 5  2002 Region x   1               10               20           50
# 8  2001 Region y   1               10               20           50
# 10 2002 Region y   0               10               30           50
</code>```

Note: R >= 4.1 used.

Data:

```<code>dat <- structure(list(year = c(2001L, 2001L, 2001L, 2002L, 2002L, 2002L,
2001L, 2001L, 2001L, 2002L, 2002L, 2002L), region = c("Region x",
"Region x", "Region x", "Region x", "Region x", "Region x", "Region y",
"Region y", "Region y", "Region y", "Region y", "Region y"),
    age = c(0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L),
    population_count = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L), cumulative_count = c(10L, 20L, 30L,
    10L, 20L, 30L, 10L, 20L, 30L, 30L, 30L, 30L), middle_value = c(50L,
    50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L)), class = "data.frame", row.names = c(NA,
-12L))
</code>```

Body:
You could de-mean the groups and look where the value is zero. You probably will have ties, depends on what you want, you could simply use the first one by subsetting with [1, ].

by(dat, dat[c('year', 'region')], \(x)
   x[x$cumulative_count - mean(x$cumulative_count) == 0, ][1, ]) |>
  do.call(what=rbind)
#    year   region age population_count cumulative_count middle_value
# 2  2001 Region x   1               10               20           50
# 5  2002 Region x   1               10               20           50
# 8  2001 Region y   1               10               20           50
# 10 2002 Region y   0               10               30           50

Note: R >= 4.1 used.

Data:

dat <- structure(list(year = c(2001L, 2001L, 2001L, 2002L, 2002L, 2002L,
2001L, 2001L, 2001L, 2002L, 2002L, 2002L), region = c("Region x",
"Region x", "Region x", "Region x", "Region x", "Region x", "Region y",
"Region y", "Region y", "Region y", "Region y", "Region y"),
    age = c(0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L),
    population_count = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L), cumulative_count = c(10L, 20L, 30L,
    10L, 20L, 30L, 10L, 20L, 30L, 30L, 30L, 30L), middle_value = c(50L,
    50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L)), class = "data.frame", row.names = c(NA,
-12L))


问:
Strange issue with replit's express option (24/7 coverage without premium payments)
I've been recently using replit to host my discord.js bot, but after dealing with many errors, I can't stop my bot, I mean, I can, but it doesn't log off of discord and express is still loaded up, should I just wait or, is it something else? Any form of help will be appreciated. Btw, it isn't giving me any errors, so it might be a problem with express (which is basically Flask but for JavaScript). And yes, I paused UptimeRobot, if it won't work, I will just load up a backup</p>

答: I won't recommend hosting bots using this method. You can get yourself a cheap vps or maybe AWS Free tier or GCP Free tier and host there!</p>


问:
c program Warning the control reaches the end of non-void function
so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error</p>
```<code>#include <iostream>
//int sum = 1;

int powerOfNumber(int n, int p) {
    if (n != 0) {
        p--;
        return powerOfNumber(n , p) * n;
    }
    if (n == 0) {
        return 1;
    }
}

int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;

}
</code>```

答:
```<code>#include <iostream>

using namespace std;

int powerOfNumber(int n, int p) {
    if(p==0)
        return 1;
    else
        return (n*powerOfNumber(n,p-1));
}

int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;
}
</code>```

Your powerOfNumber function never terminates because n is always 5.

Body:
so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error

#include <iostream>
//int sum = 1;

int powerOfNumber(int n, int p) {
    if (n != 0) {
        p--;
        return powerOfNumber(n , p) * n;
    }
    if (n == 0) {
        return 1;
    }
}

int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;

}

Body:
#include <iostream>

using namespace std;

int powerOfNumber(int n, int p) {
    if(p==0)
        return 1;
    else
        return (n*powerOfNumber(n,p-1));
}

int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;
}

Your powerOfNumber function never terminates because n is always 5.