问:
MaxTraceFileSize is showing invalid attribute WCF tracing

```<code>    <sources>
        <source name="System.ServiceModel" switchValue="All">
            <listeners>
                <add name="System.ServiceModel.XmlTrace.Listener" />
            </listeners>
        </source>

        <source name="System.Runtime.Serialization" switchValue="All">
            <listeners>
                <add name="System.Runtime.Serialization.XmlTrace.Listener" />
            </listeners>
        </source>
    </sources>

    <sharedListeners>
        <add
            type="MarcW.Tools.Diagnostics.RollingXmlWriterTraceListener, MarcW.Tools"
            name="System.ServiceModel.XmlTrace.Listener"
            traceOutputOptions="None"
            initializeData=".Logs\System.ServiceModel.svclog"
            MaxTraceFileSize="134217728" />
        <add
            type="MarcW.Tools.Diagnostics.RollingXmlWriterTraceListener, MarcW.Tools"
            name="System.Runtime.Serialization.XmlTrace.Listener"
            traceOutputOptions="None"
            initializeData=".Logs\System.Runtime.Serialization.svclog"
            MaxTraceFileSize="134217728" />
    </sharedListeners>
</system.diagnostics>
</code>```

in Config File , When We are using Tracing for WCF **MaxTraceFileSize**  is showing invalid attribute how it can be resolved

答:
You can try to implement GetSupportedAttributes to make .NET read attribute values from config file.

The Attributes collection is not populated from the configuration file until an instance of the listener is fully constructed.

```<code>protected override string[] GetSupportedAttributes()
{
    return new[] { "MaxTraceFileSize" };
}
</code>```

Loading Trace Listener Attributes

local

example:https://github.com/SebastiaanLubbers/WF_WCF_Samples/tree/master/WCF/Basic/Management/CircularTracing/CS

Body:
    <sources>
        <source name="System.ServiceModel" switchValue="All">
            <listeners>
                <add name="System.ServiceModel.XmlTrace.Listener" />
            </listeners>
        </source>

        <source name="System.Runtime.Serialization" switchValue="All">
            <listeners>
                <add name="System.Runtime.Serialization.XmlTrace.Listener" />
            </listeners>
        </source>
    </sources>

    <sharedListeners>
        <add
            type="MarcW.Tools.Diagnostics.RollingXmlWriterTraceListener, MarcW.Tools"
            name="System.ServiceModel.XmlTrace.Listener"
            traceOutputOptions="None"
            initializeData=".Logs\System.ServiceModel.svclog"
            MaxTraceFileSize="134217728" />
        <add
            type="MarcW.Tools.Diagnostics.RollingXmlWriterTraceListener, MarcW.Tools"
            name="System.Runtime.Serialization.XmlTrace.Listener"
            traceOutputOptions="None"
            initializeData=".Logs\System.Runtime.Serialization.svclog"
            MaxTraceFileSize="134217728" />
    </sharedListeners>
</system.diagnostics>

in Config File , When We are using Tracing for WCF **MaxTraceFileSize**  is showing invalid attribute how it can be resolved

Body:
You can try to implement GetSupportedAttributes to make .NET read attribute values from config file.

The Attributes collection is not populated from the configuration file until an instance of the listener is fully constructed.

protected override string[] GetSupportedAttributes()
{
    return new[] { "MaxTraceFileSize" };
}

Loading Trace Listener Attributes

local

example:https://github.com/SebastiaanLubbers/WF_WCF_Samples/tree/master/WCF/Basic/Management/CircularTracing/CS


来源: stackexchange

问:
How to align the text on the right and the button on the left and make it responsive css
I have a card I want to align the text on the left and the button on the right with space between the two and put it responsive on the devices
knowing that the button I add the backgroud-image

here is what i tried but it is still not responsive

.component {
  display: flex;
  justify-content: space-between;
}

.link {
  display: flex;
  justify-content: center;
  background-image: url("../../myicon.svg");
  background-repeat: no-repeat;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: right;
  height: 24px;
  width: 64px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="component">
  <div>
    <span class="">DEV</span>
  </div>
  <div>
    <div class="btn">
      <button>Button </button>
    </div>
  </div>
</div></code>```

答:
I think you want something like this (tightly grouped)

```<code><div class="component">
'    <span class="link">DEV</span>
    <div class="btn">
      <button>Button</button>
    </div>
</div>
</code>```

but then
.

```<code>.btn {
  float : left;
}
</code>```

or maybe you want the anchor to actually do something, so maybe Dev. Always try to keep it simple. Each component - the container component, the span, the div, the button, the anchor should have its own thing. I can imagine more things being added to this container component in the future (an image, an ajax of imformation coming and so on), so the simpler it is now, the simpler it will be to adjust in the future.

ContentLicense: CC BY-SA 4.0

Body:
I have a card I want to align the text on the left and the button on the right with space between the two and put it responsive on the devices
knowing that the button I add the backgroud-image

here is what i tried but it is still not responsive

.component {
  display: flex;
  justify-content: space-between;
}

.link {
  display: flex;
  justify-content: center;
  background-image: url("../../myicon.svg");
  background-repeat: no-repeat;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: right;
  height: 24px;
  width: 64px;
}

    DEV

      <button>Button </button>

Body:
I think you want something like this (tightly grouped)

<div class="component">
'    <span class="link">DEV</span>
    <div class="btn">
      <button>Button</button>
    </div>
</div>

but then
.

.btn {
  float : left;
}

or maybe you want the anchor to actually do something, so maybe <a onclick="..." href="...">Dev</a>. Always try to keep it simple. Each component - the container component, the span, the div, the button, the anchor should have its own thing. I can imagine more things being added to this container component in the future (an image, an ajax of imformation coming and so on), so the simpler it is now, the simpler it will be to adjust in the future.


问:
I am new to Python and I wonder what is wrong with this code
I am new to Python and I wonder what is wrong with this code, I searched for this,I guess in the end of the make_list function I have to return, and not print(). and in the end I have to write
if name[0]  and not if name[1], but what else is wrong with it?

Code:

```<code>def make_list(number):
    names = []
    for item in number:
        names.append(input("Enter your name with a capital letter."))
        print(names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [1] == 'A':
        print("Name", name, "starts with A")

</code>```

Compiler says:

```<code>Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 3, in make_list
TypeError: 'int' object is not iterable
</code>```

答:
You need to have range(numbers) to iterate, and you also forgot to return names from the make_list function. Also, as the arrays in Python are zero-indexed, you probably want to check if name [0]

def make_list(number):
    names = []
    for item in range(number):
        names.append(input("Enter your name with a capital letter."))
        print(names)
    return names

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [0] == 'A':
        print("Name", name, "starts with A")
```

Body:
I am new to Python and I wonder what is wrong with this code, I searched for this,I guess in the end of the make_list function I have to return, and not print(). and in the end I have to write
if name[0]  and not if name[1], but what else is wrong with it?

Code:

def make_list(number):
    names = []
    for item in number:
        names.append(input("Enter your name with a capital letter."))
        print(names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [1] == 'A':
        print("Name", name, "starts with A")

Compiler says:

Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 3, in make_list
TypeError: 'int' object is not iterable


问:
Sliding card from left side when clicked on button in react
In image 1, when the user click on "Apply Coupen", than a window slides from left just above the webpage(see image 2). How to achieve this? And in image 2, we can see a blue transparent color on the webpage just adjacent to the window which slides from left. How to do achieve it?

Image 1

Image 2

答:
See it. Click here and see demo code
If this helps you, please mark as an answer;</p>
```<code>import { useState } from 'react'
import "./styles.css";
import Sidebar from './component/sidebar'

export default function App() {
  const [toggle, setToggle] = useState(false);

  const handleToggle = () => {
    setToggle(pre => !pre)
  }

  return (
    <div className="App">
      <button onClick={handleToggle} >Click Me</button>
     {toggle && <Sidebar close={() => setToggle(false)} />}
    </div>
  );
}
</code>```

Body:
See it. Click here and see demo code
If this helps you, please mark as an answer;

import { useState } from 'react'
import "./styles.css";
import Sidebar from './component/sidebar'

export default function App() {
  const [toggle, setToggle] = useState(false);

  const handleToggle = () => {
    setToggle(pre => !pre)
  }

  return (
    <div className="App">
      <button onClick={handleToggle} >Click Me</button>
     {toggle && <Sidebar close={() => setToggle(false)} />}
    </div>
  );
}


问:
QT on Raspberry Pi 4
I have a Raspberry Pi 4 Model B Rev 1.4 and I am using Ubuntu 20.04 running in VirtualBox on a Windows 10 machine.

I have been following the steps presented in this video https://www.youtube.com/watch?v=TmtN3Rmx9Rk&list=PLXAxzIhirYJGp1dMN0SxMRNCumubmpzWj&index=2&t=1686s. The goal is to run QT C++ applications on the Raspberry Pi

@24.20, the presenter issues the command:

 rsync -avz  --rsync-path="sudo rsync" pi@192.168.1.237:/lib sysroot

His host machine receives a number of files. On the video I can see the contents of lib/firmware, lib/modules.bak, lib/modules, lib/udev

However, when I issue the same command, I only receive a symbolic link

```<code>receiving incremental file list
lib -> usr/lib
</code>```

BTW, a symbolic link is also what I see on the RPi

```<code>lrwxrwxrwx   1 root root     7 May  7  2021 bin -> usr/bin
</code>```

I tried adding the option --copy-links. It allows me to copy the files, but the usr/bin directory is about 3GB and it seems to have a many more folders (for instance chromium-browser) when compared to what I saw in the  video

Why the discrepancy? Did I miss an initial setup step, maybe? Any advice?

答:
Had the same problem.
the /lib you want to copy is a link, not a folder. It's linked to /usr/lib. So try it with</p>
```<code>rsync -avz  --rsync-path="sudo rsync" pi@192.168.1.237:/usr/lib sysroot
</code>```

Title: QT on Raspberry Pi 4

Body:
I have a Raspberry Pi 4 Model B Rev 1.4 and I am using Ubuntu 20.04 running in VirtualBox on a Windows 10 machine.

I have been following the steps presented in this video https://www.youtube.com/watch?v=TmtN3Rmx9Rk&list=PLXAxzIhirYJGp1dMN0SxMRNCumubmpzWj&index=2&t=1686s. The goal is to run QT C++ applications on the Raspberry Pi

@24.20, the presenter issues the command:

 rsync -avz  --rsync-path="sudo rsync" pi@192.168.1.237:/lib sysroot

His host machine receives a number of files. On the video I can see the contents of lib/firmware, lib/modules.bak, lib/modules, lib/udev

However, when I issue the same command, I only receive a symbolic link

receiving incremental file list
lib -> usr/lib

BTW, a symbolic link is also what I see on the RPi

lrwxrwxrwx   1 root root     7 May  7  2021 bin -> usr/bin

I tried adding the option --copy-links. It allows me to copy the files, but the usr/bin directory is about 3GB and it seems to have a many more folders (for instance chromium-browser) when compared to what I saw in the  video

Why the discrepancy? Did I miss an initial setup step, maybe? Any advice?

Body:
Had the same problem.
the /lib you want to copy is a link, not a folder. It's linked to /usr/lib. So try it with

rsync -avz  --rsync-path="sudo rsync" pi@192.168.1.237:/usr/lib sysroot


问:
C# why LINQ string array Contains show false
my question is ABC006 is in testA, why Contains show false?
and testB  show true?</p>
```<code>public class Program
{
    public static void Main()
    {
        string[] testA = " ABC666,777".Split(',');
    Console.WriteLine(testA.Contains("ABC666"));
    string testB =" ABC666";
    Console.WriteLine( testB.Contains("ABC666"));

    }
}
</code>```

答:
Here's your difference in the two Contains methods:

The first contains is asking "does the enumerable contain this value". The second is asking "does this string contain this other string".

The first one does not ask "does any string in this enumerable contain the other string".

To do that you would need this code:

```<code>Console.WriteLine(testA.Any(x => x.Contains("ABC666")));
</code>```

Body:
my question is ABC006 is in testA, why Contains show false?
and testB  show true?

public class Program
{
    public static void Main()
    {
        string[] testA = " ABC666,777".Split(',');
    Console.WriteLine(testA.Contains("ABC666"));
    string testB =" ABC666";
    Console.WriteLine( testB.Contains("ABC666"));

    }
}

Body:
Here's your difference in the two Contains methods:

The first contains is asking "does the enumerable contain this value". The second is asking "does this string contain this other string".

The first one does not ask "does any string in this enumerable contain the other string".

To do that you would need this code:

Console.WriteLine(testA.Any(x => x.Contains("ABC666")));


问:
VSCode hits breakpoints then stops
So first of all since October for some reason my previously working Xdebug config for VSCode + Docker stopped working.

I switched over to an Xdebug 3 config to try it out, since 2.9 appears to have stopped working for me. Maybe because of a VSCode or PHP Debug plugin update?

But so far I have been unable to get it working or get it working only half?

VSCode launch.json:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/html/backend": "${workspaceRoot}",
            },
            "xdebugSettings": {
                "resolved_breakpoints": "0",
                "max_data": -1,
                "max_children": -1,
                "max_depth": -1
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        }
    ]
}
</code>```

xdebug.ini in Docker (LAMP):

```<code>zend_extension=xdebug.so
xdebug.idekey = VSCODE
xdebug.mode = debug,profile,trace
xdebug.start_with_request = yes
xdebug.client_port = 9003
xdebug.client_host=host.docker.internal

xdebug.profiler_enable_trigger = 1
xdebug.profiler_enable = 0
xdebug.remote_enable = 1
xdebug.profiler_output_dir = "/tmp"
</code>```

xdebug.log:

My breakpoint is on module.class.php:209

```<code>[17] Log opened at 2021-12-16 15:36:39.557066
[17] [Step Debug] INFO: Connecting to configured address/port: host.docker.internal:9003.
[17] [Step Debug] INFO: Connected to debugging client: host.docker.internal:9003 (through xdebug.client_host/xdebug.client_port). :-)
[17] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/html/company_v2_backend/index.php" language="PHP" xdebug:language_version="7.2.34" protocol_version="1.0" appid="17" idekey="VSCODE"><engine version="3.1.2"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>

[17] [Step Debug] <- feature_set -i 1 -n resolved_breakpoints -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 2 -n notify_ok -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="2" feature="notify_ok" success="1"></response>

[17] [Step Debug] <- feature_set -i 3 -n extended_properties -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="3" feature="extended_properties" success="1"></response>

[17] [Step Debug] <- feature_set -i 4 -n resolved_breakpoints -v 0
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="4" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 5 -n max_data -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="5" feature="max_data" success="1"></response>

[17] [Step Debug] <- feature_set -i 6 -n max_children -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="6" feature="max_children" success="1"></response>

[17] [Step Debug] <- feature_set -i 7 -n max_depth -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="7" feature="max_depth" success="1"></response>

[17] [Step Debug] <- breakpoint_set -i 8 -t line -f file:///var/www/html/backend/classes/data/module.class.php -n 209
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="8" id="170001"></response>

[17] [Step Debug] <- run -i 9
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:10.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:10'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:11.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:11'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:12.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:12'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:15.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:15'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:16.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:16'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="run" transaction_id="9" status="stopping" reason="ok"></response>

[17] [Step Debug] <- stop -i 10
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="stop" transaction_id="10" status="stopped" reason="ok"></response>

[17] Log closed at 2021-12-16 15:36:39.656857

[17] Log opened at 2021-12-16 15:36:39.676911
[17] [Step Debug] INFO: Connecting to configured address/port: host.docker.internal:9003.
[17] [Step Debug] INFO: Connected to debugging client: host.docker.internal:9003 (through xdebug.client_host/xdebug.client_port). :-)
[17] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/html/company_v2_backend/index.php" language="PHP" xdebug:language_version="7.2.34" protocol_version="1.0" appid="17" idekey="VSCODE"><engine version="3.1.2"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>

[17] [Step Debug] <- feature_set -i 1 -n resolved_breakpoints -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 2 -n notify_ok -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="2" feature="notify_ok" success="1"></response>

[17] [Step Debug] <- feature_set -i 3 -n extended_properties -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="3" feature="extended_properties" success="1"></response>

[17] [Step Debug] <- feature_set -i 4 -n resolved_breakpoints -v 0
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="4" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 5 -n max_data -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="5" feature="max_data" success="1"></response>

[17] [Step Debug] <- feature_set -i 6 -n max_children -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="6" feature="max_children" success="1"></response>

[17] [Step Debug] <- feature_set -i 7 -n max_depth -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="7" feature="max_depth" success="1"></response>

[17] [Step Debug] <- breakpoint_set -i 8 -t line -f file:///var/www/html/backend/classes/data/module.class.php -n 209
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="8" id="170002"></response>

[17] [Step Debug] <- run -i 9
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:10.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:10'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
</code>```

... and it's kind of the same from here on out

EDIT:
phpinfo xdebug wizard instructions are:

```<code>Download xdebug-3.1.2.tgz
Install the pre-requisites for compiling PHP extensions. These packages are often called 'php-dev', or 'php-devel', 'automake' and 'autoconf'.
Unpack the downloaded file with tar -xvzf xdebug-3.1.2.tgz
Run: cd xdebug-3.1.2
Run: phpize (See the FAQ if you don't have phpize).

As part of its output it should show:

Configuring for:
...
Zend Module Api No:      20170718
Zend Extension Api No:   320170718
If it does not, you are using the wrong phpize. Please follow this FAQ entry and skip the next step.

Run: ./configure
Run: make
Run: cp modules/xdebug.so /usr/local/lib/php/extensions/no-debug-non-zts-20170718
Update /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini to have the line:
zend_extension = xdebug
Restart the Apache Webserver
</code>```

Follow these instructions but it doesn't appear to help.

答:
UPDATE 2022/03/01:1300 - Got it working!

We switched from Docker for Windows to running through WSL (See old comments below) and it appeared that I had installed the remote wsl extension in VSCode which I thought was required.

The conclusion is that either Docker got updated and it stopped working with our specific environment or the environment wasn't set up right to begin with (ie. maybe some bug got 'fixed' that it work for us previously).

The configuration I we are using now is very similar:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "pathMappings": {
                "/var/www/php": "\\\\wsl$\\Ubuntu\\code\\company\\myapp-backend"
            }
        },
    ]
}
</code>```

docker compose

```<code>version: "3.8"

# Services
services:
  # Redis service
  myapp-backend-redis:
    build: ./.docker/redis
    networks:
      - myapp-backend_network
    ports:
      - "6379:6379"
    expose:
      - 6379
    restart: always
    container_name: myapp-backend-redis

  # Nginx Service
  myapp-backend-nginx:
    image: nginx:1.19
    ports:
      - 8181:80
    volumes:
      - ./:/var/www/php
      - ./.docker/nginx/conf.d:/etc/nginx/conf.d
    depends_on:
      - myapp-backend-php
    networks:
      - myapp-backend_network
    restart: always
    container_name: myapp-backend-nginx

  # PHP Service
  myapp-backend-php:
    build: ./.docker/php
    working_dir: /var/www/php
    #environment:
    #    DEBUG: 1
    volumes:
      - ./:/var/www/php
    depends_on:
      - myapp-backend-mysql
    networks:
      - myapp-backend_network
    restart: always
    container_name: myapp-backend-php

  # Mysql service
  myapp-backend-mysql:
    build: ./.docker/mysql
    ports:
      - "3306:3306"
    volumes:
      - ./.docker/mysql/my.cnf:/etc/my.cnf
      - /storage/docker/myapp-backend-mysql-datadir:/var/lib/mysql

    environment:
      MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}"
      MYSQL_DATABASE: "${DB_NAME}"
      MYSQL_USER: "${DB_USERNAME}"
      MYSQL_PASSWORD: "${DB_PASSWORD}"
      MYSQL_ROOT_HOST: "%"
    networks:
      - myapp-backend_network
    restart: always
    container_name: myapp-backend-mysql

networks:
  myapp-backend_network:
    driver: bridge
</code>```

php dockerfile:

```<code>FROM php:7.2-fpm

RUN apt-get update && apt-get install -y \
    zip \
    unzip \
    zlib1g-dev \
    libzip-dev \
    libjpeg-dev \
    jpegoptim \
    libicu-dev \
    libonig-dev \
    libxml2-dev \
    g++ \
    curl \
    python

RUN docker-php-ext-install mysqli pdo pdo_mysql zip mbstring simplexml dom

COPY config.aws /var/www/.aws/config
COPY credentials.aws /var/www/.aws/credentials

COPY xdebug.ini $PHP_INI_DIR/conf.d/
RUN pecl install xdebug redis
RUN docker-php-ext-enable xdebug redis

# Install AWS-CLI
RUN curl https://bootstrap.pypa.io/pip/2.7/get-pip.py| python && \
    pip install awscli==1.16.100

#COPY config.aws /.aws/config
#COPY credentials.aws /.aws/credentials

RUN mkdir /var/company
RUN chmod -R 777 /var/company/
</code>```

xdebug.ini

```<code>[XDebug]
xdebug.client_port = 9000
xdebug.mode = debug,profile
xdebug.start_with_request = yes
xdebug.client_host=host.docker.internal
xdebug.remote_log=/var/log/xdebug.log
xdebug.remote_connect_back=0
</code>```

So if you are using Docker I would recommend you to check your environment for issues or try switching to something else. Either WSL or maybe something like Xampp or Laragon just for quick testing purposes. So you can know that it is your environment that is the problem.

UPDATE 2022/03/01:1200 - I have migrated to our new WSL environment and xdebug + phpdebug works for two other dev's in vscode. But still not for me, I have also reinstalled vscode, removed all extensions (total reset) but still no luck.

Must be something with my PC.

OLD:

FYI - The problem is probably Docker / Docker Desktop, I tried looking into downgrading but firstly you would have to go back in version quite far and below 4 is not listed anymore on the website.

I know this because we confirmed XDebug makes a connection with vscode but then appears to break somewhere along the way. A colleague has tried a pure WSL setup without the docker(desktop) layer and got it working there.

Sadly I have not been able to figure out the exact issue but will update this post when I migrate over to our new WSL environment.

Title: VSCode hits breakpoints then stops

Body:
So first of all since October for some reason my previously working Xdebug config for VSCode + Docker stopped working.

I switched over to an Xdebug 3 config to try it out, since 2.9 appears to have stopped working for me. Maybe because of a VSCode or PHP Debug plugin update?

But so far I have been unable to get it working or get it working only half?

VSCode launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/html/backend": "${workspaceRoot}",
            },
            "xdebugSettings": {
                "resolved_breakpoints": "0",
                "max_data": -1,
                "max_children": -1,
                "max_depth": -1
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        }
    ]
}

xdebug.ini in Docker (LAMP):

zend_extension=xdebug.so
xdebug.idekey = VSCODE
xdebug.mode = debug,profile,trace
xdebug.start_with_request = yes
xdebug.client_port = 9003
xdebug.client_host=host.docker.internal

xdebug.profiler_enable_trigger = 1
xdebug.profiler_enable = 0
xdebug.remote_enable = 1
xdebug.profiler_output_dir = "/tmp"

xdebug.log:

My breakpoint is on module.class.php:209

[17] Log opened at 2021-12-16 15:36:39.557066
[17] [Step Debug] INFO: Connecting to configured address/port: host.docker.internal:9003.
[17] [Step Debug] INFO: Connected to debugging client: host.docker.internal:9003 (through xdebug.client_host/xdebug.client_port). :-)
[17] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/html/company_v2_backend/index.php" language="PHP" xdebug:language_version="7.2.34" protocol_version="1.0" appid="17" idekey="VSCODE"><engine version="3.1.2"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>

[17] [Step Debug] <- feature_set -i 1 -n resolved_breakpoints -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 2 -n notify_ok -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="2" feature="notify_ok" success="1"></response>

[17] [Step Debug] <- feature_set -i 3 -n extended_properties -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="3" feature="extended_properties" success="1"></response>

[17] [Step Debug] <- feature_set -i 4 -n resolved_breakpoints -v 0
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="4" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 5 -n max_data -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="5" feature="max_data" success="1"></response>

[17] [Step Debug] <- feature_set -i 6 -n max_children -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="6" feature="max_children" success="1"></response>

[17] [Step Debug] <- feature_set -i 7 -n max_depth -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="7" feature="max_depth" success="1"></response>

[17] [Step Debug] <- breakpoint_set -i 8 -t line -f file:///var/www/html/backend/classes/data/module.class.php -n 209
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="8" id="170001"></response>

[17] [Step Debug] <- run -i 9
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:10.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:10'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:11.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:11'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:12.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:12'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:15.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:15'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:16.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:16'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="run" transaction_id="9" status="stopping" reason="ok"></response>

[17] [Step Debug] <- stop -i 10
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="stop" transaction_id="10" status="stopped" reason="ok"></response>

[17] Log closed at 2021-12-16 15:36:39.656857

[17] Log opened at 2021-12-16 15:36:39.676911
[17] [Step Debug] INFO: Connecting to configured address/port: host.docker.internal:9003.
[17] [Step Debug] INFO: Connected to debugging client: host.docker.internal:9003 (through xdebug.client_host/xdebug.client_port). :-)
[17] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/html/company_v2_backend/index.php" language="PHP" xdebug:language_version="7.2.34" protocol_version="1.0" appid="17" idekey="VSCODE"><engine version="3.1.2"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>

[17] [Step Debug] <- feature_set -i 1 -n resolved_breakpoints -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 2 -n notify_ok -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="2" feature="notify_ok" success="1"></response>

[17] [Step Debug] <- feature_set -i 3 -n extended_properties -v 1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="3" feature="extended_properties" success="1"></response>

[17] [Step Debug] <- feature_set -i 4 -n resolved_breakpoints -v 0
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="4" feature="resolved_breakpoints" success="1"></response>

[17] [Step Debug] <- feature_set -i 5 -n max_data -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="5" feature="max_data" success="1"></response>

[17] [Step Debug] <- feature_set -i 6 -n max_children -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="6" feature="max_children" success="1"></response>

[17] [Step Debug] <- feature_set -i 7 -n max_depth -v -1
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="7" feature="max_depth" success="1"></response>

[17] [Step Debug] <- breakpoint_set -i 8 -t line -f file:///var/www/html/backend/classes/data/module.class.php -n 209
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="8" id="170002"></response>

[17] [Step Debug] <- run -i 9
[17] [Step Debug] DEBUG: Checking whether to break on /var/www/html/backend/classes/data/module.class.php:209.
[17] [Step Debug] DEBUG: I: Current location: /var/www/html/company_v2_backend/index.php:10.
[17] [Step Debug] DEBUG: I: Matching breakpoint '/var/www/html/backend/classes/data/module.class.php:209' against location '/var/www/html/company_v2_backend/index.php:10'.
[17] [Step Debug] DEBUG: R: File name length (41) doesn't match with breakpoint (51).

... and it's kind of the same from here on out

EDIT:
phpinfo xdebug wizard instructions are:

Download xdebug-3.1.2.tgz
Install the pre-requisites for compiling PHP extensions. These packages are often called 'php-dev', or 'php-devel', 'automake' and 'autoconf'.
Unpack the downloaded file with tar -xvzf xdebug-3.1.2.tgz
Run: cd xdebug-3.1.2
Run: phpize (See the FAQ if you don't have phpize).

As part of its output it should show:

Configuring for:
...
Zend Module Api No:      20170718
Zend Extension Api No:   320170718
If it does not, you are using the wrong phpize. Please follow this FAQ entry and skip the next step.

Run: ./configure
Run: make
Run: cp modules/xdebug.so /usr/local/lib/php/extensions/no-debug-non-zts-20170718
Update /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini to have the line:
zend_extension = xdebug
Restart the Apache Webserver

Follow these instructions but it doesn't appear to help.

Body:
UPDATE 2022/03/01:1300 - Got it working!

We switched from Docker for Windows to running through WSL (See old comments below) and it appeared that I had installed the remote wsl extension in VSCode which I thought was required.

The conclusion is that either Docker got updated and it stopped working with our specific environment or the environment wasn't set up right to begin with (ie. maybe some bug got 'fixed' that it work for us previously).

The configuration I we are using now is very similar:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "pathMappings": {
                "/var/www/php": "\\\\wsl$\\Ubuntu\\code\\company\\myapp-backend"
            }
        },
    ]
}

docker compose

version: "3.8"

# Services
services:
  # Redis service
  myapp-backend-redis:
    build: ./.docker/redis
    networks:
      - myapp-backend_network
    ports:
      - "6379:6379"
    expose:
      - 6379
    restart: always
    container_name: myapp-backend-redis

  # Nginx Service
  myapp-backend-nginx:
    image: nginx:1.19
    ports:
      - 8181:80
    volumes:
      - ./:/var/www/php
      - ./.docker/nginx/conf.d:/etc/nginx/conf.d
    depends_on:
      - myapp-backend-php
    networks:
      - myapp-backend_network
    restart: always
    container_name: myapp-backend-nginx

  # PHP Service
  myapp-backend-php:
    build: ./.docker/php
    working_dir: /var/www/php
    #environment:
    #    DEBUG: 1
    volumes:
      - ./:/var/www/php
    depends_on:
      - myapp-backend-mysql
    networks:
      - myapp-backend_network
    restart: always
    container_name: myapp-backend-php

  # Mysql service
  myapp-backend-mysql:
    build: ./.docker/mysql
    ports:
      - "3306:3306"
    volumes:
      - ./.docker/mysql/my.cnf:/etc/my.cnf
      - /storage/docker/myapp-backend-mysql-datadir:/var/lib/mysql

    environment:
      MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}"
      MYSQL_DATABASE: "${DB_NAME}"
      MYSQL_USER: "${DB_USERNAME}"
      MYSQL_PASSWORD: "${DB_PASSWORD}"
      MYSQL_ROOT_HOST: "%"
    networks:
      - myapp-backend_network
    restart: always
    container_name: myapp-backend-mysql

networks:
  myapp-backend_network:
    driver: bridge

php dockerfile:

FROM php:7.2-fpm

RUN apt-get update && apt-get install -y \
    zip \
    unzip \
    zlib1g-dev \
    libzip-dev \
    libjpeg-dev \
    jpegoptim \
    libicu-dev \
    libonig-dev \
    libxml2-dev \
    g++ \
    curl \
    python

RUN docker-php-ext-install mysqli pdo pdo_mysql zip mbstring simplexml dom

COPY config.aws /var/www/.aws/config
COPY credentials.aws /var/www/.aws/credentials

COPY xdebug.ini $PHP_INI_DIR/conf.d/
RUN pecl install xdebug redis
RUN docker-php-ext-enable xdebug redis

# Install AWS-CLI
RUN curl https://bootstrap.pypa.io/pip/2.7/get-pip.py| python && \
    pip install awscli==1.16.100

#COPY config.aws /.aws/config
#COPY credentials.aws /.aws/credentials

RUN mkdir /var/company
RUN chmod -R 777 /var/company/

xdebug.ini

[XDebug]
xdebug.client_port = 9000
xdebug.mode = debug,profile
xdebug.start_with_request = yes
xdebug.client_host=host.docker.internal
xdebug.remote_log=/var/log/xdebug.log
xdebug.remote_connect_back=0

So if you are using Docker I would recommend you to check your environment for issues or try switching to something else. Either WSL or maybe something like Xampp or Laragon just for quick testing purposes. So you can know that it is your environment that is the problem.

UPDATE 2022/03/01:1200 - I have migrated to our new WSL environment and xdebug + phpdebug works for two other dev's in vscode. But still not for me, I have also reinstalled vscode, removed all extensions (total reset) but still no luck.

Must be something with my PC.

OLD:

FYI - The problem is probably Docker / Docker Desktop, I tried looking into downgrading but firstly you would have to go back in version quite far and below 4 is not listed anymore on the website.

I know this because we confirmed XDebug makes a connection with vscode but then appears to break somewhere along the way. A colleague has tried a pure WSL setup without the docker(desktop) layer and got it working there.

Sadly I have not been able to figure out the exact issue but will update this post when I migrate over to our new WSL environment.


问:
Does anyone have or know where can I find good documentation on Watir-Webdriver?

I am trying to get my automated test scripts switched over to the watir-webdriver.

Unfortunately I have been unable to completely do so, what I am looking for is a way to drive my web browser and still include add-ons and such. Right now it runs using non of the above.

Does anyone have or know where I can find good documentation on Watir-Webdriver?

答: There is a new site just launched: http://watirwebdriver.com</p>

ContentLicense: CC BY-SA 3.0


问:
Create column from all possible combination of two columns in dataframe based on groupby in Python
I have a dataframe in like below

id
group
log

10
UU1Q
23

10
UU1Q
12

10
UU2Q
15

11
UU2Q
17

11
UU3Q
35.6

11
UU1Q
29.8

11
UU1Q
33

11
UU1Q
44

13
UU2Q
17.77

13
UU2Q
19.90

13
UU2Q
55

14
UU3Q
33

15
UU3Q
22

For Each ID and group I want to create all possible combination of log values present in the dataframe in a new column.
Desired Output

id
group
log
new_col

10
UU1Q
23
(23,23)

10
UU1Q
12
(23,12)

10
UU2Q
15
(15,15)

11
UU2Q
17
(17,17)

11
UU3Q
35.6
(35.6,35.6)

11
UU1Q
29.8
(29.8, 29.8)

11
UU1Q
33
(29.8,33)

11
UU1Q
44
(29.8,44)

11
UU1Q

(33,44)

13
UU2Q
17.77
(17.77,17.77)

13
UU2Q
19.90
(17.77,19.90)

13
UU2Q
55
(17.77,55)

13
UU2Q

(19.90,55)

14
UU3Q
33
(33,33)

15
UU3Q
22
(22,22)

I used shift function but it is only generating combinations with next matching cell. I want to get all the possible combination in each group.

dummy['new'] = dummy.groupby(['ID', 'group'])['log'].shift()

Body:
This will return the desired output:

df.groupby(['id','group'], as_index=False).agg({'log':lambda x: list(x)})

Output:

    id  group   log
0   10  UU1Q    [23.0, 12.0]
1   10  UU2Q    [15.0]
2   11  UU1Q    [29.8, 33.0, 44.0]
3   11  UU2Q    [17.0]
4   11  UU3Q    [35.6]
5   13  UU2Q    [17.77, 19.9, 55.0]
6   14  UU3Q    [33.0]
7   15  UU3Q    [22.0]


问:
We are unable to get verification from Huawei server for IAP kit
We are implementing the In-app purchase module. While the implementation we have done all the implementation of the mobile end and server end but after purchasing a subscription we are trying to verify that purchase from the Huawei server through our server in which we got the following error:

```<code>get token error! the oauth server response={"sub_error":20003,"error_description":"parameter invalid","error":1101}
</code>```

can you suggest to us what's the wrong part we are implementing or we are missing something?

答:
According the official documentation, error code 1101 means ,the value of client_id in code or refresh_token is different from that of the input parameter. Here client_id means : App ID, which is the unique identifier allocated by AppGallery Connect to an app after the app is created. For details about how to query the app ID, please refer to Viewing App Basic Information.

For details about API for Obtaining an App-Level Access Token, please refer to:

https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/obtain-application-level-at-0000001051066052

For details about API  to check whether a product has been successfully purchased by verifying the purchase token for the subscription service, please refer to:

https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/api-subscription-verify-purchase-token-0000001050706080

Body:
We are implementing the In-app purchase module. While the implementation we have done all the implementation of the mobile end and server end but after purchasing a subscription we are trying to verify that purchase from the Huawei server through our server in which we got the following error:

get token error! the oauth server response={"sub_error":20003,"error_description":"parameter invalid","error":1101}

can you suggest to us what's the wrong part we are implementing or we are missing something?


问:
Django Rest Framework Manipulating Serialize.pop
I'm trying a view function that does the necessary operation depending on the data coming from the body. There is a registration model serializer that takes an additional variable group and if the group is student, the institute ID will have "ST22" at the beginning. I couldn't find a way to pop 'group' from serializer before sending it to the database. The data is saved but since it sends group as well and It does not have a field, it throws an error.

post function:

```<code>    def post(self, request, format='json'):
    serializer = RegistrationSerializer(data=request.data)
    if serializer.is_valid():
        if (serializer.validated_data["group"].lower() == "student"):
            serializer.validated_data["institute_id"]= "ST22" + serializer.validated_data["institute_id"]
        user = serializer.save()
        if user:
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status= status.HTTP_418_IM_A_TEAPOT)
</code>```

serializer class:

```<code>class StudentRegistrationSerializer(serializers.ModelSerializer):
group = serializers.CharField()
class Meta:
    model= CustomUser
    fields= ("id", "username", "password", "institute_id", "group")
    extra_kwargs = {
        'password': {
            'write_only': True
            }
        }

def create(self, validated_data):
    password = validated_data.pop('password')
    password = validated_data.pop('group')
    user = CustomUser(**validated_data)
    user.set_password(password)
    user.save()
    return user
</code>```

error:
CustomUser() got an unexpected keyword argument 'group'

答:
```<code>group: str
</code>```

instead of

```<code>group = serializers.CharField()
</code>```

you can access to group using request.data and you won't need to manipulate serializer. You you can send query inside body as follows:

```<code>{
"username": "",
"password": "",
"institute_id": "",
"group": ""
}
</code>```

Body:
I'm trying a view function that does the necessary operation depending on the data coming from the body. There is a registration model serializer that takes an additional variable group and if the group is student, the institute ID will have "ST22" at the beginning. I couldn't find a way to pop 'group' from serializer before sending it to the database. The data is saved but since it sends group as well and It does not have a field, it throws an error.

post function:

    def post(self, request, format='json'):
    serializer = RegistrationSerializer(data=request.data)
    if serializer.is_valid():
        if (serializer.validated_data["group"].lower() == "student"):
            serializer.validated_data["institute_id"]= "ST22" + serializer.validated_data["institute_id"]
        user = serializer.save()
        if user:
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status= status.HTTP_418_IM_A_TEAPOT)

serializer class:

class StudentRegistrationSerializer(serializers.ModelSerializer):
group = serializers.CharField()
class Meta:
    model= CustomUser
    fields= ("id", "username", "password", "institute_id", "group")
    extra_kwargs = {
        'password': {
            'write_only': True
            }
        }

def create(self, validated_data):
    password = validated_data.pop('password')
    password = validated_data.pop('group')
    user = CustomUser(**validated_data)
    user.set_password(password)
    user.save()
    return user

error:
CustomUser() got an unexpected keyword argument 'group'

Body:
group: str

instead of

group = serializers.CharField()

you can access to group using request.data and you won't need to manipulate serializer. You you can send query inside body as follows:

{
"username": "",
"password": "",
"institute_id": "",
"group": ""
}


答:
actually number is an integer, the error is saying in line 3 you are trying to loop through an integer which is not possible

Wrong : for item in number
What you may do instead : for item in range(number)

Here is some reading on the range function https://www.w3schools.com/python/ref_func_range.asp

Title: I am new to Python and I wonder what is wrong with this code


问:
Domain Driven Design - How do I model a Company and Employee use case?
I've been digging into DDD for the first time the last few weeks. I'm developing an HR application and am really struggling with the idea of Aggregate Roots.

So the current entities would be:

Company

Employee

Now given the lifecycle of an Employee, it makes sense at first to include it as a child entity on Company. An Employee can be added to a Company (new hire or existing) and then that Employee could resign or be fired - at which point that Employee record would likely be updated with some kind of status, so it can be differentiated from active Employees.

In regards to domain logic, every Employee at a Company must have a unique email. So if a Company always contained a list of all its Employees, I imagined that could be modeled as:

company.AddEmployee(employee) - This method would contain logic that makes sure the email is unique. In addition, it would update the size property of the Company, based on how many Employees they have. (<100 is small, <500 is medium, etc)

Now the biggest issue I have seen people discuss is concerning large Aggregates. I think this use case would fall under that concern, as a Company could have 10k+ Employees in this HR application. If I'm adding a single Employee at a time, it seems really wasteful to gather all 10k+, even if it's just their emails.

Am I doing the right thing here by making the Company the Aggregate Root, or is there a better way?

答:
I assume the app you are developing handles many organisations, otherwise there would not be a need for a separate "Company" aggregate.

An aggregate should preserve its transaction boundary. There is always a tradeoff when you establish this boundary. E.g. you can make the whole system an aggregate. But then you will only be able to process all the requests strictly sequentially with a lot of locking and waiting.

Or you can make a Company an aggregate to handle Employees. Then all the Employees of a given company will be processed sequentially. That may not work well at the scale of big company.

Or you can make a Company an aggregate to handle organisation-wide stuff. And make Employee an aggregate to handle personal stuff. In this case you will need some job to check after the fact if the e-mail is uniquie, or if some other properties are Ok (making a request to some external security system, for example), and updating this Employee to "verified" or "active" status.

The last approach will work well in a highly concurrent setting.

So, as a system designer you should pick one of the approaches and accept the trade-offs.


问:
ERR_SSL_VERSION_OR_CIPHER_MISMATCH error on Chrome only
While opening my private website, I am getting the following error in CHROME only.  in internet explorer its working without any issue.

I tried resetting chrome, delete all cache but no luck. nothing changed from backend site and error was started as of sudden.

weird thing is, if I open Fiddler 4 at the same time then its working. don't know what Fiddler is doing to fix that prob but when I close it again, then its again giving the same error.

答:
just fixed this problem by opening Chrome. Add in the search bar
chrome://flags/#enable-quic, select the first entry "Experimental Quick protocol" and change its status into disabled. Save the changes and restart Chrome.

It should be solved, if not there are  other fixes here you can try as well.

Let me know if you managed.
Cheers


问:
conditions statements. why I can't solve this ( there's so many wrong codes I cannot identify)
```<code>income = float(input("your income: "))
if income <= 100000:
    initalIncome = income * 0.5
elif income in range (100001,250000):
    initalIncome = income * 0.10
elif income in range (250001,500000):
    initialIncome = income * 0.15
elif income >= 500001:
    initialIncome = income * 0.20
</code>```

print(initialIncome)

#why is it giving the wrong answer?

#I think there's something wrong with the conditions

I cannot find the right code on how do i find the  final tax in this code

答:
I hope this is the answer you looking for, but you did not create the InitialIncome variable. Thus executing your code, this is the result:

```<code>income = float(input("your income: "))

if income <= 100000:

    initalIncome = income * 0.5

elif income in range (100001,250000):

    initalIncome = income * 0.10

elif income in range (250001,500000):

    initialIncome = income * 0.15

elif income >= 500001:

    initialIncome = income * 0.20

print(initialIncome)

your income:  100

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-306fbda6a7e7> in <module>
      9     initialIncome = income * 0.20
     10
---> 11 print(initialIncome)

NameError: name 'initialIncome' is not defined
</code>```

Try to add the variable you are looking for with value of 0.
In that case your code works.

```<code>def income_calc():
    income = float(input("your income: "))
    initialIncome = 0

    if income <= 100000:
        initialIncome = income *0.5
    elif income in range (100001, 250000):
        initialIncome = income *0.10
    elif income in range (250001, 500000):
        initialIncome = income *0.15
    elif income >= 500001:
        initialIncome = income *0.20

    return initialIncome
</code>```

Executing:

Body:
income = float(input("your income: "))
if income <= 100000:
    initalIncome = income * 0.5
elif income in range (100001,250000):
    initalIncome = income * 0.10
elif income in range (250001,500000):
    initialIncome = income * 0.15
elif income >= 500001:
    initialIncome = income * 0.20

print(initialIncome)

#why is it giving the wrong answer?

#I think there's something wrong with the conditions

I cannot find the right code on how do i find the  final tax in this code

Body:
I hope this is the answer you looking for, but you did not create the InitialIncome variable. Thus executing your code, this is the result:

income = float(input("your income: "))

if income <= 100000:

    initalIncome = income * 0.5

elif income in range (100001,250000):

    initalIncome = income * 0.10

elif income in range (250001,500000):

    initialIncome = income * 0.15

elif income >= 500001:

    initialIncome = income * 0.20

print(initialIncome)

your income:  100

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-306fbda6a7e7> in <module>
      9     initialIncome = income * 0.20
     10
---> 11 print(initialIncome)

NameError: name 'initialIncome' is not defined

Try to add the variable you are looking for with value of 0.
In that case your code works.

def income_calc():
    income = float(input("your income: "))
    initialIncome = 0

    if income <= 100000:
        initialIncome = income *0.5
    elif income in range (100001, 250000):
        initialIncome = income *0.10
    elif income in range (250001, 500000):
        initialIncome = income *0.15
    elif income >= 500001:
        initialIncome = income *0.20

    return initialIncome

Executing:


答:
This is my solution:

```<code>def make_list(number):
    names = []
    for _ in range(number):
        names.append(input("Enter your name with a capital letter: "))
        print(names)
    return(names)

number = int(input("How many names need to be entered? "))
names = make_list(number)
for name in names:
    if name.startswith('A'):
        print("Name", name, "starts with A")
</code>```

Results:

```<code>How many names need to be entered?3
Enter your name with a capital letter.RUNE
['RUNE']
Enter your name with a capital letter.PETER
['RUNE', 'PETER']
Enter your name with a capital letter.ANDERS
['RUNE', 'PETER', 'ANDERS']
Name ANDERS starts with A
</code>```

Body:
This is my solution:

def make_list(number):
    names = []
    for _ in range(number):
        names.append(input("Enter your name with a capital letter: "))
        print(names)
    return(names)

number = int(input("How many names need to be entered? "))
names = make_list(number)
for name in names:
    if name.startswith('A'):
        print("Name", name, "starts with A")

Results:

How many names need to be entered?3
Enter your name with a capital letter.RUNE
['RUNE']
Enter your name with a capital letter.PETER
['RUNE', 'PETER']
Enter your name with a capital letter.ANDERS
['RUNE', 'PETER', 'ANDERS']
Name ANDERS starts with A


问:
Loading files from .npz with Keras custom data generator
I'm training a CNN using a Keras data generator (tf.keras.utils.Sequence) on NumPy arrays saved locally. For my baseline on a small dataset, loading the arrays like so works fine:

```<code>X_data = np.load("X_data.npz")
y_data = np.load("y_data.npz")

X = X_data["arr_0"]
y = y_data["arr_0"]

class Gen_Data(tf.keras.utils.Sequence):

    def __init__(self,batch_size,t_size,X_data,y_data):

        self.batch_size = batch_size
        self.t_size = t_size
        self.X_data = X_data
        self.y_data = y_data
        self.n_batches = len(self.X_data)//self.batch_size
        self.batch_idx = np.array_split(range(len(self.X_data)), self.n_batches)

    def __len__(self):

        return self.n_batches

    def __getitem__(self,idx):

        batch_X = self.X_data[self.batch_idx[idx]]
        batch_y = self.y_data[self.batch_idx[idx]]
        return batch_X, batch_y
</code>```

The problem is that this requires me to load the whole dataset into memory, right? Which might be a problem when I use my actual dataset which is much much larger. When the arrays are saved as .npz files using np.savez_compressed, I have to load the whole thing to access any of the data.

I would therefore like to know if there is a way to load batches of arrays from X.npz without loading it in its entirety? This way I can build this into the __getitem__ part of the generator.

I would also be interested in hearing any alternative strategies for batch-loading large arrays into Keras/TensorFlow. Thanks for any advice!

答:
EDIT: After reading more on the docs, I realised that load() called on .npz files returns a lazy loader (an NpzFile object), thus not actually storing all the data in ram at the same time. It only stores file names and it will bring them in main memory only when required (calling data["filename"]), meaning you shouldn't worry about the data being loaded into main memory when you call load()

You could instead store the filenames in the generator, and load them when needed during training, using something like this:

class DataGenerator(tf.keras.utils.Sequence):
    def __init__(self, db_dir, batch_size, input_shape, num_classes,
                 shuffle=True):
        self.input_shape = input_shape
        self.batch_size = batch_size
        self.num_classes = num_classes
        self.shuffle = shuffle
        self.db_dir = db_dir
        # load the data from the root directory
        self.data, self.labels = self.get_data(db_dir)
        self.indices = np.arange(len(self.data))
        self.on_epoch_end()

    def get_data(self, root_dir):
        """"
        Loads the paths to the images and their corresponding labels from the database directory
        """
        self.data = []
        self.labels = []
        with open('labels.txt', 'r') as f:
            for line in f.readlines():
                splitted = line.split()
                self.data.append("./{0}/".format(root_dir) + splitted[0] + ".jpg")
                self.labels.append(int(splitted[1]))
        return self.data, self.labels

    def __len__(self):
        """
        Returns the number of batches per epoch: the total size of the dataset divided by the batch size
        """
        return int(np.floor(len(self.data) / self.batch_size))

    def __getitem__(self, index):
        """"
        Generates a batch of data
        """
        batch_indices = self.indices[index*self.batch_size : (index+1)*self.batch_size]
        for index in batch_indices:
            img = cv2.imread(self.data[index])
            dimensions = img.shape
        batch_x = [cv2.cvtColor(cv2.imread(self.data[index]), cv2.COLOR_BGR2RGB) for index in batch_indices] # TODO load the image from batch_indices
        batch_y = [self.labels[index] - 1 for index in batch_indices] # TODO load the corresponding labels of the images you loaded
        # optionally you can use: batch_y = tf.keras.utils.to_categorical(batch_y, num_classes=self.num_classes)
        return np.array(batch_x), np.array(batch_y)

    def on_epoch_end(self):
        """"
        Called at the end of each epoch
        """
        # if required, shuffle your data after each epoch
        self.indices = np.arange(len(self.data))
        if self.shuffle:
            # TODO shuffle data
            # you might find np.random.shuffle useful here
            np.random.shuffle(self.indices)
```

In this example i was using jpg's and loading them using opencv, but it should be similar with any file format. This will only load data when needed, and otherwise it will only store the path and indices. The indices are only necessary if you want to reshuffle between epochs.

That though of course requires you actually splitting the data into separate files, instead of having everything in a single file. Of course loading a single file will always be stored in RAM completely.

Body:
I'm training a CNN using a Keras data generator (tf.keras.utils.Sequence) on NumPy arrays saved locally. For my baseline on a small dataset, loading the arrays like so works fine:

X_data = np.load("X_data.npz")
y_data = np.load("y_data.npz")

X = X_data["arr_0"]
y = y_data["arr_0"]

class Gen_Data(tf.keras.utils.Sequence):

    def __init__(self,batch_size,t_size,X_data,y_data):

        self.batch_size = batch_size
        self.t_size = t_size
        self.X_data = X_data
        self.y_data = y_data
        self.n_batches = len(self.X_data)//self.batch_size
        self.batch_idx = np.array_split(range(len(self.X_data)), self.n_batches)

    def __len__(self):

        return self.n_batches

    def __getitem__(self,idx):

        batch_X = self.X_data[self.batch_idx[idx]]
        batch_y = self.y_data[self.batch_idx[idx]]
        return batch_X, batch_y

The problem is that this requires me to load the whole dataset into memory, right? Which might be a problem when I use my actual dataset which is much much larger. When the arrays are saved as .npz files using np.savez_compressed, I have to load the whole thing to access any of the data.

I would therefore like to know if there is a way to load batches of arrays from X.npz without loading it in its entirety? This way I can build this into the __getitem__ part of the generator.

I would also be interested in hearing any alternative strategies for batch-loading large arrays into Keras/TensorFlow. Thanks for any advice!

Body:
EDIT: After reading more on the docs, I realised that load() called on .npz files returns a lazy loader (an NpzFile object), thus not actually storing all the data in ram at the same time. It only stores file names and it will bring them in main memory only when required (calling data["filename"]), meaning you shouldn't worry about the data being loaded into main memory when you call load()

You could instead store the filenames in the generator, and load them when needed during training, using something like this:

class DataGenerator(tf.keras.utils.Sequence):
    def __init__(self, db_dir, batch_size, input_shape, num_classes,
                 shuffle=True):
        self.input_shape = input_shape
        self.batch_size = batch_size
        self.num_classes = num_classes
        self.shuffle = shuffle
        self.db_dir = db_dir
        # load the data from the root directory
        self.data, self.labels = self.get_data(db_dir)
        self.indices = np.arange(len(self.data))
        self.on_epoch_end()

    def get_data(self, root_dir):
        """"
        Loads the paths to the images and their corresponding labels from the database directory
        """
        self.data = []
        self.labels = []
        with open('labels.txt', 'r') as f:
            for line in f.readlines():
                splitted = line.split()
                self.data.append("./{0}/".format(root_dir) + splitted[0] + ".jpg")
                self.labels.append(int(splitted[1]))
        return self.data, self.labels

    def __len__(self):
        """
        Returns the number of batches per epoch: the total size of the dataset divided by the batch size
        """
        return int(np.floor(len(self.data) / self.batch_size))

    def __getitem__(self, index):
        """"
        Generates a batch of data
        """
        batch_indices = self.indices[index*self.batch_size : (index+1)*self.batch_size]
        for index in batch_indices:
            img = cv2.imread(self.data[index])
            dimensions = img.shape
        batch_x = [cv2.cvtColor(cv2.imread(self.data[index]), cv2.COLOR_BGR2RGB) for index in batch_indices] # TODO load the image from batch_indices
        batch_y = [self.labels[index] - 1 for index in batch_indices] # TODO load the corresponding labels of the images you loaded
        # optionally you can use: batch_y = tf.keras.utils.to_categorical(batch_y, num_classes=self.num_classes)
        return np.array(batch_x), np.array(batch_y)

    def on_epoch_end(self):
        """"
        Called at the end of each epoch
        """
        # if required, shuffle your data after each epoch
        self.indices = np.arange(len(self.data))
        if self.shuffle:
            # TODO shuffle data
            # you might find np.random.shuffle useful here
            np.random.shuffle(self.indices)

In this example i was using jpg's and loading them using opencv, but it should be similar with any file format. This will only load data when needed, and otherwise it will only store the path and indices. The indices are only necessary if you want to reshuffle between epochs.

That though of course requires you actually splitting the data into separate files, instead of having everything in a single file. Of course loading a single file will always be stored in RAM completely.


问:
Creating directory in application package on internal storage
Is it possible for android application to create several directories in internal storage for storing there different kinds of files? I need this capability, because I'll need to delete a kind of files at definite time moment in my application.

When I try to use standard Context method openFileOutput() and send to it filename with "/" symbol I get IllegalArgumentException.

Tell me please what classes and methods could allow me such functionality?

答:
Use Context.getDir(String name, int mode) method to create or access directories in internal storage. Quote from docs:

Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.

UPD Example:

```<code>File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
</code>```

Body:
Use Context.getDir(String name, int mode) method to create or access directories in internal storage. Quote from docs:

Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.

UPD Example:

File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.


问:
Is there a way to test the size (height and width) of the view using espresso for android Instrumentation test?

I want to check if the visibility and size of the adFrame changes after clicking the buttonShow

```<code>onView(withId(buttonShow)).perform(click());
onView(withId(adFrame)).check(matches(isDisplayed()));
onView(withId(adFrame)).check(?);
</code>```

I am looking for a solution of this ?.

Do we have an assertion that can test the size of the adFrame using the espresso for this Android Instrumentation test?

答:
Given the following matchers:

```<code>class WidthMatcher(private val width: Int = ViewGroup.LayoutParams.MATCH_PARENT) : TypeSafeMatcher<View>() {
    companion object {
        fun withWidth(width: Int) = WidthMatcher(width)
    }

    override fun describeTo(description: Description?) {
        description?.appendText("View with width: ${width}px")
    }

    override fun matchesSafely(item: View): Boolean {
        return item.layoutParams?.width == width
    }
}

class HeightMatcher(private val height: Int = ViewGroup.LayoutParams.MATCH_PARENT) : TypeSafeMatcher<View>() {
    companion object {
        fun withHeight(height: Int) = HeightMatcher(height)
    }

    override fun describeTo(description: Description?) {
        description?.appendText("View with height: ${height}px")
    }

    override fun matchesSafely(item: View): Boolean {
        return item.layoutParams?.height == height
    }
}
</code>```

You just have to check as follows:

```<code>onView(withId(adFrame)).check(matches(withHeight(ViewGroup.LayoutParams.MATCH_PARENT)))
</code>```

You can also check for any size in px. You can convert from dp to px by using:

```<code>/**
 * Converts dp unit to its equivalent in pixels, based on device density.
 *
 * @param dp The value in dp (density independent pixels) unit aim to convert into pixels
 * @return The equivalent int value in px of the provided dp value depending on device density
 */
fun dpToPx(dp: Int): Int {
    (dp * Resources.getSystem().displayMetrics.density).roundToInt()
}

/**
 * This method converts device specific pixels to density independent pixels.
 *
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @return The equivalent int value in dp of the provided px value depending on device density
 */
fun pxToDp(px: Int): Int {
    (px / Resources.getSystem().displayMetrics.density).roundToInt()
}
</code>```

Body:
I want to check if the visibility and size of the adFrame changes after clicking the buttonShow

onView(withId(buttonShow)).perform(click());
onView(withId(adFrame)).check(matches(isDisplayed()));
onView(withId(adFrame)).check(?);

I am looking for a solution of this ?.

Do we have an assertion that can test the size of the adFrame using the espresso for this Android Instrumentation test?

Body:
Given the following matchers:

class WidthMatcher(private val width: Int = ViewGroup.LayoutParams.MATCH_PARENT) : TypeSafeMatcher<View>() {
    companion object {
        fun withWidth(width: Int) = WidthMatcher(width)
    }

    override fun describeTo(description: Description?) {
        description?.appendText("View with width: ${width}px")
    }

    override fun matchesSafely(item: View): Boolean {
        return item.layoutParams?.width == width
    }
}

class HeightMatcher(private val height: Int = ViewGroup.LayoutParams.MATCH_PARENT) : TypeSafeMatcher<View>() {
    companion object {
        fun withHeight(height: Int) = HeightMatcher(height)
    }

    override fun describeTo(description: Description?) {
        description?.appendText("View with height: ${height}px")
    }

    override fun matchesSafely(item: View): Boolean {
        return item.layoutParams?.height == height
    }
}

You just have to check as follows:

onView(withId(adFrame)).check(matches(withHeight(ViewGroup.LayoutParams.MATCH_PARENT)))

You can also check for any size in px. You can convert from dp to px by using:

/**
 * Converts dp unit to its equivalent in pixels, based on device density.
 *
 * @param dp The value in dp (density independent pixels) unit aim to convert into pixels
 * @return The equivalent int value in px of the provided dp value depending on device density
 */
fun dpToPx(dp: Int): Int {
    (dp * Resources.getSystem().displayMetrics.density).roundToInt()
}

/**
 * This method converts device specific pixels to density independent pixels.
 *
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @return The equivalent int value in dp of the provided px value depending on device density
 */
fun pxToDp(px: Int): Int {
    (px / Resources.getSystem().displayMetrics.density).roundToInt()
}


答:
You are printing the wrong variable

check your spelling for initialIncome in each condition

Title: conditions statements. why I can't solve this ( there's so many wrong codes I cannot identify)


问:
Does get-childItem -recurse -include return different objects than get-childItem -recurse?
Here's a simple PowerShell script whose output I cannot explain.

Both foreach loops return System.IO.FileInfo objects, yet the objects of the first loop, when cast to a string, evaluate to a full and absolute path, the objects of the second forach loop to a bare filename only:

```<code>foreach ($file in get-childItem . -recurse -include *.ps1) {
  [string] $name  = $file
   $name

   $file.GetType().FullName
}

foreach ($file in get-childItem . -recurse          *.ps1) {
  [string] $name  = $file
   $name

   $file.GetType().FullName
}
</code>```

I am puzzled over this behavior. Apparantly, the returned objects are different, yet I cannot find any difference between them.

答:
If you run $cmdDef = Get-Command Get-ChildItem and you check $cmdDef.ParameterSet you will see the following:

```<code>    Parameter Name: Path
    ParameterType = System.String[]
    Position = 0
    IsMandatory = False
    IsDynamic = False
    HelpMessage =
    ValueFromPipeline = True
    ValueFromPipelineByPropertyName = True
    ValueFromRemainingArguments = False
    Aliases = {}
    Attributes =

  Parameter Name: Filter
    ParameterType = System.String
    Position = 1
    IsMandatory = False
    IsDynamic = False
    HelpMessage =
    ValueFromPipeline = False
    ValueFromPipelineByPropertyName = False
    ValueFromRemainingArguments = False
    Aliases = {}
    Attributes =
</code>```

Have a look at the Position attribute.

Basically what's happening, in the first example the *.ps1 is passed to the -include parameter, whereas in the second example it is passed to the -filter parameter.

To see the difference between -include and -filter have a look at the documentation of the Get-ChildItem

Body:
Here's a simple PowerShell script whose output I cannot explain.

Both foreach loops return System.IO.FileInfo objects, yet the objects of the first loop, when cast to a string, evaluate to a full and absolute path, the objects of the second forach loop to a bare filename only:

foreach ($file in get-childItem . -recurse -include *.ps1) {
  [string] $name  = $file
   $name

   $file.GetType().FullName
}

foreach ($file in get-childItem . -recurse          *.ps1) {
  [string] $name  = $file
   $name

   $file.GetType().FullName
}

I am puzzled over this behavior. Apparantly, the returned objects are different, yet I cannot find any difference between them.

Body:
If you run $cmdDef = Get-Command Get-ChildItem and you check $cmdDef.ParameterSet you will see the following:

    Parameter Name: Path
    ParameterType = System.String[]
    Position = 0
    IsMandatory = False
    IsDynamic = False
    HelpMessage =
    ValueFromPipeline = True
    ValueFromPipelineByPropertyName = True
    ValueFromRemainingArguments = False
    Aliases = {}
    Attributes =

  Parameter Name: Filter
    ParameterType = System.String
    Position = 1
    IsMandatory = False
    IsDynamic = False
    HelpMessage =
    ValueFromPipeline = False
    ValueFromPipelineByPropertyName = False
    ValueFromRemainingArguments = False
    Aliases = {}
    Attributes =

Have a look at the Position attribute.

Basically what's happening, in the first example the *.ps1 is passed to the -include parameter, whereas in the second example it is passed to the -filter parameter.

To see the difference between -include and -filter have a look at the documentation of the Get-ChildItem


问:
Embedded HTML page from S3 bucket via iframe can't load resources and media files
We have an s3 bucket where we have multiple folders with different small projects that contain basic, static webpages with an index.html entry point.
The plan is to integrate those static pages within a react-app through an iframe. When we do that with an example page, the embedding of the HTML document works but none of the resources get loaded (image files + stylesheets), throwing the following error:

```<code>DOMException: Blocked a frame with origin "BUCKET-DOMAIN" from accessing a cross-origin frame.
</code>```

When looking up that error I usually find people trying to control some parts of the document rendered within the iframe using the postMessage API. In my case however I only want to make sure that the iframe embeds the website as it is shown on the publically available link with all resources.

I've tried making the S3 bucket specifically serve just one static website, thinking that this might influence the way the embedding works. However it's still the same problem.
Pretty sure there's a very simple solution to this and something I'm overlooking.
One potential option would be to give the S3 bucket a subdomain on our site, but I don't see how that would work for example in local development.

答:
If you bucket is public then you can access with your cdn link . Otherwise You will configure it with aws sdk. I think this link will help you

Access files stored on Amazon S3 through web browser

Body:
We have an s3 bucket where we have multiple folders with different small projects that contain basic, static webpages with an index.html entry point.
The plan is to integrate those static pages within a react-app through an iframe. When we do that with an example page, the embedding of the HTML document works but none of the resources get loaded (image files + stylesheets), throwing the following error:

DOMException: Blocked a frame with origin "BUCKET-DOMAIN" from accessing a cross-origin frame.

When looking up that error I usually find people trying to control some parts of the document rendered within the iframe using the postMessage API. In my case however I only want to make sure that the iframe embeds the website as it is shown on the publically available link with all resources.

I've tried making the S3 bucket specifically serve just one static website, thinking that this might influence the way the embedding works. However it's still the same problem.
Pretty sure there's a very simple solution to this and something I'm overlooking.
One potential option would be to give the S3 bucket a subdomain on our site, but I don't see how that would work for example in local development.


问:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in .NET
I got this error when running an application that involves Microsoft Office's Excel. My computer doesn't have a Microsoft Office installed so I think that might be the problem. I referenced some libraries that would help the application run but it didn't help and I still encounter the error.

This is the whole error message:
"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in 'application name'.

Additional information: COM object with CLSID {00024500-0000-0000-C000-000000000046} is either not valid or not registered."

Below are the libraries I used:

Interop.Excel

Interop.KEYCODEV2Lib

Interop.Microsoft.Office.Core

Interop.Office

Interop.VBIDE

Microsoft.Office.Interop.Excel

Microsoft.Vbe.Interop

stdole

System

System.Data

System.Drawing

System.Windows.Form

System.XML

Here is the code block where the error occurs:

```<code>cboCounty.Enabled = False
    If ofdExcel.ShowDialog = DialogResult.OK Then
        txtFile3.Text = ofdExcel.FileName
        btnClear.Enabled = True
        Application.DoEvents()

        myExcel = New Excel.Application
        myExcel.DisplayAlerts = False

        wbLog = myExcel.Workbooks.Open(ofdExcel.FileName, True, True)
        cboCounty.Items.Clear()

        For s As Integer = 1 To wbLog.Worksheets.Count
            wsLog = wbLog.Worksheets(s)
            If UCase(wsLog.Name) <> "SUMMARY" Then
                cboCounty.Items.Add(wsLog.Name)
            End If
        Next

        cboCounty.Enabled = True
    End If
</code>```

On the line myExcel = New Excel.Application where the error occurs.

Could somebody help me with a work around with this.
Thank You.

答:
The idea behind this is that your opening Excel externally as an unhandled object, if you do not have it installed this is your problem.

When using external objects remember to run garbage collection with them as they are on the unmanaged heap and cannot be cleaned automatically from within the .NET framework.

Body:
I got this error when running an application that involves Microsoft Office's Excel. My computer doesn't have a Microsoft Office installed so I think that might be the problem. I referenced some libraries that would help the application run but it didn't help and I still encounter the error.

This is the whole error message:
"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in 'application name'.

Additional information: COM object with CLSID {00024500-0000-0000-C000-000000000046} is either not valid or not registered."

Below are the libraries I used:

Interop.Excel

Interop.KEYCODEV2Lib

Interop.Microsoft.Office.Core

Interop.Office

Interop.VBIDE

Microsoft.Office.Interop.Excel

Microsoft.Vbe.Interop

stdole

System

System.Data

System.Drawing

System.Windows.Form

System.XML

Here is the code block where the error occurs:

cboCounty.Enabled = False
    If ofdExcel.ShowDialog = DialogResult.OK Then
        txtFile3.Text = ofdExcel.FileName
        btnClear.Enabled = True
        Application.DoEvents()

        myExcel = New Excel.Application
        myExcel.DisplayAlerts = False

        wbLog = myExcel.Workbooks.Open(ofdExcel.FileName, True, True)
        cboCounty.Items.Clear()

        For s As Integer = 1 To wbLog.Worksheets.Count
            wsLog = wbLog.Worksheets(s)
            If UCase(wsLog.Name) <> "SUMMARY" Then
                cboCounty.Items.Add(wsLog.Name)
            End If
        Next

        cboCounty.Enabled = True
    End If

On the line myExcel = New Excel.Application where the error occurs.

Could somebody help me with a work around with this.
Thank You.


问:
Are these round-off errors avoidable in the following code?
I am trying to write a program in Matlab to solve a system of linear equations using LU decomposition which employs the use of gauss elimination and hence a lot of arithmetic steps.

The answers are close to the right solution but the round-off errors are pretty high as compared to other languages like Python etc.

For instance, one of the solutions is exactly 3 but I get 2.9877.

I know in-built functions should be used for such trivial things since Matlab is a high-computing language but if I still wanted to do it with loops etc would I always get round-off errors or is there a way to reduce those while doing numerical calculations?

I am attaching the code but it's big and not worth reading. I have still attached it for the sake of completion.
One can just note the use of many arithmetic operations which introduce a lot of round-off errors.

Are these round-off errors intrinsic to Matlab and unavoidable?

```<code>clc
clear
%No of equations is n
n=3;
%WRITING THE Coefficients
A(1,1)=3;
A(1,2)=-0.1;
A(1,3)=-0.2;
B(1)=7.85;

A(2,1)=0.1;
A(2,2)=7;
A(2,3)=-0.3;
B(2)=-19.3;

A(3,1)=0.3;
A(3,2)=-0.2;
A(3,3)=10;
B(3)=71.4;
%Forward Elimination
for i=1:n-1
  for j=i+1:n
    fact=A(j,i)/A(i,i);
    A(j,i)=fact;

    A(j,j:n)=A(j,j:n)-fact*A(i,j:n);
    B(j)=B(j)-fact*B(i);
  end
end
disp(A)
% Calculating d matrix
sum=0;
D(1)=B(1);
for i=2:n
  for j=1:i-1
    sum=sum+A(i,j)*B(j);
    D(i)=B(i)-sum;
  end
end
disp("D =")
disp(transpose(D))

%Back Substitution
X(n)=D(n)/A(n,n);
for z=n-1:-1:1
  sum=0;
  for w=z+1:n
    sum=sum+A(z,w)*X(w);
  end
  X(z)=(D(z)-sum)/(A(z,z));
end
disp("Solution X is:")
disp(transpose(X))
</code>```

答:
Never forget to distrust your coding.

If you comment out line 24 and replace 26 with A(j,i:n)=A(j,i:n)-fact*A(i,i:n); you get the nice solution (long format)

```<code>   3.000000000000000
  -2.500000000000000
   7.000000000000002
</code>```

I am not saying that this is the best fix (it is not), but it clearly shows that roundoff is not guilty. The wrong solution remained close because the system is strongly diagonal-dominant.

Body:
I am trying to write a program in Matlab to solve a system of linear equations using LU decomposition which employs the use of gauss elimination and hence a lot of arithmetic steps.

The answers are close to the right solution but the round-off errors are pretty high as compared to other languages like Python etc.

For instance, one of the solutions is exactly 3 but I get 2.9877.

I know in-built functions should be used for such trivial things since Matlab is a high-computing language but if I still wanted to do it with loops etc would I always get round-off errors or is there a way to reduce those while doing numerical calculations?

I am attaching the code but it's big and not worth reading. I have still attached it for the sake of completion.
One can just note the use of many arithmetic operations which introduce a lot of round-off errors.

Are these round-off errors intrinsic to Matlab and unavoidable?

clc
clear
%No of equations is n
n=3;
%WRITING THE Coefficients
A(1,1)=3;
A(1,2)=-0.1;
A(1,3)=-0.2;
B(1)=7.85;

A(2,1)=0.1;
A(2,2)=7;
A(2,3)=-0.3;
B(2)=-19.3;

A(3,1)=0.3;
A(3,2)=-0.2;
A(3,3)=10;
B(3)=71.4;
%Forward Elimination
for i=1:n-1
  for j=i+1:n
    fact=A(j,i)/A(i,i);
    A(j,i)=fact;

    A(j,j:n)=A(j,j:n)-fact*A(i,j:n);
    B(j)=B(j)-fact*B(i);
  end
end
disp(A)
% Calculating d matrix
sum=0;
D(1)=B(1);
for i=2:n
  for j=1:i-1
    sum=sum+A(i,j)*B(j);
    D(i)=B(i)-sum;
  end
end
disp("D =")
disp(transpose(D))

%Back Substitution
X(n)=D(n)/A(n,n);
for z=n-1:-1:1
  sum=0;
  for w=z+1:n
    sum=sum+A(z,w)*X(w);
  end
  X(z)=(D(z)-sum)/(A(z,z));
end
disp("Solution X is:")
disp(transpose(X))

Body:
Never forget to distrust your coding.

If you comment out line 24 and replace 26 with A(j,i:n)=A(j,i:n)-fact*A(i,i:n); you get the nice solution (long format)

   3.000000000000000
  -2.500000000000000
   7.000000000000002

I am not saying that this is the best fix (it is not), but it clearly shows that roundoff is not guilty. The wrong solution remained close because the system is strongly diagonal-dominant.


问:
How to change Developer-Name & Company-Name in Xcode?
```<code>//
//  MyViewController.h
//  MyApp
//
//  Created by **Developer-Name** on 11. 12. 27..
//  Copyright (c) 2011 **Company-Name**. All rights reserved.
//
</code>```

I want to change them. How can I change them?

答:
On Mac OS 12.x, these options are little bit different. Follow the below steps to change the user name.

Go to System Preference > Users & Groups.

Click the clock to make changes.

Select the User which we need to change.

Right click on User > Advanced Options.

Change the full name under In Advanced options > Full Name > OK.

Body:
//
//  MyViewController.h
//  MyApp
//
//  Created by **Developer-Name** on 11. 12. 27..
//  Copyright (c) 2011 **Company-Name**. All rights reserved.
//

I want to change them. How can I change them?


问:
Karate Java String interpolation
I am trying to call a java method that accepts a string as a parameter inside a karate script, and interpolate a value defined in karate in that string.

In my case it's a simple database INSERT statement, for example:

```<code>INSERT INTO A(id, time, value) VALUES(1, '2099-05-10 18:20:18.674 UTC', 'test')
</code>```

The script itself looks as follows:

```<code>Background:
    * def db = Java.type('com.example.DbTestHelper')
    * def offsetDateTime = Java.type('java.time.OffsetDateTime')
    * def zoneId = Java.type('java.time.ZoneId')

  Scenario: testScenario
    * def t = offsetDateTime.now(zoneId.of("Europe/Berlin")).plusDays(1)
    * def row = db.insertRow("INSERT INTO A(id, time, value) VALUES(123, #t, 'test')")
</code>```

And the insertRow method looks as follows:

```<code>    @JvmStatic
    fun insertRow(vararg strings: String) {
        jdbc.batchUpdate(*strings)
    }
</code>```

I have tried multiple combinations of setting value t like #(t), #t, "#(t)" etc. Unfortunately, none of them worked resulting in various javascript parse errors even before the java method gets invoked.

What would be the right way to achieve that? Is it even possible?

答:
First read this: https://github.com/karatelabs/karate#rules-for-embedded-expressions

The good news is that in 1.0 onwards Karate supports ES6 JS string interpolation within backticks:

```<code>* def foo = 1
* def txt = `hello ${foo}`
* match txt == 'hello 1'
</code>```

Of course string concatenation will always work. You just have to think of most Karate syntax especially when you call Java - as being nothing but plain old JavaScript.

```<code>* db.insertRow("INSERT INTO A(id, time, value) VALUES(123, " + t + ", 'test')")
</code>```

I think you will be able to proceed now.

Title: Karate Java String interpolation

Body:
I am trying to call a java method that accepts a string as a parameter inside a karate script, and interpolate a value defined in karate in that string.

In my case it's a simple database INSERT statement, for example:

INSERT INTO A(id, time, value) VALUES(1, '2099-05-10 18:20:18.674 UTC', 'test')

The script itself looks as follows:

Background:
    * def db = Java.type('com.example.DbTestHelper')
    * def offsetDateTime = Java.type('java.time.OffsetDateTime')
    * def zoneId = Java.type('java.time.ZoneId')

  Scenario: testScenario
    * def t = offsetDateTime.now(zoneId.of("Europe/Berlin")).plusDays(1)
    * def row = db.insertRow("INSERT INTO A(id, time, value) VALUES(123, #t, 'test')")

And the insertRow method looks as follows:

    @JvmStatic
    fun insertRow(vararg strings: String) {
        jdbc.batchUpdate(*strings)
    }

I have tried multiple combinations of setting value t like #(t), #t, "#(t)" etc. Unfortunately, none of them worked resulting in various javascript parse errors even before the java method gets invoked.

What would be the right way to achieve that? Is it even possible?

Body:
First read this: https://github.com/karatelabs/karate#rules-for-embedded-expressions

The good news is that in 1.0 onwards Karate supports ES6 JS string interpolation within backticks:

* def foo = 1
* def txt = `hello ${foo}`
* match txt == 'hello 1'

Of course string concatenation will always work. You just have to think of most Karate syntax especially when you call Java - as being nothing but plain old JavaScript.

* db.insertRow("INSERT INTO A(id, time, value) VALUES(123, " + t + ", 'test')")

I think you will be able to proceed now.


问:
Installing MSSQL functions in PHP
I'm trying to connect to my SQL server through PHP. Obviously using MySQL php functions do not work, how do I go about installing MSSQL functions for PHP on OSX? After exhausting google, I thought there would be a lot more tutorials are resources available which suggests to me this isn't the best way to connect to an SQL server.

Thank you in advance!

答:
From the PHP Manual...

To use the MSSQL extension on Unix/Linux, you first need to build and
  install the FreeTDS library. Source code and installation instructions
  are available at the FreeTDS home page: » http://www.freetds.org/

I have never even tried to do this but just had a look and it seems to be fairly comprehensively documented - although it does assume you know a little bit about building from source on *nix... You will also need gcc or similar...

Title: Installing MSSQL functions in PHP