问:
Data stay in .db-wal or .db-shm file when conection of SQLite 3 was not closed
I am using SQLite3 in my Android App for data storing from Bluetooth LE. There are two occurrences when the SQLite is used:

First when I check after scanning that the Bluetooth LE Device had been already connected before. There is no problem I open connection, read or save data, and close connection. Then in Device Explorer, I see only one file with .db extension where data is properly stored. I can read this file for example with some viewer: sqliteonline.com

Second I open the connection in service which is running on the background. The app can be logging and store data from BLE although the App or the Activity is not visible (I need this feature). But when the system kills the service or I kill the app from the launcher the connection is not closed and there stay next two files (.db-wal and .db-shm) where the last saved data are probably stored. I can see last stored data in .db file and the other files are not possible to open and read for me. The app can read the last stored data (so also from .db-wal and .db-shm files).

My ask is: Is this the correct solution? Is it possible to let the connection open? I won't delete the last stored data by some system cleaner for example. Also, I want to see all of my data during app development. I call closing connection in onDestroy method in service but I read that it is not recommended for release.

```<code>@Override
public void onDestroy() {
    if(writableTestbedDb != null){
       writableTestbedDb.close();
    }
    if(testbedDbHelper != null) {
        testbedDbHelper.close();
    }
    Log.w(TAG, "SERVICE DESTROYED");
    this.stopSelf();
    super.onDestroy();
}
</code>```

I using a singleton design pattern for database connection.

```<code>public static TestbedDbHelper getInstance(Context context) {

    if (mInstance == null) {
        mInstance = new TestbedDbHelper(context.getApplicationContext());
    }
    mInstance.setWriteAheadLoggingEnabled(false);
    return mInstance;
}
</code>```

答:
This happens because you use write-ahead logging. I see that you have the code to disable it, but somehow you still use it. Nevertheless, these files (wal & shm) are OK generally and there is nothing wrong with them.
But if you want to make sure that you have only one file (.db), you can execute somewhere in your code:

```<code>pragma wal_checkpoint
</code>```

to ensure everything is cleared. You can do it, for example, right after you open your db instance. This will save all the data that remained unsaved from the previous time - to the main file.

Body:
I am using SQLite3 in my Android App for data storing from Bluetooth LE. There are two occurrences when the SQLite is used:

First when I check after scanning that the Bluetooth LE Device had been already connected before. There is no problem I open connection, read or save data, and close connection. Then in Device Explorer, I see only one file with .db extension where data is properly stored. I can read this file for example with some viewer: sqliteonline.com

Second I open the connection in service which is running on the background. The app can be logging and store data from BLE although the App or the Activity is not visible (I need this feature). But when the system kills the service or I kill the app from the launcher the connection is not closed and there stay next two files (.db-wal and .db-shm) where the last saved data are probably stored. I can see last stored data in .db file and the other files are not possible to open and read for me. The app can read the last stored data (so also from .db-wal and .db-shm files).

My ask is: Is this the correct solution? Is it possible to let the connection open? I won't delete the last stored data by some system cleaner for example. Also, I want to see all of my data during app development. I call closing connection in onDestroy method in service but I read that it is not recommended for release.

@Override
public void onDestroy() {
    if(writableTestbedDb != null){
       writableTestbedDb.close();
    }
    if(testbedDbHelper != null) {
        testbedDbHelper.close();
    }
    Log.w(TAG, "SERVICE DESTROYED");
    this.stopSelf();
    super.onDestroy();
}

I using a singleton design pattern for database connection.

public static TestbedDbHelper getInstance(Context context) {

    if (mInstance == null) {
        mInstance = new TestbedDbHelper(context.getApplicationContext());
    }
    mInstance.setWriteAheadLoggingEnabled(false);
    return mInstance;
}

Body:
This happens because you use write-ahead logging. I see that you have the code to disable it, but somehow you still use it. Nevertheless, these files (wal & shm) are OK generally and there is nothing wrong with them.
But if you want to make sure that you have only one file (.db), you can execute somewhere in your code:

pragma wal_checkpoint

to ensure everything is cleared. You can do it, for example, right after you open your db instance. This will save all the data that remained unsaved from the previous time - to the main file.


来源: stackexchange

问:
How to run a PowerShell script without displaying a window?
How is it possible to run a PowerShell script without displaying a window or any other sign to the user?

In other words, the script should run quietly in the background without any sign to the user.

Extra credit for an answer that does not use third party components :)

答:
Here is a working solution in windows 10 that does not include any third-party components. It works by wrapping the PowerShell script into VBScript.

Step 1: we need to change some windows features to allow VBScript to run PowerShell and to open .ps1 files with PowerShell by default.

-go to run and type "regedit". Click on ok and then allow it to run.

-paste this path "HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell" and press enter.

-now open the entry on the right and change the value to 0.

-open PowerShell as an administrator and type "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned", press enter and confirm the change with "y" and then enter.

Step 2: Now we can start wrapping our script.

-save your Powershell script as a .ps1 file.

-create a new text document and paste this script.

```<code>Dim objShell,objFSO,objFile

Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")

'enter the path for your PowerShell Script
 strPath="c:\your script path\script.ps1"

'verify file exists
 If objFSO.FileExists(strPath) Then
   'return short path name
   set objFile=objFSO.GetFile(strPath)
   strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
    objFile.ShortPath & "}" & Chr(34)
   'Uncomment next line for debugging
   'WScript.Echo strCMD

  'use 0 to hide window
   objShell.Run strCMD,0

Else

  'Display error message
   WScript.Echo "Failed to find " & strPath
   WScript.Quit

End If
</code>```

-now change the file path to the location of your .ps1 script and save the text document.

-Now right-click on the file and go to rename. Then change the filename extension to .vbs and press enter and then click ok.

DONE! If you now open the .vbs you should see no console window while your script is running in the background.

ContentLicense: CC BY-SA 2.5

Body:
Here is a working solution in windows 10 that does not include any third-party components. It works by wrapping the PowerShell script into VBScript.

Step 1: we need to change some windows features to allow VBScript to run PowerShell and to open .ps1 files with PowerShell by default.

-go to run and type "regedit". Click on ok and then allow it to run.

-paste this path "HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell" and press enter.

-now open the entry on the right and change the value to 0.

-open PowerShell as an administrator and type "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned", press enter and confirm the change with "y" and then enter.

Step 2: Now we can start wrapping our script.

-save your Powershell script as a .ps1 file.

-create a new text document and paste this script.

Dim objShell,objFSO,objFile

Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")

'enter the path for your PowerShell Script
 strPath="c:\your script path\script.ps1"

'verify file exists
 If objFSO.FileExists(strPath) Then
   'return short path name
   set objFile=objFSO.GetFile(strPath)
   strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
    objFile.ShortPath & "}" & Chr(34)
   'Uncomment next line for debugging
   'WScript.Echo strCMD

  'use 0 to hide window
   objShell.Run strCMD,0

Else

  'Display error message
   WScript.Echo "Failed to find " & strPath
   WScript.Quit

End If

-now change the file path to the location of your .ps1 script and save the text document.

-Now right-click on the file and go to rename. Then change the filename extension to .vbs and press enter and then click ok.

DONE! If you now open the .vbs you should see no console window while your script is running in the background.

ContentLicense: CC BY-SA 4.0


问:
Android invalid color state list tag gradient
I've an app with over 5000 downloads and more than 500 users active daily and out of nowhere I started get an weird error on Crashlytics:

```<code>Caused by android.content.res.Resources$NotFoundException: File res/drawable-anydpi-v24/ic_tickets.xml from drawable resource ID #0x7f0700b3
       at android.content.res.Resources.loadDrawableForCookie(Resources.java:2748)
       at android.content.res.Resources.loadDrawable(Resources.java:2643)
       at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
       at android.widget.TextView.<init>(TextView.java:921)
       at android.widget.TextView.<init>(TextView.java:703)
       at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:76)
       at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:72)
       at java.lang.reflect.Constructor.newInstance(Constructor.java)

Caused by android.content.res.Resources$NotFoundException: File res/drawable-anydpi-v24/$ic_tickets__0.xml from color state list resource ID #0x7f070017
       at android.content.res.Resources.loadColorStateListForCookie(Resources.java:2858)
       at android.content.res.Resources.loadColorStateList(Resources.java:2807)
       at android.content.res.TypedArray.getColor(TypedArray.java:439)
       at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:1605)
       at android.graphics.drawable.VectorDrawable$VFullPath.inflate(VectorDrawable.java:1584)
       at android.graphics.drawable.VectorDrawable.inflateInternal(VectorDrawable.java:666)
       at android.graphics.drawable.VectorDrawable.inflate(VectorDrawable.java:571)
       at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1215)
       at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1124)

Caused by org.xmlpull.v1.XmlPullParserException: Binary XML file line #6: invalid color state list tag gradient
       at android.content.res.ColorStateList.createFromXmlInner(ColorStateList.java:217)
       at android.content.res.ColorStateList.createFromXml(ColorStateList.java:201)
       at android.content.res.Resources.loadColorStateListForCookie(Resources.java:2854)
       at android.content.res.Resources.loadColorStateList(Resources.java:2807)
       at android.content.res.TypedArray.getColor(TypedArray.java:439)
       at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:1605)
</code>```

The stack trace is way longer than this, more than 500 lines on Crashlytics, I pasted here what I thought might be useful to understand the problem.

If I got it right it is complaining like one of my resources is missing or corrupted; what could it be?

But the resource is intact in the apk:

```<code><vector android:height="24dp" android:viewportHeight="512"
    android:viewportWidth="512" android:width="24dp"
    xmlns:aapt="http://schemas.android.com/aapt" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:pathData="M381.845,292.27c0,11.032 -8.943,19.975 -19.975,19.975s-19.975,-8.943 -19.975,-19.975c0,-11.032 8.943,-19.975 19.975,-19.975S381.845,281.238 381.845,292.27zM361.869,332.221c-11.032,0 -19.975,8.943 -19.975,19.975s8.943,19.975 19.975,19.975s19.975,-8.943 19.975,-19.975S372.902,332.221 361.869,332.221zM361.869,392.147c-11.032,0 -19.975,8.943 -19.975,19.975s8.943,19.975 19.975,19.975s19.975,-8.943 19.975,-19.975S372.902,392.147 361.869,392.147zM307.418,136.36c-9.983,4.696 -14.268,16.596 -9.572,26.578c4.696,9.983 16.596,14.268 26.578,9.572c9.983,-4.696 14.268,-16.596 9.572,-26.578C329.3,135.95 317.401,131.664 307.418,136.36zM451.759,352.197c0,22.029 17.922,39.951 39.951,39.951h19.975V512H0.314V392.147H20.29c22.029,0 39.951,-17.922 39.951,-39.951s-17.922,-39.951 -39.951,-39.951H0.314V192.393h0.509l-0.042,-0.089L408.489,0l50.866,108.128l-17.013,8.861c-13.29,6.921 -21.544,20.506 -21.544,35.453c0,22.029 17.922,39.951 39.951,39.951h50.937v119.853H491.71C469.681,312.246 451.759,330.168 451.759,352.197zM94.244,192.393h297.352c-6.822,-11.763 -10.75,-25.403 -10.75,-39.951c0,-23.307 10.023,-44.953 27.021,-59.913l-18.505,-39.335l-81.134,38.269c4.355,9.886 0.068,21.491 -9.762,26.115c-9.818,4.618 -21.473,0.536 -26.323,-9.095L94.244,192.393zM411.808,352.197c0,-37.163 25.503,-68.482 59.926,-77.374v-42.479h-89.889c0,11.032 -8.943,19.975 -19.975,19.975s-19.975,-8.943 -19.975,-19.975H40.265v42.479c34.424,8.891 59.926,40.211 59.926,77.374s-25.503,68.482 -59.926,77.374v42.479h301.629c0,-11.032 8.943,-19.975 19.975,-19.975s19.975,8.943 19.975,19.975h89.889V429.57C437.31,420.678 411.808,389.36 411.808,352.197z">
        <aapt:attr name="android:fillColor">
            <gradient android:endX="256.00745" android:endY="511.99982"
                android:startX="256.00745"
                android:startY="-0.0150070675" android:type="linear">
                <item android:color="#FF2AF598" android:offset="0"/>
                <item android:color="#FF009EFD" android:offset="1"/>
            </gradient>
        </aapt:attr>
    </path>
</vector>
</code>```

The drawable is a very small and simple icon for a button in the app, I downloaded it from a icon library it opens and run fine on all my tests.

The second weird thing about this is that over 500 active users I had today this is happening only with 4 users all with the same smartphone:

```<code>Device
Brand: LGE
Model: LG K10 LTE
Orientation: Portrait
RAM free: 170.92 MB
Disk free: 574.64 MB
Operating System
Version: 6.0
Orientation: Portrait
Rooted: No
Crash
</code>```

Is there any know issue about this smartphone model? What can I do in order to fix this for the affected users?

答: Instead of using .xml to set the image resource, just set the image resource programmatically from your java code.</p>

Body:
I've an app with over 5000 downloads and more than 500 users active daily and out of nowhere I started get an weird error on Crashlytics:

Caused by android.content.res.Resources$NotFoundException: File res/drawable-anydpi-v24/ic_tickets.xml from drawable resource ID #0x7f0700b3
       at android.content.res.Resources.loadDrawableForCookie(Resources.java:2748)
       at android.content.res.Resources.loadDrawable(Resources.java:2643)
       at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
       at android.widget.TextView.<init>(TextView.java:921)
       at android.widget.TextView.<init>(TextView.java:703)
       at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:76)
       at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:72)
       at java.lang.reflect.Constructor.newInstance(Constructor.java)

Caused by android.content.res.Resources$NotFoundException: File res/drawable-anydpi-v24/$ic_tickets__0.xml from color state list resource ID #0x7f070017
       at android.content.res.Resources.loadColorStateListForCookie(Resources.java:2858)
       at android.content.res.Resources.loadColorStateList(Resources.java:2807)
       at android.content.res.TypedArray.getColor(TypedArray.java:439)
       at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:1605)
       at android.graphics.drawable.VectorDrawable$VFullPath.inflate(VectorDrawable.java:1584)
       at android.graphics.drawable.VectorDrawable.inflateInternal(VectorDrawable.java:666)
       at android.graphics.drawable.VectorDrawable.inflate(VectorDrawable.java:571)
       at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1215)
       at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1124)

Caused by org.xmlpull.v1.XmlPullParserException: Binary XML file line #6: invalid color state list tag gradient
       at android.content.res.ColorStateList.createFromXmlInner(ColorStateList.java:217)
       at android.content.res.ColorStateList.createFromXml(ColorStateList.java:201)
       at android.content.res.Resources.loadColorStateListForCookie(Resources.java:2854)
       at android.content.res.Resources.loadColorStateList(Resources.java:2807)
       at android.content.res.TypedArray.getColor(TypedArray.java:439)
       at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:1605)

The stack trace is way longer than this, more than 500 lines on Crashlytics, I pasted here what I thought might be useful to understand the problem.

If I got it right it is complaining like one of my resources is missing or corrupted; what could it be?

But the resource is intact in the apk:

<vector android:height="24dp" android:viewportHeight="512"
    android:viewportWidth="512" android:width="24dp"
    xmlns:aapt="http://schemas.android.com/aapt" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:pathData="M381.845,292.27c0,11.032 -8.943,19.975 -19.975,19.975s-19.975,-8.943 -19.975,-19.975c0,-11.032 8.943,-19.975 19.975,-19.975S381.845,281.238 381.845,292.27zM361.869,332.221c-11.032,0 -19.975,8.943 -19.975,19.975s8.943,19.975 19.975,19.975s19.975,-8.943 19.975,-19.975S372.902,332.221 361.869,332.221zM361.869,392.147c-11.032,0 -19.975,8.943 -19.975,19.975s8.943,19.975 19.975,19.975s19.975,-8.943 19.975,-19.975S372.902,392.147 361.869,392.147zM307.418,136.36c-9.983,4.696 -14.268,16.596 -9.572,26.578c4.696,9.983 16.596,14.268 26.578,9.572c9.983,-4.696 14.268,-16.596 9.572,-26.578C329.3,135.95 317.401,131.664 307.418,136.36zM451.759,352.197c0,22.029 17.922,39.951 39.951,39.951h19.975V512H0.314V392.147H20.29c22.029,0 39.951,-17.922 39.951,-39.951s-17.922,-39.951 -39.951,-39.951H0.314V192.393h0.509l-0.042,-0.089L408.489,0l50.866,108.128l-17.013,8.861c-13.29,6.921 -21.544,20.506 -21.544,35.453c0,22.029 17.922,39.951 39.951,39.951h50.937v119.853H491.71C469.681,312.246 451.759,330.168 451.759,352.197zM94.244,192.393h297.352c-6.822,-11.763 -10.75,-25.403 -10.75,-39.951c0,-23.307 10.023,-44.953 27.021,-59.913l-18.505,-39.335l-81.134,38.269c4.355,9.886 0.068,21.491 -9.762,26.115c-9.818,4.618 -21.473,0.536 -26.323,-9.095L94.244,192.393zM411.808,352.197c0,-37.163 25.503,-68.482 59.926,-77.374v-42.479h-89.889c0,11.032 -8.943,19.975 -19.975,19.975s-19.975,-8.943 -19.975,-19.975H40.265v42.479c34.424,8.891 59.926,40.211 59.926,77.374s-25.503,68.482 -59.926,77.374v42.479h301.629c0,-11.032 8.943,-19.975 19.975,-19.975s19.975,8.943 19.975,19.975h89.889V429.57C437.31,420.678 411.808,389.36 411.808,352.197z">
        <aapt:attr name="android:fillColor">
            <gradient android:endX="256.00745" android:endY="511.99982"
                android:startX="256.00745"
                android:startY="-0.0150070675" android:type="linear">
                <item android:color="#FF2AF598" android:offset="0"/>
                <item android:color="#FF009EFD" android:offset="1"/>
            </gradient>
        </aapt:attr>
    </path>
</vector>

The drawable is a very small and simple icon for a button in the app, I downloaded it from a icon library it opens and run fine on all my tests.

The second weird thing about this is that over 500 active users I had today this is happening only with 4 users all with the same smartphone:

Device
Brand: LGE
Model: LG K10 LTE
Orientation: Portrait
RAM free: 170.92 MB
Disk free: 574.64 MB
Operating System
Version: 6.0
Orientation: Portrait
Rooted: No
Crash

Is there any know issue about this smartphone model? What can I do in order to fix this for the affected users?


问:
Passing a number to a function in react js
I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

```<code>import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(
        <div>
            Counter : {this.state.counter}</div>
        );
    }
}

export default lesson2
</code>```

This is my App.js

```<code>import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (
    <div className="App">

        <p>
          <Variable name='D' />
          <Lesson2 increment={10}/>
        </p>

    </div>
  );
}

export default App;
</code>```

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.

答:
You have defined your function add(), but you never called it anywhere in your lesson2.js file. Hence, the counter is not updated with the prop you pass.

Call add() function just after the component mounted using componentDidMount().

So, your lesson2.js file should be as follows.

```<code>import React from 'react';

class lesson2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { counter: 1 };
  }

  componentDidMount() {
    this.add();
  }

  add() {
    this.setState(function (state, props) {
      return {
        counter: state.counter + props.increment,
      };
    });
  }

  render() {
    return <div>Counter : {this.state.counter}</div>;
  }
}

export default lesson2;
</code>```

Body:
I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(

            Counter : {this.state.counter}

        );
    }
}

export default lesson2

This is my App.js

import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (

          <Variable name='D' />
          <Lesson2 increment={10}/>

  );
}

export default App;

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.

Body:
You have defined your function add(), but you never called it anywhere in your lesson2.js file. Hence, the counter is not updated with the prop you pass.

Call add() function just after the component mounted using componentDidMount().

So, your lesson2.js file should be as follows.

import React from 'react';

class lesson2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { counter: 1 };
  }

  componentDidMount() {
    this.add();
  }

  add() {
    this.setState(function (state, props) {
      return {
        counter: state.counter + props.increment,
      };
    });
  }

  render() {
    return <div>Counter : {this.state.counter}</div>;
  }
}

export default lesson2;


问:
Java Records StackOverflow RuntimeException
I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .

```<code>    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public record Course(String name, Student topper) { }
        public record Student(String name, List<Course> enrolled) {}

        public static void main(String[] args) {
            Student john = new Student("John", new ArrayList<>());
            john.enrolled().add(new Course("Enrolled for Math", john));
            john.enrolled().add(new Course("Enrolled for History", john));
            System.out.println(john);
        }
    }

Below is the exception trace :

 java --enable-preview Example
 Exception in thread "main" java.lang.StackOverflowError
    at Example$Course.toString(Example.java:6)
    at java.base/java.lang.String.valueOf(String.java:3388)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)
</code>```

From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the Exception .

```<code>// code with implementation of toString()
public class Example {

    public record Course(String name, Student topper) {
    public String toString()
        {
            return name;
        }
   }
   public record Student(String name, List<Course> enrolled) {
   public String toString()
        {
             return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
        }
   }
   public static void main(String... args) {
       Student john = new Student("John", new ArrayList<>());
       john.enrolled().add(new Course("Enrolled for Math", john));
       john.enrolled().add(new Course("Enrolled for History", john));
       System.out.println(john);
   }
}
</code>```

This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override  toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()

答:
As others pointed out, the issue is that you have a circular reference in your record.

You are able to create such a circular reference because Records are only shallowly immutable.

In your case, enrolled is a List<Course>, that you initialize with an empty ArrayList<>.

To avoid that, you should make a defensive copy when creating the record:

```<code>public record Student(String name, List<Course> enrolled) {
    public Student {
        enrolled = List.copyOf(enrolled);
    }
}
</code>```

You then have to supply a list of the courses when you create a Student:

```<code>List<Course> courses = List.of(
        new Course("Enrolled for Math", null),
        new Course("Enrolled for History", null)
);
Student john = new Student("John", courses);
</code>```

This makes it impossible to have a circular reference.

But it looks like your model requires those circular references. So you might need to change the model.

Body:
I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public record Course(String name, Student topper) { }
        public record Student(String name, List<Course> enrolled) {}

        public static void main(String[] args) {
            Student john = new Student("John", new ArrayList<>());
            john.enrolled().add(new Course("Enrolled for Math", john));
            john.enrolled().add(new Course("Enrolled for History", john));
            System.out.println(john);
        }
    }

Below is the exception trace :

 java --enable-preview Example
 Exception in thread "main" java.lang.StackOverflowError
    at Example$Course.toString(Example.java:6)
    at java.base/java.lang.String.valueOf(String.java:3388)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)

From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the Exception .

// code with implementation of toString()
public class Example {

    public record Course(String name, Student topper) {
    public String toString()
        {
            return name;
        }
   }
   public record Student(String name, List<Course> enrolled) {
   public String toString()
        {
             return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
        }
   }
   public static void main(String... args) {
       Student john = new Student("John", new ArrayList<>());
       john.enrolled().add(new Course("Enrolled for Math", john));
       john.enrolled().add(new Course("Enrolled for History", john));
       System.out.println(john);
   }
}

This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override  toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()

Body:
As others pointed out, the issue is that you have a circular reference in your record.

You are able to create such a circular reference because Records are only shallowly immutable.

In your case, enrolled is a List<Course>, that you initialize with an empty ArrayList<>.

To avoid that, you should make a defensive copy when creating the record:

public record Student(String name, List<Course> enrolled) {
    public Student {
        enrolled = List.copyOf(enrolled);
    }
}

You then have to supply a list of the courses when you create a Student:

List<Course> courses = List.of(
        new Course("Enrolled for Math", null),
        new Course("Enrolled for History", null)
);
Student john = new Student("John", courses);

This makes it impossible to have a circular reference.

But it looks like your model requires those circular references. So you might need to change the model.


问:
Unable to write regular expression to capture numbers in Jmeter
```<code><a href=\"#\" onclick=\"acquireManualTask('189234','MyTask ')\"><img src=\"resources/images/go-next.png\"
</code>```

<p>I dont have much knowledge on regex, in above line my dynamic value is 189234. Can anyone please suggest how to write Regular expression for the same in Jmeter. </p>

答: You need to escape \ and ( char in your expression. Below regex will work for you:- href=\\"#\\" onclick=\\"acquireManualTask\('(\d*?)',

Body:
<img src=\"resources/images/go-next.png\"

I dont have much knowledge on regex, in above line my dynamic value is 189234. Can anyone please suggest how to write Regular expression for the same in Jmeter.

Body: You need to escape \ and ( char in your expression. Below regex will work for you:- <a href=\\"#\\" onclick=\\"acquireManualTask\('(\d*?)',


问:
Nextcloud Kubernetes deployment Internal server error
I want to install nextcloud in kubernetes according to this guide: https://www.codementor.io/@alicheaito/deploying-nextcloud-on-kubernetes-with-kustomize-tn78vcz0a

I don't use any ingress. For testing I used RunAsUser: 0 at the deployment, I know this is not secure, and I will change it to port 8080 and user id 1099 in production. When I call the page I get this screen:

I don't see anything suspecting in the logs:

I am new to kubernetes, and I don't know where to begin to debug.

My deployment.yaml for nextcloud:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    component: app
  name: app
spec:
  selector:
    matchLabels:
      component: app
  replicas: 1
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        component: app
    spec:
      securityContext:
        fsGroup: 1099
        runAsUser: 33
        runAsGroup: 1099
      containers:
        - image: nextcloud:apache
          imagePullPolicy: Always
          name: app
          ports:
            - containerPort: 80
          env:
            - name: MYSQL_DATABASE
              valueFrom:
                secretKeyRef:
                  key: MYSQL_DATABASE
                  name: db-secrets
            - name: MYSQL_PASSWORD
              valueFrom:
                secretKeyRef:
                  key: MYSQL_PASSWORD
                  name: db-secrets
            - name: MYSQL_USER
              valueFrom:
                secretKeyRef:
                  key: MYSQL_USER
                  name: db-secrets
          volumeMounts:
            - mountPath: /var/www/html
              name: app-persistent-storage
            - mountPath: /usr/local/etc/php/conf.d/
              name: app-persistent-storage
      restartPolicy: Always
      volumes:
        - name: app-persistent-storage
          persistentVolumeClaim:
            claimName: app-pvc
</code>```

The service.yaml for nextcloud:

```<code>apiVersion: v1
kind: Service
metadata:
  name: app
  labels:
    component: app
spec:
  type: LoadBalancer
  ports:
    - port: 80
  selector:
    component: app
</code>```

Screenshots from services and  pods:

Here is the nextcloud.log file there is something suspicious, but that didn't help me:

```<code>{"reqId":"4cSKDj718CckiPwauoRU","level":3,"time":"2020-05-28T11:00:55+00:00","remoteAddr":"10.20.0.8","user":"--","app":"base","method":"GET","url":"/","message":{"Exception":"Exception","Message":"Failed to start session","Code":0,"Trace":[{"file":"/var/www/html/lib/base.php","line":429,"function":"__construct","class":"OC\\Session\\Internal","type":"->","args":["oci0uf3awll8"]},{"file":"/var/www/html/lib/base.php","line":647,"function":"initSession","class":"OC","type":"::","args":[]},{"file":"/var/www/html/lib/base.php","line":1089,"function":"init","class":"OC","type":"::","args":[]},{"file":"/var/www/html/index.php","line":36,"args":["/var/www/html/lib/base.php"],"function":"require_once"}],"File":"/var/www/html/lib/private/Session/Internal.php","Line":65,"CustomMessage":"--"},"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36","version":""}
{"reqId":"4cSKDj718CckiPwauoRU","level":3,"time":"2020-05-28T11:00:56+00:00","remoteAddr":"10.20.0.8","user":"--","app":"PHP","method":"GET","url":"/","message":"You are using a fallback implementation of the intl extension. Installing the native one is highly recommended instead. at /var/www/html/3rdparty/patchwork/utf8/src/Patchwork/Utf8/Bootup/intl.php#18","userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36","version":""}
</code>```

答:
Let me address the "I don't know where to begin to debug" part of your question as I am sure that it would be the most beneficial approach for you in the long-run.

There are two most common things to debug which also applies in your use-case:

Debug Services by checking:

Does the Service exist?

Does the Service work by DNS name?

Does the Service work by IP?

Is the Service defined correctly?

Does the Service have any Endpoints?

Is the kube-proxy working?

Debug Running Pods which explains how to debug Pods running (or crashing) on a Node by:

Examining pod logs

Debugging with container exec

Debugging with an ephemeral debug container

Debugging via a shell on the node

I also recommend going through the Troubleshoot Applications guide:

This guide is to help users debug applications that are deployed into
  Kubernetes and not behaving correctly.

Steps and details can be found in the linked sources.

Knowing the above methods will help you understand where and what to check in the first place from the Kubernetes side. I hope you'll find it useful.

Body:
I want to install nextcloud in kubernetes according to this guide: https://www.codementor.io/@alicheaito/deploying-nextcloud-on-kubernetes-with-kustomize-tn78vcz0a

I don't use any ingress. For testing I used RunAsUser: 0 at the deployment, I know this is not secure, and I will change it to port 8080 and user id 1099 in production. When I call the page I get this screen:

I don't see anything suspecting in the logs:

I am new to kubernetes, and I don't know where to begin to debug.

My deployment.yaml for nextcloud:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    component: app
  name: app
spec:
  selector:
    matchLabels:
      component: app
  replicas: 1
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        component: app
    spec:
      securityContext:
        fsGroup: 1099
        runAsUser: 33
        runAsGroup: 1099
      containers:
        - image: nextcloud:apache
          imagePullPolicy: Always
          name: app
          ports:
            - containerPort: 80
          env:
            - name: MYSQL_DATABASE
              valueFrom:
                secretKeyRef:
                  key: MYSQL_DATABASE
                  name: db-secrets
            - name: MYSQL_PASSWORD
              valueFrom:
                secretKeyRef:
                  key: MYSQL_PASSWORD
                  name: db-secrets
            - name: MYSQL_USER
              valueFrom:
                secretKeyRef:
                  key: MYSQL_USER
                  name: db-secrets
          volumeMounts:
            - mountPath: /var/www/html
              name: app-persistent-storage
            - mountPath: /usr/local/etc/php/conf.d/
              name: app-persistent-storage
      restartPolicy: Always
      volumes:
        - name: app-persistent-storage
          persistentVolumeClaim:
            claimName: app-pvc

The service.yaml for nextcloud:

apiVersion: v1
kind: Service
metadata:
  name: app
  labels:
    component: app
spec:
  type: LoadBalancer
  ports:
    - port: 80
  selector:
    component: app

Screenshots from services and  pods:

Here is the nextcloud.log file there is something suspicious, but that didn't help me:

{"reqId":"4cSKDj718CckiPwauoRU","level":3,"time":"2020-05-28T11:00:55+00:00","remoteAddr":"10.20.0.8","user":"--","app":"base","method":"GET","url":"/","message":{"Exception":"Exception","Message":"Failed to start session","Code":0,"Trace":[{"file":"/var/www/html/lib/base.php","line":429,"function":"__construct","class":"OC\\Session\\Internal","type":"->","args":["oci0uf3awll8"]},{"file":"/var/www/html/lib/base.php","line":647,"function":"initSession","class":"OC","type":"::","args":[]},{"file":"/var/www/html/lib/base.php","line":1089,"function":"init","class":"OC","type":"::","args":[]},{"file":"/var/www/html/index.php","line":36,"args":["/var/www/html/lib/base.php"],"function":"require_once"}],"File":"/var/www/html/lib/private/Session/Internal.php","Line":65,"CustomMessage":"--"},"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36","version":""}
{"reqId":"4cSKDj718CckiPwauoRU","level":3,"time":"2020-05-28T11:00:56+00:00","remoteAddr":"10.20.0.8","user":"--","app":"PHP","method":"GET","url":"/","message":"You are using a fallback implementation of the intl extension. Installing the native one is highly recommended instead. at /var/www/html/3rdparty/patchwork/utf8/src/Patchwork/Utf8/Bootup/intl.php#18","userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36","version":""}


问:
deleting only first instance occurring in a list
I have a data-frame that has text in the first column named 'original_column'.

I have successfully been able to pick specific words out of the text column 'original_column' with a list and have them appended to another column and deleted from the original column with the following code:

```<code>list1 = {’text’ , ‘and’ , ‘example’}

finder = lambda x: next(iter([y for y in x.split() if y in list1]), None)

df['list1'] = df.original_column.apply(finder)

df['original column']=df['original column'].replace(regex=r'(?i)'+ df['list1'],value="")
</code>```

I would now like to build on this code by being able to delete ONLY THE FIRST instance of the the specific words in the list from the 'original_column' after appending the listed word to a new column.

The data-frame currently looks like this:

```<code>|   original column  |
__________________________
|   text text word   |
--------------------------
|    and other and   |
</code>```

My current code outputs this:

```<code>|   original column   | list1
______________________________
|        word         | text
------------------------------
|        other        |  and
</code>```

My desired to output this:

```<code>|   original column   | list1
_______________________________
|      text word      | text
-------------------------------
|      other and      |  and
</code>```

答:
To match the first pattern occurrence and remove it without removing the text before this first occurrence you may use

```<b>^(.*?)</b><i>pattern</i>```

and replace it with the backreference to the capturing group value, here, \1.

You may match any of your words in the list1 list as whole words (with \b(?:word1|word2|wordN)\b like pattern) and capture all the text before it with (?s)^(.*?) pattern that would match the least amount of any chars from the start of the string.

Use

```<code>df['original column'] = df['original column'].str.replace(rf"(?s)^(.*?)\b(?:{'|'.join(list1)})\b", r"\1").str.strip()
</code>```

The regex used is

```<code>(?s)^(.*?)\b(?:text|and|example)\b
</code>```

See the regex demo.

Details

(?s) - re.DOTALL enabled to let . match any char including line break chars

^ - start of string

(.*?) - Group 1: any 0 or more chars, as few as possible

\b(?:text|and|example)\b - a whole word from a list of alphanumeric words (that may also contain an undersocre)

The replacement is \1, the backreference to the value captured with the first (and only here) capturing group.

Body:
I have a data-frame that has text in the first column named 'original_column'.

I have successfully been able to pick specific words out of the text column 'original_column' with a list and have them appended to another column and deleted from the original column with the following code:

list1 = {’text’ , ‘and’ , ‘example’}

finder = lambda x: next(iter([y for y in x.split() if y in list1]), None)

df['list1'] = df.original_column.apply(finder)

df['original column']=df['original column'].replace(regex=r'(?i)'+ df['list1'],value="")

I would now like to build on this code by being able to delete ONLY THE FIRST instance of the the specific words in the list from the 'original_column' after appending the listed word to a new column.

The data-frame currently looks like this:

|   original column  |
__________________________
|   text text word   |
--------------------------
|    and other and   |

My current code outputs this:

|   original column   | list1
______________________________
|        word         | text
------------------------------
|        other        |  and

My desired to output this:

|   original column   | list1
_______________________________
|      text word      | text
-------------------------------
|      other and      |  and

Body:
To match the first pattern occurrence and remove it without removing the text before this first occurrence you may use

^(.*?)pattern

and replace it with the backreference to the capturing group value, here, \1.

You may match any of your words in the list1 list as whole words (with \b(?:word1|word2|wordN)\b like pattern) and capture all the text before it with (?s)^(.*?) pattern that would match the least amount of any chars from the start of the string.

Use

df['original column'] = df['original column'].str.replace(rf"(?s)^(.*?)\b(?:{'|'.join(list1)})\b", r"\1").str.strip()

The regex used is

(?s)^(.*?)\b(?:text|and|example)\b

See the regex demo.

Details

(?s) - re.DOTALL enabled to let . match any char including line break chars

^ - start of string

(.*?) - Group 1: any 0 or more chars, as few as possible

\b(?:text|and|example)\b - a whole word from a list of alphanumeric words (that may also contain an undersocre)

The replacement is \1, the backreference to the value captured with the first (and only here) capturing group.


Title: Parse JSON using Python

Body:
I am calling an API and I am getting a JSON response like the one above:

{
  "data": {
    "styles": [
      {
        "groups": [
          {
            "product": [
              {
                "code": "0000001",
                "date": null
              }
            ]
          },
          {
            "product": [
              {
                "code": "0000002",
                "date": "2020-05-02T00:00:00.000Z"
              }
            ]
          },
          {
            "product": [
              {
                "code": "0000003",
                "date": "2020-04-22T00:00:00.000Z"
              }
            ]
          }
        ]
      },
      {
        "groups": [
          {
            "product": [
              {
                "code": "0000011",
                "date": "2020-05-12T00:00:00.000Z"
              }
            ]
          },
          {
            "product": [
              {
                "code": "0000012",
                "date": "2020-05-12T00:00:00.000Z"
              }
            ]
          }
        ]
      }
    ]
  }
}

I am not familiar with handling JSON and this one is super nested. All I want to do is to create a tuple (or a dict) which would look like:

(0000001, null)
(0000002, 2020-05-02T00:00:00.000Z)
(0000003, 2020-04-22T00:00:00.000Z)
(0000011, 2020-05-12T00:00:00.000Z)
(0000012, 2020-05-12T00:00:00.000Z)

Could you please advice me one how to do that?

Body:
import json

# your work

d = json.load(xxxx) # load it.
for i in d["data"]["styles"]:
    for j in i["groups"]:
        print((j['product'][0]['code'], j['product'][0]['date']))

Result:

('0000001', None) # In python, there is no null. it will be replace to None.
('0000002', '2020-05-02T00:00:00.000Z')
('0000003', '2020-04-22T00:00:00.000Z')
('0000011', '2020-05-12T00:00:00.000Z')
('0000012', '2020-05-12T00:00:00.000Z')


问:
How to return an array of class type and fill?
I have a function which is supposed to return an array of class type.

So from database I picked data and filled datatable. Now from datatable I am picking columns value and assigning to the properties of the class. But problem is that what I am doing will assign a single record only but I want to fill the class type array with multiple record.

My code:

```<code>Private Sub BindGridInfoFunctionalLocation()
        Dim v_ObjDs As New DataSet
        Try
            v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")

            Dim dtTableFL As DataTable
            dtTableFL.Columns.Add("TagNo", GetType(String))
            dtTableFL.Columns.Add("TagDescription", GetType(String))
            dtTableFL.Columns.Add("ParentHeirarchy", GetType(String))
            dtTableFL.Columns.Add("Class", GetType(String))

            dtTableFL = v_ObjDs.Tables(0)

            Dim AssetsCls As New AssetsDto
            'Dim AssetsClsArray As New AssetsDto()

            If v_ObjDs.Tables(0).Rows.Count > 0 Then
                'v_ObjDs.Tables(0).Rows.Add(v_ObjDs.Tables(0).NewRow())

                For Each Item In dtTableFL.Rows

                    AssetsCls.ASSETTAG = Item("TagNo")
                    AssetsCls.ASSETDESC = Item("TagDescription")
                    AssetsCls.PARENTTAG = Item("ParentHeirarchy")
                    AssetsCls.ASSETTYPE = Item("TypeClass")

                Next

                gv_InfoFunctionalLocation.DataSource = v_ObjDs
                gv_InfoFunctionalLocation.DataBind()
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
</code>```

Note:

the return type and everything should be like this since I am interacting with the client's web service and it expects it this way only.

答:
In your example there is no array where each element of the table could be stored after the transform in an AssetsDto. Moreover, you need to change from Sub to Function if you want to return anything to the caller.

Another important change is relative to the data structure used to store the Dtos. Instead of using an array (you need to know the number of elements to effectively use it), I suggest to use a List(Of AssetsDto) where you can dynamically add elements without worrying about the size to the list.

```<code>' Declare as a Function that returns a List(Of AssetsDto)
Private Function BindGridInfoFunctionalLocation() as List(Of AssetsDto)
    Dim v_ObjDs As New DataSet

    ' This is where we store each record transformed in an AssetsDto
    Dim result as List(Of AssetsDto) = new List(Of AssetsDto)
    Try
        v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")

        Dim dtTableFL As DataTable = v_ObjDs.Tables(0)

        ' Cycle to create the AssetsDto
        For Each Item In dtTableFL.Rows

            ' IMPORTANT. At each loop create a new AssetsDto, otherwise you
            ' will just change the values of the same instance
            Dim AssetsCls As AssetsDto = new AssetsDto()
            AssetsCls.ASSETTAG = Item("TagNo")
            AssetsCls.ASSETDESC = Item("TagDescription")
            AssetsCls.PARENTTAG = Item("ParentHeirarchy")
            AssetsCls.ASSETTYPE = Item("TypeClass")

            ' Add the instance to the list
            result.Add(AssetsCls)
        Next
        gv_InfoFunctionalLocation.DataSource = v_ObjDs
        gv_InfoFunctionalLocation.DataBind()
    End If

    ' Return to caller the results
    Return results
    Catch ex As Exception
        Throw ex
    End Try
End Function
</code>```

Body:
I have a function which is supposed to return an array of class type.

So from database I picked data and filled datatable. Now from datatable I am picking columns value and assigning to the properties of the class. But problem is that what I am doing will assign a single record only but I want to fill the class type array with multiple record.

My code:

Private Sub BindGridInfoFunctionalLocation()
        Dim v_ObjDs As New DataSet
        Try
            v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")

            Dim dtTableFL As DataTable
            dtTableFL.Columns.Add("TagNo", GetType(String))
            dtTableFL.Columns.Add("TagDescription", GetType(String))
            dtTableFL.Columns.Add("ParentHeirarchy", GetType(String))
            dtTableFL.Columns.Add("Class", GetType(String))

            dtTableFL = v_ObjDs.Tables(0)

            Dim AssetsCls As New AssetsDto
            'Dim AssetsClsArray As New AssetsDto()

            If v_ObjDs.Tables(0).Rows.Count > 0 Then
                'v_ObjDs.Tables(0).Rows.Add(v_ObjDs.Tables(0).NewRow())

                For Each Item In dtTableFL.Rows

                    AssetsCls.ASSETTAG = Item("TagNo")
                    AssetsCls.ASSETDESC = Item("TagDescription")
                    AssetsCls.PARENTTAG = Item("ParentHeirarchy")
                    AssetsCls.ASSETTYPE = Item("TypeClass")

                Next

                gv_InfoFunctionalLocation.DataSource = v_ObjDs
                gv_InfoFunctionalLocation.DataBind()
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

Note:

the return type and everything should be like this since I am interacting with the client's web service and it expects it this way only.

Body:
In your example there is no array where each element of the table could be stored after the transform in an AssetsDto. Moreover, you need to change from Sub to Function if you want to return anything to the caller.

Another important change is relative to the data structure used to store the Dtos. Instead of using an array (you need to know the number of elements to effectively use it), I suggest to use a List(Of AssetsDto) where you can dynamically add elements without worrying about the size to the list.

' Declare as a Function that returns a List(Of AssetsDto)
Private Function BindGridInfoFunctionalLocation() as List(Of AssetsDto)
    Dim v_ObjDs As New DataSet

    ' This is where we store each record transformed in an AssetsDto
    Dim result as List(Of AssetsDto) = new List(Of AssetsDto)
    Try
        v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")

        Dim dtTableFL As DataTable = v_ObjDs.Tables(0)

        ' Cycle to create the AssetsDto
        For Each Item In dtTableFL.Rows

            ' IMPORTANT. At each loop create a new AssetsDto, otherwise you
            ' will just change the values of the same instance
            Dim AssetsCls As AssetsDto = new AssetsDto()
            AssetsCls.ASSETTAG = Item("TagNo")
            AssetsCls.ASSETDESC = Item("TagDescription")
            AssetsCls.PARENTTAG = Item("ParentHeirarchy")
            AssetsCls.ASSETTYPE = Item("TypeClass")

            ' Add the instance to the list
            result.Add(AssetsCls)
        Next
        gv_InfoFunctionalLocation.DataSource = v_ObjDs
        gv_InfoFunctionalLocation.DataBind()
    End If

    ' Return to caller the results
    Return results
    Catch ex As Exception
        Throw ex
    End Try
End Function


问:
Apache Flink read at least 2 record to trigger sink
I am write my Apache Flink(1.10) to update records real time like this:

```<code>public class WalletConsumeRealtimeHandler {

    public static void main(String[] args) throws Exception {
        walletConsumeHandler();
    }

    public static void walletConsumeHandler() throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        FlinkUtil.initMQ();
        FlinkUtil.initEnv(env);
        DataStream<String> dataStreamSource = env.addSource(FlinkUtil.initDatasource("wallet.consume.report.realtime"));
        DataStream<ReportWalletConsumeRecord> consumeRecord =
                dataStreamSource.map(new MapFunction<String, ReportWalletConsumeRecord>() {
                    @Override
                    public ReportWalletConsumeRecord map(String value) throws Exception {
                        ObjectMapper mapper = new ObjectMapper();
                        ReportWalletConsumeRecord consumeRecord = mapper.readValue(value, ReportWalletConsumeRecord.class);
                        consumeRecord.setMergedRecordCount(1);
                        return consumeRecord;
                    }
                }).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessGenerator());

        consumeRecord.keyBy(
                new KeySelector<ReportWalletConsumeRecord, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> getKey(ReportWalletConsumeRecord value) throws Exception {
                        return Tuple2.of(value.getConsumeItem(), value.getTenantId());
                    }
                })
                .timeWindow(Time.seconds(5))
                .reduce(new SumField(), new CollectionWindow())
                .addSink(new SinkFunction<List<ReportWalletConsumeRecord>>() {
                    @Override
                    public void invoke(List<ReportWalletConsumeRecord> reportPumps, Context context) throws Exception {
                        WalletConsumeRealtimeHandler.invoke(reportPumps);
                    }
                });
        env.execute(WalletConsumeRealtimeHandler.class.getName());
    }

    private static class CollectionWindow extends ProcessWindowFunction<ReportWalletConsumeRecord,
            List<ReportWalletConsumeRecord>,
            Tuple2<String, Long>,
            TimeWindow> {
        public void process(Tuple2<String, Long> key,
                            Context context,
                            Iterable<ReportWalletConsumeRecord> minReadings,
                            Collector<List<ReportWalletConsumeRecord>> out) throws Exception {
            ArrayList<ReportWalletConsumeRecord> employees = Lists.newArrayList(minReadings);
            if (employees.size() > 0) {
                out.collect(employees);
            }
        }
    }

    private static class SumField implements ReduceFunction<ReportWalletConsumeRecord> {
        public ReportWalletConsumeRecord reduce(ReportWalletConsumeRecord d1, ReportWalletConsumeRecord d2) {
            Integer merged1 = d1.getMergedRecordCount() == null ? 1 : d1.getMergedRecordCount();
            Integer merged2 = d2.getMergedRecordCount() == null ? 1 : d2.getMergedRecordCount();
            d1.setMergedRecordCount(merged1 + merged2);
            d1.setConsumeNum(d1.getConsumeNum() + d2.getConsumeNum());
            return d1;
        }
    }

    public static void invoke(List<ReportWalletConsumeRecord> records) {
        WalletConsumeService service = FlinkUtil.InitRetrofit().create(WalletConsumeService.class);
        Call<ResponseBody> call = service.saveRecords(records);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

}
</code>```

and now I found the Flink task only receive at least 2 records to trigger sink, is the reduce action need this?

答:
You need two records to trigger the window. Flink only knows when to close a window (and fire subsequent calculation) when it receives a watermark that is larger than the configured value of the end of the window.

In your case, you use BoundedOutOfOrdernessGenerator, which updates the watermark according to the incoming records. So it generates a second watermark only after having seen the second record.

You can use a different watermark generator. In the troubleshooting training there is a watermark generator that also generates watermarks on timeout.

Body:
I am write my Apache Flink(1.10) to update records real time like this:

public class WalletConsumeRealtimeHandler {

    public static void main(String[] args) throws Exception {
        walletConsumeHandler();
    }

    public static void walletConsumeHandler() throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        FlinkUtil.initMQ();
        FlinkUtil.initEnv(env);
        DataStream<String> dataStreamSource = env.addSource(FlinkUtil.initDatasource("wallet.consume.report.realtime"));
        DataStream<ReportWalletConsumeRecord> consumeRecord =
                dataStreamSource.map(new MapFunction<String, ReportWalletConsumeRecord>() {
                    @Override
                    public ReportWalletConsumeRecord map(String value) throws Exception {
                        ObjectMapper mapper = new ObjectMapper();
                        ReportWalletConsumeRecord consumeRecord = mapper.readValue(value, ReportWalletConsumeRecord.class);
                        consumeRecord.setMergedRecordCount(1);
                        return consumeRecord;
                    }
                }).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessGenerator());

        consumeRecord.keyBy(
                new KeySelector<ReportWalletConsumeRecord, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> getKey(ReportWalletConsumeRecord value) throws Exception {
                        return Tuple2.of(value.getConsumeItem(), value.getTenantId());
                    }
                })
                .timeWindow(Time.seconds(5))
                .reduce(new SumField(), new CollectionWindow())
                .addSink(new SinkFunction<List<ReportWalletConsumeRecord>>() {
                    @Override
                    public void invoke(List<ReportWalletConsumeRecord> reportPumps, Context context) throws Exception {
                        WalletConsumeRealtimeHandler.invoke(reportPumps);
                    }
                });
        env.execute(WalletConsumeRealtimeHandler.class.getName());
    }

    private static class CollectionWindow extends ProcessWindowFunction<ReportWalletConsumeRecord,
            List<ReportWalletConsumeRecord>,
            Tuple2<String, Long>,
            TimeWindow> {
        public void process(Tuple2<String, Long> key,
                            Context context,
                            Iterable<ReportWalletConsumeRecord> minReadings,
                            Collector<List<ReportWalletConsumeRecord>> out) throws Exception {
            ArrayList<ReportWalletConsumeRecord> employees = Lists.newArrayList(minReadings);
            if (employees.size() > 0) {
                out.collect(employees);
            }
        }
    }

    private static class SumField implements ReduceFunction<ReportWalletConsumeRecord> {
        public ReportWalletConsumeRecord reduce(ReportWalletConsumeRecord d1, ReportWalletConsumeRecord d2) {
            Integer merged1 = d1.getMergedRecordCount() == null ? 1 : d1.getMergedRecordCount();
            Integer merged2 = d2.getMergedRecordCount() == null ? 1 : d2.getMergedRecordCount();
            d1.setMergedRecordCount(merged1 + merged2);
            d1.setConsumeNum(d1.getConsumeNum() + d2.getConsumeNum());
            return d1;
        }
    }

    public static void invoke(List<ReportWalletConsumeRecord> records) {
        WalletConsumeService service = FlinkUtil.InitRetrofit().create(WalletConsumeService.class);
        Call<ResponseBody> call = service.saveRecords(records);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

}

and now I found the Flink task only receive at least 2 records to trigger sink, is the reduce action need this?


问:
How does Kubernetes Horizontal Pod Autoscaler calculate CPU Utilization for Multi Container Pods?

Question 1.)

Given the scenario a multi-container pod, where all containers have a defined CPU request:

How would Kubernetes Horizontal Pod Autoscaler calculate CPU Utilization for Multi Container pods?

Does it average them? (((500m cpu req + 50m cpu req) /2) * X% HPA target cpu utilization

Does it add them? ((500m cpu req + 50m cpu req) * X% HPA target cpu utilization

Does it track them individually? (500m cpu req * X% HPA target cpu utilization = target #1, 50m cpu req * X% HPA target cpu utilization = target #2.)

Question 2.)

Given the scenario of a multi-container pod, where 1 container has a defined CPU request and a blank CPU request for the other containers:

How would Kubernetes Horizontal Pod Autoscaler calculate CPU Utilization for Multi Container pods?

Does it work as if you only had a 1 container pod?

Question 3.)

Do the answers to questions 1 and 2 change based on the HPA API version?
I noticed stable/nginx-ingress helm chart, chart version 1.10.2, deploys an HPA for me with these specs:

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
```
<p>(I noticed apiVersion: autoscaling/v2beta2 now exists)</p>
<p><strong>Background Info:</strong>
<br> I recently had an issue with unexpected wild scaling / constantly going back and forth between min and max pods after adding a sidecar(2nd container) to an nginx ingress controller deployment (which is usually a pod with a single container). In my case, it was an oauth2 proxy, although I image istio sidecar container folks might run into this sort of problem all the time as well.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
spec:
  replicas: 3
  template:
    spec:
      containers:
        - name: nginx-ingress-controller #(primary-container)
          resources:
            requests:
              cpu: 500m    #baseline light load usage in my env
              memory: 2Gi  #according to kubectl top pods
            limits:
              memory: 8Gi  #(oom kill pod if this high, because somethings wrong)
        - name: oauth2-proxy #(newly-added-2nd-sidecar-container)
          resources:
            requests:
              cpu: 50m
              memory: 50Mi
            limits:
              memory: 4Gi
</code>```

I have an HPA (apiVersion: autoscaling/v1) with:

min 3 replicas (to preserve HA during rolling updates)

targetCPUUtilizationPercentage = 150%

It occurred to me that my misconfiguration leads to unexpected wild scaling was caused by 2 issues:

I don't actually understand how HPAs work when the pod has multiple containers

I don't know how to dig deep to get metrics of what's going on.

To address the first issue: I brainstormed my understanding of how it works in the single container scenario (and then realized I don't know the multi-container scenario so I decided to ask this question)

This is my understanding of how HPA (autoscaling/v1) works when I have 1 container (temporarily ignore the 2nd container in the above deployment spec):

The HPA would spawn more replicas when the CPU utilization average of all pods shifted from my normal expected load of 500m or less to 750m (150% x 500m request)

To address the 2nd issue: I found out how to dig to see concrete numeric value-based metrics vs relative percentage-based metrics to help figure out what's happening behind the scenes:

bash# kubectl describe horizontalpodautoscaler nginx-ingress-controller -n=ingress | grep Metrics: -A 1
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  5% (56m) / 100%
```

(Note: kubectl top pods -n=ingress, showed cpu usage of the 5 replicas as 36m, 34m, 88m, 36m, 91m, so that 57m current which ~matches 56m current)

Also now it's a basic proportions Math Problem that allows solving for target static value:

(5% / 56m) = (100% / x m) --> x = 56 * 100 / 5 = 1120m target cpu

 (Note: this HPA isn't associated with the deployment mentioned above, that's why the numbers are off.)

答:
For question 2 if we look at source code we can see that it looks all containers individually and returns if container doesn't have request.

```<code>func calculatePodRequests(pods []*v1.Pod, resource v1.ResourceName) (map[string]int64, error) {
   requests := make(map[string]int64, len(pods))
   for _, pod := range pods {
      podSum := int64(0)
      for _, container := range pod.Spec.Containers {
         if containerRequest, ok := container.Resources.Requests[resource]; ok {
            podSum += containerRequest.MilliValue()
         } else {
            return nil, fmt.Errorf("missing request for %s", resource)
         }
      }
      requests[pod.Name] = podSum
   }
   return requests, nil
}

</code>```

Body:
Question 1.)

Given the scenario a multi-container pod, where all containers have a defined CPU request:

How would Kubernetes Horizontal Pod Autoscaler calculate CPU Utilization for Multi Container pods?

Does it average them? (((500m cpu req + 50m cpu req) /2) * X% HPA target cpu utilization

Does it add them? ((500m cpu req + 50m cpu req) * X% HPA target cpu utilization

Does it track them individually? (500m cpu req * X% HPA target cpu utilization = target #1, 50m cpu req * X% HPA target cpu utilization = target #2.)

Question 2.)

Given the scenario of a multi-container pod, where 1 container has a defined CPU request and a blank CPU request for the other containers:

How would Kubernetes Horizontal Pod Autoscaler calculate CPU Utilization for Multi Container pods?

Does it work as if you only had a 1 container pod?

Question 3.)

Do the answers to questions 1 and 2 change based on the HPA API version?
I noticed stable/nginx-ingress helm chart, chart version 1.10.2, deploys an HPA for me with these specs:

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler

(I noticed apiVersion: autoscaling/v2beta2 now exists)

Background Info:

 I recently had an issue with unexpected wild scaling / constantly going back and forth between min and max pods after adding a sidecar(2nd container) to an nginx ingress controller deployment (which is usually a pod with a single container). In my case, it was an oauth2 proxy, although I image istio sidecar container folks might run into this sort of problem all the time as well.

apiVersion: apps/v1
kind: Deployment
spec:
  replicas: 3
  template:
    spec:
      containers:
        - name: nginx-ingress-controller #(primary-container)
          resources:
            requests:
              cpu: 500m    #baseline light load usage in my env
              memory: 2Gi  #according to kubectl top pods
            limits:
              memory: 8Gi  #(oom kill pod if this high, because somethings wrong)
        - name: oauth2-proxy #(newly-added-2nd-sidecar-container)
          resources:
            requests:
              cpu: 50m
              memory: 50Mi
            limits:
              memory: 4Gi

I have an HPA (apiVersion: autoscaling/v1) with:

min 3 replicas (to preserve HA during rolling updates)

targetCPUUtilizationPercentage = 150%

It occurred to me that my misconfiguration leads to unexpected wild scaling was caused by 2 issues:

I don't actually understand how HPAs work when the pod has multiple containers

I don't know how to dig deep to get metrics of what's going on.

To address the first issue: I brainstormed my understanding of how it works in the single container scenario (and then realized I don't know the multi-container scenario so I decided to ask this question)

This is my understanding of how HPA (autoscaling/v1) works when I have 1 container (temporarily ignore the 2nd container in the above deployment spec):

The HPA would spawn more replicas when the CPU utilization average of all pods shifted from my normal expected load of 500m or less to 750m (150% x 500m request)

To address the 2nd issue: I found out how to dig to see concrete numeric value-based metrics vs relative percentage-based metrics to help figure out what's happening behind the scenes:

bash# kubectl describe horizontalpodautoscaler nginx-ingress-controller -n=ingress | grep Metrics: -A 1
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  5% (56m) / 100%

(Note: kubectl top pods -n=ingress, showed cpu usage of the 5 replicas as 36m, 34m, 88m, 36m, 91m, so that 57m current which ~matches 56m current)

Also now it's a basic proportions Math Problem that allows solving for target static value:

(5% / 56m) = (100% / x m) --> x = 56 * 100 / 5 = 1120m target cpu

 (Note: this HPA isn't associated with the deployment mentioned above, that's why the numbers are off.)

Body:
For question 2 if we look at source code we can see that it looks all containers individually and returns if container doesn't have request.

func calculatePodRequests(pods []*v1.Pod, resource v1.ResourceName) (map[string]int64, error) {
   requests := make(map[string]int64, len(pods))
   for _, pod := range pods {
      podSum := int64(0)
      for _, container := range pod.Spec.Containers {
         if containerRequest, ok := container.Resources.Requests[resource]; ok {
            podSum += containerRequest.MilliValue()
         } else {
            return nil, fmt.Errorf("missing request for %s", resource)
         }
      }
      requests[pod.Name] = podSum
   }
   return requests, nil
}


问:
Check if column exists and then do selects from table using C#
please can anyone point me in the right direction. I want to check if the column exists, if so do this select else do another select

```<code>    select case
   when exists (
      SELECT *
      FROM Sys.columns c
      WHERE c.[object_id] = OBJECT_ID('dbo.Municipality')
         AND c.name = 'AmountTypeLabel'
   )
   then 1
   else 0
 end
</code>```

This Checks if column exists and then return a 0 or a 1 but there is no column name so i can't check it in C#

This is what i have tried in C# but as i said before there is no column name

```<code>DataTable DT;
        string SQL = "";
        try
        {

            SQL = "select case " +
                  " when exists( " +
                  "  SELECT 1 " +
                  "  FROM Sys.columns c " +
                  " WHERE c.[object_id] = OBJECT_ID('dbo.Municipality')" +
                  "  AND c.name = 'AmountTypeLabel'" +
                  ")" +
                  " then 1 " +
                  " else 0 " +
                  " end ";
            DT = Conn.ExecuteDT(SQL);
        }
        catch (Exception ex)
        {
            throw new Exception("Unable to get Tables", ex);
        }
        return DT;
    }
</code>```

答:
With existing code you can fetch the value by using the below and use it in another function:

```<code>if(DT.Rows[0][0].ToString() == "1")
 //Do Something
</code>```

OR you could to use SQL Alias in your SQL query like below :

```<code>" end AS ColumnExists";
</code>```

and then you can refer this in your other function. Sample snippet below -

```<code> if(DT.Rows[0]["ColumnExists"].ToString() == "1")
    //Do Something
</code>```

On a side note if the requirement is to fetch only the 1 or 0 from SQL server then use the ExecuteScalar as mentioned by Matteo1010 in comments.

```<code> var columnExists = cmd.ExecuteScalar();
 if(columnExists.ToString() == "1")
  //Do Something
</code>```

Body:
please can anyone point me in the right direction. I want to check if the column exists, if so do this select else do another select

    select case
   when exists (
      SELECT *
      FROM Sys.columns c
      WHERE c.[object_id] = OBJECT_ID('dbo.Municipality')
         AND c.name = 'AmountTypeLabel'
   )
   then 1
   else 0
 end

This Checks if column exists and then return a 0 or a 1 but there is no column name so i can't check it in C#

This is what i have tried in C# but as i said before there is no column name

DataTable DT;
        string SQL = "";
        try
        {

            SQL = "select case " +
                  " when exists( " +
                  "  SELECT 1 " +
                  "  FROM Sys.columns c " +
                  " WHERE c.[object_id] = OBJECT_ID('dbo.Municipality')" +
                  "  AND c.name = 'AmountTypeLabel'" +
                  ")" +
                  " then 1 " +
                  " else 0 " +
                  " end ";
            DT = Conn.ExecuteDT(SQL);
        }
        catch (Exception ex)
        {
            throw new Exception("Unable to get Tables", ex);
        }
        return DT;
    }

Body:
With existing code you can fetch the value by using the below and use it in another function:

if(DT.Rows[0][0].ToString() == "1")
 //Do Something

OR you could to use SQL Alias in your SQL query like below :

" end AS ColumnExists";

and then you can refer this in your other function. Sample snippet below -

 if(DT.Rows[0]["ColumnExists"].ToString() == "1")
    //Do Something

On a side note if the requirement is to fetch only the 1 or 0 from SQL server then use the ExecuteScalar as mentioned by Matteo1010 in comments.

 var columnExists = cmd.ExecuteScalar();
 if(columnExists.ToString() == "1")
  //Do Something


问:
How can I get a calendar weeks start and end date in Python?
I would like to have a function get_cw_borders(year: int, cw: int) -> Tuple[datetime.datetime, datetime.datetime] which should behave like this:

```<code>>>> get_cw_borders(2020, 17)
(datetime.datetime(2020, 4, 20), datetime.datetime(2020, 4, 26))

>>> get_cw_borders(2020, 18)
(datetime.datetime(2020, 4, 27), datetime.datetime(2020, 5, 3))

>>> get_cw_borders(2020, 1)
(datetime.datetime(2019, 12, 30), datetime.datetime(2020, 1, 5))

>>> get_cw_borders(2017, 1)
(datetime.datetime(2017, 1, 2), datetime.datetime(2017, 1, 8))
</code>```

I'm aware that some countries start the week on Sunday instead of Monday. I think (please correct me if I'm wrong) that this is just a constant offset for this function, so that would not be a big deal.

Is there a built-in function to get this?

Non-Duplicates

Thank you for linking similar questions.

Python: give start and end of week data from a given date: I don't have a given date

答:
You can either use the method described in this answer or you can use a 3rd party package like arrow to achieve it a bit more easily with the following:

```<code>import arrow

today = arrow.utcnow()

print(f'{today:YYYY-MM-DD}')
print(f'{today.ceil("week"):YYYY-MM-DD}')
print(f'{today.floor("week"):YYYY-MM-DD}')
</code>```

Output:

```<code>2020-06-02
2020-06-07
2020-06-01
</code>```

Using span instead of floor and ceil will give you the tuple:

```<code>print(f'{today.span("week")}')
>>> (<Arrow [2020-06-01T00:00:00+00:00]>, <Arrow [2020-06-07T23:59:59.999999+00:00]>)
</code>```

Body:
I would like to have a function get_cw_borders(year: int, cw: int) -> Tuple[datetime.datetime, datetime.datetime] which should behave like this:

>>> get_cw_borders(2020, 17)
(datetime.datetime(2020, 4, 20), datetime.datetime(2020, 4, 26))

>>> get_cw_borders(2020, 18)
(datetime.datetime(2020, 4, 27), datetime.datetime(2020, 5, 3))

>>> get_cw_borders(2020, 1)
(datetime.datetime(2019, 12, 30), datetime.datetime(2020, 1, 5))

>>> get_cw_borders(2017, 1)
(datetime.datetime(2017, 1, 2), datetime.datetime(2017, 1, 8))

I'm aware that some countries start the week on Sunday instead of Monday. I think (please correct me if I'm wrong) that this is just a constant offset for this function, so that would not be a big deal.

Is there a built-in function to get this?

Non-Duplicates

Thank you for linking similar questions.

Python: give start and end of week data from a given date: I don't have a given date

Body:
You can either use the method described in this answer or you can use a 3rd party package like arrow to achieve it a bit more easily with the following:

import arrow

today = arrow.utcnow()

print(f'{today:YYYY-MM-DD}')
print(f'{today.ceil("week"):YYYY-MM-DD}')
print(f'{today.floor("week"):YYYY-MM-DD}')

Output:

2020-06-02
2020-06-07
2020-06-01

Using span instead of floor and ceil will give you the tuple:

print(f'{today.span("week")}')
>>> (<Arrow [2020-06-01T00:00:00+00:00]>, <Arrow [2020-06-07T23:59:59.999999+00:00]>)


问:
How to extract value from selected TextBlock element in a ListBox?
I'm using a ListBox to display all values contained in Dictionary<> object:

```<code><ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>
</code>```

Content is filled by the following code:

```<code>Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
</code>```

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

I tried doing something like that, but obviosly it doesn't work:

```<code>private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
</code>```

I would really appreciate your help!

答:
you can even do the follwing:

```<code><ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding Key}" Margin="5"/>
                        <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
            <TextBlock Text="{Binding Value}"/>
        </Grid>
</code>```

So you don't need code behind...

BR,

TJ

ContentLicense: CC BY-SA 3.0

Body:
I'm using a ListBox to display all values contained in Dictionary<> object:

<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
                    <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

Content is filled by the following code:

Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;

Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.

I tried doing something like that, but obviosly it doesn't work:

private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
    this.Test_SomeOtherTextBlock.Text = lb.ToString();
}

I would really appreciate your help!

Body:
you can even do the follwing:

<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding Key}" Margin="5"/>
                        <TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
            <TextBlock Text="{Binding Value}"/>
        </Grid>

So you don't need code behind...

BR,

TJ


答:
Building on @Leonardo Rignanese's answer. An extension function for a more functional approach:

```<code>extension MapExt<T, U> on Map<T, U> {
  Map<T, U> sortedBy(Comparable value(U u)) {
    final entries = this.entries.toList();
    entries.sort((a, b) => value(a.value).compareTo(value(b.value)));
    return Map<T, U>.fromEntries(entries);
  }
}
</code>```

General usage:

```<code>foos.sortedBy((it) => it.bar);
</code>```

Usage for OP:

```<code>final sortedChordtypes = chordtypes.sortedBy((it) => it.length);
</code>```

Gist here: https://gist.github.com/nmwilk/68ae0424e848b9f05a8239db6b708390

Title: How to sort map's values?

Body:
Can someone give me a hint? I want to sort a map's values by the length of the lists.

var chordtypes = {
  "maj": [0, 4, 7],
  "M7": [0, 4, 7, 11],
  "m7": [0, 3, 7, 10],
  "6": [0, 4, 7, 9],
  "9": [0, 4, 7, 10, 14],
  "sus2": [0, 2, 7],
  "sus4": [0, 5, 7],
  "omit3": [0, 7],
  "#5": [0, 4, 8],
  "+7b9#11": [0, 4, 8, 10, 13, 18],
  "+9": [0, 4, 8, 10, 14]
};

Body:
Building on @Leonardo Rignanese's answer. An extension function for a more functional approach:

extension MapExt<T, U> on Map<T, U> {
  Map<T, U> sortedBy(Comparable value(U u)) {
    final entries = this.entries.toList();
    entries.sort((a, b) => value(a.value).compareTo(value(b.value)));
    return Map<T, U>.fromEntries(entries);
  }
}

General usage:

foos.sortedBy((it) => it.bar);

Usage for OP:

final sortedChordtypes = chordtypes.sortedBy((it) => it.length);

Gist here: https://gist.github.com/nmwilk/68ae0424e848b9f05a8239db6b708390


问:
how can i link my javascript file with html???? I think i have linked properly but not working?
WHAT is problem in linking javascript code to html code???
 my html code:

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>PARUL</title>
    <script  src="script.js"></script>
    <script>
    console.log(x)
    </script>

</head>
<body></body>
</html>
</code>```

my javascript code:

```<code>var x="hello world";
</code>```

答:
You have already linked your HTML code with your JS file.
Follow these steps :

Right click on your mouse and you will get the option Inspect at the bottom.

Click on it and you will get the developer tool having multiple tabs in it like Elements,Console,etc.

You just need to click on the Console tab. Then you will able to see the output which you have given the statement console.log("")

Body:
WHAT is problem in linking javascript code to html code???
 my html code:

<!doctype html>

    <meta charset="utf-8">
    <title>PARUL</title>

my javascript code:

var x="hello world";


问:
How do I make partition dynamically?
So i have this partition which makes an error because i search on google it said mostly like "the value is bigger than the partition"

```<code>PARTITION BY LIST (BUSINESS_DATE)
    (PARTITION D20200326 VALUES (TO_DATE('26/03/2020','DD/MM/YYYY'))
        PCTFREE 10 INITRANS 1 MAXTRANS 255
        STORAGE ( BUFFER_POOL DEFAULT)
        TABLESPACE DWH LOGGING NOCOMPRESS)
GO
</code>```

This is the partition with the date '26/03/2020', but i wanted to make the partition is dynamic, so i have this ETL jobs, if the ETL jobs run on '27/03/2020' my ETL job error and doesn't want to insert, so i have to change the partition into 27/03/2020.

But how do i do this dynamically?

```<code>PARTITION BY LIST (INSERT_DATE)
    (PARTITION D20200326 VALUES (TO_DATE(SYSDATE))
        PCTFREE 10 INITRANS 1 MAXTRANS 255
        STORAGE ( BUFFER_POOL DEFAULT)
        TABLESPACE DWH LOGGING NOCOMPRESS)
GO
</code>```

i've tried with changing SYSDATE but only gave me an error

ORA-14308: partition bound element must be one of: string, datetime or interval literal, number, or NULL
 Script line 23, statement line 23, column 47

答:
If you need day-wise partition to be automatically created then you can use the INTERVAL partition which creates the partition as and when inserted data do not fall in any of the partition as follows:

```<code>CREATE TABLE YOUR_TABLE (
  ......
  created_date DATE
)
PARTITION BY RANGE (created_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(
   PARTITION YT_PART_01 values LESS THAN (TO_DATE('02-JUN-2020','DD-MON-YYYY'))
);
</code>```

It will automatically create the new partition if you insert any data beyond the 02-jun.

Refer to this documents regarding this feature.

Title: How do I make partition dynamically?

Body:
So i have this partition which makes an error because i search on google it said mostly like "the value is bigger than the partition"

PARTITION BY LIST (BUSINESS_DATE)
    (PARTITION D20200326 VALUES (TO_DATE('26/03/2020','DD/MM/YYYY'))
        PCTFREE 10 INITRANS 1 MAXTRANS 255
        STORAGE ( BUFFER_POOL DEFAULT)
        TABLESPACE DWH LOGGING NOCOMPRESS)
GO

This is the partition with the date '26/03/2020', but i wanted to make the partition is dynamic, so i have this ETL jobs, if the ETL jobs run on '27/03/2020' my ETL job error and doesn't want to insert, so i have to change the partition into 27/03/2020.

But how do i do this dynamically?

PARTITION BY LIST (INSERT_DATE)
    (PARTITION D20200326 VALUES (TO_DATE(SYSDATE))
        PCTFREE 10 INITRANS 1 MAXTRANS 255
        STORAGE ( BUFFER_POOL DEFAULT)
        TABLESPACE DWH LOGGING NOCOMPRESS)
GO

i've tried with changing SYSDATE but only gave me an error

ORA-14308: partition bound element must be one of: string, datetime or interval literal, number, or NULL
 Script line 23, statement line 23, column 47

Body:
If you need day-wise partition to be automatically created then you can use the INTERVAL partition which creates the partition as and when inserted data do not fall in any of the partition as follows:

CREATE TABLE YOUR_TABLE (
  ......
  created_date DATE
)
PARTITION BY RANGE (created_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(
   PARTITION YT_PART_01 values LESS THAN (TO_DATE('02-JUN-2020','DD-MON-YYYY'))
);

It will automatically create the new partition if you insert any data beyond the 02-jun.

Refer to this documents regarding this feature.


问:
Web Applications Converted To Desktop Applications
I have been reading some of the posts here, but haven't really seen the answers to my questions directly.  I am a web developer and need to integrate some of my web applications to some sort of desktop application.  For example, say a business has some kind of booking, it needs to be available offline (desktop in office/stores) and online, with the master database offline.  What I would like to know is the best way in doing something like this and different options.  If I can use web technology like PHP/MySQL and then use something like WinBinder to be able to handle all the work, then great, but from my research, I get the impression this is not a great approach.  PHP/MySQL is what I mainly use for backend development, however know some other languages, just haven't mastered them yet.

Can you guys suggest some methods of acheiving what I need and what languages, etc are the best?  Can I stick with web technologies, but create simple install packages so clients can install the application easily?

Thanks in advance for your help.

答:
I discourage to use PHP as desktop application.

You should sepearte the 2 appliaction.

Web app using PHP

Desktop app using Java (or whatever you want)

In your desktop app you should provide a "journaled" system that can save all the actions users make offline and upload it when the users go online (or when the users want) to your PHP application so you can push those actions in your DB.


问:
How to import entire folder to another?
This is what my folder looks like (both folders have empty __init__.py file:

```<code>.
├── Filter
│   ├── __init__.py
│   └── stp.py
└── Time
    ├── __init__.py
    └── event.py
</code>```

In event.py I currently have (which works):

```<code>from Filter.stp import *
</code>```

But I want to change it to (import entire folder since I have many more files in reality):

```<code>import Filter
</code>```

How can I do that?

答:
Let's say the stp.py and event.py file contain the following content:

# Filter/stp.py
a = 3
b = 4

# Time/event.py
class Event:
    pass
```

<p>You could then import these values in the respective <code>__init__.py</code> files:</p>

<pre class="lang-py prettyprint-override"><code># Filter/__init__.py
from Filter.stp import a, b

# Time/__init__.py
from Time.event import Event
</code>```

By using this setup, you can have a main file that looks like this:

import Filter
import Time

if __name__ == '__main__':
    print(Filter.a)  # 3
    print(Time.Event) # <class 'Time.event.Event'>
```

Title: How to import entire folder to another?

Body:
This is what my folder looks like (both folders have empty __init__.py file:

.
├── Filter
│   ├── __init__.py
│   └── stp.py
└── Time
    ├── __init__.py
    └── event.py

In event.py I currently have (which works):

from Filter.stp import *

But I want to change it to (import entire folder since I have many more files in reality):

import Filter

How can I do that?

Body:
Let's say the stp.py and event.py file contain the following content:

# Filter/stp.py
a = 3
b = 4

# Time/event.py
class Event:
    pass

You could then import these values in the respective __init__.py files:

# Filter/__init__.py
from Filter.stp import a, b

# Time/__init__.py
from Time.event import Event

By using this setup, you can have a main file that looks like this:

import Filter
import Time

if __name__ == '__main__':
    print(Filter.a)  # 3
    print(Time.Event) # <class 'Time.event.Event'>


问:
What am I doing wrong to get group.selected working in graph API?
I'm currently trying implement an app to read calendars only for a group that's permitted to the app. The idea behind this is that when I want to add a another calendar all I'd have to do is add the object to a specific o365 group. I'm taking the application approach over delegation that way I don't have anything actually logging in to utilize the app. Ultimately I'd like to stay away from any of the *.All permissions for security reasons.

Steps taken :
- created o365 group
- added resource objects and one user service account (just for testing) to the group
- registered app
- generated secret
- assigned group to the app
- granted admin consent to groups.selected via the azure portal

When I run a GET  for group/{id}/members :

```<code>{'error': {'code': 'Authorization_RequestDenied', 'message': 'Insufficient privileges to complete the operation.', 'innerError': {'request-id': '473410a8-4db4-49d6-8d2c-92b9fbd4edb1', 'date': '2020-03-05T14:59:28'}}}
</code>```

答:
MS docs says:

Note: This permission is exposed in the Azure portal for a feature that is not available for general use. Do not use this permission as it is subject to change.

https://learn.microsoft.com/en-us/graph/permissions-reference

Body:
I'm currently trying implement an app to read calendars only for a group that's permitted to the app. The idea behind this is that when I want to add a another calendar all I'd have to do is add the object to a specific o365 group. I'm taking the application approach over delegation that way I don't have anything actually logging in to utilize the app. Ultimately I'd like to stay away from any of the *.All permissions for security reasons.

Steps taken :
- created o365 group
- added resource objects and one user service account (just for testing) to the group
- registered app
- generated secret
- assigned group to the app
- granted admin consent to groups.selected via the azure portal

When I run a GET  for group/{id}/members :

{'error': {'code': 'Authorization_RequestDenied', 'message': 'Insufficient privileges to complete the operation.', 'innerError': {'request-id': '473410a8-4db4-49d6-8d2c-92b9fbd4edb1', 'date': '2020-03-05T14:59:28'}}}


问:
ERROR ITMS-90034: Missing or invalid signature
Every time trying to submit but some result. Like this

ERROR ITMS-90034: "Missing or invalid signature. The bundle '****.******.****' at bundle path 'Payload/APP_NAME.app' is not signed using an Apple submission certificate."

Everything looks fine, we click submit, it goes to validate, and starts to upload to the app store. Then at the very last second ,the error pops up no matter what we've done to try to fix it.

Tried following steps to.

1) Tried to make just new app and upload ( With this excluded depending from any framework or source and any settings) - some result

2) Tried to remove account from Xcode->Preferences->Account (Remove account) and then add again.

3) Tried revoke certificate make again and then refresh provisioning profile

4) Tried to make app zip and upload from Application Loader

5) Tried to make IPA

6) Make change in Keychain Access for related Certification Authority certificate from "Always Trust" to "Use the system default".

7) remove all certificates and provisioning profiles and add again.

The build is valid

Some Error for every time, when trying to upload for submission.

Error from Application loader.

Error from Organizer.

Has anyone been able to work through this or a similar issue, and can you help?

答: Go to Keychain Access, delete all the expired certificates, and add the corresponding valid ones.</p>


问:
Ads for European Economic Area (EEA) using Tag For Under Age of Consent (TFUA)
When implementing AdMob into my mobile app I get an error when attempting to display the consent form after I set Tag For Under Age Of Consent (as all my users are expected to be children).

First I set Tag For Under Age Of Consent using:

```<code>ConsentInformation.getInstance(context).setTagForUnderAgeOfConsent(true);
</code>```

Then attempting to show the consent form and I get an error. I found additional information about this at: https://developers.google.com/admob/android/eu-consent#users_under_the_age_of_consent

However, I am a bit confused as to what is needed. Do I need to display a custom consent form if I have TFUA set or does setting TFUA no longer require a consent form at all?

答:
As described on the developer document when you set Tag for Users under the age of consent

Once the TFUA setting is enabled, the Google-rendered consent form
  will fail to load. All ad requests that include TFUA will be made
  ineligible for personalized advertising and remarketing. TFUA disables
  requests to third-party ad technology providers, such as ad
  measurement pixels and third-party ad servers.

For your query, you do not require a consent form.

As per my understanding, even if you try showing personalized ads, it will still display non-personalized ads. In one of the app which I developed for kids, I m getting error as it is failing to display the form due to this tag, I myself calling the setting to show Non - Personalized ads.

Body:
When implementing AdMob into my mobile app I get an error when attempting to display the consent form after I set Tag For Under Age Of Consent (as all my users are expected to be children).

First I set Tag For Under Age Of Consent using:

ConsentInformation.getInstance(context).setTagForUnderAgeOfConsent(true);

Then attempting to show the consent form and I get an error. I found additional information about this at: https://developers.google.com/admob/android/eu-consent#users_under_the_age_of_consent

However, I am a bit confused as to what is needed. Do I need to display a custom consent form if I have TFUA set or does setting TFUA no longer require a consent form at all?