问:
how to pass values using @Input()
enter image description here
How should I do so that my card can get data from another file?

OneProcessItemComponent.ts

```<code>export class OneProcessItemComponent {
  @Input() item = processItem;
}
</code>```

OneProcessItemComponent.html

```<code><div class="process__item">
  <div class="process__wrap">
    <img src="{{ item.image }}" alt="process" class="process__img">
    <div class="process__item-title">{{ item.title }}</div>
    <div class="process__item-subtitle">{{ item.subtitle }}</div>
  </div>
</div>
</code>```

processItem.ts

```<code>export const processItem: IProcessItem[] = [
  {
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
    spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
  },
</code>```

答:
You can do

```<code>// app component
<hello name="{{ name }}"></hello>

// hello component
@Input() name: string;
</code>```

// Example

https://stackblitz.com/edit/angular-ivy-x77xcs?file=src%2Fapp%2Fhello.component.ts

Title: how to pass values using @Input()

Body:
enter image description here
How should I do so that my card can get data from another file?

OneProcessItemComponent.ts

export class OneProcessItemComponent {
  @Input() item = processItem;
}

OneProcessItemComponent.html

{{ item.title }}

{{ item.subtitle }}

processItem.ts

export const processItem: IProcessItem[] = [
  {
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
    spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
  },

Body:
You can do

// app component
<hello name="{{ name }}"></hello>

// hello component
@Input() name: string;

// Example

https://stackblitz.com/edit/angular-ivy-x77xcs?file=src%2Fapp%2Fhello.component.ts


来源: stackexchange

问:
CSS property resize does not work correctly in Safari (dont shrink when height is set)
is there any solution how fix shrinking in Safari?
when the height is set and I try to reduce the element to the height so it doesn't work.

Firefox, Chrome works fine ...

div {
    background: blue;
    width: 300px;
    height: 300px;
    resize: vertical;
    overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

答:
I had the same issue and found the answer here in the comments: https://css-tricks.com/almanac/properties/r/resize/

Adding to your div :active{ height: 0; } solves it.

div {
    background: blue;
    width: 300px;
    height: 300px;
    resize: vertical;
    overflow: hidden;
}
div:active {
    height: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I had the same issue and found the answer here in the comments: https://css-tricks.com/almanac/properties/r/resize/

Adding to your div :active{ height: 0; } solves it.

div {
    background: blue;
    width: 300px;
    height: 300px;
    resize: vertical;
    overflow: hidden;
}
div:active {
    height: 0;
}

<div></div>


问:
confusion in choosing tomcat docker image for cloud run
hey I am new to docker and I want to deploy my tomcat application on cloud run , so I need to choose an image which is slim and my second question is do I need to install Java or jdk with it if I choose
tomcat:9-slim</p>

答: You can explore the container content. For instance, go to that page and you can see that openjdk-11 is installed. No need to install another version (expect if you need a more recent version.</p>


问:
Airflow DAG optimization
I'm developing a DAGS structure for several clients

The DAGS are exactly the same for all clients, except for:

A numerical value that changes according to the client ID

Schedule interval.

Is there any way to reuse the code already made for the various DAGS. What would be the best approach here ?

Tanks,
M

答:
You can can create dag dynamically.

```<code>def create_dag(dag_id):
    """
    A function returning a DAG object.
    """

    return DAG(dag_id)

for i in range(10):
    dag_id = f"foo_{i}"
    globals()[dag_id] = DAG(dag_id)

    # or better, call a function that returns a DAG object!
    other_dag_id = f"bar_{i}"
    globals()[other_dag_id] = create_dag(other_dag_id)
</code>```

So in your case set the client_id as part of the dag_id.

A good tutorial can be found here.

Title: Airflow DAG optimization

Body:
You can can create dag dynamically.

def create_dag(dag_id):
    """
    A function returning a DAG object.
    """

    return DAG(dag_id)

for i in range(10):
    dag_id = f"foo_{i}"
    globals()[dag_id] = DAG(dag_id)

    # or better, call a function that returns a DAG object!
    other_dag_id = f"bar_{i}"
    globals()[other_dag_id] = create_dag(other_dag_id)

So in your case set the client_id as part of the dag_id.

A good tutorial can be found here.


问:
'React Hook useEffect has missing dependencies' in react
I've seen similar issues on this site, but I didn't understood properly why it occurs.

What I'm facing, is that I'm trying to make a Todo List with React. It's my first time using and building a project with react, so I'm still learning.

So, what I want to do, is when a user clicks on a button, a modal opens, then it collects the title and the details of that todo, the user clicks save and the modal closes, then a card is displayed displaying that todo.

Code:

```<code>let firstRender = useRef(true);
useEffect(()=> {
    if(firstRender.current) {
        firstRender.current = false;
    }
    else{
        if(!modalState) {
            if(!modalCancel) {
                let Title = todoTitle;
                let Detail = todoDetail;
                setTodo([...todo, {
                    title: Title.toUpperCase(),
                    detail: Detail
                }])
            }

        }

    }
}, [modalState, modalCancel])
</code>```

The modalState is just a state that tells if the modal is open or closed and the modalCancel is a state which tells if the modal is saved or cancelled. I have some other states as well which are responsible for getting the details and title of the todo from the modal, and a state which keeps track of all the todos.

This works fine but displays the following warning in the terminal :

```<code>React Hook useEffect has missing dependencies: 'todo', 'todoDetail', and 'todoTitle'. Either include them or remove the dependency array. You can also do a functional update 'setTodo(t => ...)' if you only need 'todo' in the 'setTodo' call  react-hooks/exhaustive-deps
</code>```

If I add all of the states, my app does not work, and I don't want to remove the two dependencies because I want to fire re-render everytime (except the first when the page loads) when the modal closes.
Can anyone help me with that? I can show how the all states are written if needed.

答:
your useEffect will re-run when its dependencies change.
if you don't put todo as a dependency, when todo change, it won't take new todo value and still use the old value (when it re-run in your case when modalState or modalClose change).

ex: when you modalState, your todo is [{title: 'one', detail: 'number one'}]
then you execute some other function that change the value of todo state (ex: fetching data from server) and the new todo is now:

[
  {title: 'one', detail: 'number one'},
  {title: 'two', detail: 'number two'}
]
```
<p>but your modalState not change! which mean the value of state <code>todo</code> in your useEffect function is not changed! (<code>[{title: 'one', detail: 'number one'}]</code>)</p>
<p>then you call setTodo inside of useEffect with <code>{title: "three", detail: "number three"}</code> will result:</p>
<pre class="lang-js prettyprint-override"><code>[
  {title: 'one', detail: 'number one'},
  {title: 'three', detail: 'number three'}
]
</code>```

instead of:

[
  {title: 'one', detail: 'number one'},
  {title: 'two', detail: 'number two'},
  {title: 'three', detail: 'number three'}
]
```
<h3>If you put todo as a dependencies and call setTodo inside of useEffect! It will cause infinite loop.</h3>
<h2>My Solution:</h2>
<p>when try to update state using useState hook, you can pass a callback instead of just a value! That callback have a prop that is previous value of todo. So now you not using the todo state in your useEffect but you still have todo's value. and by "not using state in useEffect" you won't have to pass <code>todo</code> as a dependency.</p>
<pre class="lang-js prettyprint-override"><code>let firstRender = useRef(true);
useEffect(()=> {
    if(firstRender.current) {
        firstRender.current = false;
    }
    else{
        if(!modalState) {
            if(!modalCancel) {
                let Title = todoTitle;
                let Detail = todoDetail;
                setTodo(prevTodo => [...prevTodo, {
                    title: Title.toUpperCase(),
                    detail: Detail
                }])
            }

        }

    }
}, [modalState, modalCancel, todoTitle, todoDetail])

</code>```

wish this help you.

Body:
I've seen similar issues on this site, but I didn't understood properly why it occurs.

What I'm facing, is that I'm trying to make a Todo List with React. It's my first time using and building a project with react, so I'm still learning.

So, what I want to do, is when a user clicks on a button, a modal opens, then it collects the title and the details of that todo, the user clicks save and the modal closes, then a card is displayed displaying that todo.

Code:

let firstRender = useRef(true);
useEffect(()=> {
    if(firstRender.current) {
        firstRender.current = false;
    }
    else{
        if(!modalState) {
            if(!modalCancel) {
                let Title = todoTitle;
                let Detail = todoDetail;
                setTodo([...todo, {
                    title: Title.toUpperCase(),
                    detail: Detail
                }])
            }

        }

    }
}, [modalState, modalCancel])

The modalState is just a state that tells if the modal is open or closed and the modalCancel is a state which tells if the modal is saved or cancelled. I have some other states as well which are responsible for getting the details and title of the todo from the modal, and a state which keeps track of all the todos.

This works fine but displays the following warning in the terminal :

React Hook useEffect has missing dependencies: 'todo', 'todoDetail', and 'todoTitle'. Either include them or remove the dependency array. You can also do a functional update 'setTodo(t => ...)' if you only need 'todo' in the 'setTodo' call  react-hooks/exhaustive-deps

If I add all of the states, my app does not work, and I don't want to remove the two dependencies because I want to fire re-render everytime (except the first when the page loads) when the modal closes.
Can anyone help me with that? I can show how the all states are written if needed.

Body:
your useEffect will re-run when its dependencies change.
if you don't put todo as a dependency, when todo change, it won't take new todo value and still use the old value (when it re-run in your case when modalState or modalClose change).

ex: when you modalState, your todo is [{title: 'one', detail: 'number one'}]
then you execute some other function that change the value of todo state (ex: fetching data from server) and the new todo is now:

[
  {title: 'one', detail: 'number one'},
  {title: 'two', detail: 'number two'}
]

but your modalState not change! which mean the value of state todo in your useEffect function is not changed! ([{title: 'one', detail: 'number one'}])

then you call setTodo inside of useEffect with {title: "three", detail: "number three"} will result:

[
  {title: 'one', detail: 'number one'},
  {title: 'three', detail: 'number three'}
]

instead of:

[
  {title: 'one', detail: 'number one'},
  {title: 'two', detail: 'number two'},
  {title: 'three', detail: 'number three'}
]

If you put todo as a dependencies and call setTodo inside of useEffect! It will cause infinite loop.

My Solution:

when try to update state using useState hook, you can pass a callback instead of just a value! That callback have a prop that is previous value of todo. So now you not using the todo state in your useEffect but you still have todo's value. and by "not using state in useEffect" you won't have to pass todo as a dependency.

let firstRender = useRef(true);
useEffect(()=> {
    if(firstRender.current) {
        firstRender.current = false;
    }
    else{
        if(!modalState) {
            if(!modalCancel) {
                let Title = todoTitle;
                let Detail = todoDetail;
                setTodo(prevTodo => [...prevTodo, {
                    title: Title.toUpperCase(),
                    detail: Detail
                }])
            }

        }

    }
}, [modalState, modalCancel, todoTitle, todoDetail])

wish this help you.


问:
How to fix "pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available" when installing Tensorflow?
I was trying to install TensorFlow with Anaconda 3.9.9.

I ran the command

pip install tensorflow
```
<p>and there was an error saying:</p>
<pre class="lang-none prettyprint-override"><code>WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/
Could not fetch URL https://pypi.org/simple/tensorflow/: There was a problem confirming the ssl certificate:  HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/tensorflow/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
ERROR: No matching distribution found for tensorflow
</code>```

I have tried adding /anaconda3, /anaconda3/Scripts and /anaconda3/library/bin to the Path variable. I have also tried running the command:

pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org tensorflow
```

but nothing seems to be working.

Did I miss anything and are there any other solution?

答:
Try running below command to fix this issue:

```<code>pip install --upgrade
pip install ssl
</code>```

Please create an virtual_environment to install TensorFlow in Anaconda.

Follow below code to install TensorFlow in virtual_environment:

```<code>conda create -n tf tensorflow  #Create a Virtual environment(tf).
conda activate tf              #Activate the Virtual environment
pip install tensorflow         #install TensorFlow in it.
</code>```

Note: You need to activate the virtual_environment each time you want to use TensorFlow.

Body:
I was trying to install TensorFlow with Anaconda 3.9.9.

I ran the command

pip install tensorflow

and there was an error saying:

WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/
Could not fetch URL https://pypi.org/simple/tensorflow/: There was a problem confirming the ssl certificate:  HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/tensorflow/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
ERROR: No matching distribution found for tensorflow

I have tried adding /anaconda3, /anaconda3/Scripts and /anaconda3/library/bin to the Path variable. I have also tried running the command:

pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org tensorflow

but nothing seems to be working.

Did I miss anything and are there any other solution?

Body:
Try running below command to fix this issue:

pip install --upgrade
pip install ssl

Please create an virtual_environment to install TensorFlow in Anaconda.

Follow below code to install TensorFlow in virtual_environment:

conda create -n tf tensorflow  #Create a Virtual environment(tf).
conda activate tf              #Activate the Virtual environment
pip install tensorflow         #install TensorFlow in it.

Note: You need to activate the virtual_environment each time you want to use TensorFlow.


问:
Windows C# implementation of linux dd command
I'm writing a C#.Net app to run on windows that needs to take an image of a removable disk and chuck it onto a Linux Live USB. The Live USB is the inserted into the target machine and boots, on start up it runs a script which uses the dd command like so to flash it onto another drive:

dd if=/path/to/file/from/csharp/program of=/dev/sdX

The problem I am having is creating the image on the windows side. I have tried my Live Linux out with files I have created on a Linux system using dd and that works fine, but I need to be able to create these files from within a C#.Net application on Windows. I'd rather not have to rely on cygwin or some other dependency so tried to use the Win32 CreateFile function to open the physical device.

CreateFile is called with the first arg set to "\.\F:" (if F: is the drive I want to image), like so:

```<code>SafeFileHandle TheDevice = CreateFile(_DevicePath, (uint)FileAccess.Read, (uint)(FileShare.Write | FileShare.Read | FileShare.Delete), IntPtr.Zero, (uint)FileMode.Open, (uint)FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_SEQUENTIAL_SCAN, IntPtr.Zero);
if (TheDevice.IsInvalid)
{
    throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error());
}
FileStream Dest = System.IO.File.Open(_SaveFile, FileMode.Create);
FileStream Src = new FileStream(TheDevice, FileAccess.Read);
Src.CopyTo(Dest);
Dest.Flush();
Src.Close();
Dest.Close();
</code>```

But when the output file is dd'd back onto a disk using the Live Linux USB the result is not as expected (the disk isn't bootable etc, but from examining the output file in a hex editor, it looks like there is an MBR at the beginning etc).

Is this a problem with endianess or should I using something other than a FileStream to copy the data into the file.

Alternatively is there an example of dd for Windows source code (C# or C++, i've looked at the Delphi for http://www.chrysocome.net/dd and don't totally understand it or have a decent Delphi IDE to pick the code apart) so I can see how that works?

UPDATE/EDIT:

Here is a hex string of the first 512 Bytes that the dd output contains:

```<code>33 C0 FA 8E D8 8E D0 BC 00 7C 89 E6 06 57 8E C0 FB FC BF 00 06 B9 00 01 F3 A5 EA 1F 06
00 00 52 52 B4 41 BB AA 55 31 C9 30 F6 F9 CD 13 72 13 81 FB 55 AA 75 0D D1 E9 73 09 66
C7 06 8D 06 B4 42 EB 15 5A B4 08 CD 13 83 E1 3F 51 0F B6 C6 40 F7 E1 52 50 66 31 C0 66
99 E8 66 00 E8 21 01 4D 69 73 73 69 6E 67 20 6F 70 65 72 61 74 69 6E 67 20 73 79 73 74
65 6D 2E 0D 0A 66 60 66 31 D2 BB 00 7C 66 52 66 50 06 53 6A 01 6A 10 89 E6 66 F7 36 F4
7B C0 E4 06 88 E1 88 C5 92 F6 36 F8 7B 88 C6 08 E1 41 B8 01 02 8A 16 FA 7B CD 13 8D 64
10 66 61 C3 E8 C4 FF BE BE 7D BF BE 07 B9 20 00 F3 A5 C3 66 60 89 E5 BB BE 07 B9 04 00
31 C0 53 51 F6 07 80 74 03 40 89 DE 83 C3 10 E2 F3 48 74 5B 79 39 59 5B 8A 47 04 3C 0F
74 06 24 7F 3C 05 75 22 66 8B 47 08 66 8B 56 14 66 01 D0 66 21 D2 75 03 66 89 C2 E8 AC
FF 72 03 E8 B6 FF 66 8B 46 1C E8 A0 FF 83 C3 10 E2 CC 66 61 C3 E8 62 00 4D 75 6C 74 69
70 6C 65 20 61 63 74 69 76 65 20 70 61 72 74 69 74 69 6F 6E 73 2E 0D 0A 66 8B 44 08 66
03 46 1C 66 89 44 08 E8 30 FF 72 13 81 3E FE 7D 55 AA 0F 85 06 FF BC FA 7B 5A 5F 07 FA
FF E4 E8 1E 00 4F 70 65 72 61 74 69 6E 67 20 73 79 73 74 65 6D 20 6C 6F 61 64 20 65 72
72 6F 72 2E 0D 0A 5E AC B4 0E 8A 3E 62 04 B3 07 CD 10 3C 0A 75 F1 CD 18 F4 EB FD 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 19 16 9F 29 00 00 80 01 01 00 06 FE 3F 0E 3F 00 00 00 61 C8 03 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 AA
</code>```

and here is what my code produces:

```<code>EB 76 90 4D 53 44 4F 53 35 2E 30 00 02 04 04 00 02 00 02 00 00 F8 F2 00 3F 00 FF 00 3F
00 00 00 61 C8 03 00 80 00 29 7A E8 21 04 4E 4F 20 4E 41 4D 45 20 20 20 20 46 41 54 31
36 20 20 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 E9 05 01 B4 0E 53 33 DB CD 10 5B C3 8A 07 3C 00 74 06 E8 EE FF 43 EB F4 C3
0D 4E 6F 20 42 50 42 3A 20 43 61 6E 27 74 20 62 6F 6F 74 20 75 73 69 6E 67 20 43 48 53
20 66 75 6E 63 74 69 6F 6E 73 00 50 B0 2E E8 BC FF 58 33 DB 8E 06 E4 01 F6 06 DC 01 02
75 42 F6 06 DC 01 04 75 07 80 3E E8 01 80 72 34 53 53 52 50 06 53 55 6A 10 8B F4 52 50
8A 16 E8 01 B8 00 42 F9 CD 13 8A EC 58 5A 8D 64 10 72 14 80 FD 00 75 0F 03 C5 83 D2 00
C3 BB 91 00 E8 78 FF F4 EB FD 83 3E 18 00 00 74 F0 52 50 8B CD F7 36 18 00 8B F2 03 D1
3B 16 18 00 76 06 8B 0E 18 00 2B CE 33 D2 F7 36 1A 00 88 16 E9 01 8B F8 8B D7 51 8A C1
8D 4C 01 C0 E6 06 0A CE 8A EA 8B 16 E8 01 B4 02 CD 13 59 73 15 80 FC 09 75 0A 49 EB DE
8A C4 04 30 E8 18 FF B4 00 CD 13 EB D1 58 5A 03 C1 83 D2 00 2B E9 74 07 C1 E1 09 03 D9
EB 94 C3 00 00 00 00 FA FC E8 00 00 5E 81 EE 85 01 2E 8B 84 E4 01 8E D8 8E C0 8E D0 2E
C7 84 7C 01 AF 01 2E 89 84 7E 01 B9 00 01 BF 00 00 F3 2E A5 2E FF AC 7C FF BC 00 0A FB
80 3E E8 01 FF 75 04 88 16 E8 01 83 06 E4 01 20 A1 E0 01 8B 16 E2 01 BD 02 00 E8 E9 FE
50 52 EB 74 90 00 00 00 00 00 00 00 00 00 00 00 D3 20 00 00 00 30 80 00 FF 00 68 41 00
40 09 FF 40 5A AC 04 00 00 AC 04 00 00 00 00 12 00 55 AA
</code>```

This was taken from exactly the same CF card without any editing/writing etc happening, so i'm confused as to why they are so different, but both end with the correct 55 AA bytes too. Does Windows mangle the MBR's on cards when they're accessed this way or is some other weird under the hood stuff happening that I'm not aware of?

答:
This is what i've written to do get the \.\PhysicalDriveX path for a given drive letter. If Pass the drive letter into this and take the return value and pass into CreateFile as the first Param I should now get something similar to dd under Linux.</p>

```<code>using System.Management; //Add in a reference to this as well in the project settings
public static string GetPhysicalDevicePath(char DriveLetter)
{
    ManagementClass devs = new ManagementClass( @"Win32_Diskdrive");
    {
        ManagementObjectCollection moc = devs.GetInstances();
        foreach(ManagementObject mo in moc)
        {
            foreach (ManagementObject b in mo.GetRelated("Win32_DiskPartition"))
            {
                foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
                {
                    string DevName = string.Format("{0}", c["Name"]);
                    if (DevName[0] == DriveLetter)
                        return string.Format("{0}", mo["DeviceId"]);
                }
            }
        }
    }
    return "";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a C#.Net app to run on windows that needs to take an image of a removable disk and chuck it onto a Linux Live USB. The Live USB is the inserted into the target machine and boots, on start up it runs a script which uses the dd command like so to flash it onto another drive:

dd if=/path/to/file/from/csharp/program of=/dev/sdX

The problem I am having is creating the image on the windows side. I have tried my Live Linux out with files I have created on a Linux system using dd and that works fine, but I need to be able to create these files from within a C#.Net application on Windows. I'd rather not have to rely on cygwin or some other dependency so tried to use the Win32 CreateFile function to open the physical device.

CreateFile is called with the first arg set to "\.\F:" (if F: is the drive I want to image), like so:

SafeFileHandle TheDevice = CreateFile(_DevicePath, (uint)FileAccess.Read, (uint)(FileShare.Write | FileShare.Read | FileShare.Delete), IntPtr.Zero, (uint)FileMode.Open, (uint)FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_SEQUENTIAL_SCAN, IntPtr.Zero);
if (TheDevice.IsInvalid)
{
    throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error());
}
FileStream Dest = System.IO.File.Open(_SaveFile, FileMode.Create);
FileStream Src = new FileStream(TheDevice, FileAccess.Read);
Src.CopyTo(Dest);
Dest.Flush();
Src.Close();
Dest.Close();

But when the output file is dd'd back onto a disk using the Live Linux USB the result is not as expected (the disk isn't bootable etc, but from examining the output file in a hex editor, it looks like there is an MBR at the beginning etc).

Is this a problem with endianess or should I using something other than a FileStream to copy the data into the file.

Alternatively is there an example of dd for Windows source code (C# or C++, i've looked at the Delphi for http://www.chrysocome.net/dd and don't totally understand it or have a decent Delphi IDE to pick the code apart) so I can see how that works?

UPDATE/EDIT:

Here is a hex string of the first 512 Bytes that the dd output contains:

33 C0 FA 8E D8 8E D0 BC 00 7C 89 E6 06 57 8E C0 FB FC BF 00 06 B9 00 01 F3 A5 EA 1F 06
00 00 52 52 B4 41 BB AA 55 31 C9 30 F6 F9 CD 13 72 13 81 FB 55 AA 75 0D D1 E9 73 09 66
C7 06 8D 06 B4 42 EB 15 5A B4 08 CD 13 83 E1 3F 51 0F B6 C6 40 F7 E1 52 50 66 31 C0 66
99 E8 66 00 E8 21 01 4D 69 73 73 69 6E 67 20 6F 70 65 72 61 74 69 6E 67 20 73 79 73 74
65 6D 2E 0D 0A 66 60 66 31 D2 BB 00 7C 66 52 66 50 06 53 6A 01 6A 10 89 E6 66 F7 36 F4
7B C0 E4 06 88 E1 88 C5 92 F6 36 F8 7B 88 C6 08 E1 41 B8 01 02 8A 16 FA 7B CD 13 8D 64
10 66 61 C3 E8 C4 FF BE BE 7D BF BE 07 B9 20 00 F3 A5 C3 66 60 89 E5 BB BE 07 B9 04 00
31 C0 53 51 F6 07 80 74 03 40 89 DE 83 C3 10 E2 F3 48 74 5B 79 39 59 5B 8A 47 04 3C 0F
74 06 24 7F 3C 05 75 22 66 8B 47 08 66 8B 56 14 66 01 D0 66 21 D2 75 03 66 89 C2 E8 AC
FF 72 03 E8 B6 FF 66 8B 46 1C E8 A0 FF 83 C3 10 E2 CC 66 61 C3 E8 62 00 4D 75 6C 74 69
70 6C 65 20 61 63 74 69 76 65 20 70 61 72 74 69 74 69 6F 6E 73 2E 0D 0A 66 8B 44 08 66
03 46 1C 66 89 44 08 E8 30 FF 72 13 81 3E FE 7D 55 AA 0F 85 06 FF BC FA 7B 5A 5F 07 FA
FF E4 E8 1E 00 4F 70 65 72 61 74 69 6E 67 20 73 79 73 74 65 6D 20 6C 6F 61 64 20 65 72
72 6F 72 2E 0D 0A 5E AC B4 0E 8A 3E 62 04 B3 07 CD 10 3C 0A 75 F1 CD 18 F4 EB FD 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 19 16 9F 29 00 00 80 01 01 00 06 FE 3F 0E 3F 00 00 00 61 C8 03 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 AA

and here is what my code produces:

EB 76 90 4D 53 44 4F 53 35 2E 30 00 02 04 04 00 02 00 02 00 00 F8 F2 00 3F 00 FF 00 3F
00 00 00 61 C8 03 00 80 00 29 7A E8 21 04 4E 4F 20 4E 41 4D 45 20 20 20 20 46 41 54 31
36 20 20 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 E9 05 01 B4 0E 53 33 DB CD 10 5B C3 8A 07 3C 00 74 06 E8 EE FF 43 EB F4 C3
0D 4E 6F 20 42 50 42 3A 20 43 61 6E 27 74 20 62 6F 6F 74 20 75 73 69 6E 67 20 43 48 53
20 66 75 6E 63 74 69 6F 6E 73 00 50 B0 2E E8 BC FF 58 33 DB 8E 06 E4 01 F6 06 DC 01 02
75 42 F6 06 DC 01 04 75 07 80 3E E8 01 80 72 34 53 53 52 50 06 53 55 6A 10 8B F4 52 50
8A 16 E8 01 B8 00 42 F9 CD 13 8A EC 58 5A 8D 64 10 72 14 80 FD 00 75 0F 03 C5 83 D2 00
C3 BB 91 00 E8 78 FF F4 EB FD 83 3E 18 00 00 74 F0 52 50 8B CD F7 36 18 00 8B F2 03 D1
3B 16 18 00 76 06 8B 0E 18 00 2B CE 33 D2 F7 36 1A 00 88 16 E9 01 8B F8 8B D7 51 8A C1
8D 4C 01 C0 E6 06 0A CE 8A EA 8B 16 E8 01 B4 02 CD 13 59 73 15 80 FC 09 75 0A 49 EB DE
8A C4 04 30 E8 18 FF B4 00 CD 13 EB D1 58 5A 03 C1 83 D2 00 2B E9 74 07 C1 E1 09 03 D9
EB 94 C3 00 00 00 00 FA FC E8 00 00 5E 81 EE 85 01 2E 8B 84 E4 01 8E D8 8E C0 8E D0 2E
C7 84 7C 01 AF 01 2E 89 84 7E 01 B9 00 01 BF 00 00 F3 2E A5 2E FF AC 7C FF BC 00 0A FB
80 3E E8 01 FF 75 04 88 16 E8 01 83 06 E4 01 20 A1 E0 01 8B 16 E2 01 BD 02 00 E8 E9 FE
50 52 EB 74 90 00 00 00 00 00 00 00 00 00 00 00 D3 20 00 00 00 30 80 00 FF 00 68 41 00
40 09 FF 40 5A AC 04 00 00 AC 04 00 00 00 00 12 00 55 AA

This was taken from exactly the same CF card without any editing/writing etc happening, so i'm confused as to why they are so different, but both end with the correct 55 AA bytes too. Does Windows mangle the MBR's on cards when they're accessed this way or is some other weird under the hood stuff happening that I'm not aware of?

Body:
This is what i've written to do get the \.\PhysicalDriveX path for a given drive letter. If Pass the drive letter into this and take the return value and pass into CreateFile as the first Param I should now get something similar to dd under Linux.

using System.Management; //Add in a reference to this as well in the project settings
public static string GetPhysicalDevicePath(char DriveLetter)
{
    ManagementClass devs = new ManagementClass( @"Win32_Diskdrive");
    {
        ManagementObjectCollection moc = devs.GetInstances();
        foreach(ManagementObject mo in moc)
        {
            foreach (ManagementObject b in mo.GetRelated("Win32_DiskPartition"))
            {
                foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
                {
                    string DevName = string.Format("{0}", c["Name"]);
                    if (DevName[0] == DriveLetter)
                        return string.Format("{0}", mo["DeviceId"]);
                }
            }
        }
    }
    return "";
}


问:
grep returns no matches for following expression
Using the (?<=_)(.*)(?=\.) regex with the 23353_test.txt test string returns nothing with grep with the -p option. It doesn’t show errors either. I expect the return to be test. But when the regex  is tried in regex101.com it runs correctly.

答:
The following GNU grep command extracts the right substring:

grep -oP '(?<=_).*(?=\.)' file
```
<p>Note that <code>.*</code> matches greedily, and if you want to make sure you match a substring between the closest <code>_</code> and <code>.</code> you need to use a</p>
<pre class="lang-sh prettyprint-override"><code>grep -oP '(?<=_)[^._]*(?=\.)' file
</code>```

where [^._]* matches zero or more chars other than . and _.

If you cannot rely on your grep, you can use sed here:

sed -n 's/.*_\(.*\)\..*/\1/p' file
```
<p>See the online demo:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
s='23353_test.txt'
grep -oP '(?<=_)(.*)(?=\.)' <<< "$s"
# => test
sed -n 's/.*_\(.*\)\..*/\1/p' <<< "$s"
# => test
</code>```

Body:
The following GNU grep command extracts the right substring:

grep -oP '(?<=_).*(?=\.)' file

Note that .* matches greedily, and if you want to make sure you match a substring between the closest _ and . you need to use a

grep -oP '(?<=_)[^._]*(?=\.)' file

where [^._]* matches zero or more chars other than . and _.

If you cannot rely on your grep, you can use sed here:

sed -n 's/.*_\(.*\)\..*/\1/p' file

See the online demo:

#!/bin/bash
s='23353_test.txt'
grep -oP '(?<=_)(.*)(?=\.)' <<< "$s"
# => test
sed -n 's/.*_\(.*\)\..*/\1/p' <<< "$s"
# => test


问:
How to make An AppBar with widget in app?
How can we make an Appbar like this which is auto adjustable ,can have this many widgets and items benwath it can be scrollable?

答: You Can use Sliver App Bar See many be</p>

Body: You Can use Sliver App Bar See many be


问:
Create a list os Kotlin with de result of a repeated function
I have a very long method that creates a list with the result of a function that adds two numbers:

```<code>private fun Add(one: Int, two:Int) : Int {

 return one + two
}

private val myList = listOf(
 Add(1, 2),
 Add(2, 3),
 Add(3, 4),
 Add(4, 5),
 Add(5, 6),
 Add(6, 7),
 Add(8, 9),
 ...
)
</code>```

Is there a way in kotlin to create this list without always repeating the name of the "add" function?

I have tried with "with" and "apply" but I think I am not using it correctly.

答:
Instead of this

```<code>private val myList = listOf(
    Add(1, 2),
    Add(2, 3),
    Add(3, 4),
    Add(4, 5),
    Add(5, 6),
    Add(6, 7),
    Add(8, 9)
)
</code>```

you can write this

```<code>private val myList = listOf(
    1, 2,
    2, 3,
    3, 4,
    4, 5,
    5, 6,
    6, 7,
    8, 9
).chunked(2).map { Add(it[0],it[1]) }
</code>```

Body:
I have a very long method that creates a list with the result of a function that adds two numbers:

private fun Add(one: Int, two:Int) : Int {

 return one + two
}

private val myList = listOf(
 Add(1, 2),
 Add(2, 3),
 Add(3, 4),
 Add(4, 5),
 Add(5, 6),
 Add(6, 7),
 Add(8, 9),
 ...
)

Is there a way in kotlin to create this list without always repeating the name of the "add" function?

I have tried with "with" and "apply" but I think I am not using it correctly.

Body:
Instead of this

private val myList = listOf(
    Add(1, 2),
    Add(2, 3),
    Add(3, 4),
    Add(4, 5),
    Add(5, 6),
    Add(6, 7),
    Add(8, 9)
)

you can write this

private val myList = listOf(
    1, 2,
    2, 3,
    3, 4,
    4, 5,
    5, 6,
    6, 7,
    8, 9
).chunked(2).map { Add(it[0],it[1]) }


问:
Suppress indirect leaks caused by third party libraries
I have this very simple C code calling a scheme script with guile:

```<code>/* main.c */
#include <libguile.h>

int main(void)
{
    scm_init_guile();
    scm_c_primitive_load("script.scm");

    SCM func = scm_variable_ref(scm_c_lookup("func"));

    scm_call_0(func);
    return 0;
}
</code>```

The scheme script:

```<code>; script.scm
(define (func)
    (display "Hello from scheme\n")
)
</code>```

Compiling and running with:

```<code>export ASAN_OPTIONS=detect_leaks=1 LSAN_OPTIONS=suppressions=asan.supp
gcc -std=c11 -Wpedantic -Wall `pkg-config --cflags guile-3.0` \
    -fsanitize=address -fno-omit-frame-pointer \
    -o demo main.c `pkg-config --libs guile-3.0`
./demo
</code>```

I'm able to suppress some of the leaks caused by guile using this suppression file (asan.supp):

```<code>leak:iconv_open
leak:libguile
</code>```

But one of the leaks doesn't provide enough information, the sanitizer output is:

```<code>=================================================================
==33333==ERROR: LeakSanitizer: detected memory leaks

Indirect leak of 208 byte(s) in 1 object(s) allocated from:
    #0 0x7ff8a9b8d517 in malloc (/lib/x86_64-linux-gnu/libasan.so.6+0xb0517)
    #1 0x7ff8a97e94f6  (/lib/x86_64-linux-gnu/libc.so.6+0x344f6)

-----------------------------------------------------
Suppressions used:
  count      bytes template
      2      32752 iconv_open
      1         32 libguile
-----------------------------------------------------

SUMMARY: AddressSanitizer: 208 byte(s) leaked in 1 allocation(s).
</code>```

As you can see, the information about the leak is very generic (malloc and libc), of course I can not put libc in the suppression file since I will not get information about my real leaks.

Is there any way to suppress all "indirect leaks" caused by third party libraries?

答:
Assuming you already use -fno-omit-frame-pointer - which you do - I believe you need to add fast_unwind_on_malloc=0 to your ASAN_OPTIONS (or LSAN_OPTIONS) in some cases. This will be slower but give more complete backtraces.

For C++ new/delete the FAQ also suggests switching to -shared-libstdc++, which would presumably be faster. That doesn’t seem relevant to you though.

Body:
I have this very simple C code calling a scheme script with guile:

/* main.c */
#include <libguile.h>

int main(void)
{
    scm_init_guile();
    scm_c_primitive_load("script.scm");

    SCM func = scm_variable_ref(scm_c_lookup("func"));

    scm_call_0(func);
    return 0;
}

The scheme script:

; script.scm
(define (func)
    (display "Hello from scheme\n")
)

Compiling and running with:

export ASAN_OPTIONS=detect_leaks=1 LSAN_OPTIONS=suppressions=asan.supp
gcc -std=c11 -Wpedantic -Wall `pkg-config --cflags guile-3.0` \
    -fsanitize=address -fno-omit-frame-pointer \
    -o demo main.c `pkg-config --libs guile-3.0`
./demo

I'm able to suppress some of the leaks caused by guile using this suppression file (asan.supp):

leak:iconv_open
leak:libguile

But one of the leaks doesn't provide enough information, the sanitizer output is:

=================================================================
==33333==ERROR: LeakSanitizer: detected memory leaks

Indirect leak of 208 byte(s) in 1 object(s) allocated from:
    #0 0x7ff8a9b8d517 in malloc (/lib/x86_64-linux-gnu/libasan.so.6+0xb0517)
    #1 0x7ff8a97e94f6  (/lib/x86_64-linux-gnu/libc.so.6+0x344f6)

-----------------------------------------------------
Suppressions used:
  count      bytes template
      2      32752 iconv_open
      1         32 libguile
-----------------------------------------------------

SUMMARY: AddressSanitizer: 208 byte(s) leaked in 1 allocation(s).

As you can see, the information about the leak is very generic (malloc and libc), of course I can not put libc in the suppression file since I will not get information about my real leaks.

Is there any way to suppress all "indirect leaks" caused by third party libraries?


问:
jq convert to csv with keys to column rows
I have JSON example like this

```<code>{
  "server1": {
    "dhcp-libs": "12:4.2.5-83.el7.centos.1",
    "perl-Time-Local": "1.2300-2.el7",
    "kbd-legacy": "1.15.5-15.el7",
    "perl-Scalar-List-Utils": "1.27-248.el7",
    "ncurses-base": "5.9-14.20130511.el7_4",
    "firewalld": "0.6.3-13.el7_9",
    "perl-threads": "1.87-4.el7",
    "aic94xx-firmware": "30-6.el7",
    "kpartx": "0.4.9-135.el7_9",
    "perl-Getopt-Long": "2.40-3.el7",
    "basesystem": "10.0-7.el7.centos",
    "rsyslog": "8.24.0-57.el7_9.1",
    "libtirpc": "0.2.4-0.16.el7",
    "python3-libs": "3.6.8-18.el7",
    "btrfs-progs": "4.9.1-1.el7",
    "ncurses-libs": "5.9-14.20130511.el7_4",
    "python36-m2crypto": "0.35.2-5.el7"
  }
}
{
  "server2": {
    "perl-Errno": "1.28-420.el8",
    "fontpackages-filesystem": "1.44-22.el8",
    "python3-hawkey": "0.63.0-3.el8",
    "geolite2-city": "20180605-1.el8",
    "bind-libs-lite": "32:9.11.26-6.el8",
    "samba-client-libs": "4.14.5-2.el8",
    "rdma-core": "35.0-1.el8",
    "iptables": "1.8.4-20.el8",
    "python3-firewall": "0.9.3-7.el8",
    "policycoreutils-python-utils": "2.9-16.el8",
    "lvm2-libs": "8:2.03.12-10.el8",
    "rpm-plugin-selinux": "4.14.3-19.el8"
  }
}
</code>```

Is it possible convert JSON usinq jq to CSV in format where keys are first row and values second? Result should be like this

```<code>dhcp-libs,12:4.2.5-83.el7.centos.1
perl-Time-Local,1.2300-2.el7
kbd-legacy,1.15.5-15.el7
perl-Scalar-List-Utils,1.27-248.el7
ncurses-base,5.9-14.20130511.el7_4
....
</code>```

Is that possible or should I try something else?

答:
This generates your desired output (keys as first, rows as second column),  formatted as CSV with escaping of delimiters used in the data and quotes around the fields:

jq -r '.[] | to_entries[] | [.[]] | @csv'
```
```"dhcp-libs","12:4.2.5-83.el7.centos.1"
"perl-Time-Local","1.2300-2.el7"
"kbd-legacy","1.15.5-15.el7"
"perl-Scalar-List-Utils","1.27-248.el7"
...
```
<p>Demo</p>
<p>If you don't want the quotes, you could use <code>join(",")</code> instead of <code>@csv</code> but this wouldn't do any escaping either:</p>
<pre class="lang-sh prettyprint-override"><code>jq -r '.[] | to_entries[] | [.[]] | join(",")'
</code>```
```<code>dhcp-libs,12:4.2.5-83.el7.centos.1
perl-Time-Local,1.2300-2.el7
kbd-legacy,1.15.5-15.el7
perl-Scalar-List-Utils,1.27-248.el7
...
</code>```

Demo

Body:
I have JSON example like this

{
  "server1": {
    "dhcp-libs": "12:4.2.5-83.el7.centos.1",
    "perl-Time-Local": "1.2300-2.el7",
    "kbd-legacy": "1.15.5-15.el7",
    "perl-Scalar-List-Utils": "1.27-248.el7",
    "ncurses-base": "5.9-14.20130511.el7_4",
    "firewalld": "0.6.3-13.el7_9",
    "perl-threads": "1.87-4.el7",
    "aic94xx-firmware": "30-6.el7",
    "kpartx": "0.4.9-135.el7_9",
    "perl-Getopt-Long": "2.40-3.el7",
    "basesystem": "10.0-7.el7.centos",
    "rsyslog": "8.24.0-57.el7_9.1",
    "libtirpc": "0.2.4-0.16.el7",
    "python3-libs": "3.6.8-18.el7",
    "btrfs-progs": "4.9.1-1.el7",
    "ncurses-libs": "5.9-14.20130511.el7_4",
    "python36-m2crypto": "0.35.2-5.el7"
  }
}
{
  "server2": {
    "perl-Errno": "1.28-420.el8",
    "fontpackages-filesystem": "1.44-22.el8",
    "python3-hawkey": "0.63.0-3.el8",
    "geolite2-city": "20180605-1.el8",
    "bind-libs-lite": "32:9.11.26-6.el8",
    "samba-client-libs": "4.14.5-2.el8",
    "rdma-core": "35.0-1.el8",
    "iptables": "1.8.4-20.el8",
    "python3-firewall": "0.9.3-7.el8",
    "policycoreutils-python-utils": "2.9-16.el8",
    "lvm2-libs": "8:2.03.12-10.el8",
    "rpm-plugin-selinux": "4.14.3-19.el8"
  }
}

Is it possible convert JSON usinq jq to CSV in format where keys are first row and values second? Result should be like this

dhcp-libs,12:4.2.5-83.el7.centos.1
perl-Time-Local,1.2300-2.el7
kbd-legacy,1.15.5-15.el7
perl-Scalar-List-Utils,1.27-248.el7
ncurses-base,5.9-14.20130511.el7_4
....

Is that possible or should I try something else?

Body:
This generates your desired output (keys as first, rows as second column),  formatted as CSV with escaping of delimiters used in the data and quotes around the fields:

jq -r '.[] | to_entries[] | [.[]] | @csv'

"dhcp-libs","12:4.2.5-83.el7.centos.1"
"perl-Time-Local","1.2300-2.el7"
"kbd-legacy","1.15.5-15.el7"
"perl-Scalar-List-Utils","1.27-248.el7"
...

Demo

If you don't want the quotes, you could use join(",") instead of @csv but this wouldn't do any escaping either:

jq -r '.[] | to_entries[] | [.[]] | join(",")'

dhcp-libs,12:4.2.5-83.el7.centos.1
perl-Time-Local,1.2300-2.el7
kbd-legacy,1.15.5-15.el7
perl-Scalar-List-Utils,1.27-248.el7
...

Demo


问:
R : How to extract the factor levels as numeric from a column and assign it to a new column using tydyverse?
Suppose I have a data frame, df

```<code>df = data.frame(name = rep(c("A", "B", "C"), each = 4))
</code>```

I want to get a new data frame with one additional column named Group, in which Group element is the numeric value of the corresponding level of name, as shown in df2.

I know case_when could do it. My issue is that my real data frame is quite complicated, there are many levels of the name column. I am too lazy to list case by case.

Is there an easier and smarter way to do it?

Thanks.

```<code>df2
   name Group
1     A     1
2     A     1
3     A     1
4     A     1
5     B     2
6     B     2
7     B     2
8     B     2
9     C     3
10    C     3
11    C     3
12    C     3
</code>```

答:
There are a few ways to do it in tidyverse

```<code>library(tidyverse)

df %>% group_by(name) %>% mutate(Group = cur_group_id())
</code>```

or

```<code>df %>% mutate(Group = as.numeric(as.factor(name)))
</code>```

Output

```<code>  name Group
1     A  1
2     A  1
3     A  1
4     A  1
5     B  2
6     B  2
7     B  2
8     B  2
9     C  3
10    C  3
11    C  3
12    C  3
</code>```

Body:
Suppose I have a data frame, df

df = data.frame(name = rep(c("A", "B", "C"), each = 4))

I want to get a new data frame with one additional column named Group, in which Group element is the numeric value of the corresponding level of name, as shown in df2.

I know case_when could do it. My issue is that my real data frame is quite complicated, there are many levels of the name column. I am too lazy to list case by case.

Is there an easier and smarter way to do it?

Thanks.

df2
   name Group
1     A     1
2     A     1
3     A     1
4     A     1
5     B     2
6     B     2
7     B     2
8     B     2
9     C     3
10    C     3
11    C     3
12    C     3

Body:
There are a few ways to do it in tidyverse

library(tidyverse)

df %>% group_by(name) %>% mutate(Group = cur_group_id())

or

df %>% mutate(Group = as.numeric(as.factor(name)))

Output

  name Group
1     A  1
2     A  1
3     A  1
4     A  1
5     B  2
6     B  2
7     B  2
8     B  2
9     C  3
10    C  3
11    C  3
12    C  3


答:
You can use

```<code>jq -r '.[] | to_entries[] | [ .key, .value ] | join(",")'
</code>```

Demo

in order to get key-value pairs without quotes

Title: jq convert to csv with keys to column rows

Body:
You can use

jq -r '.[] | to_entries[] | [ .key, .value ] | join(",")'

Demo

in order to get key-value pairs without quotes


问:
Delegate Method: "willSpeakRangeOfSpeechString" of AVSpeechSynthesizerDelegate gets not called
In my app I want Siri to read out a text. This works fine. But I also want to use the delegate methods of AVSpeechSynthesizerDelegate. These 2 methods are called properly, but willSpeakRangeOfSpeechString not:

speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance)

speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance)

Thats my code to generate the AVSpeechSynthesizer. This is done in didSelectItemAt of my UICollectionViewController:

```<code>let utterance = AVSpeechUtterance(string: "testString")
utterance.rate = 0.5
utterance.volume = 1

utterance.preUtteranceDelay = 0.0
utterance.postUtteranceDelay = 0.0

self.synthesizer.speak(utterance)
</code>```

The AVSpeechSynthesizer is declared at the top of the class, and the delegate is set in viewDidLoad:

```<code>override func viewDidLoad() {
   super.viewDidLoad()
    self.synthesizer.delegate = self
}
</code>```

Why this delegate method is`nt called?

Edit:

Of course I have implemented AVSpeechSynthesizerDelegate and imported AVFoundation.

答: I've just run into this or a similar problem. I was setting the AVSpeechSynthesizer delegate after calling the its speak function. This caused the willSpeakRangeOfSpeechString not to be called. Assigning the delegate prior to calling the speak function fixed this.</p>

Body:
In my app I want Siri to read out a text. This works fine. But I also want to use the delegate methods of AVSpeechSynthesizerDelegate. These 2 methods are called properly, but willSpeakRangeOfSpeechString not:

speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance)

speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance)

Thats my code to generate the AVSpeechSynthesizer. This is done in didSelectItemAt of my UICollectionViewController:

let utterance = AVSpeechUtterance(string: "testString")
utterance.rate = 0.5
utterance.volume = 1

utterance.preUtteranceDelay = 0.0
utterance.postUtteranceDelay = 0.0

self.synthesizer.speak(utterance)

The AVSpeechSynthesizer is declared at the top of the class, and the delegate is set in viewDidLoad:

override func viewDidLoad() {
   super.viewDidLoad()
    self.synthesizer.delegate = self
}

Why this delegate method is`nt called?

Edit:

Of course I have implemented AVSpeechSynthesizerDelegate and imported AVFoundation.


问:
Selenium - Basic Authentication via url
In my Selenium-Test (with chromedriver-2.24) I'm trying to access my webpage via basic authentication with the following statement:

```<code>WebDriver driver  = ...;
driver.get("http://admin:admin@localhost:8080/project/");
</code>```

But Google Chrome gives me the following warning in the console:

[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass@host/) are blocked. See https://www.chromestatus.com/feature/5669008342777856 for more details.

In the tagged link is mentioned that the support was dropped:

Drop support for embedded credentials in subresource requests. (removed)

My question now is, is there an other way to basic-authenticate from Selenium?

NOTE: this has not helped: How to Handle HTTP Basic Auth headers in Selenium Webdriver using Java ?

答:
Selenium 4 supports basic authentication

```<code>WebDriver driver = new ChromeDriver();
HasAuthentication authentication = (HasAuthentication) driver;
authentication.register(() -> new UsernameAndPassword("username", "pwd"));
driver.get("your-site.com");
</code>```

https://www.selenium.dev/blog/2021/a-tour-of-4-authentication/

Title: Selenium - Basic Authentication via url

Body:
In my Selenium-Test (with chromedriver-2.24) I'm trying to access my webpage via basic authentication with the following statement:

WebDriver driver  = ...;
driver.get("http://admin:admin@localhost:8080/project/");

But Google Chrome gives me the following warning in the console:

[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass@host/) are blocked. See https://www.chromestatus.com/feature/5669008342777856 for more details.

In the tagged link is mentioned that the support was dropped:

Drop support for embedded credentials in subresource requests. (removed)

My question now is, is there an other way to basic-authenticate from Selenium?

NOTE: this has not helped: How to Handle HTTP Basic Auth headers in Selenium Webdriver using Java ?

Body:
Selenium 4 supports basic authentication

WebDriver driver = new ChromeDriver();
HasAuthentication authentication = (HasAuthentication) driver;
authentication.register(() -> new UsernameAndPassword("username", "pwd"));
driver.get("your-site.com");

https://www.selenium.dev/blog/2021/a-tour-of-4-authentication/


问:
Is it possible to Create Testcases and Test Run Automatically on Testrail using Selenium
I have been able to integrate my Selenium and Testrail . I can pass testresults to the specified Testrun I have created manually on test rail.

I have a challenge and I want to know if this is possible currently.

I do not want to manually create the test cases  I have on selenium on test rail and I also do not want to have to create a new test run when I run my automation scripts .

I want to automatically check If the test case I'm running is not on test rail, selenium should add it automatically. Also I do not want to specify the TEST_RUN_ID . I want immediately I trigger or run a test cases it should create a test run by itself on Tesrrail. I need this because I'm implementing a CI/CD approach and I do not want any manual intervention . Please let me know if possible

答:
You might want to have a look at our product called Railflow, which provides very flexible integration of various testing platforms with TestRail.

It also has convenient integration with TestNG and Selenium, please see more details in our docs: https://docs.railflow.io/docs/testing-frameworks/testng

Please feel free to register for free 14-day evaluation:
https://railflow.io/register

Disclaimer: I'm developer of Railflow


问:
convert string to char c
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

```<code>char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}
</code>```

OwnerDisplayName: robUK

Title: convert string to char c

Body:
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}

LastEditorDisplayName: robUK

Body: return digits_conversion[i][1][0];

OwnerDisplayName: fbinder

ContentLicense: CC BY-SA 2.5


问:
How to get filename, function, line, and column from Error for EntryLog.SourceLocation
I am using winston logger with EntryLog spec for logging, and I wanna get these data from new Error().stack:

```<code>{
  file: "index.js",
  function: "getData",
  line: 20,
  column: 50
}
</code>```

答:
I figure it out:

```<code>/**
 * Parses and returns info about the call stack.
 */
function getSouceLocation(error) {
  // get call stack, and analyze it and
  // remove unnecessary stacktrace [node_modules, <anonymous>]
  // get all file, method, and line numbers
  const stacklist = error.stack
    .replace(/^.*[\\/]node_modules[\\/].*$|^.((?!at).)*$|^.*<anonymous>.*$|^.*internal\/timers.js.*$/gm, "")
    .replace(/\n+/g, "\n").split("\n")
    .filter((item, index, array) => {
      if (!!item) {
        return index === array.indexOf(item);
      }
    });

  // stack trace format:
  // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  // do not remove the regex expresses to outside of this method (due to a BUG in node.js)
  var stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi
  var stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi

  const sources = []
  stacklist.forEach((item) => {
    var sp = stackReg.exec(item) || stackReg2.exec(item)
    if (sp && sp.length === 5) {
      sources.push(
        {
          function: sp[1],
          file: path.relative(PROJECT_ROOT, sp[2]),
          line: sp[3],
          column: sp[4],
        }
      )
    }
  });
  const stack = stacklist.join('\n');
  return { sources, stack };
}
</code>```

Result:

```<code>"sourceLocation": {
    "sources": [
      {
        "column": "36",
        "file": "src\\app\\controllers\\informasi\\panduan\\panduan-search.js",
        "function": "module.exports",
        "line": "11"
      },
      {
        "column": "7",
        "file": "src\\utils\\callback.js",
        "function": "",
        "line": "18"
      }
    ],
    "stack": "SequelizeDatabaseError: column a.nourutt does not exist\n    at module.exports (D:\\GOLANG\\gocode\\src\\github.com\\oss-rba\\back-portal\\src\\app\\controllers\\informasi\\panduan\\panduan-search.js:11:36)\n    at D:\\GOLANG\\gocode\\src\\github.com\\oss-rba\\back-portal\\src\\utils\\callback.js:18:7"
  },
</code>```

Source: winston logger with filename:linenumber

Body:
I am using winston logger with EntryLog spec for logging, and I wanna get these data from new Error().stack:

{
  file: "index.js",
  function: "getData",
  line: 20,
  column: 50
}

Body:
I figure it out:

/**
 * Parses and returns info about the call stack.
 */
function getSouceLocation(error) {
  // get call stack, and analyze it and
  // remove unnecessary stacktrace [node_modules, <anonymous>]
  // get all file, method, and line numbers
  const stacklist = error.stack
    .replace(/^.*[\\/]node_modules[\\/].*$|^.((?!at).)*$|^.*<anonymous>.*$|^.*internal\/timers.js.*$/gm, "")
    .replace(/\n+/g, "\n").split("\n")
    .filter((item, index, array) => {
      if (!!item) {
        return index === array.indexOf(item);
      }
    });

  // stack trace format:
  // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  // do not remove the regex expresses to outside of this method (due to a BUG in node.js)
  var stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi
  var stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi

  const sources = []
  stacklist.forEach((item) => {
    var sp = stackReg.exec(item) || stackReg2.exec(item)
    if (sp && sp.length === 5) {
      sources.push(
        {
          function: sp[1],
          file: path.relative(PROJECT_ROOT, sp[2]),
          line: sp[3],
          column: sp[4],
        }
      )
    }
  });
  const stack = stacklist.join('\n');
  return { sources, stack };
}

Result:

"sourceLocation": {
    "sources": [
      {
        "column": "36",
        "file": "src\\app\\controllers\\informasi\\panduan\\panduan-search.js",
        "function": "module.exports",
        "line": "11"
      },
      {
        "column": "7",
        "file": "src\\utils\\callback.js",
        "function": "",
        "line": "18"
      }
    ],
    "stack": "SequelizeDatabaseError: column a.nourutt does not exist\n    at module.exports (D:\\GOLANG\\gocode\\src\\github.com\\oss-rba\\back-portal\\src\\app\\controllers\\informasi\\panduan\\panduan-search.js:11:36)\n    at D:\\GOLANG\\gocode\\src\\github.com\\oss-rba\\back-portal\\src\\utils\\callback.js:18:7"
  },

Source: winston logger with filename:linenumber


问:
How can I detect whether a tooltip is visible at a given moment?
I'm looking for a way to detect whether a Qt widget's ToolTip is visible at the moment when a particular key combination is pressed. If it is, I want to copy the ToolTip's text to the clipboard.

Specifically, I have a QListView containing abbreviated strings, which is set up (via the Qt::ToolTipRole of the associated model) to show the full string of the appropriate list item when the mouse is hovered over it. The behaviour I'm looking for is that if the user presses CTRL-C (as detected by a QShortcut) while the tooltip is visible, then the tooltip text is copied to the clipboard.

My original idea was to use the children() method of the QListView widget to see if there was a tooltip preset among them:

```<code>// Inisde the slot connected to QShortcut::activated...
auto children = _ui -> myListView -> children();
QString selectionText;
for (const auto & child : children)
{
    if (qobject_cast<QToolTip *>(child))
    {
        selectionText = qobject_cast<QToolTip *>(child) -> text();
        break;
    }
}
</code>```

...but this failed because it turns out that QToolTip does not inherit from QObject.

I've also thought of screening for QEvent::QToolTip events in the ListView's main event handler, and while I could probably get this to work it seems excessively low-level; I'd need to use screen co-ordinates to determine which item in the list was being hovered over and look for the widget's timeout to check that the tooltip hadn't disappeared again by the time that the QShortcut was fired. I'd be disappointed if there weren't a simpler way.

Is there an obvious way forward that I've failed to see?

答:
With thanks to @V.K., this is what worked:</p>
```<code>auto candidates = qApp->topLevelWidgets();
QString selectionText;
for (const auto & candidate : candidates)
{
    if (strcmp(candidate->metaObject()->className(), "QTipLabel") == 0)
    {
        QLabel * label = qobject_cast<QLabel *>(candidate);
        if (label->isVisible())
        {
            selectionText = label -> text();
            break;
        }
    }
}
if (!selectionText.isEmpty())
    QGuiApplication::clipboard() -> setText(selectionText);
</code>```

Body:
I'm looking for a way to detect whether a Qt widget's ToolTip is visible at the moment when a particular key combination is pressed. If it is, I want to copy the ToolTip's text to the clipboard.

Specifically, I have a QListView containing abbreviated strings, which is set up (via the Qt::ToolTipRole of the associated model) to show the full string of the appropriate list item when the mouse is hovered over it. The behaviour I'm looking for is that if the user presses CTRL-C (as detected by a QShortcut) while the tooltip is visible, then the tooltip text is copied to the clipboard.

My original idea was to use the children() method of the QListView widget to see if there was a tooltip preset among them:

// Inisde the slot connected to QShortcut::activated...
auto children = _ui -> myListView -> children();
QString selectionText;
for (const auto & child : children)
{
    if (qobject_cast<QToolTip *>(child))
    {
        selectionText = qobject_cast<QToolTip *>(child) -> text();
        break;
    }
}

...but this failed because it turns out that QToolTip does not inherit from QObject.

I've also thought of screening for QEvent::QToolTip events in the ListView's main event handler, and while I could probably get this to work it seems excessively low-level; I'd need to use screen co-ordinates to determine which item in the list was being hovered over and look for the widget's timeout to check that the tooltip hadn't disappeared again by the time that the QShortcut was fired. I'd be disappointed if there weren't a simpler way.

Is there an obvious way forward that I've failed to see?

Body:
With thanks to @V.K., this is what worked:

auto candidates = qApp->topLevelWidgets();
QString selectionText;
for (const auto & candidate : candidates)
{
    if (strcmp(candidate->metaObject()->className(), "QTipLabel") == 0)
    {
        QLabel * label = qobject_cast<QLabel *>(candidate);
        if (label->isVisible())
        {
            selectionText = label -> text();
            break;
        }
    }
}
if (!selectionText.isEmpty())
    QGuiApplication::clipboard() -> setText(selectionText);


问:
How to deploy a React App on Apache web server
I have created a basic React App from https://www.tutorialspoint.com/reactjs/reactjs_jsx.htm here , I want to run this test code on Apache based server, I know that I need to create a distributable build but I am not able to figure out how to do that and couldnt find clear instructions.

I have seen this post React,js on Apache server but it doesn't have anything more than few guidelines

答:
First install apache2 with sudo apt install apache2 then run commend blow in proj dir

```<code>npm run build
</code>```

or

```<code>yarn run build
</code>```

then

```<code>sudo cp -rf build/* /var/www/html/mySite;
cd /etc/apache2/sites-available/;
sudo cp 000-default.conf mySite.conf;
sudo nano /mySite.conf
</code>```

in this file add/uncomment these lines

```<code>ServerName myDomin.com
ServerAlias www.myDomin.com
DocumentRoot /var/www/html/mySite
</code>```

after appache configurations you should add your domin to your system so

```<code>sudo nano /etc/hosts
</code>```

in this file add your VPS IP address for example if your ip address is 192.168.1.1 so

```<code>127.0.0.1       localhost myDomin.com
192.168.1.1       myDomin.com www.myDomin.com
</code>```

now set your name servers in your VPS by your own if you know how or just use cloudflare or similar things.

note: If you want use in localhost just run this cp build/* /var/www/html/ && sudo systemctl restart apache2

Body:
First install apache2 with sudo apt install apache2 then run commend blow in proj dir

npm run build

or

yarn run build

then

sudo cp -rf build/* /var/www/html/mySite;
cd /etc/apache2/sites-available/;
sudo cp 000-default.conf mySite.conf;
sudo nano /mySite.conf

in this file add/uncomment these lines

ServerName myDomin.com
ServerAlias www.myDomin.com
DocumentRoot /var/www/html/mySite

after appache configurations you should add your domin to your system so

sudo nano /etc/hosts

in this file add your VPS IP address for example if your ip address is 192.168.1.1 so

127.0.0.1       localhost myDomin.com
192.168.1.1       myDomin.com www.myDomin.com

now set your name servers in your VPS by your own if you know how or just use cloudflare or similar things.

note: If you want use in localhost just run this cp build/* /var/www/html/ && sudo systemctl restart apache2


问:
Problem trying to configure USB debugging from android phone: Device is not recognized
I'm having Samsung Galaxy I9003 phone and I want to debug my android app from the device.

I'm using Windows 7 - 32 bit

I have installed USB driver but when I connect my device to computer, it is not recognized.

I trying to update the installer through Computer->Manage, it is saying the best driver is already installed.

When I run "adb devices" command, it is showing "List of devices attached" but nothing listed down.

Any help in this regard is very much appreciated. Thanks in advance.

答: try enabling USB debugging mode by going to Menu>Settings>Applications>Development>USB Debugging and then connect</p>


问:
Angular 2: Listen to a scroll event of parent element inside Directive
I have a directive for validation [appInvalidField], it's like a custom tooltip. Since I need to use it inside dialogs and show it above everything else, I append that to body and position near a field it has to be shown next to.

But there is a problem with scrolling. I need to listen to a scroll event on form and change a tooltip position. How can I do that without changing my html? Just inside the directive file. Here is my HTML(an example of using it inside a form):

<form #ngForm="ngForm" [formGroup]="form" (ngSubmit)="onSave()">

         {{'substance.IUPACName-title' | translate}}

          <input class="p-col" pInputText [maxLength]="formService.maxLength" appAutofocus  formControlName="names" />

</form>```

答:
A much more elegant native solution would be using the IntersectionObserver as shown in the following post: How to check if element is visible after scrolling?

combining it with a directive would looks something like this:

```<code>@Directive({
  selector: '[fixedscroll]'
})
export class FixedscrollDirective{
@Input() windowOnly = false;
constructor(
    @Inject(ElementRef) {nativeElement}: ElementRef<Element>,
) {
    var observer = new IntersectionObserver(onIntersection, {
      root: null,   // default is the viewport
      threshold: .5 // percentage of taregt's visible area. Triggers "onIntersection"
    })

    // callback is called on intersection change
    function onIntersection(entries, opts){
      entries.forEach(entry =>
        entry.target.classList.toggle('visible', entry.isIntersecting)
      )
    }

    // Use the bserver to observe an element
    observer.observe( nativeElement )
}
}
</code>```

Body:
A much more elegant native solution would be using the IntersectionObserver as shown in the following post: How to check if element is visible after scrolling?

combining it with a directive would looks something like this:

@Directive({
  selector: '[fixedscroll]'
})
export class FixedscrollDirective{
@Input() windowOnly = false;
constructor(
    @Inject(ElementRef) {nativeElement}: ElementRef<Element>,
) {
    var observer = new IntersectionObserver(onIntersection, {
      root: null,   // default is the viewport
      threshold: .5 // percentage of taregt's visible area. Triggers "onIntersection"
    })

    // callback is called on intersection change
    function onIntersection(entries, opts){
      entries.forEach(entry =>
        entry.target.classList.toggle('visible', entry.isIntersecting)
      )
    }

    // Use the bserver to observe an element
    observer.observe( nativeElement )
}
}


问:
CORS error on some API endpoints but not others in same controller
I have a controller with multiple API endpoints. Most endpoints work as expected but there are 2 which throw a CORS error when deployed on a remote server.

Access to fetch at 'BACKEND URL' from origin 'FRONTEND URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have omitted some code below for brevity.

The API /api/person/uid/14 works as expected in both localhost and on a remote server.

The API /person/email/john@email.com works on localhost, but returns an error when deployed on a remote server.

Both frontend and backend are hosted on the same machine and sit on the same domain. The only difference in the URL are the ports (frontend 3000; backend API 8082).

Having said that, the first API (and many others in this controller) work on both local and the remote server, only the email and mobileNumber validation APIs are throwing a CORS error, which makes this really puzzling.

Any thoughts are appreciated.

PersonController.java

```<code>@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api")
public class PersonController {

@Autowired
PersonService personService;

@GetMapping("/person/uid/{uid}")
public Boolean uidExists(@PathVariable("uid") String uid) {
    return personService.uidInUse(uid);
}

@GetMapping("/person/mobileNumber/{mobileNumber}")
public Boolean mobileNumberExists(@PathVariable("mobileNumber") String mobileNumber) {
    return personService.mobileNumberInUse(mobileNumber);
}

@GetMapping("/person/email/{email}")
public Boolean emailExists(@PathVariable("email") String email) {
    return personService.emailInUse(email);
}

@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
        MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}
}
</code>```

PersonService.java

```<code>@Service
public class PersonService {

@Autowired
PersonRepository personRepository;

// NOTE: ...NotDeleted and ...InUse methods implies deleted == false

// read methods
public List<PersonDto> findAllNotDeleted() {
    return personRepository.findByDeleted(false).stream()
            .filter(p -> !p.getDeleted())
            .map(Person::toDto)
            .collect(Collectors.toList());
}

public Optional<Person> findByIdInUse(Long personId) {
    return personRepository.findByPersonIdAndDeleted(personId, false);
}

// checkers
public Boolean uidInUse(String uid) {
    return personRepository.findByPersonUidAndDeleted(uid, false)
            .isPresent();
}

//edit: check if personid is the same as personname
public Boolean uidInUse(String uid, Long personId) {
    Optional<Person> personOptional = personRepository
            .findByPersonUidAndDeleted(uid, false);
    return personOptional.isPresent() &&
            !Objects.equals(personOptional.get().getPersonId(), personId);
}

public Boolean mobileNumberInUse(String personMobileNumber) {
    return personRepository.findByPersonMobileNumberAndDeleted(personMobileNumber, false)
            .isPresent();
}

public Boolean emailInUse(String email) {
    return personRepository.findByPersonEmail(email).size() > 0;
}

public Boolean idInUse(Long id) {
    return personRepository.findByPersonIdAndDeleted(id, false).isPresent();
}

// create / update methods
public PersonDto createNotDeleted(CreatePersonDto personDto) {
    return personRepository.save(personDto.toPerson(false)).toDto();
}

//for deletion
public PersonDto save(PersonDto personDto, Boolean deleted) {
    return personRepository.save(personDto.toPerson(deleted)).toDto();
}

//normal save
public Person save(Person person) {
    return personRepository.save(person);
}

// helpers (if other controllers need can move to util)
public String generateUid() {
    String randomString;

    do {
        randomString = generateRandomString(8);
    } while (uidInUse(randomString));
    return randomString;
}

private String generateRandomString(int length) {
    int leftLimit = 48; // "0"
    int rightLimit = 122; // "z"
    Random random = new Random();

    return random.ints(leftLimit, rightLimit + 1)
            .filter(i -> i <= 57 || (i >= 65 && i <= 90) || i >= 97)
            // "9" and below OR "A" to "Z" OR "a" and above
            .limit(length)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();

}
}
</code>```

答: Could be an issue with consumes/produces, try adding produces = MediaType.APPLICATION_JSON or other media type and adjust your request headers as well.</p>

Body:
I have a controller with multiple API endpoints. Most endpoints work as expected but there are 2 which throw a CORS error when deployed on a remote server.

Access to fetch at 'BACKEND URL' from origin 'FRONTEND URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have omitted some code below for brevity.

The API /api/person/uid/14 works as expected in both localhost and on a remote server.

The API /person/email/john@email.com works on localhost, but returns an error when deployed on a remote server.

Both frontend and backend are hosted on the same machine and sit on the same domain. The only difference in the URL are the ports (frontend 3000; backend API 8082).

Having said that, the first API (and many others in this controller) work on both local and the remote server, only the email and mobileNumber validation APIs are throwing a CORS error, which makes this really puzzling.

Any thoughts are appreciated.

PersonController.java

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api")
public class PersonController {

@Autowired
PersonService personService;

@GetMapping("/person/uid/{uid}")
public Boolean uidExists(@PathVariable("uid") String uid) {
    return personService.uidInUse(uid);
}

@GetMapping("/person/mobileNumber/{mobileNumber}")
public Boolean mobileNumberExists(@PathVariable("mobileNumber") String mobileNumber) {
    return personService.mobileNumberInUse(mobileNumber);
}

@GetMapping("/person/email/{email}")
public Boolean emailExists(@PathVariable("email") String email) {
    return personService.emailInUse(email);
}

@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
        MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}
}

PersonService.java

@Service
public class PersonService {

@Autowired
PersonRepository personRepository;

// NOTE: ...NotDeleted and ...InUse methods implies deleted == false

// read methods
public List<PersonDto> findAllNotDeleted() {
    return personRepository.findByDeleted(false).stream()
            .filter(p -> !p.getDeleted())
            .map(Person::toDto)
            .collect(Collectors.toList());
}

public Optional<Person> findByIdInUse(Long personId) {
    return personRepository.findByPersonIdAndDeleted(personId, false);
}

// checkers
public Boolean uidInUse(String uid) {
    return personRepository.findByPersonUidAndDeleted(uid, false)
            .isPresent();
}

//edit: check if personid is the same as personname
public Boolean uidInUse(String uid, Long personId) {
    Optional<Person> personOptional = personRepository
            .findByPersonUidAndDeleted(uid, false);
    return personOptional.isPresent() &&
            !Objects.equals(personOptional.get().getPersonId(), personId);
}

public Boolean mobileNumberInUse(String personMobileNumber) {
    return personRepository.findByPersonMobileNumberAndDeleted(personMobileNumber, false)
            .isPresent();
}

public Boolean emailInUse(String email) {
    return personRepository.findByPersonEmail(email).size() > 0;
}

public Boolean idInUse(Long id) {
    return personRepository.findByPersonIdAndDeleted(id, false).isPresent();
}

// create / update methods
public PersonDto createNotDeleted(CreatePersonDto personDto) {
    return personRepository.save(personDto.toPerson(false)).toDto();
}

//for deletion
public PersonDto save(PersonDto personDto, Boolean deleted) {
    return personRepository.save(personDto.toPerson(deleted)).toDto();
}

//normal save
public Person save(Person person) {
    return personRepository.save(person);
}

// helpers (if other controllers need can move to util)
public String generateUid() {
    String randomString;

    do {
        randomString = generateRandomString(8);
    } while (uidInUse(randomString));
    return randomString;
}

private String generateRandomString(int length) {
    int leftLimit = 48; // "0"
    int rightLimit = 122; // "z"
    Random random = new Random();

    return random.ints(leftLimit, rightLimit + 1)
            .filter(i -> i <= 57 || (i >= 65 && i <= 90) || i >= 97)
            // "9" and below OR "A" to "Z" OR "a" and above
            .limit(length)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();

}
}


问:
What's the difference between a generic slice argument and an argument constrained to slice types?
Consider the experimental package slices. The package is experimental, so I understand the signatures may change; I'm using it to illustrate the issue.

Consider the signatures of two functions from this package, slices.Contains and slices.Grow:

func Contains[E comparable](s []E, v E) bool

func Grow[S ~[]E, E any](s S, n int) S

The first argument to Contains has type []E (slice of Es) with E constrained by comparable (types that are comparable).

The first argument to Grow instead has type S (just S), with S constrained by ~[]E (types whose underlying type is a slice of E)

However it looks like there isn't any practical difference between what operations are allowed inside functions with such type params. If we declare some fake funcs with the same type parameters, we can see that both compile just fine:

As expected, in both functions we can len/cap, append, range, allocate with make, and index with [ ].

```<code>func fakeContains[E comparable](s []E, v E) {
    fmt.Println(len(s), cap(s))

    var e E
    fmt.Println(append(s, e))
    fmt.Println(make([]E, 4))

    for _, x := range s {
        fmt.Println(x)
    }
    fmt.Println(s[0])

    fmt.Println(reflect.TypeOf(s).Kind())
}

func fakeGrow[S ~[]E, E any](s S, n int) {
    fmt.Println(len(s), cap(s))

    var e E
    fmt.Println(append(s, e))
    fmt.Println(make(S, 4))

    for _, x := range s {
        fmt.Println(x)
    }
        fmt.Println(s[0])

    fmt.Println(reflect.TypeOf(s).Kind())
}
</code>```

Even reflect.TypeOf(s).Kind() gives reflect.Slice in all cases.

The functions can also be tested with different types, and all compile:

```<code>// compiles just fine
func main() {
    type MyUint64 uint64
    type MyUint64Slice []uint64

    foo := []uint64{0, 1, 2}
    fakeContains(foo, 0)
    fakeGrow(foo, 5)

    bar := []MyUint64{3, 4, 5}
    fakeContains(bar, 0)
    fakeGrow(bar, 5)

    baz := MyUint64Slice{6, 7, 8}
    fakeContains(baz, 0)
    fakeGrow(baz, 5)
}
</code>```

The only actual difference in my understanding is that in slices.Grow the argument s S is not a slice. It's just constrained to slice types. And as a matter of fact reflect.TypeOf(s) gives a different output when the arg is an instance of type MyUint64Slice []uint64:

Contains with arg s []E gives reflect.TypeOf(s) -> []uint64

Grow with arg s S gives reflect.TypeOf(s) -> main.MyUint64Slice

However it's not immediately apparent to me what's the practical difference between the two.

Playground with the code: https://gotipplay.golang.org/p/zg2dGtSJwuI

Question

Are these two declarations equivalent in practice? If not, when should I choose one over the other?

答:
It matters if you have to return a slice of the same (possibly named) type as the argument.

If you do not have to return a slice (just some other info e.g. a bool to report if the value is contained), you do not need to use a type parameter that itself constraints to a slice, you may use a type parameter for the element only.

If you have to return a slice of the same type as the input, you must use a type parameter that itself constraints to a slice (e.g. ~[]E).

To demonstrate, let's see these 2 implementations of Grow():

```<code>func Grow[S ~[]E, E any](s S, n int) S {
    return append(s, make(S, n)...)[:len(s)]
}

func Grow2[E any](s []E, n int) []E {
    return append(s, make([]E, n)...)[:len(s)]
}
</code>```

If you pass a slice of a custom type having a slice as its underlying type, Grow() can return a value of the same type. Grow2() cannot: it can only return a value of an unnamed slice type: []E.

And the demonstration:

```<code>x := []int{1}

x2 := Grow(x, 10)
fmt.Printf("x2 %T len=%d cap=%d\n", x2, len(x2), cap(x2))

x3 := Grow2(x, 10)
fmt.Printf("x3 %T len=%d cap=%d\n", x3, len(x3), cap(x3))

type ints []int
y := ints{1}

y2 := Grow(y, 10)
fmt.Printf("y2 %T len=%d cap=%d\n", y2, len(y2), cap(y2))

y3 := Grow2(y, 10)
fmt.Printf("y3 %T len=%d cap=%d\n", y3, len(y3), cap(y3))
</code>```

Output (try it on the Go Playground):

```<code>x2 []int len=1 cap=12
x3 []int len=1 cap=12
y2 main.ints len=1 cap=12
y3 []int len=1 cap=12
</code>```

As you can see Grow2(y, 10) receives a value of type main.ints and yet it returns a value of type []int. This is not what we would want from it.

Body:
Consider the experimental package slices. The package is experimental, so I understand the signatures may change; I'm using it to illustrate the issue.

Consider the signatures of two functions from this package, slices.Contains and slices.Grow:

func Contains[E comparable](s []E, v E) bool

func Grow[S ~[]E, E any](s S, n int) S

The first argument to Contains has type []E (slice of Es) with E constrained by comparable (types that are comparable).

The first argument to Grow instead has type S (just S), with S constrained by ~[]E (types whose underlying type is a slice of E)

However it looks like there isn't any practical difference between what operations are allowed inside functions with such type params. If we declare some fake funcs with the same type parameters, we can see that both compile just fine:

As expected, in both functions we can len/cap, append, range, allocate with make, and index with [ ].

func fakeContains[E comparable](s []E, v E) {
    fmt.Println(len(s), cap(s))

    var e E
    fmt.Println(append(s, e))
    fmt.Println(make([]E, 4))

    for _, x := range s {
        fmt.Println(x)
    }
    fmt.Println(s[0])

    fmt.Println(reflect.TypeOf(s).Kind())
}

func fakeGrow[S ~[]E, E any](s S, n int) {
    fmt.Println(len(s), cap(s))

    var e E
    fmt.Println(append(s, e))
    fmt.Println(make(S, 4))

    for _, x := range s {
        fmt.Println(x)
    }
        fmt.Println(s[0])

    fmt.Println(reflect.TypeOf(s).Kind())
}

Even reflect.TypeOf(s).Kind() gives reflect.Slice in all cases.

The functions can also be tested with different types, and all compile:

// compiles just fine
func main() {
    type MyUint64 uint64
    type MyUint64Slice []uint64

    foo := []uint64{0, 1, 2}
    fakeContains(foo, 0)
    fakeGrow(foo, 5)

    bar := []MyUint64{3, 4, 5}
    fakeContains(bar, 0)
    fakeGrow(bar, 5)

    baz := MyUint64Slice{6, 7, 8}
    fakeContains(baz, 0)
    fakeGrow(baz, 5)
}

The only actual difference in my understanding is that in slices.Grow the argument s S is not a slice. It's just constrained to slice types. And as a matter of fact reflect.TypeOf(s) gives a different output when the arg is an instance of type MyUint64Slice []uint64:

Contains with arg s []E gives reflect.TypeOf(s) -> []uint64

Grow with arg s S gives reflect.TypeOf(s) -> main.MyUint64Slice

However it's not immediately apparent to me what's the practical difference between the two.

Playground with the code: https://gotipplay.golang.org/p/zg2dGtSJwuI

Question

Are these two declarations equivalent in practice? If not, when should I choose one over the other?

Body:
It matters if you have to return a slice of the same (possibly named) type as the argument.

If you do not have to return a slice (just some other info e.g. a bool to report if the value is contained), you do not need to use a type parameter that itself constraints to a slice, you may use a type parameter for the element only.

If you have to return a slice of the same type as the input, you must use a type parameter that itself constraints to a slice (e.g. ~[]E).

To demonstrate, let's see these 2 implementations of Grow():

func Grow[S ~[]E, E any](s S, n int) S {
    return append(s, make(S, n)...)[:len(s)]
}

func Grow2[E any](s []E, n int) []E {
    return append(s, make([]E, n)...)[:len(s)]
}

If you pass a slice of a custom type having a slice as its underlying type, Grow() can return a value of the same type. Grow2() cannot: it can only return a value of an unnamed slice type: []E.

And the demonstration:

x := []int{1}

x2 := Grow(x, 10)
fmt.Printf("x2 %T len=%d cap=%d\n", x2, len(x2), cap(x2))

x3 := Grow2(x, 10)
fmt.Printf("x3 %T len=%d cap=%d\n", x3, len(x3), cap(x3))

type ints []int
y := ints{1}

y2 := Grow(y, 10)
fmt.Printf("y2 %T len=%d cap=%d\n", y2, len(y2), cap(y2))

y3 := Grow2(y, 10)
fmt.Printf("y3 %T len=%d cap=%d\n", y3, len(y3), cap(y3))

Output (try it on the Go Playground):

x2 []int len=1 cap=12
x3 []int len=1 cap=12
y2 main.ints len=1 cap=12
y3 []int len=1 cap=12

As you can see Grow2(y, 10) receives a value of type main.ints and yet it returns a value of type []int. This is not what we would want from it.


问:
How can I process this array more efficiently
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

```<code>       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }
</code>```

答:
I did not compare the efficiency of this with the above answers but if you are  dealing with names, using PersonNameComponentsFormatter will help you a lot. Check the documentation here.

In your case following code gives the required output.

```<code>let formatter = PersonNameComponentsFormatter()

let contacts = ["John Doe", "Mary Blog"]
var initalsArray: [String] = []

for contact in contacts {
    if let name = formatter.personNameComponents(from: contact) {
        formatter.style = .abbreviated
        initalsArray.append(formatter.string(from: name))
    }
}
</code>```

output -> ["JD", "MB"]

Body:
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }

Body:
I did not compare the efficiency of this with the above answers but if you are  dealing with names, using PersonNameComponentsFormatter will help you a lot. Check the documentation here.

In your case following code gives the required output.

let formatter = PersonNameComponentsFormatter()

let contacts = ["John Doe", "Mary Blog"]
var initalsArray: [String] = []

for contact in contacts {
    if let name = formatter.personNameComponents(from: contact) {
        formatter.style = .abbreviated
        initalsArray.append(formatter.string(from: name))
    }
}

output -> ["JD", "MB"]


问:
How to split number and char
I want to assign char and numbers to variables. How can it be done with the sscanf() function?

```<code>char buffer[50]= "A123.4,B567.8,C901.2";

char a = << A;
char b = << B;
char c = << C;

double x = << 123.4;
double y = << 567.8;
double z = << 901.2;
</code>```

答:
use sscanf:

```<code>char buffer[50]= "A123.4,B567.8,C901.2";
char a, b, c;
double x, y, z;

sscanf(buffer, "%c%lf,%c%lf,%c%lf", &a, &x, &b, &y, &c, &z);
</code>```

Title: How to split number and char

Body:
I want to assign char and numbers to variables. How can it be done with the sscanf() function?

char buffer[50]= "A123.4,B567.8,C901.2";

char a = << A;
char b = << B;
char c = << C;

double x = << 123.4;
double y = << 567.8;
double z = << 901.2;

Body:
use sscanf:

char buffer[50]= "A123.4,B567.8,C901.2";
char a, b, c;
double x, y, z;

sscanf(buffer, "%c%lf,%c%lf,%c%lf", &a, &x, &b, &y, &c, &z);