问:
Powershell Script that takes username and checks security groups
I want to create a powershell script that checks a users profile which security groups the user belongs to inside the active directory. Then I want to write it to a file.
I'm having trouble solving this problem.

Example of the expected output.

User1

Security Groups

Domain users
Domain admins...

User2

Security Groups

Domain users
Enterprise admins

```<code>New-Item "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"

$users = @("User1", "User2", "User3", "User4")

foreach ($user in $users){
Get-ADPrincipalGroupMembership $user | sort name | select name | Out-File "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
}
</code>```

答:
I think it will be something like this:

```<code>  $users = @("User1", "User2", "User3", "User4")
   $file= "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
""| Out-File $file; #Clear content of file
foreach ($user in $users){ ""| Out-File -Append $file; #Add a new line
    "$User is in Security groups:"| Out-File -Append $file; # making a Title
    "---------------------------------"| Out-File -Append $file; # making a Title
    Get-ADPrincipalGroupMembership $user | sort Name | ft -HideTableHeaders Name | Out-File -Append $file #Writing data
    }
</code>```

The txt file will be replaced each time, when running script.

Body:
I want to create a powershell script that checks a users profile which security groups the user belongs to inside the active directory. Then I want to write it to a file.
I'm having trouble solving this problem.

Example of the expected output.

User1

Security Groups

Domain users
Domain admins...

User2

Security Groups

Domain users
Enterprise admins

New-Item "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"

$users = @("User1", "User2", "User3", "User4")

foreach ($user in $users){
Get-ADPrincipalGroupMembership $user | sort name | select name | Out-File "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
}

Body:
I think it will be something like this:

  $users = @("User1", "User2", "User3", "User4")
   $file= "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
""| Out-File $file; #Clear content of file
foreach ($user in $users){ ""| Out-File -Append $file; #Add a new line
    "$User is in Security groups:"| Out-File -Append $file; # making a Title
    "---------------------------------"| Out-File -Append $file; # making a Title
    Get-ADPrincipalGroupMembership $user | sort Name | ft -HideTableHeaders Name | Out-File -Append $file #Writing data
    }

The txt file will be replaced each time, when running script.


来源: stackexchange

问:
Espresso test Fail
I am doing some Espresso testing in Android. The test is failing with this error:

java.lang.ClassCastException:
androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity
cannot be cast to com.stavro_xhardha.pockettreasure.MainActivity

This is my test method:

@Test
fun toolbarTitle_shouldContainCorrectInput() {
    val mockNavController = mock(NavController::class.java)
    val fragmentScenario = launchFragmentInContainer<SetupFragment>()
    fragmentScenario.onFragment {
        Navigation.setViewNavController(it.view!! , mockNavController)
    }
    onView(withId(R.id.toolbar)).check(matches(withText("Pick your country")))
}
```
<p>But the error doesn't come from the Test class but from my Fragment under test.
The crash is executed in this line of code:</p>
```override fun onStart() {
    super.onStart()
    (activity!! as MainActivity).supportActionBar?.hide() //here
}
```

What I don't get here is that I face no error when I run the app normally without test.

答:
Here is the full answer.

About launchFragmentInContainer - it takes the given fragment and launches it inside of an internal EmptyFragmentActivity class — placing the fragment inside of the root view container.

So, it should be used to check fragment only, which doesn't depend on it's parent activity.

In your case, you try to hide an action bar inside the fragment you're testing. But in test your fragment will not be launched in MainActivity.

If you want to check only the fragment, instead of (activity!! as MainActivity).supportActionBar?.hide() you need to write something like this:

if(activity!! is MainActivity){
    activity?.supportActionBar?.hide()
}
```

Or you should write the test for your MainActivity or where you use your fragment

ContentLicense: CC BY-SA 4.0

Title: Espresso test Fail

Body:
I am doing some Espresso testing in Android. The test is failing with this error:

java.lang.ClassCastException:
androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity
cannot be cast to com.stavro_xhardha.pockettreasure.MainActivity

This is my test method:

@Test
fun toolbarTitle_shouldContainCorrectInput() {
    val mockNavController = mock(NavController::class.java)
    val fragmentScenario = launchFragmentInContainer<SetupFragment>()
    fragmentScenario.onFragment {
        Navigation.setViewNavController(it.view!! , mockNavController)
    }
    onView(withId(R.id.toolbar)).check(matches(withText("Pick your country")))
}

But the error doesn't come from the Test class but from my Fragment under test.
The crash is executed in this line of code:

override fun onStart() {
    super.onStart()
    (activity!! as MainActivity).supportActionBar?.hide() //here
}

What I don't get here is that I face no error when I run the app normally without test.

Body:
Here is the full answer.

About launchFragmentInContainer - it takes the given fragment and launches it inside of an internal EmptyFragmentActivity class — placing the fragment inside of the root view container.

So, it should be used to check fragment only, which doesn't depend on it's parent activity.

In your case, you try to hide an action bar inside the fragment you're testing. But in test your fragment will not be launched in MainActivity.

If you want to check only the fragment, instead of (activity!! as MainActivity).supportActionBar?.hide() you need to write something like this:

if(activity!! is MainActivity){
    activity?.supportActionBar?.hide()
}

Or you should write the test for your MainActivity or where you use your fragment


问:
DOMDocument appendXML with special characters
I am retreiving some html strings from my database and I would like to parse these strings into my DOMDocument. The problem is, that the DOMDocument gives warnings at special characters.

Warning:
  DOMDocumentFragment::appendXML()
  [domdocumentfragment.appendxml]:
  Entity: line 2: parser error : Entity
  'nbsp' not defined in
  page.php
  on line 189

I wonder why and I wonder how to solve this. This are some code fragments of my page. How can I fix these kind of warnings?

```<code>$doc = new DOMDocument();

// .. create some elements first, like some divs and a h1 ..

while($row = mysql_fetch_array($result))
{
    $messageEl = $doc->createDocumentFragment();
    $messageEl->appendXML($row['message']); // gives it's warnings here!

    $otherElement->appendChild($messageEl);
}

echo $doc->saveHTML();
</code>```

I also found something about validation, but when I apply that, my page won't load anymore. The code I tried for that was something like this.

```<code>$implementation = new DOMImplementation();
$dtd = $implementation->createDocumentType('html','-//W3C//DTD XHTML 1.0 Transitional//EN','http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd');

$doc = $implementation->createDocument('','',$dtd);
$doc->validateOnParse = true;
$doc->formatOutput = true;

// in the same whileloop, I used the following:
$messageEl = $doc->createDocumentFragment();
$doc->validate(); // which stopped my code, but error- and warningless.
$messageEl->appendXml($row['message']);
</code>```

Thanks in advance!

答:
Here's another approach, because we did not want possibly slow network requests (or any network requests at all resulting from user input):

```<code><?php
$document = new \DOMDocument();
$document->loadHTML('<html><body></body></html>');

$html = '<b>test </b>';
$fragment = $document->createDocumentFragment();

$html = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE document [
<!ENTITY nbsp   " " >
]>
<document>'.$html.'</document>';

$newdom = new \DOMDocument();
$newdom->loadXML($html, LIBXML_HTML_NOIMPLIED | LIBXML_NOCDATA | LIBXML_NOENT | LIBXML_NONET | LIBXML_NOBLANKS);

foreach ($newdom->documentElement->childNodes as $childnode)
  $fragment->appendChild($fragment->ownerDocument->importNode($childnode, TRUE));

$document->getElementsByTagName('body')[0]->appendChild($fragment);

echo $document->saveHTML();
</code>```

Here we include the relevant part of the DTD, specifically the latin1 entity definitions as an internal DOCTYPE definition. Then the HTML content is wrapped in a document element to be able to process a sequence of child elements. The parsed nodes are then imported and added into the target DOM.

Our actual implementation uses file_get_contents to load the DTD containing all entity definitions from a local file.

ContentLicense: CC BY-SA 2.5

Body:
I am retreiving some html strings from my database and I would like to parse these strings into my DOMDocument. The problem is, that the DOMDocument gives warnings at special characters.

Warning:
  DOMDocumentFragment::appendXML()
  [domdocumentfragment.appendxml]:
  Entity: line 2: parser error : Entity
  'nbsp' not defined in
  page.php
  on line 189

I wonder why and I wonder how to solve this. This are some code fragments of my page. How can I fix these kind of warnings?

$doc = new DOMDocument();

// .. create some elements first, like some divs and a h1 ..

while($row = mysql_fetch_array($result))
{
    $messageEl = $doc->createDocumentFragment();
    $messageEl->appendXML($row['message']); // gives it's warnings here!

    $otherElement->appendChild($messageEl);
}

echo $doc->saveHTML();

I also found something about validation, but when I apply that, my page won't load anymore. The code I tried for that was something like this.

$implementation = new DOMImplementation();
$dtd = $implementation->createDocumentType('html','-//W3C//DTD XHTML 1.0 Transitional//EN','http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd');

$doc = $implementation->createDocument('','',$dtd);
$doc->validateOnParse = true;
$doc->formatOutput = true;

// in the same whileloop, I used the following:
$messageEl = $doc->createDocumentFragment();
$doc->validate(); // which stopped my code, but error- and warningless.
$messageEl->appendXml($row['message']);

Thanks in advance!

Body:
Here's another approach, because we did not want possibly slow network requests (or any network requests at all resulting from user input):

<?php
$document = new \DOMDocument();
$document->loadHTML('<html><body></body></html>');

$html = '<b>test&nbsp;</b>';
$fragment = $document->createDocumentFragment();

$html = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE document [
<!ENTITY nbsp   "&#160;" >
]>
<document>'.$html.'</document>';

$newdom = new \DOMDocument();
$newdom->loadXML($html, LIBXML_HTML_NOIMPLIED | LIBXML_NOCDATA | LIBXML_NOENT | LIBXML_NONET | LIBXML_NOBLANKS);

foreach ($newdom->documentElement->childNodes as $childnode)
  $fragment->appendChild($fragment->ownerDocument->importNode($childnode, TRUE));

$document->getElementsByTagName('body')[0]->appendChild($fragment);

echo $document->saveHTML();

Here we include the relevant part of the DTD, specifically the latin1 entity definitions as an internal DOCTYPE definition. Then the HTML content is wrapped in a document element to be able to process a sequence of child elements. The parsed nodes are then imported and added into the target DOM.

Our actual implementation uses file_get_contents to load the DTD containing all entity definitions from a local file.


问:
Nested defaultdict of defaultdict
Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)

I want to be able to do:

```<code>x = defaultdict(...stuff...)
x[0][1][0]
{}
</code>```

So, I can do x = defaultdict(defaultdict), but that's only a second level:

```<code>x[0]
{}
x[0][0]
KeyError: 0
</code>```

There are recipes that can do this. But can it be done simply just using the normal defaultdict arguments?

Note this is asking how to do an infinite-level recursive defaultdict, so it's distinct to Python: defaultdict of defaultdict?, which was how to do a two-level defaultdict.

I'll probably just end up using the bunch pattern, but when I realized I didn't know how to do this, it got me interested.

答:
I would also propose more OOP-styled implementation, which supports infinite nesting as well as properly formatted repr.

```<code>class NestedDefaultDict(defaultdict):
    def __init__(self, *args, **kwargs):
        super(NestedDefaultDict, self).__init__(NestedDefaultDict, *args, **kwargs)

    def __repr__(self):
        return repr(dict(self))
</code>```

Usage:

```<code>my_dict = NestedDefaultDict()
my_dict['a']['b'] = 1
my_dict['a']['c']['d'] = 2
my_dict['b']

print(my_dict)  # {'a': {'b': 1, 'c': {'d': 2}}, 'b': {}}
</code>```

Title: Nested defaultdict of defaultdict

Body:
Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)

I want to be able to do:

x = defaultdict(...stuff...)
x[0][1][0]
{}

So, I can do x = defaultdict(defaultdict), but that's only a second level:

x[0]
{}
x[0][0]
KeyError: 0

There are recipes that can do this. But can it be done simply just using the normal defaultdict arguments?

Note this is asking how to do an infinite-level recursive defaultdict, so it's distinct to Python: defaultdict of defaultdict?, which was how to do a two-level defaultdict.

I'll probably just end up using the bunch pattern, but when I realized I didn't know how to do this, it got me interested.

Body:
I would also propose more OOP-styled implementation, which supports infinite nesting as well as properly formatted repr.

class NestedDefaultDict(defaultdict):
    def __init__(self, *args, **kwargs):
        super(NestedDefaultDict, self).__init__(NestedDefaultDict, *args, **kwargs)

    def __repr__(self):
        return repr(dict(self))

Usage:

my_dict = NestedDefaultDict()
my_dict['a']['b'] = 1
my_dict['a']['c']['d'] = 2
my_dict['b']

print(my_dict)  # {'a': {'b': 1, 'c': {'d': 2}}, 'b': {}}


问:
How to code a substr version that holds leading zeros in numeric values (in R)?
While preparing a function that converts normalized double precision numbers to decimal numbers, I needed something like following:

```<code>substr(01001011, 2, 5) # what is in fact:"0010" (because leading 0 is ignored)
substr(01001011, 2, 5) # what I want:"1001"
substr("01001011", 2, 5) # "1001"; gives what I want BUT the following:
</code>```

In substr("01001011", 2, 5), it is impossible (for me) to turn it to a function since input=01001011 and double quote concatenations very very problematic. Each time the user must manually enter the value of argument not in in function's call but also in the body of the function where substr(...) part is located.

The problem caused by the fact that 01001011 is hold as numeric and hence all leading 0s are ignored.

```<code>01001011 # [1] 1001011
class(01001011) # "numeric"

substrCorrectly <- function(x) {
substr("x", 2, 5) }
</code>```

For example, for number "01001011";

```<code>substrCorrectly <- function(x) {
substr("01001011", 2, 5) }
substrCorrectly(01001011) # "1001"
</code>```

This function is definitely very ugly, and against the notion of function: Each time user must change the body of function before applying it!

Any idea?

More examples:

```<code>substr(000101001011, 1, 4) # "1010"; but what I want is 0001 here.
substr(10001, 1, 2) # "10" and what I want (10) coincides since 1 is leading.
</code>```

答:
You can use formatC that will allows to keep first 0s

```<code>substrCorrectly <- function(x) {
  x <- formatC(x, flag="0", width=8, format="d")
  substr(x, 2, 5)
}
substrCorrectly(01001011) # "1001"
</code>```

Body:
While preparing a function that converts normalized double precision numbers to decimal numbers, I needed something like following:

substr(01001011, 2, 5) # what is in fact:"0010" (because leading 0 is ignored)
substr(01001011, 2, 5) # what I want:"1001"
substr("01001011", 2, 5) # "1001"; gives what I want BUT the following:

In substr("01001011", 2, 5), it is impossible (for me) to turn it to a function since input=01001011 and double quote concatenations very very problematic. Each time the user must manually enter the value of argument not in in function's call but also in the body of the function where substr(...) part is located.

The problem caused by the fact that 01001011 is hold as numeric and hence all leading 0s are ignored.

01001011 # [1] 1001011
class(01001011) # "numeric"

substrCorrectly <- function(x) {
substr("x", 2, 5) }

For example, for number "01001011";

substrCorrectly <- function(x) {
substr("01001011", 2, 5) }
substrCorrectly(01001011) # "1001"

This function is definitely very ugly, and against the notion of function: Each time user must change the body of function before applying it!

Any idea?

More examples:

substr(000101001011, 1, 4) # "1010"; but what I want is 0001 here.
substr(10001, 1, 2) # "10" and what I want (10) coincides since 1 is leading.

Body:
You can use formatC that will allows to keep first 0s

substrCorrectly <- function(x) {
  x <- formatC(x, flag="0", width=8, format="d")
  substr(x, 2, 5)
}
substrCorrectly(01001011) # "1001"


问:
Install Kubectl Plugin on Windows
Question: What are the steps to install a kubectl plugin on Windows?

I have written a plugin standalone binary that I would like to invoke from within kubectl (following the instructions in https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/)

The documentation for installation states to perform the following steps:
"A plugin is nothing more than a standalone executable file, whose name begins with kubectl-. To install a plugin, simply move this executable file to anywhere on your PATH."

This works fine on Mac and Linux, but performing those instructions on Windows does not seem to work. Running "kubectl plugin list" does not list my plugin and I cannot invoke it from within kubectl. I even tried adding my binary to the .kube directory autogenerated by kubectl, and it does not detect the plugin.

Several discussions on github reference this issue, without providing a response of how to install a kubectl plugin on Windows (ex: https://github.com/kubernetes/kubernetes/issues/73289). And after performing a lengthy google/stackoverflow search, there don't seem to be any tutorials/solutions that I (or my teammates) could locate. Any help would be much appreciated! Thank you.

答:
In my case I don't have an issue with installing a plugin on Windows 10 machine (by simply including it on my PATH). Here is the output of 'kubectl plugin list':

```<code>c:\opt\bin>kubectl plugin list

The following kubectl-compatible plugins are available:

c:\opt\bin\kubectl-getbuildver.bat

  - warning: c:\opt\bin\kubectl-getbuildver.bat identified as a kubectl plugin, but it is not executable

c:\opt\bin\kubectl-hello.exe

c:\opt\bin\kubectl-helloworld.p6

  - warning: c:\opt\bin\kubectl-helloworld.p6 identified as a kubectl plugin, but it is not executable

error: 2 plugin warnings were found
</code>```

Instead I'm encountering a known github issue: 'not supported by windows' error, while invoking my plugin with kubectl (v1.13.4).

```<code>c:\opt\bin>kubectl hello

not supported by windows

c:\opt\bin>kubectl-hello.exe

Tuesday
</code>```

*kubectl-hello.exe - is console application written in csharp. I tried also to use Windows batch file and Perl6 program as plugins, but none of these worked out on Windows.

Title: Install Kubectl Plugin on Windows

Body:
In my case I don't have an issue with installing a plugin on Windows 10 machine (by simply including it on my PATH). Here is the output of 'kubectl plugin list':

c:\opt\bin>kubectl plugin list

The following kubectl-compatible plugins are available:

c:\opt\bin\kubectl-getbuildver.bat

  - warning: c:\opt\bin\kubectl-getbuildver.bat identified as a kubectl plugin, but it is not executable

c:\opt\bin\kubectl-hello.exe

c:\opt\bin\kubectl-helloworld.p6

  - warning: c:\opt\bin\kubectl-helloworld.p6 identified as a kubectl plugin, but it is not executable

error: 2 plugin warnings were found

Instead I'm encountering a known github issue: 'not supported by windows' error, while invoking my plugin with kubectl (v1.13.4).

c:\opt\bin>kubectl hello

not supported by windows

c:\opt\bin>kubectl-hello.exe

Tuesday

*kubectl-hello.exe - is console application written in csharp. I tried also to use Windows batch file and Perl6 program as plugins, but none of these worked out on Windows.


问:
Issue while working with SAP Hana History Tables
I was trying to understand how history tables work in HANA.

I have a query whether the following requirement can be achieved using history table.

Suppose, I've a table which maintains site and article wise STOCK.
The STOCK gets updated according to the change in inventory.

Now, if I want the current as well as the previous picture of site-article wise stock can I use the history table for same.
I created a history table and inserted a row in it which gives output :

```<code>SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF utctimestamp '2019-05-22 12:36:17.909';
</code>```

I updated the stock and re-run the query :

```<code>SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF utctimestamp '2019-05-22 12:37:38.55'
</code>```

Now, I want to get the earlier and the current picture of my stock in the same query.

Is that feasible to achieve this ?

答:
May be you can achieve this by Union query.

```<code>    SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF utctimestamp '2019-05-22 12:36:17.909'
    union
    SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF now();
</code>```

Try this :)

Body:
I was trying to understand how history tables work in HANA.

I have a query whether the following requirement can be achieved using history table.

Suppose, I've a table which maintains site and article wise STOCK.
The STOCK gets updated according to the change in inventory.

Now, if I want the current as well as the previous picture of site-article wise stock can I use the history table for same.
I created a history table and inserted a row in it which gives output :

SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF utctimestamp '2019-05-22 12:36:17.909';

I updated the stock and re-run the query :

SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF utctimestamp '2019-05-22 12:37:38.55'

Now, I want to get the earlier and the current picture of my stock in the same query.

Is that feasible to achieve this ?

Body:
May be you can achieve this by Union query.

    SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF utctimestamp '2019-05-22 12:36:17.909'
    union
    SELECT site,article,stock FROM PH_STOCK_HISTORY AS OF now();

Try this :)


问:
Java Codemodel - Annotate a method or class
I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:

```<code>JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
</code>```

When I run (assume all other necessary codes are there);

```<code>public String getCustomerInfo() { }
</code>```

But I want to annotate above method like this:

```<code>@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }
</code>```

For which I tried below methods:
method.annotate(...) and method.annotate2(...)

But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.

Say I should be able to do like this: method.annotate("Path").

Can anyone help me?

答:
```<code>public class AppendJavaCode {

    public List<String> getExistingFileData(String permFile, String newPojoClassPath) throws Exception {

        System.out.println("Existing File DATA...............................................\n");
        List<String> listListFileAdd = new ArrayList<String>();
        try {
        BufferedReader in = new BufferedReader(new FileReader(permFile));
        List<String> listListFile = new ArrayList<String>();
        String str = in.readLine();
        while (str!= null) {
            listListFile.add(str);
            str = in.readLine();
            }
        in.close();

        int ii=0;
        for(int i=0;i<listListFile.size();i++)
        {
            if(i==(listListFile.size()-1))
            {

            }
            else
            {
                listListFileAdd.add(listListFile.get(i));
                if(listListFile.get(i).contains("import") && ii==0)
                {
                    listListFileAdd.add(newPojoClassPath);
                    ii++;
                }
            }
        }

        for(String s:listListFileAdd)
        {
            System.out.print(s+"\n");
        }

        } catch (Exception e) {
        }
        return listListFileAdd;
    }

    public List<String> getNewFileData(String tmpFile) throws Exception {

        System.out.println("New File DATA...............................................\n");
        List<String> listListFileAdd = new ArrayList<String>();
        try {
        BufferedReader in = new BufferedReader(new FileReader(tmpFile));
        List<String> listListFile = new ArrayList<String>();
        String str = in.readLine();
        while (str!= null) {
            listListFile.add(str);
            str = in.readLine();
            }
        in.close();

        int ind=0;
        for(int i=0;i<listListFile.size();i++)
        {
            if(listListFile.get(i).contains("RequestMapping(va"))
            {
                ind = i;
                break;
            }
        }
        for(int i=0;i<listListFile.size();i++)
        {
            if(i>=ind)
            {
                listListFileAdd.add(listListFile.get(i));
            }
        }

        for(String s:listListFileAdd)
        {
            System.out.print(s+"\n");
        }

        } catch (Exception e) {
        }
        return listListFileAdd;
    }

    public void appendDataInFile(String permFile, List<String> existedData, List<String> newData) throws Exception {

        try {
            // create a writer for permFile
            BufferedWriter out = new BufferedWriter(new FileWriter(permFile, false));

            for(int i=0;i<existedData.size();i++)
            {
                out.write(existedData.get(i)+"\n");
            }
            for(int i=0;i<newData.size();i++)
            {
                out.write(newData.get(i)+"\n");
            }

            out.close();

            } catch (Exception e) {
            }
    }

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

          AppendJavaCode appendJavaCode = new AppendJavaCode();
          // Define two filenames:
          String permFile = "E:/ViewUrlController.java";
          String tmpFile =  "E:/ViewUrlControllerGen.java";
          String newPojoClassPath = "import com.discom.springmvc.pojo.Studentinfo;";

          List<String> existedData = appendJavaCode.getExistingFileData(permFile,newPojoClassPath);
          List<String> newData = appendJavaCode.getNewFileData(tmpFile);
          appendJavaCode.appendDataInFile(permFile, existedData, newData);

          }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:

JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");

When I run (assume all other necessary codes are there);

public String getCustomerInfo() { }

But I want to annotate above method like this:

@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }

For which I tried below methods:
method.annotate(...) and method.annotate2(...)

But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.

Say I should be able to do like this: method.annotate("Path").

Can anyone help me?


问:
Autofocus first form element inside active div in a form
I have a form with several divs (10+) and I display only 1 at a time whereas the rest are set to display: hidden.When I click on the Next button, the current div gets hidden and the next one gets visible. There is a Previous button too.

Is there a way to focus the first form element of the currently visible div using JavaScript?

HTML Structure is as follows:

```<code><form id = "myForm">
<div id="div1">
<!-------Div can hav 2 cols---->
    <div class = "row">
        <div class= "col">
            <input autofocus>
        </div>
        <div class = "col">
            <select></select>
        </div>
    </div>
</div>
<div id="div2" style = "display: none;">
<!-------Or Div can have 1 col---->
    <div class = "row">
        <div class = "col">
             <!-------First element can be input---->
            <input>
        </div>
    </div>
</div>
<div id="div3" style = "display: none;">
    <div class = "row">
        <div class = "col">
             <!-------Or First element can be select---->
             <select> </select>
             <input>
        </div>
    </div>
</div>
<!-------More Divs---->
</form>
</code>```

The autofocus works on the first element but then I need to focus on the first elements of the rest of the divs inside the form using JavaScript.

答:
To do this, you'd have to use css :visible modifier and call this code everytime the change happens

Using jquery:

```<code>function focusOnVisible(){
    $("#myForm input:visible, #myForm input:visible").first().focus()
}
</code>```

And then call this on pageload and after next button is clicked

```<code>$('document').ready(focusOnVisible);
$('.next').click(focusOnVisible);
</code>```

Body:
I have a form with several divs (10+) and I display only 1 at a time whereas the rest are set to display: hidden.When I click on the Next button, the current div gets hidden and the next one gets visible. There is a Previous button too.

Is there a way to focus the first form element of the currently visible div using JavaScript?

HTML Structure is as follows:

<form id = "myForm">

            <input autofocus>

            <select></select>

            <input>

             <select> </select>
             <input>

</form>

The autofocus works on the first element but then I need to focus on the first elements of the rest of the divs inside the form using JavaScript.

Body:
To do this, you'd have to use css :visible modifier and call this code everytime the change happens

Using jquery:

function focusOnVisible(){
    $("#myForm input:visible, #myForm input:visible").first().focus()
}

And then call this on pageload and after next button is clicked

$('document').ready(focusOnVisible);
$('.next').click(focusOnVisible);


问:
C# strange with DateTime
I got some strange result for:

```<code>Console.WriteLine(new DateTime(1296346155).ToString());
</code>```

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

答:
That constructor is not what you want as the time is not measured in ticks.</p>

```<code>DateTime start = new DateTime(1970,1,1,0,0,0,0);
start = start.AddSeconds(1296346155).ToLocalTime();
Console.WriteLine(start);
// You don't need to use ToString() in a Console.WriteLine call
</code>```

Title: C# strange with DateTime

Body:
I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

Body:
That constructor is not what you want as the time is not measured in ticks.

DateTime start = new DateTime(1970,1,1,0,0,0,0);
start = start.AddSeconds(1296346155).ToLocalTime();
Console.WriteLine(start);
// You don't need to use ToString() in a Console.WriteLine call


问:
ASP.NET Core 2.2 - Password reset not working on Azure (Invalid token)
I have an ASP.NET Core 2.2 application running on multiple instances on an Azure Web App; it uses EF Core 2.2 and ASP.NET Identity.

Everything works fine except the Password Reset flow where a user receives a link with token per e-mail and needs to choose a new password by clicking on that link. It works perfectly locally, but on Azure it always fails with an "Invalid Token" error.

The tokens are HTML encoded and decoded as necessary; and I have checks in place to ensure they match those on the database; URL encoding is not the issue.

I've configured DataProtection to store the keys to an Azure Blob storage, but to no avail.
The keys are stored  in the blob store all right, but I still get an "Invalid Token" error.

Here's my set up on Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // This needs to happen before "AddMvc"
    // Code for this method shown below
    AddDataProtecion(services);

    services.AddDbContext<MissDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    var sp = services.BuildServiceProvider();

    services.ConfigureApplicationCookie(x =>
    {
        x.Cookie.Name = ".MISS.SharedCookie";
        x.ExpireTimeSpan = TimeSpan.FromHours(8);
        // We need to set the cookie's DataProtectionProvider to ensure it will get stored in the azure blob storage
        x.DataProtectionProvider = sp.GetService<IDataProtectionProvider>();
    });

    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<MissDbContext>()
        .AddDefaultTokenProviders();

    // https://tech.trailmax.info/2017/07/user-impersonation-in-asp-net-core/
    services.Configure<SecurityStampValidatorOptions>(options =>
    {
        options.ValidationInterval = TimeSpan.FromMinutes(10);
        options.OnRefreshingPrincipal = context =>
        {
            var originalUserIdClaim = context.CurrentPrincipal.FindFirst("OriginalUserId");
            var isImpersonatingClaim = context.CurrentPrincipal.FindFirst("IsImpersonating");
            if (isImpersonatingClaim?.Value == "true" && originalUserIdClaim != null)
            {
                context.NewPrincipal.Identities.First().AddClaim(originalUserIdClaim);
                context.NewPrincipal.Identities.First().AddClaim(isImpersonatingClaim);
            }
            return Task.FromResult(0);
        };
    });

     // some more initialisations here
}
```

<p>And here is the <code>AddDataProtection</code> method:</p>

<pre class="lang-cs prettyprint-override"><code>/// <summary>
/// Add Data Protection so that cookies don't get invalidated when swapping slots.
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
void AddDataProtecion(IServiceCollection services)
{
    var sasUrl = Configuration.GetValue<string>("DataProtection:SaSUrl");
    var containerName = Configuration.GetValue<string>("DataProtection:ContainerName");
    var applicationName = Configuration.GetValue<string>("DataProtection:ApplicationName");
    var blobName = Configuration.GetValue<string>("DataProtection:BlobName");
    var keyIdentifier = Configuration.GetValue<string>("DataProtection:KeyVaultIdentifier");

    if (sasUrl == null || containerName == null || applicationName == null || blobName == null)
        return;

    var storageUri = new Uri($"{sasUrl}");

    var blobClient = new CloudBlobClient(storageUri);

    var container = blobClient.GetContainerReference(containerName);
    container.CreateIfNotExistsAsync().GetAwaiter().GetResult();

    applicationName = $"{applicationName}-{Environment.EnvironmentName}";
    blobName = $"{applicationName}-{blobName}";

    services.AddDataProtection()
        .SetApplicationName(applicationName)
        .PersistKeysToAzureBlobStorage(container, blobName);
}
</code>```

I've also tried persisting the keys to the DbContext, but the result is the same: keys are stored, but I still get anInvalid token message when attempting a password reset, Every. Single. Time.

the Request Password Reset method

public async Task RequestPasswordReset(string emailAddress, string ip, Request httpRequest)
{
    var user = await _userManager.FindByEmailAsync(emailAddress);

    var resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

    var resetRequest = new PasswordResetRequest
    {
        CreationDate = DateTime.Now,
        ExpirationDate = DateTime.Now.AddDays(1),
        UserId = user.Id,
        Token = resetToken,
        IP = ip
    };

    _context.PasswordResetRequests.Add(resetRequest);
    await _context.SaveChangesAsync();

    await SendPasswordResetEmail(user, resetRequest, httpRequest);
}
```

<h3>The Reset password method</h3>

<p>Once the user requests a password reset, they receive an e-mail with a link and a token; here's how I attempt to reset the user's password after the user clicks on that link:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<IdentityResult> ResetPassword(string token, string password)
{
    // NO PROBLEM HERE - The received token matches with the one in the Db
    var resetRequest = await _context.PasswordResetRequests
        .AsNoTracking()
        .FirstOrDefaultAsync(x => x.Token == token);

    var user = await _userManager.FindByIdAsync(resetRequest.UserId);

    // PROBLEM - This method returns "Invalid Token"
    var result = await _userManager.ResetPasswordAsync(user, resetRequest.Token, password);

    if (result.Succeeded)
        await SendPasswordChangedEmail(user);

    return result;
}
</code>```

As I state in the code comments, the token received in the request matches the one generated in the database, but  ResetPasswordAsync does it's own token validation, and that fails.

Any help would still be appreciated

答:
It seams your token was generated with a different way.
Could you try this ?
generate new token :

```<code>var code = await UserManager.GeneratePasswordResetTokenAsync(resetRequest.UserId);
</code>```

and reset password :

```<code>var resetResult = await userManager.ResetPasswordAsync(resetRequest.UserId, code, password);
</code>```

the other case is incorrect HTML encoding for token:

```<code>token = HttpUtility.UrlDecode(token) ;
</code>```

The next case is userManager has to be  singleton (or at least tokenProvider class) for each requests.

this is link to source code
https://github.com/aspnet/Identity/blob/rel/2.0.0/src/Microsoft.Extensions.Identity.Core/UserManager.cs#L29

manually token processing in case different instances for token providers due to storing tokens into private variable:

```<code>private readonly Dictionary<string, IUserTwoFactorTokenProvider<TUser>> _tokenProviders =
            new Dictionary<string, IUserTwoFactorTokenProvider<TUser>>();
</code>```

The next code might be implemented:

```<code>  public override async Task<bool> VerifyUserTokenAsync(TUser user, string tokenProvider, string purpose, string token)
        {
            ThrowIfDisposed();
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (tokenProvider == null)
            {
                throw new ArgumentNullException(nameof(tokenProvider));
            }
//should be overriden
// if (!_tokenProviders.ContainsKey(tokenProvider))
//           {
//              throw new
//NotSupportedException(string.Format(CultureInfo.CurrentCulture,
//Resources.NoTokenProvider, tokenProvider));
//          }
// Make sure the token is valid
//        var result = await _tokenProviders[tokenProvider].ValidateAsync(purpose, token, this, user);

  //          if (!result)
  //        {
  //          Logger.LogWarning(9, "VerifyUserTokenAsync() failed with //purpose: {purpose} for user {userId}.", purpose, await GetUserIdAsync(user));
       //    }
var resetRequest = await _context.PasswordResetRequests
        .AsNoTracking()
        .FirstOrDefaultAsync(x => x.Token == token);
            if (resetRequest == null )
            {
                return IdentityResult.Failed(ErrorDescriber.InvalidToken());
            }

            // Make sure the token is valid
            var result = resetRequest.IsValid();

            if (!result)
            {
                Logger.LogWarning(9, "VerifyUserTokenAsync() failed with purpose: {purpose} for user {userId}.", purpose, await GetUserIdAsync(user));
            }
            return result;
        }
</code>```

Body:
I have an ASP.NET Core 2.2 application running on multiple instances on an Azure Web App; it uses EF Core 2.2 and ASP.NET Identity.

Everything works fine except the Password Reset flow where a user receives a link with token per e-mail and needs to choose a new password by clicking on that link. It works perfectly locally, but on Azure it always fails with an "Invalid Token" error.

The tokens are HTML encoded and decoded as necessary; and I have checks in place to ensure they match those on the database; URL encoding is not the issue.

I've configured DataProtection to store the keys to an Azure Blob storage, but to no avail.
The keys are stored  in the blob store all right, but I still get an "Invalid Token" error.

Here's my set up on Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // This needs to happen before "AddMvc"
    // Code for this method shown below
    AddDataProtecion(services);

    services.AddDbContext<MissDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    var sp = services.BuildServiceProvider();

    services.ConfigureApplicationCookie(x =>
    {
        x.Cookie.Name = ".MISS.SharedCookie";
        x.ExpireTimeSpan = TimeSpan.FromHours(8);
        // We need to set the cookie's DataProtectionProvider to ensure it will get stored in the azure blob storage
        x.DataProtectionProvider = sp.GetService<IDataProtectionProvider>();
    });

    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<MissDbContext>()
        .AddDefaultTokenProviders();

    // https://tech.trailmax.info/2017/07/user-impersonation-in-asp-net-core/
    services.Configure<SecurityStampValidatorOptions>(options =>
    {
        options.ValidationInterval = TimeSpan.FromMinutes(10);
        options.OnRefreshingPrincipal = context =>
        {
            var originalUserIdClaim = context.CurrentPrincipal.FindFirst("OriginalUserId");
            var isImpersonatingClaim = context.CurrentPrincipal.FindFirst("IsImpersonating");
            if (isImpersonatingClaim?.Value == "true" && originalUserIdClaim != null)
            {
                context.NewPrincipal.Identities.First().AddClaim(originalUserIdClaim);
                context.NewPrincipal.Identities.First().AddClaim(isImpersonatingClaim);
            }
            return Task.FromResult(0);
        };
    });

     // some more initialisations here
}

And here is the AddDataProtection method:

///
/// Add Data Protection so that cookies don't get invalidated when swapping slots.
///
/// <param name="services"></param>
/// <returns></returns>
void AddDataProtecion(IServiceCollection services)
{
    var sasUrl = Configuration.GetValue<string>("DataProtection:SaSUrl");
    var containerName = Configuration.GetValue<string>("DataProtection:ContainerName");
    var applicationName = Configuration.GetValue<string>("DataProtection:ApplicationName");
    var blobName = Configuration.GetValue<string>("DataProtection:BlobName");
    var keyIdentifier = Configuration.GetValue<string>("DataProtection:KeyVaultIdentifier");

    if (sasUrl == null || containerName == null || applicationName == null || blobName == null)
        return;

    var storageUri = new Uri($"{sasUrl}");

    var blobClient = new CloudBlobClient(storageUri);

    var container = blobClient.GetContainerReference(containerName);
    container.CreateIfNotExistsAsync().GetAwaiter().GetResult();

    applicationName = $"{applicationName}-{Environment.EnvironmentName}";
    blobName = $"{applicationName}-{blobName}";

    services.AddDataProtection()
        .SetApplicationName(applicationName)
        .PersistKeysToAzureBlobStorage(container, blobName);
}

I've also tried persisting the keys to the DbContext, but the result is the same: keys are stored, but I still get anInvalid token message when attempting a password reset, Every. Single. Time.

the Request Password Reset method

public async Task RequestPasswordReset(string emailAddress, string ip, Request httpRequest)
{
    var user = await _userManager.FindByEmailAsync(emailAddress);

    var resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

    var resetRequest = new PasswordResetRequest
    {
        CreationDate = DateTime.Now,
        ExpirationDate = DateTime.Now.AddDays(1),
        UserId = user.Id,
        Token = resetToken,
        IP = ip
    };

    _context.PasswordResetRequests.Add(resetRequest);
    await _context.SaveChangesAsync();

    await SendPasswordResetEmail(user, resetRequest, httpRequest);
}

The Reset password method

Once the user requests a password reset, they receive an e-mail with a link and a token; here's how I attempt to reset the user's password after the user clicks on that link:

public async Task<IdentityResult> ResetPassword(string token, string password)
{
    // NO PROBLEM HERE - The received token matches with the one in the Db
    var resetRequest = await _context.PasswordResetRequests
        .AsNoTracking()
        .FirstOrDefaultAsync(x => x.Token == token);

    var user = await _userManager.FindByIdAsync(resetRequest.UserId);

    // PROBLEM - This method returns "Invalid Token"
    var result = await _userManager.ResetPasswordAsync(user, resetRequest.Token, password);

    if (result.Succeeded)
        await SendPasswordChangedEmail(user);

    return result;
}

As I state in the code comments, the token received in the request matches the one generated in the database, but  ResetPasswordAsync does it's own token validation, and that fails.

Any help would still be appreciated

Body:
It seams your token was generated with a different way.
Could you try this ?
generate new token :

var code = await UserManager.GeneratePasswordResetTokenAsync(resetRequest.UserId);

and reset password :

var resetResult = await userManager.ResetPasswordAsync(resetRequest.UserId, code, password);

the other case is incorrect HTML encoding for token:

token = HttpUtility.UrlDecode(token) ;

The next case is userManager has to be  singleton (or at least tokenProvider class) for each requests.

this is link to source code
https://github.com/aspnet/Identity/blob/rel/2.0.0/src/Microsoft.Extensions.Identity.Core/UserManager.cs#L29

manually token processing in case different instances for token providers due to storing tokens into private variable:

private readonly Dictionary<string, IUserTwoFactorTokenProvider<TUser>> _tokenProviders =
            new Dictionary<string, IUserTwoFactorTokenProvider<TUser>>();

The next code might be implemented:

  public override async Task<bool> VerifyUserTokenAsync(TUser user, string tokenProvider, string purpose, string token)
        {
            ThrowIfDisposed();
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (tokenProvider == null)
            {
                throw new ArgumentNullException(nameof(tokenProvider));
            }
//should be overriden
// if (!_tokenProviders.ContainsKey(tokenProvider))
//           {
//              throw new
//NotSupportedException(string.Format(CultureInfo.CurrentCulture,
//Resources.NoTokenProvider, tokenProvider));
//          }
// Make sure the token is valid
//        var result = await _tokenProviders[tokenProvider].ValidateAsync(purpose, token, this, user);

  //          if (!result)
  //        {
  //          Logger.LogWarning(9, "VerifyUserTokenAsync() failed with //purpose: {purpose} for user {userId}.", purpose, await GetUserIdAsync(user));
       //    }
var resetRequest = await _context.PasswordResetRequests
        .AsNoTracking()
        .FirstOrDefaultAsync(x => x.Token == token);
            if (resetRequest == null )
            {
                return IdentityResult.Failed(ErrorDescriber.InvalidToken());
            }

            // Make sure the token is valid
            var result = resetRequest.IsValid();

            if (!result)
            {
                Logger.LogWarning(9, "VerifyUserTokenAsync() failed with purpose: {purpose} for user {userId}.", purpose, await GetUserIdAsync(user));
            }
            return result;
        }


问:
How to render child components only in react
I am learning react, and is trying to plot a map with mapbox. I am stuck with how to render elements seperatly.

In the render part, there is a
 element and a component <CityWeather/> wrapped. div is a reference to map. The <Cityweather /> is an info  box which is supposed to display weather information based on lat and long. The app.js file render method is

```<code>render(){
    console.log(this.state);
    return(
        <section>
            <div className="map-container" ref={x => { this.mapContainer = x;}}/>
            <CityWeather lat={this.state.lat} lng={this.state.lng} />
        </section>
    );
</code>```

The componentDidMount() is

```<code>componentDidMount() {
    this.getLocation();
    mapboxgl.accessToken = "";

    const { lng, lat, zoom } = this.state;
    const map = new mapboxgl.Map({
        container: this.mapContainer,
        style: "mapbox://styles/mapbox/streets-v11",
        center: [lng, lat],
        zoom: zoom
    });
   map.on("moveend", () => {
       const { lng, lat } = map.getCenter();
       this.setState({
           lng: lng.toFixed(4),
           lat: lat.toFixed(4),
           zoom: map.getZoom().toFixed(2)
       });
   });
 }
</code>```

The <CityWeather /> component

```<code>class CityWeather extends Component {
    constructor(props) {
        super(props);
        this.state = {
        name: ""
    };
 }
 componentDidMount() {
     console.log(this.props); // this logs only 1 time when the page loads
    fetch("api?lat=" + this.props.lat +"&lon=" +this.props.lng +       "&appid=")
        .then(res => res.json())
        .then(data => {this.setState({ name: data.name });
    }); // get name from lat and long and store it in state
}

render() {
    return (
        <div className="city-weather">
            <p>
                City | <span className="city">
                {this.state.name}</span>
            </p>
       </div>
    );
}
}
</code>```

On each event the console is logging the updated latitude, longitude and zoom. Also the <CityWeather/> is also rendered for Ist time. After that the component is not rendered on state change.

答: Did you add a log in the listener? I think the method was not called because you did not move. you can use timer and some mock data to test the render.</p>

Body:
I am learning react, and is trying to plot a map with mapbox. I am stuck with how to render elements seperatly.

In the render part, there is a
 element and a component <CityWeather/> wrapped. div is a reference to map. The <Cityweather /> is an info  box which is supposed to display weather information based on lat and long. The app.js file render method is

render(){
    console.log(this.state);
    return(

 { this.mapContainer = x;}}/>
            <CityWeather lat={this.state.lat} lng={this.state.lng} />

    );

The componentDidMount() is

componentDidMount() {
    this.getLocation();
    mapboxgl.accessToken = "";

    const { lng, lat, zoom } = this.state;
    const map = new mapboxgl.Map({
        container: this.mapContainer,
        style: "mapbox://styles/mapbox/streets-v11",
        center: [lng, lat],
        zoom: zoom
    });
   map.on("moveend", () => {
       const { lng, lat } = map.getCenter();
       this.setState({
           lng: lng.toFixed(4),
           lat: lat.toFixed(4),
           zoom: map.getZoom().toFixed(2)
       });
   });
 }

The <CityWeather /> component

class CityWeather extends Component {
    constructor(props) {
        super(props);
        this.state = {
        name: ""
    };
 }
 componentDidMount() {
     console.log(this.props); // this logs only 1 time when the page loads
    fetch("api?lat=" + this.props.lat +"&lon=" +this.props.lng +       "&appid=")
        .then(res => res.json())
        .then(data => {this.setState({ name: data.name });
    }); // get name from lat and long and store it in state
}

render() {
    return (

                City |
                {this.state.name}

    );
}
}

On each event the console is logging the updated latitude, longitude and zoom. Also the <CityWeather/> is also rendered for Ist time. After that the component is not rendered on state change.


问:
Modifying a regular expression by another by adding a something to it
I am trying to modifying my regex expression using replace. What ultimately want to do is to add 01/ in the front of my existing pattern.It is litterally replacing a pattern by another.
Here is what I am doing with replace:

```<code> df['found_d'].str.replace(pattern2, '1/'+pattern2)
 #must be str, not _sre.SRE_Pattern
</code>```

I would like to use sub it takes 3 arguments and I am not too sure of how to use it at this point.
Here is an expected input:

```<code> df['found_d']= 01/07/91 or 01/07/1991
</code>```

I need to add a missing date to my pattern.

答:
Starting from version 0.20, pandas str.replace can accept a callable that will receive a match object. For example if a column has a pattern of 2 uppercase letters followed with 2 decimal digits and you would want to reverse them with a colon between, you could use:

```<code>df['col'] = df['col'].str.replace(r'([A-Z]{2})([0-9]{2})',
                                  lamdba m: "{}:{}".format(m.group(2), m.group(1)))
</code>```

It gives you the full power of the re module inside pandas, changing here 'AB12' with '12:AB'

Body:
I am trying to modifying my regex expression using replace. What ultimately want to do is to add 01/ in the front of my existing pattern.It is litterally replacing a pattern by another.
Here is what I am doing with replace:

 df['found_d'].str.replace(pattern2, '1/'+pattern2)
 #must be str, not _sre.SRE_Pattern

I would like to use sub it takes 3 arguments and I am not too sure of how to use it at this point.
Here is an expected input:

 df['found_d']= 01/07/91 or 01/07/1991

I need to add a missing date to my pattern.

Body:
Starting from version 0.20, pandas str.replace can accept a callable that will receive a match object. For example if a column has a pattern of 2 uppercase letters followed with 2 decimal digits and you would want to reverse them with a colon between, you could use:

df['col'] = df['col'].str.replace(r'([A-Z]{2})([0-9]{2})',
                                  lamdba m: "{}:{}".format(m.group(2), m.group(1)))

It gives you the full power of the re module inside pandas, changing here 'AB12' with '12:AB'


问:
How to get lines from the last match to the end of file?
Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

```<code>MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll
</code>```

Output desired is

```<code>jjj
kkk
lll
</code>```

Do I use awk with RS and FS to get the desired output?

答:
This might work for you (GNU sed):

```<code>sed -nz 's/.*MARKER.//p' file
</code>```

This uses greed to delete all lines upto and including the last occurrence of MARKER.

Body:
Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll

Output desired is

jjj
kkk
lll

Do I use awk with RS and FS to get the desired output?

Body:
This might work for you (GNU sed):

sed -nz 's/.*MARKER.//p' file

This uses greed to delete all lines upto and including the last occurrence of MARKER.


问:
How to hold collection of files throughout application?
In my mobile application I need to hold a collection of File objects (pictures, documents) that can be accessed throughout the whole application and users can make various operations over the collection:

view all/individual files

upload subsets of the collection to a server

share individual files

...

The collection is initialized only once.

I was wondering if it is a good idea to use a singleton pattern as an object that holds the collection so I do not have to initialize the collection every time user opens a particular screen?

答:
Absolutely, that's the purpose of the singleton pattern.

From Wikipedia, The Singleton Pattern is

useful when exactly one object is
  needed to coordinate actions across
  the system.

Example:

```<code>public class SingletonCollection {

    private Collection<File> fileCollection;
    private static SingletonCollection instance;

    private SingletonCollection() {
        fileCollection = new ArrayList<File>();
    }

    public static SingletonCollection getInstance() {
        if (instance == null) {
            instance = new SingletonCollection();
        }

        reutrn instance;
    }

    public void addFile(File f) {
        fileCollection.add(f);
    }

    public Collection<File> getFiles() {
        return fileCollection;
    }
}
</code>```

Body:
Absolutely, that's the purpose of the singleton pattern.

From Wikipedia, The Singleton Pattern is

useful when exactly one object is
  needed to coordinate actions across
  the system.

Example:

public class SingletonCollection {

    private Collection<File> fileCollection;
    private static SingletonCollection instance;

    private SingletonCollection() {
        fileCollection = new ArrayList<File>();
    }

    public static SingletonCollection getInstance() {
        if (instance == null) {
            instance = new SingletonCollection();
        }

        reutrn instance;
    }

    public void addFile(File f) {
        fileCollection.add(f);
    }

    public Collection<File> getFiles() {
        return fileCollection;
    }
}


问:
Python: Conversion of data into timeseries
I have some data (trade data) in a dataframe that I need to summarise on a daily basis.

The data is connected to flows, so I have lots of rows, which have the following data points that are important for this (there are many more so not reproducing here)

Volume, Start Date, End Date

So for example:

```<code>Volume, Start Date, End Date
100, 1 April 2019, 30 June 2019
50, 1 Jan 2019, 30 June 2019
</code>```

All these rows can have overlapping start and end dates.

What I am looking for is a simple way to create an output with: (using the 2 trades above as example data)
Day, Total Volume

So for example:

```<code>1 Jan, 50
2 Jan, 50
....
1 April, 150
2 April, 150
...
29 June, 150
30 June, 150
1 July, 0
...
31 Dec, 0
</code>```

I could iterate through each row, and then through each trade. But with so many, that seems a long slow process.

I am using Jupyter notebooks, with Python 3.

Any help appreciated - even if it is pointing me towards a solution I might have missed in my search here...

答:
I have solved this question via filtering.

```<code>def volumebyday(date, df, start, end, col):
#date = date to sum, df = dataframe, start/end = name of start/end date column, col = column to sum
    trade1 = df[start] <= date
    trade2 = df[end] >= date
    return df[col][trade1 & trade2].sum(axis=0)
</code>```

then using this via a lambda function

```<code>df = df.apply(lambda row: volumebyday(row["date"], trades, "start_date","end_date","qty")
</code>```

Body:
I have some data (trade data) in a dataframe that I need to summarise on a daily basis.

The data is connected to flows, so I have lots of rows, which have the following data points that are important for this (there are many more so not reproducing here)

Volume, Start Date, End Date

So for example:

Volume, Start Date, End Date
100, 1 April 2019, 30 June 2019
50, 1 Jan 2019, 30 June 2019

All these rows can have overlapping start and end dates.

What I am looking for is a simple way to create an output with: (using the 2 trades above as example data)
Day, Total Volume

So for example:

1 Jan, 50
2 Jan, 50
....
1 April, 150
2 April, 150
...
29 June, 150
30 June, 150
1 July, 0
...
31 Dec, 0

I could iterate through each row, and then through each trade. But with so many, that seems a long slow process.

I am using Jupyter notebooks, with Python 3.

Any help appreciated - even if it is pointing me towards a solution I might have missed in my search here...

Body:
I have solved this question via filtering.

def volumebyday(date, df, start, end, col):
#date = date to sum, df = dataframe, start/end = name of start/end date column, col = column to sum
    trade1 = df[start] <= date
    trade2 = df[end] >= date
    return df[col][trade1 & trade2].sum(axis=0)

then using this via a lambda function

df = df.apply(lambda row: volumebyday(row["date"], trades, "start_date","end_date","qty")


问:
Why does facebook’s graph API return a permissions error when I try to get the “owner” of any facebook event that I am personally invited to?
I am using facebook's graph api. The access token I am using is the User's access token, (my personal access token). I am invited to these events personally. These events are public.

When I type /{eventid}/?fields=owner, I get

```<code>{
  "error": {
    "message": "(#200) Permissions error",
    "type": "OAuthException",
    "code": 200,
    "fbtrace_id": "DcJaHySwF7S"
  }
}
</code>```

When I do /{eventid}/?fields=cover or most other fields it works just fine.

I am using the online graph tool v3.3 and tried it on v3.2 as well.
I have also tried this on curl on my personal terminal.

Below is the oath permissions I have set using the Graph API explorer.

Permission's Image

答:
Since you cannot even get the list of Page Events right now (even if you own the Page), I assume it´s not possible: https://developers.facebook.com/docs/graph-api/reference/page/events/

This is a restricted edge. You cannot request access at this time.

Body:
I am using facebook's graph api. The access token I am using is the User's access token, (my personal access token). I am invited to these events personally. These events are public.

When I type /{eventid}/?fields=owner, I get

{
  "error": {
    "message": "(#200) Permissions error",
    "type": "OAuthException",
    "code": 200,
    "fbtrace_id": "DcJaHySwF7S"
  }
}

When I do /{eventid}/?fields=cover or most other fields it works just fine.

I am using the online graph tool v3.3 and tried it on v3.2 as well.
I have also tried this on curl on my personal terminal.

Below is the oath permissions I have set using the Graph API explorer.

Permission's Image


问:
How do I get the text of my WordPress posts left indented?
I'm using the theme "blogito" for my WordPress blog.
In my articles, the text (
) is weirdly right indented and in some browsers you cant see the whole text.

How do I get a left indentation, so the text is aligned with the pictures.
On this post page you can see what I mean:

https://couch-investing.de/shopdoc-das-allrounder-tool-fuer-amazon-verkaeufer/

Does that have something to do with the class entry-content col-xs-12 col-lg-10 col-lg-push-2?

I'm really bad at JavaScript and CSS and would be happy about your help :)

Cheers

Rob

答:
You have offset set for the content area

find this line in the code

```<code><div id="primary" class="content-area col-lg-10 col-lg-offset-1">
</code>```

and remove col-lg-offset-1 for better placement of text

like this :

```<code><div id="primary" class="content-area col-lg-10">
</code>```

Body:
You have offset set for the content area

find this line in the code

<div id="primary" class="content-area col-lg-10 col-lg-offset-1">

and remove col-lg-offset-1 for better placement of text

like this :

<div id="primary" class="content-area col-lg-10">


问:
Embedding dynamic script when page scrolls
I am trying to add an iframe which consist of form . I am inserting this iframe when the page is loaded already and scrolled at some position ,I have used jquery this script is working fine it appending that script tag  under that div but the thing it should load iframe at that place.  please help out

please point out whats wrong in this question

i found that iframe is generated by script its not loaded first itself

$(document).ready(function() {
  var element_position = $('#Banner').offset().top;

  $(window).one('scroll', function() {

    if (y_scroll_pos < 300) {
      //do stuff
      $('#form1').load("http://www.samisite.com/test-csb2nf/ifform/somejsthatgenrateiframe");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Banner"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-in">
  <script id="form1"></script></code>```

答:
There's a lot wrong here...

$('#Banner').offset().top; will return undefined - see html fix below

var scroll_pos_test = element_position; is just duplication - just use element_position

if (y_scroll_pos > scroll_pos_test) will not run since y_scroll_pos is undefined

$('#form1').append(' You say you're trying to load an iframe, so use an iframe not a script.

 Your example needs a closing div.

So after all that here I think is your solution:

```<code><div id="Banner"></div>    <!--corrected id-->
    <div class="form-in" style="height:1500px;"> <!--added height to easily scroll-->
        <iframe id="form1"></iframe> <!--use an iframe-->
    </div>

    <!--keep your scripts organised at the bottom of page-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            var element_position = $('#Banner').offset().top;

            $(window).on('scroll', function() {
                var y_scroll_pos = window.pageYOffset;
                if (y_scroll_pos > element_position) {

                    $('#form1').prop({ //'#form1 is now an iframe
                        'src': 'http://www.samisite.com/test-csb2nf/ifform/ssform.php',
                        'height' : '500',
                        'width' : '100%' //make sure the height and width are enough to display the page
                    });
                }
            });
        });
    </script>
</code>```

Now after all that you may get an error in developer console Blocked loading mixed active content “http://www.samisite.com/test-csb2nf/ifform/ssform.php”
In that case your iframe content is being blocked by the the browser because that page is loaded over http:// and you are running on a site served over https://. More info can be found at https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

Body:
There's a lot wrong here...

$('#Banner').offset().top; will return undefined - see html fix below

var scroll_pos_test = element_position; is just duplication - just use element_position

if (y_scroll_pos > scroll_pos_test) will not run since y_scroll_pos is undefined

$('#form1').append('<script src= "http://www.samisite.com/test-csb2nf/ifform/ssform.php"><script>);

You are putting a script tag within a script tag. If this works all it is the browser being kind to you.

Your src attribute is a page, not a script.

You are also missing a closing single quote.

<div id="#Banner"></div> remove the '#' from id.

<script id="form1"></script> You say you're trying to load an iframe, so use an iframe not a script.

</div> Your example needs a closing div.

So after all that here I think is your solution:

<div id="Banner"></div>    <!--corrected id-->
    <div class="form-in" style="height:1500px;"> <!--added height to easily scroll-->
        <iframe id="form1"></iframe> <!--use an iframe-->
    </div>

    <!--keep your scripts organised at the bottom of page-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            var element_position = $('#Banner').offset().top;

            $(window).on('scroll', function() {
                var y_scroll_pos = window.pageYOffset;
                if (y_scroll_pos > element_position) {

                    $('#form1').prop({ //'#form1 is now an iframe
                        'src': 'http://www.samisite.com/test-csb2nf/ifform/ssform.php',
                        'height' : '500',
                        'width' : '100%' //make sure the height and width are enough to display the page
                    });
                }
            });
        });
    </script>

Now after all that you may get an error in developer console Blocked loading mixed active content “http://www.samisite.com/test-csb2nf/ifform/ssform.php”
In that case your iframe content is being blocked by the the browser because that page is loaded over http:// and you are running on a site served over https://. More info can be found at https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content


问:
FirebaseAuth.getInstance().signOut() doesn't signout
I try to signout user from firebase but after i close my app and open again the user is stills connect

I tried the regular signout of user from firebase and it not solve the problem.
I am wondering what could cause the problem

 logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent picture_intent = new Intent(Dashboard.this,LoginActivity.class);
                startActivity(picture_intent );
            }
        });
```

<p>my check if user connect:</p>

```@Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser currentUser = firebaseAuth.getCurrentUser();
        if(currentUser != null)
        {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            int again = preferences.getInt(String.valueOf(R.string.remember_me), 0);
            if(again == 0)
            {
                Intent i = new Intent(getApplicationContext(), PagerActivity.class);
                startActivity(i);
            }
            else
            {
                Intent i = new Intent(getApplicationContext(), Dashboard.class);
                startActivity(i);
            }

        }
    }
```

答:
I think you are being logged out correctly but as you are moving to

LoginActivity.class

Where you might be logging the user back in again you would have to make certain changes in Login activity.

Body:
I try to signout user from firebase but after i close my app and open again the user is stills connect

I tried the regular signout of user from firebase and it not solve the problem.
I am wondering what could cause the problem

 logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent picture_intent = new Intent(Dashboard.this,LoginActivity.class);
                startActivity(picture_intent );
            }
        });

my check if user connect:

@Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser currentUser = firebaseAuth.getCurrentUser();
        if(currentUser != null)
        {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            int again = preferences.getInt(String.valueOf(R.string.remember_me), 0);
            if(again == 0)
            {
                Intent i = new Intent(getApplicationContext(), PagerActivity.class);
                startActivity(i);
            }
            else
            {
                Intent i = new Intent(getApplicationContext(), Dashboard.class);
                startActivity(i);
            }

        }
    }


问:
two objects have the same value
Both object is the same when i edit.
show the solution to seprate objects.
i have an object and with v-model i bind it to inputs to update it but when i edit it but don't save changes the object is changed. for not occurring this situation i use a second object(temporary) when editing i use that object but again it changes the first object.</p>

```<code>data(){
   return{
      user:{
        id:'',
        firstname:'',
        lastname: ''
      },
    tuser:{}
     }
  },
 mounted(){
     axios.get('/user')
         .then((response) => {
              this.user = response.data
             })
         .catch(error)
    },
 methods:{
      edit(){
      this.tuser = this.user
      },
 update(){
      axios.patch(`/user/${this.tuser.id}`,this.tuser)
         .then((response)=>{
                 this.user = this.tuser
          })
       .error()
      }
 }
</code>```

答:
It is most likely because you reference one object to another.
As objects are reference not primitive values.
What it means is:
if you make obj1 = obj2, then actually they both point to the same object, if you change one, another change also.
You need to use something like Object.assign()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign</p>

Title: two objects have the same value

Body:
Both object is the same when i edit.
show the solution to seprate objects.
i have an object and with v-model i bind it to inputs to update it but when i edit it but don't save changes the object is changed. for not occurring this situation i use a second object(temporary) when editing i use that object but again it changes the first object.

data(){
   return{
      user:{
        id:'',
        firstname:'',
        lastname: ''
      },
    tuser:{}
     }
  },
 mounted(){
     axios.get('/user')
         .then((response) => {
              this.user = response.data
             })
         .catch(error)
    },
 methods:{
      edit(){
      this.tuser = this.user
      },
 update(){
      axios.patch(`/user/${this.tuser.id}`,this.tuser)
         .then((response)=>{
                 this.user = this.tuser
          })
       .error()
      }
 }


问:
Save changes before renaming
How can I add my own implementation to Rename context menu of eclipse explorer view. When I click on Rename I want to do some verification before I rename the project

```<code>  <extension
     point="org.eclipse.ltk.core.refactoring.renameParticipants">
  <renameParticipant
        class="core.ui.project.RenameProject"
        id="core.ui.renameParticipant"
        name="Rename">
  </renameParticipant>
</code>```

```<code>public class RenameProject extends RenameParticipant {

@Override
protected boolean initialize(Object element) {
    System.out.println("HERE");
    return false;
}

@Override
public String getName() {
    System.out.println("HERE");
    return null;
}

@Override
public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
        throws OperationCanceledException {
    System.out.println("HERE");
    return null;
}

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    System.out.println("HERE");
    return null;
}

}
</code>```

Thanks

答:
You don't need to change the implementation of the menu in order to verify something during a rename.

Instead use the org.eclipse.ltk.core.refactoring.renameParticipants extension point to define a 'rename participant' which will be called during rename operations. The participant can check that the rename is valid and add additional work to be done during the rename.

The participant code extends the org.eclipse.ltk.core.refactoring.participants.RenameParticipant class which is in the org.eclipse.ltk.core.refactoring plug-in.

There are also participants for create, copy, move and delete.

An example participant for file renames from the Ant plugin:

<extension point="org.eclipse.ltk.core.refactoring.renameParticipants">
  <renameParticipant
         class="org.eclipse.ant.internal.ui.refactoring.LaunchConfigurationBuildfileRenameParticipant"
         name="%AntRenameParticipant.name"
         id="org.eclipse.ant.ui.refactoring.launchConfiguration.buildfileRename">
      <enablement>
        <with variable="element">
          <instanceof value="org.eclipse.core.resources.IFile"/>
        </with>
      </enablement>
   </renameParticipant>
```

Title: Save changes before renaming

Body:
How can I add my own implementation to Rename context menu of eclipse explorer view. When I click on Rename I want to do some verification before I rename the project

  <extension
     point="org.eclipse.ltk.core.refactoring.renameParticipants">
  <renameParticipant
        class="core.ui.project.RenameProject"
        id="core.ui.renameParticipant"
        name="Rename">
  </renameParticipant>

public class RenameProject extends RenameParticipant {

@Override
protected boolean initialize(Object element) {
    System.out.println("HERE");
    return false;
}

@Override
public String getName() {
    System.out.println("HERE");
    return null;
}

@Override
public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
        throws OperationCanceledException {
    System.out.println("HERE");
    return null;
}

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    System.out.println("HERE");
    return null;
}

}

Thanks


问:
Why are these bootstrap buttons touching each other?
These two bootstrap buttons touch each other. Do I need to add some custom CSS to get some space between them? The docs here https://getbootstrap.com/docs/4.1/components/buttons/ don't touch each other.

```<code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container-fluid">
  <form>
    <div class="btn-toolbar">
      <button type="submit" class="btn btn-primary">Submit</button>
      <button type="reset" class="btn btn-secondary">Reset</button>
    </div>
  </form>
</div>
</code>```

StackBlitz https://stackblitz.com/edit/js-u5zg9m

答: the buttons are touching each other because you are putting them in a btn-toolbar (by the way btn-group will do the same). You can eather remove it or use CSS to add margin.

Body:
These two bootstrap buttons touch each other. Do I need to add some custom CSS to get some space between them? The docs here https://getbootstrap.com/docs/4.1/components/buttons/ don't touch each other.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <form>

      <button type="submit" class="btn btn-primary">Submit</button>
      <button type="reset" class="btn btn-secondary">Reset</button>

  </form>

StackBlitz https://stackblitz.com/edit/js-u5zg9m


问:
Decoding unnamed JSON array swift 4 with structure
I have been trying to decode an array for an app where I have to decode JSON.

I just can't decode it with my actual structure and others which I tried before.

Here are my latest structures:

```<code>struct peticion: Decodable{
    let datos_conexion: datos_conexion
    let estado_lanzamiento: estado_lanzamiento
    let usuario: usuario
}

struct datos_conexion: Decodable {
    let conexion: datosConexion
}

struct datosConexion: Decodable{
    let datos_conexion: String
}

struct estado_lanzamiento: Decodable{
    let tiempo_restante: String
    let etapa_actual: String
}

struct usuario: Decodable {
    let Id: Int
    let Nombre: String
    let Password: String
    let Imagen: String
    let Puesto: String
    let Departamento: String
}
</code>```

JSON full example from Request

```<code>[
    {
        "datos_conexion": {
            "conexion": "2019-05-27 17:05:45"
        }
    },
    {
        "estado_lanzamiento": {
            "tiempo_restante": 240,
            "etapa_actual": "Configuracion"
        }
    },
    {
        "usuario": [
            {
                "Id": "4",
                "Nombre": "This is the Name",
                "Email": "email@gmail.com",
                "Password": "1234",
                "Imagen": "default.jpg",
                "Puesto": "",
                "Departamento": "Etapa Final"
            }
        ]
    }
]
</code>```

decoding code

```<code>URLSession.shared.dataTask(with: url2) { (data, resp, err) in
    guard let data = data else{return}
    let dataAsString = String(data: data, encoding: .utf8)
//      print(dataAsString)
    do {
        let JSONDATA = try JSONDecoder().decode([peticion].self, from: data)
//     print(data)
    } catch let jsonErr {
        print("cant decode", jsonErr)
    }
</code>```

Errors trying to do this:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode dictionary but found an Array instead.", underlyingError: nil))

答:
Based on your JSON, you are receiving an [[String: Any]] which is Array containing Dictionaries of Any values and String keys. This is tricky, since the dictionaries are containing values of Any which is not Decodable. Also, the container is Array, usually we would have a Dictionary as the container.

Normally, we would simplify this response.. But we cannot on this scenario.

One way to decode this is:

```<code>
struct Peticion: Decodable{
    let datosConexion: DatosConexion
    let estadoLanzamiento: EstadoLanzamiento
    let usuario: [Usuario]

    init(from decoder : Decoder) throws {
        //unkeyed because we are getting an array as container
        var unkeyedContainer = try decoder.unkeyedContainer()
        let datosConexionWrapper = try unkeyedContainer.decode(DatosConexionWrapper.self)

        let estadoLanzamientoWrapper = try unkeyedContainer.decode(EstadoLanzamientoWrapper.self)
        let usuarioWrapper = try unkeyedContainer.decode(UsuarioWrapper.self)

        datosConexion = datosConexionWrapper.datosConexion
        estadoLanzamiento = estadoLanzamientoWrapper.estadoLanzamiento
        usuario = usuarioWrapper.usuario

    }
}

//use wrappers to handle the outer dictionary
struct DatosConexionWrapper: Decodable{
   let datosConexion: DatosConexion

   enum CodingKeys: String, CodingKey{
      case datosConexion = "datos_conexion"
   }
}

struct DatosConexion: Decodable{
   let conexion: String
}

struct EstadoLanzamientoWrapper: Decodable{
  let estadoLanzamiento: EstadoLanzamiento

  enum CodingKeys: String, CodingKey{
      case estadoLanzamiento = "estado_lanzamiento"
   }
}

struct EstadoLanzamiento: Decodable{
   let tiempoRestante: Int
   let etapaActual: String

   enum CodingKeys: String, CodingKey {
        case tiempoRestante = "tiempo_restante"
        case etapaActual = "etapa_actual"
    }
}

struct UsuarioWrapper: Decodable{
  let usuario: [Usuario]

}

struct Usuario: Decodable{
   let id: String
   let nombre: String
   let email: String
   let password: String
   let imagen: String
   let puesto: String
   let departamento: String

   enum CodingKeys: String, CodingKey {
        case id = "Id"
        case nombre = "Nombre"
        case email = "Email"
        case password = "Password"
        case imagen = "Imagen"
        case puesto = "Puesto"
        case departamento = "Departamento"
   }
}

</code>```

Decoding code //i only changed the decoding type to my Peticion struct

```<code>
URLSession.shared.dataTask(with: url2) { (data, resp, err) in
    guard let data = data else{return}
    let dataAsString = String(data: data, encoding: .utf8)
//      print(dataAsString)
    do {
        let JSONDATA = try JSONDecoder().decode(Peticion.self, from: data)
//     print(data)
    } catch let jsonErr {
        print("cant decode", jsonErr)
    }

</code>```

This was a fun exercise. This is also untested code, but I'm pretty sure it would work.

Body:
I have been trying to decode an array for an app where I have to decode JSON.

I just can't decode it with my actual structure and others which I tried before.

Here are my latest structures:

struct peticion: Decodable{
    let datos_conexion: datos_conexion
    let estado_lanzamiento: estado_lanzamiento
    let usuario: usuario
}

struct datos_conexion: Decodable {
    let conexion: datosConexion
}

struct datosConexion: Decodable{
    let datos_conexion: String
}

struct estado_lanzamiento: Decodable{
    let tiempo_restante: String
    let etapa_actual: String
}

struct usuario: Decodable {
    let Id: Int
    let Nombre: String
    let Password: String
    let Imagen: String
    let Puesto: String
    let Departamento: String
}

JSON full example from Request

[
    {
        "datos_conexion": {
            "conexion": "2019-05-27 17:05:45"
        }
    },
    {
        "estado_lanzamiento": {
            "tiempo_restante": 240,
            "etapa_actual": "Configuracion"
        }
    },
    {
        "usuario": [
            {
                "Id": "4",
                "Nombre": "This is the Name",
                "Email": "email@gmail.com",
                "Password": "1234",
                "Imagen": "default.jpg",
                "Puesto": "",
                "Departamento": "Etapa Final"
            }
        ]
    }
]

decoding code

URLSession.shared.dataTask(with: url2) { (data, resp, err) in
    guard let data = data else{return}
    let dataAsString = String(data: data, encoding: .utf8)
//      print(dataAsString)
    do {
        let JSONDATA = try JSONDecoder().decode([peticion].self, from: data)
//     print(data)
    } catch let jsonErr {
        print("cant decode", jsonErr)
    }

Errors trying to do this:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode dictionary but found an Array instead.", underlyingError: nil))

Body:
Based on your JSON, you are receiving an [[String: Any]] which is Array containing Dictionaries of Any values and String keys. This is tricky, since the dictionaries are containing values of Any which is not Decodable. Also, the container is Array, usually we would have a Dictionary as the container.

Normally, we would simplify this response.. But we cannot on this scenario.

One way to decode this is:

struct Peticion: Decodable{
    let datosConexion: DatosConexion
    let estadoLanzamiento: EstadoLanzamiento
    let usuario: [Usuario]

    init(from decoder : Decoder) throws {
        //unkeyed because we are getting an array as container
        var unkeyedContainer = try decoder.unkeyedContainer()
        let datosConexionWrapper = try unkeyedContainer.decode(DatosConexionWrapper.self)

        let estadoLanzamientoWrapper = try unkeyedContainer.decode(EstadoLanzamientoWrapper.self)
        let usuarioWrapper = try unkeyedContainer.decode(UsuarioWrapper.self)

        datosConexion = datosConexionWrapper.datosConexion
        estadoLanzamiento = estadoLanzamientoWrapper.estadoLanzamiento
        usuario = usuarioWrapper.usuario

    }
}

//use wrappers to handle the outer dictionary
struct DatosConexionWrapper: Decodable{
   let datosConexion: DatosConexion

   enum CodingKeys: String, CodingKey{
      case datosConexion = "datos_conexion"
   }
}

struct DatosConexion: Decodable{
   let conexion: String
}

struct EstadoLanzamientoWrapper: Decodable{
  let estadoLanzamiento: EstadoLanzamiento

  enum CodingKeys: String, CodingKey{
      case estadoLanzamiento = "estado_lanzamiento"
   }
}

struct EstadoLanzamiento: Decodable{
   let tiempoRestante: Int
   let etapaActual: String

   enum CodingKeys: String, CodingKey {
        case tiempoRestante = "tiempo_restante"
        case etapaActual = "etapa_actual"
    }
}

struct UsuarioWrapper: Decodable{
  let usuario: [Usuario]

}

struct Usuario: Decodable{
   let id: String
   let nombre: String
   let email: String
   let password: String
   let imagen: String
   let puesto: String
   let departamento: String

   enum CodingKeys: String, CodingKey {
        case id = "Id"
        case nombre = "Nombre"
        case email = "Email"
        case password = "Password"
        case imagen = "Imagen"
        case puesto = "Puesto"
        case departamento = "Departamento"
   }
}

Decoding code //i only changed the decoding type to my Peticion struct

URLSession.shared.dataTask(with: url2) { (data, resp, err) in
    guard let data = data else{return}
    let dataAsString = String(data: data, encoding: .utf8)
//      print(dataAsString)
    do {
        let JSONDATA = try JSONDecoder().decode(Peticion.self, from: data)
//     print(data)
    } catch let jsonErr {
        print("cant decode", jsonErr)
    }

This was a fun exercise. This is also untested code, but I'm pretty sure it would work.


问:
The acpi error occurred on Linux boot
```<code>[    0.133440] ACPI FADT declares the system doesn't support PCIe ASPM, so disable it
[    0.133440] ACPI: bus type PCI registered
[    0.133440] acpiphp: ACPI Hot Plug PCI Controller Driver version: 0.5
[    0.133440] PCI: MMCONFIG for domain 0000 [bus 00-3f] at [mem 0xf8000000-0xfbffffff] (base 0xf8000000)
[    0.133440] PCI: MMCONFIG at [mem 0xf8000000-0xfbffffff] reserved in E820
[    0.133440] PCI: Using configuration type 1 for base access
[    0.137025] HugeTLB registered 1.00 GiB page size, pre-allocated 0 pages
[    0.137025] HugeTLB registered 2.00 MiB page size, pre-allocated 0 pages
[    0.137063] ACPI: Added _OSI(Module Device)
[    0.137064] ACPI: Added _OSI(Processor Device)
[    0.137065] ACPI: Added _OSI(3.0 _SCP Extensions)
[    0.137065] ACPI: Added _OSI(Processor Aggregator Device)
[    0.138810] ACPI Error: [_SB_.PCI0.RP05.PXSX] Namespace lookup failure, AE_NOT_FOUND (20170831/dswload2-191)
[    0.138810] ACPI Exception: AE_NOT_FOUND, During name lookup/catalog (20170831/psobject-252)
[    0.138810] ACPI Error: Method parse/execution failed \_SB.PCI0.RP04.PXSX, AE_NOT_FOUND (20170831/psparse-550)
[    0.138926] ACPI Error: [_SB_.PCI0.RP09.PXSX] Namespace lookup failure, AE_NOT_FOUND (20170831/dswload2-191)
[    0.138930] ACPI Exception: AE_NOT_FOUND, During name lookup/catalog (20170831/psobject-252)
[    0.138933] ACPI Error: Method parse/execution failed \_SB.PCI0.RP08.PXSX, AE_NOT_FOUND (20170831/psparse-550)
</code>```

答:
I had the same error with Linux Mint 19, my OS worked fine and suddenly Linux booted right into emergency mode with your error.

This thread led me to checking my /etc/fstab which I had previously edited to add an external hard drive. After removing my own edits there it booted normally.

Looking for a solution now to add my external hard drive without causing that error.

Title: The acpi error occurred on Linux boot


问:
How can i get all value from child node using htmlagilitypack?
How can i get value from child node like href value and add them to list using html agility pack with the class name of parent node?

I have tried this code but fail

```<code>var pagedivs = htmlDocument.DocumentNode.SelectNodes("div").Where(e => e.GetAttributeValue("class", "").Equals("pagination"))
                .Where(k => k.Descendants().Any(t => t.Name == "li")).ToList();
</code>```

HTML code in web:

```<code><div class="pagination">
        <ul class="pagination-list">
            <li class="hidden-phone current"><a title="1" href="" class="pagenav">1</a></li>
            <li class="hidden-phone"><a title="2" href="/collections/remarkable-products?page=2" class="pagenav">2</a></li>
            <li><a title="Next page" href="/collections/remarkable-products?page=2" class="pagenav"><i class="fa fa-chevron-right"></i></a></li>
        </ul>
        <input type="hidden" name="limitstart" value="0">
    </div>
</code>```

答:
To get the href value specifically, you can do something like this:

```<code>var links = document.DocumentNode
    .Descendants("div") // 1
    .Where(div => div.HasClass("pagination")) // 2
    .First() // 3
    .Descendants("a") // 4
    .Select(a => a.GetAttributeValue("href", "")) // 5
    .Where(link => !string.IsNullOrWhiteSpace(link)) // 6
    .ToList();
</code>```

Get all descendant divs. This includes both children and children's children

Only keep the div that has the class pagination

Select the first div that match our criteria

Once again get all descendants, but this time the as

Get the value of the as href value

Filter out the links with empty values (like the first one in the submitted HTML

Body:
How can i get value from child node like href value and add them to list using html agility pack with the class name of parent node?

I have tried this code but fail

var pagedivs = htmlDocument.DocumentNode.SelectNodes("div").Where(e => e.GetAttributeValue("class", "").Equals("pagination"))
                .Where(k => k.Descendants().Any(t => t.Name == "li")).ToList();

HTML code in web:

1

2

        <input type="hidden" name="limitstart" value="0">

Body:
To get the href value specifically, you can do something like this:

var links = document.DocumentNode
    .Descendants("div") // 1
    .Where(div => div.HasClass("pagination")) // 2
    .First() // 3
    .Descendants("a") // 4
    .Select(a => a.GetAttributeValue("href", "")) // 5
    .Where(link => !string.IsNullOrWhiteSpace(link)) // 6
    .ToList();

Get all descendant divs. This includes both children and children's children

Only keep the div that has the class pagination

Select the first div that match our criteria

Once again get all descendants, but this time the as

Get the value of the as href value

Filter out the links with empty values (like the first one in the submitted HTML