问:
Attach TCPDF to mail in Laravel
I want to attach pdf generated with tcpdf library without save.
I'm able to attach the pdf generated but it's corrupt.

I search a lot examples but any seems don't work

This my code:

```<code>public function index($id) {
    $viaje = Viaje::find($id);
    $users = User::orderBy('id', 'asc')->get();
    // usersPdf is the view that includes the downloading content
    $view = \View::make('usersPdf', ['viaje' => $viaje, 'users' => $users]);
    $html_content = $view->render();
    // Set title in the PDF
    PDF::SetTitle("List of users");
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');

    //PDF::Output('userlist.pdf');
    $fileatt = PDF::Output($name='yourfilename.pdf', $dest='E');

    $pdf = chunk_split($fileatt);

    $contactopro = Contactoviajespro::find($id);

    $data = [
        'link' => 'http://',
        'contacto' => $contactopro->name,
    ];

    Mail::send('emails.notificacion', $data, function($msg) use($pdf) {
        $msg->from('administracion@buendialogistica.com', 'Javier');
        $msg->to('xavieeee@gmail.com')->subject('Notificación');

        $msg->attachData($pdf, 'orden.pdf');

    });

    return redirect()->route('home')
                    ->with(['message' => 'Email enviado correctamene']);
}
</code>```

答: Use "S" to generate pdf and do not do chunk_split(), Laravel will do that. Additionally, if you are using queue() instead of send(), it will fail because of the attachment. To queue, write a job and send with the job queue.</p>

Title: Attach TCPDF to mail in Laravel

Body:
I want to attach pdf generated with tcpdf library without save.
I'm able to attach the pdf generated but it's corrupt.

I search a lot examples but any seems don't work

This my code:

public function index($id) {
    $viaje = Viaje::find($id);
    $users = User::orderBy('id', 'asc')->get();
    // usersPdf is the view that includes the downloading content
    $view = \View::make('usersPdf', ['viaje' => $viaje, 'users' => $users]);
    $html_content = $view->render();
    // Set title in the PDF
    PDF::SetTitle("List of users");
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');

    //PDF::Output('userlist.pdf');
    $fileatt = PDF::Output($name='yourfilename.pdf', $dest='E');

    $pdf = chunk_split($fileatt);

    $contactopro = Contactoviajespro::find($id);

    $data = [
        'link' => 'http://',
        'contacto' => $contactopro->name,
    ];

    Mail::send('emails.notificacion', $data, function($msg) use($pdf) {
        $msg->from('administracion@buendialogistica.com', 'Javier');
        $msg->to('xavieeee@gmail.com')->subject('Notificación');

        $msg->attachData($pdf, 'orden.pdf');

    });

    return redirect()->route('home')
                    ->with(['message' => 'Email enviado correctamene']);
}


来源: stackexchange

问:
Short way to serialize datetime with marshmallow
Here is my situation: I store some datetime in MSSQL, which i get in my python application via SQLAlchemy, and then serialize it thru Marshmallow like this:

```<code>class MyVisitSchema(Schema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta:
        additional = ('duration',)
        ordered = True
</code>```

But here the problem: after serialization i get something like "started_at": "1994-05-20T00:00:00+00:00" which says that UTC+0, but i store all my dates in DB without any timezone info, but in UTC+3.

I know that i can use fields.Method() to change output timezone, but it looks inconvenient. Any ideas how to make my serializer work as it should?)

答:
I would rather use datetimeformat, see: https://marshmallow.readthedocs.io/en/3.0/api_reference.html

Example:

```<code>class MyVisitSchema(Schema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta:
        additional = ('duration',)
        ordered = True
        # dateformat = '%Y-%m-%dT%H:%M:%S%z'
        dateformat = '%Y-%m-%dT%H:%M:%S+03:00'
</code>```

And I prefer to:

```<code>class BaseSchema(Schema):
    class Meta:
        dateformat = '%Y-%m-%dT%H:%M:%S+03:00'

class MyVisitSchema(BaseSchema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta(BaseSchema.Meta):
        additional = ('duration',)
        ordered = True
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my situation: I store some datetime in MSSQL, which i get in my python application via SQLAlchemy, and then serialize it thru Marshmallow like this:

class MyVisitSchema(Schema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta:
        additional = ('duration',)
        ordered = True

But here the problem: after serialization i get something like "started_at": "1994-05-20T00:00:00+00:00" which says that UTC+0, but i store all my dates in DB without any timezone info, but in UTC+3.

I know that i can use fields.Method() to change output timezone, but it looks inconvenient. Any ideas how to make my serializer work as it should?)

Body:
I would rather use datetimeformat, see: https://marshmallow.readthedocs.io/en/3.0/api_reference.html

Example:

class MyVisitSchema(Schema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta:
        additional = ('duration',)
        ordered = True
        # dateformat = '%Y-%m-%dT%H:%M:%S%z'
        dateformat = '%Y-%m-%dT%H:%M:%S+03:00'

And I prefer to:

class BaseSchema(Schema):
    class Meta:
        dateformat = '%Y-%m-%dT%H:%M:%S+03:00'

class MyVisitSchema(BaseSchema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta(BaseSchema.Meta):
        additional = ('duration',)
        ordered = True

ContentLicense: CC BY-SA 4.0


问:
Guidelines for build a .Net web application that can use "plug-in" data access layers
I'm building an application which will initially use SQLServer 2008 as the DBMS. How should I structure my application so that at a later stage I can use a different DBMS, e.g. Oracle, without changing my code i.e. via configuration only.

I suspect my core application will call code in an assembly/layer that encapsulates all the database calls required for the application to function. This layer will then call a DBMS-specific layer (based on config) to make the actual DB call? Can anyone point me to a clear example of this?

Thanks!

Added an explanation below:

My thought was that I could have multiple assemblies e.g. MyApp, MyApp.Database, MyApp.Database.SQLServer, MyApp.Database.Oracle, etc.

MyApp would make a call like:

```<code>DataSet ds = MyApp.Database.GetSomeData();
</code>```

...which looks like...

```<code>public DataSet MyApp.Database.GetSomeData()
{
  return GetDataFromDBMS();
}
</code>```

GetSomeData is a generic call i.e. MyApp needs "GetSomeData()" in order to do something. It doesn't care where the data is from.

Then, GetDataFromDBMS would know, via a configuration file, to call either MyApp.Database.SQLServer.GetTheData() OR MyApp.Database.Oracle.GetTheData(). These methods could do whatever is required to get/process the data from each DBMS.

答:
What you should look at doing is either use an ORM tool that abstracts the database for you (nHibernate), or define a set of interfaces that represent your DAL and then use an IoC implementation (Ninject, Castle, etc) to swap out the underlying implementation at will, so long as it implements the interface.

However, designing an interface that is future-proof (ie, can cope with subtle quirks of working with other databases) is not simple, so you could end up needing to make changes anyway.

I'd do one of two things, in this order:

Review if you really need to swap out databases.

Go down the ORM tool route as a lot of leg-work is done for you.

A good example of abstracting a database, not necessarily the DAL per-se is the Enterprise Library Data Access Application Block from Microsoft.

Body:
I'm building an application which will initially use SQLServer 2008 as the DBMS. How should I structure my application so that at a later stage I can use a different DBMS, e.g. Oracle, without changing my code i.e. via configuration only.

I suspect my core application will call code in an assembly/layer that encapsulates all the database calls required for the application to function. This layer will then call a DBMS-specific layer (based on config) to make the actual DB call? Can anyone point me to a clear example of this?

Thanks!

Added an explanation below:

My thought was that I could have multiple assemblies e.g. MyApp, MyApp.Database, MyApp.Database.SQLServer, MyApp.Database.Oracle, etc.

MyApp would make a call like:

DataSet ds = MyApp.Database.GetSomeData();

...which looks like...

public DataSet MyApp.Database.GetSomeData()
{
  return GetDataFromDBMS();
}

GetSomeData is a generic call i.e. MyApp needs "GetSomeData()" in order to do something. It doesn't care where the data is from.

Then, GetDataFromDBMS would know, via a configuration file, to call either MyApp.Database.SQLServer.GetTheData() OR MyApp.Database.Oracle.GetTheData(). These methods could do whatever is required to get/process the data from each DBMS.


问:
Jenkins: How to check server directory exist in Nexus with powershell?
We using Jenkins.
I want to upload a directory+files, from a directory on windows server into Nexus with powershell.

But before doing this I want to check if this directory already exist in Nexus.

With wget I can download the directory+files from Nexus into my workspace of Jenkins.

But I want just check the directory/file by url ("http://xxxxx/yyyyy/zzzzz/") if it exist in Nexus on the server.

I have tried:
- Test-Path -Path,
- Get-SpWeb (is not recognized),
- invoke-request,
- HTTPRequest =[System.Net.WebRequest]::Create('url').

I have tried a lot but invoke request and the HTTPRequest is working if the directory exist. But if it not exist I get the 404 error ($HTTP_Response = $HTTP_Request.GetResponse()) or it hangs...

I looking for an example/tutorial of powershell (Jenkins) which is checking if a directory/file "http://xxxxx/yyyyy/zzzzz/" in Nexus on a server exist or NOT exist.

答:
"Only" this was working for me with Jenkins and I don't know now why -Mehthod HEAD is necessary and what it does, but at least it works within Jenkins:</p>

```<code>try {
    $Response = Invoke-WebRequest -Method HEAD -Uri $url
    $status = $_.Exception.Response.StatusCode.Value__

} catch {
    $status = $_.Exception.Response.StatusCode.Value__
} # END try {...} catch {...}

if (($status -eq 200) -Or ([string]::IsNullOrWhiteSpace($status))) {...}
</code>```

Body:
"Only" this was working for me with Jenkins and I don't know now why -Mehthod HEAD is necessary and what it does, but at least it works within Jenkins:

try {
    $Response = Invoke-WebRequest -Method HEAD -Uri $url
    $status = $_.Exception.Response.StatusCode.Value__

} catch {
    $status = $_.Exception.Response.StatusCode.Value__
} # END try {...} catch {...}

if (($status -eq 200) -Or ([string]::IsNullOrWhiteSpace($status))) {...}


问:
How to handle the case when FirebaseAuth sign in fails due to network being offline?
I am trying to implement sign in authentication with FirebaseAuth using signInWithEmailAndPassword() for my Android app. How can I handle the case when Internet connection is offline so that I can generate a Toast message regarding network issue.

答: After fiddling around a bit, I found out that that it can be handled using OnFailureListener as Exception generated by signInWithEmailAndPassword() is an instance of FirebaseNetworkException.


问:
ASP.Net MVC how does back-end know if user signed in
I created a ASP.Net C# MVC app with "Individual User Account" for Authentication + localDB. I started the app in visual studio with IIS express on localhost, signed up an user and logged in with that user.

I am trying to understand how back-end know a user has logged in in the following scenario:

start the iis express & app in visual studio

log in

stop the iis express & app in visual studio

start again the iis express & app in visual studio

user still logged in (WHY???)

I checked the user tables in db, and could not find any fields indicate a logged in user. I am thinking stop & restart iis express should clear everything in the back-end as well.

So how does the back-end know there was an user logged in in the step 5 above??

I found the following cookie in the http request

Cookie: _ga=GA1.1.1546797954.1551225891; __RequestVerificationToken=PSFeb9iP4aZr3wxxb8nJNKtki_1XPTzGO1Hzaf0W3iDsSCnV_qCfMsC9TY980X51c2rANZA-zureu6UHKEssAHza58AdmQUdZVL98VGYlRc1; .AspNet.ApplicationCookie=VUPznoprBRK2z13u03ArrC9HLHeGGUyTSvu9rYpSnZju_Rz4X2V5n9faw0EhnmuFjVN1AIva7HZSAhUBeSZ5jQHSej6XaAExy0hkwF_9vC190LfWBPP-oH3Zp0jj0ZmZ7L3sLlLqux4HV5CZSA-jqhDF4IXAFKyisFFV136PlxrJTmb9OXRrmo9rigCiIy0z_oixDlg1eHVI3T6ptVgn1Qhohtr1mTqoBJsF7gi7CHymSBlyFJ5MgYxfPcWNhJnj3H-WWK1ijkfzxsm0R13m2_6IbIiK1y5uzQBkklb8oMuz0mD27GlwMzteQBP3VLOXn77BreOPefJ8_2AekYjFGjgBIGGpngxLVzDneT4rC-BDiVKdWO_FRuail4ivVAN2ZJtdjK0uEPqnln5rmOlT0MLAhYzHMkk-HTvtW-Xo-Kexinlh58uxz0E7bncY5I6troc19E0fBLMnfXThtaL7ur6CN4pqUyq4yALJCTHszG3RPLQoJja0u1g34i-mKunZ

答:
In web development there is very basic concept called cookie.The cookie is responsible too store user information in browser. When you sign-in in membership system ,it adds a special header called Set-Cookie to response which afterward get's stored in browser cache.The information send through header contains information about loged in user's identity. With subsequent requests browser send the same cookie to the server and the membership system parses that info to identify the user which makes request and if the information is valid you are logged in and system identifies you.

EDIT :
The detail of operations taking place is not unique and depends on which library you use for authentication but if you use asp.net default authentication system then you can go and see how things get done in the source code.For  ASP.NET CORE check https://github.com/aspnet/AspNetIdentity and for ASP.NET MVC check : https://github.com/aspnet/Identity


问:
Python compare list of dictionaries with another dictionary in loop
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

```<code>a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)
</code>```

Below is the output When I tried to execute above code

```<code>Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]
</code>```

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

答:
you need to reverse the order of your loops.

```<code>a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for i,j in valueDict.items():

    for d in a:

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j

            break
    else:

        print('no value')

print(a)
</code>```

This works for me and does not print 'no value'

Body:
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)

Below is the output When I tried to execute above code

Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

Body:
you need to reverse the order of your loops.

a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for i,j in valueDict.items():

    for d in a:

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j

            break
    else:

        print('no value')

print(a)

This works for me and does not print 'no value'


问:
Julia | DataFrame | Replacing missing Values
How can we replace missing values with 0.0 for a column in a DataFrame?

答:
This is a shorter and more updated answer since Julia introduced the missing attribute recently.

```<code>using DataFrames
df = DataFrame(A=rand(1:50, 5), B=rand(1:50, 5), C=vcat(rand(1:50,3), missing, rand(1:50))) ## Creating random 5 integers within the range of 1:50, while introducing a missing variable in one of the rows
df = DataFrame(replace!(convert(Matrix, df), missing=>0)) ## Converting to matrix first, since replacing values directly within type dataframe is not allowed
</code>```

Body:
This is a shorter and more updated answer since Julia introduced the missing attribute recently.

using DataFrames
df = DataFrame(A=rand(1:50, 5), B=rand(1:50, 5), C=vcat(rand(1:50,3), missing, rand(1:50))) ## Creating random 5 integers within the range of 1:50, while introducing a missing variable in one of the rows
df = DataFrame(replace!(convert(Matrix, df), missing=>0)) ## Converting to matrix first, since replacing values directly within type dataframe is not allowed


问:
Can't resolve a promise with an ElementArrayFinder as argument
I'm writing a function in protractor that gets all the row elements of a list. The function checks for multiple types of lists. It uses the method isPresent() to check if one type of list exists. If not, it moves on to the next type. Since the isPresent() method is async, I must return my array of rows through a Promise. I am trying to return it as an ElementArrayFinder.

```<code>  public getAllListElements(listName: string): Promise<ElementArrayFinder> {

    return new Promise<ElementArrayFinder>((resolve) => {
      element(by.css('.list-title')).isPresent().then((result) => {
        let elems: ElementArrayFinder;
        if (result === true) {
          elems = element(by.cssContainingText('.list-title', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        } else {
          elems = element(by.cssContainingText('.mat-header-cell', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        }
      });
    });
  }
</code>```

After debugging, I can confirm that the data stored in the elems variable is an ElementArrayFinder. Therefore, the function which has called the getAllListElements function recieves an Array OF ElementFinders in it's callback. Here is one of the calls:

```<code>  navigateAllContacts() {
    this.helpers.getAllListElements('Contacts').then((contacts) => {
      contacts.count().then((size) => {
        console.log('Navigating trough ' + size + ' contacts');
      });
    });
  }
</code>```

So since i'm expecting contacts to be an ElementArrayFinder, i try calling its count() method. This fails since contacts is of the wrong type.

I have found a workaround to this. I "encapsulate" my ElementArrayFinder in a parent object and I resolve my promise with it. This way, the data type doesn't change. But I have to access the object's member in my callback, which is not ideal.

Here is the workaround:

```<code>  public getAllListElements(listName: string): Promise<any> {

    return new Promise<any>((resolve) => {
      element(by.css('.list-title')).isPresent().then((result) => {
        let elems = { eaf : null};
        if (result === true) {
          elems.eaf = element(by.cssContainingText('.list-title', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        } else {
          elems.eaf = element(by.cssContainingText('.mat-header-cell', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        }
      });
    });
  }
</code>```

And the method call:

```<code>  navigateAllContacts() {
    this.helpers.getAllListElements('Contacts').then((contacts) => {
      contacts.eaf.count().then((size) => {
        console.log('Navigating trough ' + size + ' contacts');
      });
    });
  }
</code>```

Any ideas of why this data alteration may occur?

答:
Try with following code.</p>

```<code>navigateAllContacts() {
    this.helpers.getAllListElements('Contacts').then(function(contacts) => {
      contacts.count().then(function(size) => {
        console.log('Navigating trough ' + size + ' contacts');
      });
    });
  }
</code>```

Body:
I'm writing a function in protractor that gets all the row elements of a list. The function checks for multiple types of lists. It uses the method isPresent() to check if one type of list exists. If not, it moves on to the next type. Since the isPresent() method is async, I must return my array of rows through a Promise. I am trying to return it as an ElementArrayFinder.

  public getAllListElements(listName: string): Promise<ElementArrayFinder> {

    return new Promise<ElementArrayFinder>((resolve) => {
      element(by.css('.list-title')).isPresent().then((result) => {
        let elems: ElementArrayFinder;
        if (result === true) {
          elems = element(by.cssContainingText('.list-title', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        } else {
          elems = element(by.cssContainingText('.mat-header-cell', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        }
      });
    });
  }

After debugging, I can confirm that the data stored in the elems variable is an ElementArrayFinder. Therefore, the function which has called the getAllListElements function recieves an Array OF ElementFinders in it's callback. Here is one of the calls:

  navigateAllContacts() {
    this.helpers.getAllListElements('Contacts').then((contacts) => {
      contacts.count().then((size) => {
        console.log('Navigating trough ' + size + ' contacts');
      });
    });
  }

So since i'm expecting contacts to be an ElementArrayFinder, i try calling its count() method. This fails since contacts is of the wrong type.

I have found a workaround to this. I "encapsulate" my ElementArrayFinder in a parent object and I resolve my promise with it. This way, the data type doesn't change. But I have to access the object's member in my callback, which is not ideal.

Here is the workaround:

  public getAllListElements(listName: string): Promise<any> {

    return new Promise<any>((resolve) => {
      element(by.css('.list-title')).isPresent().then((result) => {
        let elems = { eaf : null};
        if (result === true) {
          elems.eaf = element(by.cssContainingText('.list-title', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        } else {
          elems.eaf = element(by.cssContainingText('.mat-header-cell', listName)).element(by.xpath('../..')).all(by.css('mat-row'));
          resolve(elems);
        }
      });
    });
  }

And the method call:

  navigateAllContacts() {
    this.helpers.getAllListElements('Contacts').then((contacts) => {
      contacts.eaf.count().then((size) => {
        console.log('Navigating trough ' + size + ' contacts');
      });
    });
  }

Any ideas of why this data alteration may occur?

Body:
Try with following code.

navigateAllContacts() {
    this.helpers.getAllListElements('Contacts').then(function(contacts) => {
      contacts.count().then(function(size) => {
        console.log('Navigating trough ' + size + ' contacts');
      });
    });
  }


问:
Logic Apps custom action similar to Request Response
Is it possible to create a Logic Apps custom action similar to the Request Response action? If so, can you please guide me how I would do this? The Request Response action is different from other actions as it doesn't call an API, but instead responds to the trigger.

I'd like to create a specific version of the Request Response action that forces a certain status code and response structure, so that people using the connector understand how to use it. The action is to be used in conjunction with a custom trigger, which is basically a webhook. The API that call the webhook requires the response to be in a specific format. Right now I can make it work with the Request Response action, but I need to make sure I return the correct JSON structure.

答: Update, try Azure Api-Management. Otherwise, I would validate that all values are present and if not I would reply which values are missing.</p>


问:
React Native lost control of iOS status bar after calling 3-party library
I am using a 3rd-party library it will hide iOS status bar when calling. After that, I can't show the status bar back on screen.

I can control status bar by StatusBar component in React Native normally.

However, I tried to call a iOS library https://www.dynamsoft.com/Products/dynamsoft-webcam-sdk.aspx it will hide the status bar when showing it's screen.
After it hide the status bar, I can't show it up again using StatusBar.setHidden(false).

It don't prompt any error, just simply no effect.

Anyone knows what's going on and how can I show the status bar back in this situation?

答:
You can add the following code in your screen where you want to show your status bar

```<code>import React, { Component } from 'react';
import { StatusBar } from 'react-native';

class MyComponent extends Component {

componentDidMount() {
   StatusBar.setHidden(false);
}
}
</code>```

or you can also do

```<code><StatusBar hidden={false} />
</code>```

This will help you to show status bar in your desired screen

Body:
You can add the following code in your screen where you want to show your status bar

import React, { Component } from 'react';
import { StatusBar } from 'react-native';

class MyComponent extends Component {

componentDidMount() {
   StatusBar.setHidden(false);
}
}

or you can also do

<StatusBar hidden={false} />

This will help you to show status bar in your desired screen


问:
Using GPS to measure area
Hey guys, I'm researching something for a friend of mine who's involved in road construction. He needs some sort of a device that he can use to measure distance or area between points. I have done some GPS programming in the past but for mobile devices and i wasn't too impressed with accuracy. That was quite a few years ago and i think the technology has improved, however i am not sure what device i should as the receiver. Since a mobile device would probably be out of the question because i'd need to be able to run my custom application on it, something that hooks up through a USB port would maybe work? I found u-blox PCI hard that works with laptops and PCs. Has anyone on here had any experience with it? Perhaps there are other devices i'd need to look into?

I appreciate any help i can get on this. Thank you.

答:
If you really need to embed your own custom software, you could roll your own and go the Arduino route:

http://www.ladyada.net/make/gpsshield/

If processing the data later is an option I've found the AMOD AGL3080 to be a great bang for your buck data logger.  The accuracy is very good once it's warmed up and it mounts like a disk on Linux, OS X and Windows where you can just pull the logs off and process them.  You can use GPSBabel to convert them into whatever format you need, though the default is NMEA.

If someone else has a better solution I'd be curious to hear it too - affordable GPS toys for programmers seem hard to come by!

OwnerDisplayName: Sergey

LastEditorDisplayName: nzpcmad

ContentLicense: CC BY-SA 2.5

Title: Using GPS to measure area

OwnerDisplayName: georgemandis


问:
Jar in classpath not recognized
Visual Studio Code does not include either servlet-api.jar or mssql-jdbc-7.0.0.jre8.jar, no matter where I put it.

I have put it in the lib directory of the jdk, jre, and local to the code(src directory).

答:
Did you add the jar in the right way ?

you could refer to this issue :https://stackoverflow.com/a/56053944/10768653

and you could look at the doucument add jar

Title: Jar in classpath not recognized


问:
Flask app can't find module when deployed to azure - works fine locally
Azure gives a module import error but the same code runs perfectly locally.

```<code>2019-05-29T02:50:47.388004719Z: [ERROR]  Traceback (most recent call last):
2019-05-29T02:50:47.388027419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-05-29T02:50:47.388031719Z: [ERROR]      worker.init_process()
2019-05-29T02:50:47.388035419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-05-29T02:50:47.388039419Z: [ERROR]      self.load_wsgi()
2019-05-29T02:50:47.388043019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-05-29T02:50:47.388047119Z: [ERROR]      self.wsgi = self.app.wsgi()
2019-05-29T02:50:47.388050819Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-05-29T02:50:47.388054619Z: [ERROR]      self.callable = self.load()
2019-05-29T02:50:47.388075019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-05-29T02:50:47.388084919Z: [ERROR]      return self.load_wsgiapp()
2019-05-29T02:50:47.388088619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-05-29T02:50:47.388092219Z: [ERROR]      return util.import_app(self.app_uri)
2019-05-29T02:50:47.388095619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2019-05-29T02:50:47.388099119Z: [ERROR]      __import__(module)
2019-05-29T02:50:47.388102419Z: [ERROR]    File "/home/site/wwwroot/app.py", line 102, in <module>
2019-05-29T02:50:47.388106219Z: [ERROR]      from views.auth import register_user_bp, user_login_bp, user_logout_bp
2019-05-29T02:50:47.388109619Z: [ERROR]    File "/home/site/wwwroot/views/auth.py", line 4, in <module>
2019-05-29T02:50:47.388113619Z: [ERROR]      from Forms import *
2019-05-29T02:50:47.388116919Z: [ERROR]  ModuleNotFoundError: No module named 'Forms'
</code>```

It seems to find one of my custom modules, but not the one in the root directory from a subdirectory. However, it appears to successfully import Config.py from app.py, which are both in the root directory.

The program runs from app.py in the root directory if that is important

I think there is something about the way that gunicorn/WSGI works that I don't understand. I can't figure out what changes the way imports behave.

```<code>project_root
├── app.py
├── Config.py
├── Forms.py
├── __init__.py
├── manage.py
├── migrations
├── Models.py
├── requirements.txt
├── static
├── templates
│   ├── change_profile.html
│   ├── dash_app_layout.py
│   ├── default_login.html
│   ├── default_logout.html
│   ├── _formhelpers.html
│   ├── header.html
│   ├── index.html
│   ├── __init__.py
│   ├── nav_layout.py
│   ├── record_meeting.html
│   ├── register_user.html
│   ├── upload_meeting.html
│   └── voice_enroll.html
├── utils
│   ├── audio_processor
│   │   ├── AudioProcessor.py
│   │   ├── audio_type_converter.py
│   │   ├── Deidentifier.py
│   │   ├── Identification
│   │   ├── __init__.py
│   │   ├── Utterance.py
│   │   └── voice_enroll.py
│   ├── db_operations.py
│   ├── __init__.py
│   ├── interim_result_processor.py
│   └── utils.py
└── views
    ├── auth.py
    ├── dash_callbacks.py
    ├── __init__.py
    ├── meeting_upload.py
    ├── profile.py
    └── record_meeting.py
</code>```

I'm not sure why it works fine locally, but can't import from Forms.py when on the webapp. I'm pretty sure it has something to do with the file structure, but I can't figure out what and how to fix it.

答:
I tried to reproduce your issue, then I discovered the issue was possibly caused by missing your project path in the sys.path.

I guess that you developed locally in a Python virtual environment, so the sys.path will include your project path automatically when you command source <project_root>/bin/active to enable virtual environment. But without virtual environment, your project path will not be default imported into the sys.path of system Python runtime.

So the solution is that you can manually append /home/site/wwwroot to sys.path via add new code line into app.py as below.

```<code>from flask import Flask

import sys
sys.path.append('/home/site/wwwroot')

# Then you can normally import Forms module
from Forms import *
</code>```

Body:
Azure gives a module import error but the same code runs perfectly locally.

2019-05-29T02:50:47.388004719Z: [ERROR]  Traceback (most recent call last):
2019-05-29T02:50:47.388027419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-05-29T02:50:47.388031719Z: [ERROR]      worker.init_process()
2019-05-29T02:50:47.388035419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-05-29T02:50:47.388039419Z: [ERROR]      self.load_wsgi()
2019-05-29T02:50:47.388043019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-05-29T02:50:47.388047119Z: [ERROR]      self.wsgi = self.app.wsgi()
2019-05-29T02:50:47.388050819Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-05-29T02:50:47.388054619Z: [ERROR]      self.callable = self.load()
2019-05-29T02:50:47.388075019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-05-29T02:50:47.388084919Z: [ERROR]      return self.load_wsgiapp()
2019-05-29T02:50:47.388088619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-05-29T02:50:47.388092219Z: [ERROR]      return util.import_app(self.app_uri)
2019-05-29T02:50:47.388095619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2019-05-29T02:50:47.388099119Z: [ERROR]      __import__(module)
2019-05-29T02:50:47.388102419Z: [ERROR]    File "/home/site/wwwroot/app.py", line 102, in <module>
2019-05-29T02:50:47.388106219Z: [ERROR]      from views.auth import register_user_bp, user_login_bp, user_logout_bp
2019-05-29T02:50:47.388109619Z: [ERROR]    File "/home/site/wwwroot/views/auth.py", line 4, in <module>
2019-05-29T02:50:47.388113619Z: [ERROR]      from Forms import *
2019-05-29T02:50:47.388116919Z: [ERROR]  ModuleNotFoundError: No module named 'Forms'

It seems to find one of my custom modules, but not the one in the root directory from a subdirectory. However, it appears to successfully import Config.py from app.py, which are both in the root directory.

The program runs from app.py in the root directory if that is important

I think there is something about the way that gunicorn/WSGI works that I don't understand. I can't figure out what changes the way imports behave.

project_root
├── app.py
├── Config.py
├── Forms.py
├── __init__.py
├── manage.py
├── migrations
├── Models.py
├── requirements.txt
├── static
├── templates
│   ├── change_profile.html
│   ├── dash_app_layout.py
│   ├── default_login.html
│   ├── default_logout.html
│   ├── _formhelpers.html
│   ├── header.html
│   ├── index.html
│   ├── __init__.py
│   ├── nav_layout.py
│   ├── record_meeting.html
│   ├── register_user.html
│   ├── upload_meeting.html
│   └── voice_enroll.html
├── utils
│   ├── audio_processor
│   │   ├── AudioProcessor.py
│   │   ├── audio_type_converter.py
│   │   ├── Deidentifier.py
│   │   ├── Identification
│   │   ├── __init__.py
│   │   ├── Utterance.py
│   │   └── voice_enroll.py
│   ├── db_operations.py
│   ├── __init__.py
│   ├── interim_result_processor.py
│   └── utils.py
└── views
    ├── auth.py
    ├── dash_callbacks.py
    ├── __init__.py
    ├── meeting_upload.py
    ├── profile.py
    └── record_meeting.py

I'm not sure why it works fine locally, but can't import from Forms.py when on the webapp. I'm pretty sure it has something to do with the file structure, but I can't figure out what and how to fix it.

Body:
I tried to reproduce your issue, then I discovered the issue was possibly caused by missing your project path in the sys.path.

I guess that you developed locally in a Python virtual environment, so the sys.path will include your project path automatically when you command source <project_root>/bin/active to enable virtual environment. But without virtual environment, your project path will not be default imported into the sys.path of system Python runtime.

So the solution is that you can manually append /home/site/wwwroot to sys.path via add new code line into app.py as below.

from flask import Flask

import sys
sys.path.append('/home/site/wwwroot')

# Then you can normally import Forms module
from Forms import *


问:
android: string format specify bold
I have a string defined in string.xml like

```<code><string name="eventtitle">Title: %1$s </string>
</code>```

which is formatted using string.format . How to define the string to get only the Titel: as Bold.

Thanks in advance for the help

答:
Actually, many of the answers are obsolete. After researching by myself, what I've found out that the best answer is one by @Wahib. Here's the improved version:

Define the string resource as a:

```<code><string name="styled_text">Hey, <b>this is bold</b> text</string>
</code>```

Use the resource like this:

```<code>String text = getResources().getString(R.string.styled_text);
CharSequence styledText = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY);
textview.setText(styledText);
</code>```

Here's the result:

Title: android: string format specify bold

Body:
I have a string defined in string.xml like

<string name="eventtitle">Title: %1$s </string>

which is formatted using string.format . How to define the string to get only the Titel: as Bold.

Thanks in advance for the help

Body:
Actually, many of the answers are obsolete. After researching by myself, what I've found out that the best answer is one by @Wahib. Here's the improved version:

Define the string resource as a:

<string name="styled_text">Hey, &lt;b>this is bold&lt;/b> text</string>

Use the resource like this:

String text = getResources().getString(R.string.styled_text);
CharSequence styledText = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY);
textview.setText(styledText);

Here's the result:


问:
How to use jq wildcard
I have the following json:

{
   "details":{
      "car": "bmw",
      "addresses":{
         "ext-118-21-8-0-29":[
            {
               "version":4,
               "addr":"89 Psr"
            },
            {
               "version":6,
               "addr":"56 apT"
            }
         ]
      }
   }
}
```
<p>The key <code>ext-118-21-8-0-29</code> is dynamic it will change the next time and I don't know the exact value, that's why I need to use wildcard. I need to get the value of the key <code>addr</code> where version is <code>4</code>.</p>
<p>I'm expectig as output <code>89 Psr</code></p>
<p>I tried the following using the function <code>startswith()</code>.</p>
<pre class="lang-bash prettyprint-override"><code>jq '.detail.addresses | select(startswith("ext"))'
</code>```

But it end with an error.

jq: error (at :0): startswith() requires string inputs

答:
If you don't care about the keys in the object you're searching, you could just search the values of the object using [] which you could then filter to your desired results.

```<code>.details.addresses[][] | select(.version == 4).addr
</code>```

If on the other hand you wanted to select keys that has a version 4, you could use to_entries to do this:

```<code>.details.addresses | to_entries[] | select(any(.value[]; .version == 4)).key
</code>```

Title: How to use jq wildcard

Body:
I have the following json:

{
   "details":{
      "car": "bmw",
      "addresses":{
         "ext-118-21-8-0-29":[
            {
               "version":4,
               "addr":"89 Psr"
            },
            {
               "version":6,
               "addr":"56 apT"
            }
         ]
      }
   }
}

The key ext-118-21-8-0-29 is dynamic it will change the next time and I don't know the exact value, that's why I need to use wildcard. I need to get the value of the key addr where version is 4.

I'm expectig as output 89 Psr

I tried the following using the function startswith().

jq '.detail.addresses | select(startswith("ext"))'

But it end with an error.

jq: error (at :0): startswith() requires string inputs

Body:
If you don't care about the keys in the object you're searching, you could just search the values of the object using [] which you could then filter to your desired results.

.details.addresses[][] | select(.version == 4).addr

If on the other hand you wanted to select keys that has a version 4, you could use to_entries to do this:

.details.addresses | to_entries[] | select(any(.value[]; .version == 4)).key


问:
Array of custom object model won't save to shared preferences
I am trying to do a module where once I fetched the JSON from the API and I am loading it into RAM memory I immediately load it to Shared Prefs and also once I any change to the data (in the adapter onClick method) I re-save the new changed array into the shared preferences. Apparently it does not work and I can't figure out why.

Here is my activity containing all of the relevant code:

```<code>
package com.example.superheros.Controllers;

import android.content.SharedPreferences;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;

import com.example.superheros.Adapter.HeroesAdapter;
import com.example.superheros.Model.Hero;
import com.example.superheros.Networking.HttpRequest;
import com.example.superheros.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    //API constant -
    private static final String BASE_URL = "https://heroapps.co.il/employee-tests/android/androidexam.json";
    public static final String SAVED_HERO_LIST = "heroesList";
    // Recyclerview variables -
    private RecyclerView heroesRecylerView;
    private ArrayList<Hero> heroesArrayList;
    private RecyclerView.LayoutManager layoutManager;
    private HeroesAdapter heroesAdapter;
    //Toolbar variables -
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView toolbarImageView;
    //Persistence variables -
    private Hero selectedFavoriteHero;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            heroesArrayList = loadFromLocal();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        if (heroesArrayList != null && heroesArrayList.size() > 0){
            initViews();
        } else {
            initNetworking();
        }

    }

    private void initNetworking() {
        HttpRequest httpRequest = new HttpRequest(this, BASE_URL, new HttpRequest.OnHttpCompleteListener() {
            @Override
            public void onComplete(String response) {
                dataToModel(response, false);
                initViews();
            }

            @Override
            public void onError(String error) {
                Log.d("error", error);
            }
        });
        httpRequest.request();
    }

    private void initViews() {
        heroesRecylerView = findViewById(R.id.herosRecyclerView);
        collapsingToolbarLayout = findViewById(R.id.collapsingHeroToolbarLayout);
        toolbarImageView = findViewById(R.id.toolbarImageview);
        heroesRecylerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        heroesRecylerView.setLayoutManager(layoutManager);
        heroesAdapter = new HeroesAdapter(heroesArrayList, new HeroesAdapter.OnHeroListClickListener() {
            @Override
            public void onListItemClicked(int position) {
                changeFavoriteHero(position);
            }
        });
        heroesRecylerView.setAdapter(heroesAdapter);

    }

    private void changeFavoriteHero(int position) {
        Hero pressedHeroRow = heroesArrayList.get(position);
        selectedFavoriteHero = pressedHeroRow;
        Picasso.get().load(pressedHeroRow.image)
                .fit()
                .centerCrop()
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_foreground)
                .into(toolbarImageView);
        collapsingToolbarLayout.setTitle(pressedHeroRow.title);
        pressedHeroRow.setFavorite(!pressedHeroRow.isFavorite());
        for (int i = 0; i < heroesArrayList.size(); i++) {
            if (i == position) continue;
            heroesArrayList.get(i).setFavorite(false);
        }
        saveToLocal(heroesArrayList);
        heroesAdapter.notifyDataSetChanged();
    }

    private ArrayList<Hero> dataToModel(String json, boolean isLocalInfo) {
        Gson gson = new Gson();
        Hero[] heroesList = gson.fromJson(json, Hero[].class);
        heroesArrayList = new ArrayList<>(Arrays.asList(heroesList));
        if (!isLocalInfo) {
            saveToLocal(heroesArrayList);
        }
        return heroesArrayList;
    }

    //Shared preferences load & save methods -

    private void saveToLocal(ArrayList<Hero> heroesArrayList) {
        sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String heroesList = gson.toJson(heroesArrayList);
        Log.d("heroArrayList", heroesList);
        prefsEditor.putString(SAVED_HERO_LIST, heroesList);
        prefsEditor.apply();
    }

    private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = gson.fromJson(SAVED_HERO_LIST, String.class);
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
}

</code>```

I hope I can be pointed about what I was missing

答:
change

```<code>prefsEditor.apply();
</code>```

to

```<code>prefsEditor.commit();
</code>```

apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. As you're accessing the same preferences object (is a singleton) you should see a consistent view at all times but not in your case you access from separate thread.

Body:
I am trying to do a module where once I fetched the JSON from the API and I am loading it into RAM memory I immediately load it to Shared Prefs and also once I any change to the data (in the adapter onClick method) I re-save the new changed array into the shared preferences. Apparently it does not work and I can't figure out why.

Here is my activity containing all of the relevant code:

package com.example.superheros.Controllers;

import android.content.SharedPreferences;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;

import com.example.superheros.Adapter.HeroesAdapter;
import com.example.superheros.Model.Hero;
import com.example.superheros.Networking.HttpRequest;
import com.example.superheros.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    //API constant -
    private static final String BASE_URL = "https://heroapps.co.il/employee-tests/android/androidexam.json";
    public static final String SAVED_HERO_LIST = "heroesList";
    // Recyclerview variables -
    private RecyclerView heroesRecylerView;
    private ArrayList<Hero> heroesArrayList;
    private RecyclerView.LayoutManager layoutManager;
    private HeroesAdapter heroesAdapter;
    //Toolbar variables -
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView toolbarImageView;
    //Persistence variables -
    private Hero selectedFavoriteHero;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            heroesArrayList = loadFromLocal();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        if (heroesArrayList != null && heroesArrayList.size() > 0){
            initViews();
        } else {
            initNetworking();
        }

    }

    private void initNetworking() {
        HttpRequest httpRequest = new HttpRequest(this, BASE_URL, new HttpRequest.OnHttpCompleteListener() {
            @Override
            public void onComplete(String response) {
                dataToModel(response, false);
                initViews();
            }

            @Override
            public void onError(String error) {
                Log.d("error", error);
            }
        });
        httpRequest.request();
    }

    private void initViews() {
        heroesRecylerView = findViewById(R.id.herosRecyclerView);
        collapsingToolbarLayout = findViewById(R.id.collapsingHeroToolbarLayout);
        toolbarImageView = findViewById(R.id.toolbarImageview);
        heroesRecylerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        heroesRecylerView.setLayoutManager(layoutManager);
        heroesAdapter = new HeroesAdapter(heroesArrayList, new HeroesAdapter.OnHeroListClickListener() {
            @Override
            public void onListItemClicked(int position) {
                changeFavoriteHero(position);
            }
        });
        heroesRecylerView.setAdapter(heroesAdapter);

    }

    private void changeFavoriteHero(int position) {
        Hero pressedHeroRow = heroesArrayList.get(position);
        selectedFavoriteHero = pressedHeroRow;
        Picasso.get().load(pressedHeroRow.image)
                .fit()
                .centerCrop()
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_foreground)
                .into(toolbarImageView);
        collapsingToolbarLayout.setTitle(pressedHeroRow.title);
        pressedHeroRow.setFavorite(!pressedHeroRow.isFavorite());
        for (int i = 0; i < heroesArrayList.size(); i++) {
            if (i == position) continue;
            heroesArrayList.get(i).setFavorite(false);
        }
        saveToLocal(heroesArrayList);
        heroesAdapter.notifyDataSetChanged();
    }

    private ArrayList<Hero> dataToModel(String json, boolean isLocalInfo) {
        Gson gson = new Gson();
        Hero[] heroesList = gson.fromJson(json, Hero[].class);
        heroesArrayList = new ArrayList<>(Arrays.asList(heroesList));
        if (!isLocalInfo) {
            saveToLocal(heroesArrayList);
        }
        return heroesArrayList;
    }

    //Shared preferences load & save methods -

    private void saveToLocal(ArrayList<Hero> heroesArrayList) {
        sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String heroesList = gson.toJson(heroesArrayList);
        Log.d("heroArrayList", heroesList);
        prefsEditor.putString(SAVED_HERO_LIST, heroesList);
        prefsEditor.apply();
    }

    private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = gson.fromJson(SAVED_HERO_LIST, String.class);
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
}

I hope I can be pointed about what I was missing

Body:
change

prefsEditor.apply();

to

prefsEditor.commit();

apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. As you're accessing the same preferences object (is a singleton) you should see a consistent view at all times but not in your case you access from separate thread.


问:
How to update Angular 7 to Angular 8 by ng update
I try update Angular project from version 7.2.5 to 8 of the core framework and CLI by running ng update @angular/cli @angular/core in terminal.

Response from terminal was 'We analyzed your package.json and everything seems to be in order. Good work!'

My version list:

```<code>$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.3.9
Node: 11.14.0
OS: darwin x64
Angular: 7.2.15
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.13.9
@angular-devkit/build-angular      0.13.9
@angular-devkit/build-ng-packagr   0.13.9
@angular-devkit/build-optimizer    0.13.9
@angular-devkit/build-webpack      0.13.9
@angular-devkit/core               7.3.9
@angular-devkit/schematics         7.3.9
@angular/cdk                       7.3.7
@angular/cli                       7.3.9
@angular/material                  7.3.7
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.3.9
@schematics/angular                7.3.9 (cli-only)
@schematics/update                 0.13.9
ng-packagr                         5.2.0
rxjs                               6.5.2
typescript                         3.2.4
webpack                            4.29.0
</code>```

答:
As of today it is alread stable 8.0.0 :)

You might want to try to run ng update --all to update all packages in your package.json file.
That might, however, not proceed if it discovers that some inter-dependencies are not met among other packages.
In such a case you might want to also add --force option.

Alternatively, you can choose a more tailored approach and hand-pick packages to update (as suggested in answer by Veeraragavan), but you no longer need to add @next version, since all Angular package 8.0.0 versions are stable as of now.

Body:
I try update Angular project from version 7.2.5 to 8 of the core framework and CLI by running ng update @angular/cli @angular/core in terminal.

Response from terminal was 'We analyzed your package.json and everything seems to be in order. Good work!'

My version list:

$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.3.9
Node: 11.14.0
OS: darwin x64
Angular: 7.2.15
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.13.9
@angular-devkit/build-angular      0.13.9
@angular-devkit/build-ng-packagr   0.13.9
@angular-devkit/build-optimizer    0.13.9
@angular-devkit/build-webpack      0.13.9
@angular-devkit/core               7.3.9
@angular-devkit/schematics         7.3.9
@angular/cdk                       7.3.7
@angular/cli                       7.3.9
@angular/material                  7.3.7
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.3.9
@schematics/angular                7.3.9 (cli-only)
@schematics/update                 0.13.9
ng-packagr                         5.2.0
rxjs                               6.5.2
typescript                         3.2.4
webpack                            4.29.0


问:
Open modal dialog on event bus event
I've created a backend and am now trying to build a frontend, using it. I'm very new to Vue.js and am having a hard time telling it to do what I want; probably because of missing some basic concepts. Hopefully someone can point me in the right direction.

The App.vue groups following components: Header, main section (routed), footer and a modal login dialog.

The issue I'm trying to solve is to display the modal login dialog when clicking the Login button (which lives in the header component); currently, nothing besides the messages being logged happens.

For this I've created an event bus and am firing an event:

```<code>export default {
  name: 'SppdTeamTunerHeader',
  methods: {
    emitShowLoginDialogEvent () {
      EventBus.$emit('ShowLoginDialog', true)
    }
  }
}
</code>```

Emitting the event works as I can see in the Vue DevTools for Chrome.

Here's the complete code of App.vue:

```<code><template>
  <div id="app">
    <SppdTeamTunerHeader/>
    <router-view></router-view>
    <SppdTeamTunerFooter/>

    <LoginDialogModal
      v-show="isLoginDialogVisible"
    />
  </div>
</template>

<script>
import SppdTeamTunerHeader from '@/components/TheHeader'
import SppdTeamTunerFooter from '@/components/TheFooter'
import LoginDialogModal from '@/components/LoginDialogModal'
import { EventBus } from '@/common/EventBus'

export default {
  name: 'App',
  components: {
    SppdTeamTunerHeader,
    SppdTeamTunerFooter,
    LoginDialogModal
  },
  data: function () {
    return {
      isLoginDialogVisible: false
    }
  },
  mounted () {
    EventBus.$on('ShowLoginDialog', function (isVisible) {
      console.log('Setting ShowLoginDialog isVisible=' + isVisible + '. isLoginDialogVisible=' + this.isLoginDialogVisible)
      if (isVisible) {
        this.isLoginDialogVisible = true
      } else {
        this.isLoginDialogVisible = false
      }
      console.log('Finished setting isLoginDialogVisible=' + this.isLoginDialogVisible)
    })
  },
  destroyed () {
    EventBus.$off('ShowLoginDialog')
  }
}
</script>
</code>```

When checking the console, following is being printed when clicking the login button:

```<code>Setting ShowLoginDialog isVisible=true. isLoginDialogVisible=undefined
Finished setting isLoginDialogVisible=true
</code>```

The value logged for isLoginDialogVisible can't come from the variable defined in the data function as it prints undefined, whereas it has been defined as false (I guess that's my main problem).

I've read quite a few articles about the subject, e.g:

https://codingexplained.com/coding/front-end/vue-js/why-components-data-properties-must-be-functions

https://v2.vuejs.org/v2/guide/instance.html#Data-and-Methods

The modal dialog example I've based the implementation comes from here: https://alligator.io/vuejs/vue-modal-component/

答:
I believe your listener for the EventBus events needs to be accessible to App. Right now EventBus and App are two separate instances. You could mount the event handler inside App like this:</p>

```<code>mounted () {
   EventBus.$on('ShowLoginDialog', function (isVisible) {
      ...
    });
</code>```

Title: Open modal dialog on event bus event

Body:
I've created a backend and am now trying to build a frontend, using it. I'm very new to Vue.js and am having a hard time telling it to do what I want; probably because of missing some basic concepts. Hopefully someone can point me in the right direction.

The App.vue groups following components: Header, main section (routed), footer and a modal login dialog.

The issue I'm trying to solve is to display the modal login dialog when clicking the Login button (which lives in the header component); currently, nothing besides the messages being logged happens.

For this I've created an event bus and am firing an event:

export default {
  name: 'SppdTeamTunerHeader',
  methods: {
    emitShowLoginDialogEvent () {
      EventBus.$emit('ShowLoginDialog', true)
    }
  }
}

Emitting the event works as I can see in the Vue DevTools for Chrome.

Here's the complete code of App.vue:

<template>

    <SppdTeamTunerHeader/>
    <router-view></router-view>
    <SppdTeamTunerFooter/>

    <LoginDialogModal
      v-show="isLoginDialogVisible"
    />

</template>

When checking the console, following is being printed when clicking the login button:

Setting ShowLoginDialog isVisible=true. isLoginDialogVisible=undefined
Finished setting isLoginDialogVisible=true

The value logged for isLoginDialogVisible can't come from the variable defined in the data function as it prints undefined, whereas it has been defined as false (I guess that's my main problem).

I've read quite a few articles about the subject, e.g:

https://codingexplained.com/coding/front-end/vue-js/why-components-data-properties-must-be-functions

https://v2.vuejs.org/v2/guide/instance.html#Data-and-Methods

The modal dialog example I've based the implementation comes from here: https://alligator.io/vuejs/vue-modal-component/

Body:
I believe your listener for the EventBus events needs to be accessible to App. Right now EventBus and App are two separate instances. You could mount the event handler inside App like this:

mounted () {
   EventBus.$on('ShowLoginDialog', function (isVisible) {
      ...
    });


问:
Hello world program of dynamicallyModifiesClasspath() of Apache Nifi properties descriptor not working
I have a processor which depends on some jar as a dependency. However changes are made to the dependency jar quite frequenctly. So I want to be able to specify the jar path as a property of processor and let the nifi load the jar each time I modify the path in the property and restart the processor. This is supposed to be doable using dynamicallyModifiesClasspath as explained in this article. However I am unable to do this. Below is my code of hello world program using dynamicallyModifiesClasspath property:

(Below, Djl stands for "dynamic jar loading", a random prefix I guessed to name this hello world program.)

DjlDependencyClass.java

This is the class on which my nifi processor depends and I want to dynamically change its jar path in my nifi processor.

```<code>public class DjlDependencyClass {

    public static String getMessage()
    {
        return "DJL-DEPENDENCY VERSION-1";
    }
}
</code>```

MyDjlProcessor.java

This is the nifi processor which depends on DjlDependencyClass.

```<code>import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.util.StandardValidators;

import com.mycompany.djldependency.DjlDependencyClass;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyDjlProcessor extends AbstractProcessor {

    public static final Relationship MY_RELATIONSHIP = new Relationship.Builder()
            .name("MY_RELATIONSHIP")
            .description("Example relationship")
            .build();

    public static final PropertyDescriptor pathToDjlDependencyJar = new PropertyDescriptor.Builder()
            .name("Djl Dependency JAR")
            .description("Djl Dependency JAR")
            .required(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .dynamicallyModifiesClasspath(true)
            .expressionLanguageSupported(true)
            .build();

    private List<PropertyDescriptor> descriptors;

    private Set<Relationship> relationships;

    @Override
    protected void init(final ProcessorInitializationContext context) {
        final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>();
        descriptors.add(pathToDjlDependencyJar);
        this.descriptors = Collections.unmodifiableList(descriptors);

        final Set<Relationship> relationships = new HashSet<Relationship>();
        relationships.add(MY_RELATIONSHIP);
        this.relationships = Collections.unmodifiableSet(relationships);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return this.relationships;
    }

    @Override
    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return descriptors;
    }

    @OnScheduled
    public void onScheduled(final ProcessContext context) {

    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
        System.out.println(DjlDependencyClass.getMessage());
    }
}
</code>```

This is how dependency inside pom is marked to have provided scope, so that the dependency jar will not be embedded inside nar:

```<code>   <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>djl-dependency</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>provided </scope>
    </dependency>
</code>```

I am testing this processor as follows:

Configuration of the processor:

I am getting following exception:

```<code>2019-05-27 17:01:54,536 ERROR [Timer-Driven Process Thread-1] com.mycompany.djl.MyDjlProcessor MyDjlProcessor[id=f8fa5750-016a-1000-ecc3-c19732119332] MyDjlProcessor[id=f8fa5750-016a-1000-ecc3-c19732119332] failed to process due to java.lang.NoClassDefFoundError: com/mycompany/djldependency/DjlDependencyClass; rolling back session: {}
java.lang.NoClassDefFoundError: com/mycompany/djldependency/DjlDependencyClass
    at com.mycompany.djl.MyDjlProcessor.onTrigger(MyDjlProcessor.java:76)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1122)
    at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:147)
    at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:47)
    at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:128)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Am I doing something stupid here?

Please download both projects (nifi and dependency jar) here.

答:
The API document for PropertyDescriptor mentions the following note:

If a component contains a PropertyDescriptor where dynamicallyModifiesClasspath is set to true, the component must also be annotated with @RequiresInstanceClassloading, otherwise the component will be considered invalid.

I'm not sure whether that 'invalid' part still holds true but yeah, after updating your processor code to have it annotated with @RequiresInstanceClassloading, I was able to get it working.

Body:
I have a processor which depends on some jar as a dependency. However changes are made to the dependency jar quite frequenctly. So I want to be able to specify the jar path as a property of processor and let the nifi load the jar each time I modify the path in the property and restart the processor. This is supposed to be doable using dynamicallyModifiesClasspath as explained in this article. However I am unable to do this. Below is my code of hello world program using dynamicallyModifiesClasspath property:

(Below, Djl stands for "dynamic jar loading", a random prefix I guessed to name this hello world program.)

DjlDependencyClass.java

This is the class on which my nifi processor depends and I want to dynamically change its jar path in my nifi processor.

public class DjlDependencyClass {

    public static String getMessage()
    {
        return "DJL-DEPENDENCY VERSION-1";
    }
}

MyDjlProcessor.java

This is the nifi processor which depends on DjlDependencyClass.

import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.util.StandardValidators;

import com.mycompany.djldependency.DjlDependencyClass;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyDjlProcessor extends AbstractProcessor {

    public static final Relationship MY_RELATIONSHIP = new Relationship.Builder()
            .name("MY_RELATIONSHIP")
            .description("Example relationship")
            .build();

    public static final PropertyDescriptor pathToDjlDependencyJar = new PropertyDescriptor.Builder()
            .name("Djl Dependency JAR")
            .description("Djl Dependency JAR")
            .required(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .dynamicallyModifiesClasspath(true)
            .expressionLanguageSupported(true)
            .build();

    private List<PropertyDescriptor> descriptors;

    private Set<Relationship> relationships;

    @Override
    protected void init(final ProcessorInitializationContext context) {
        final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>();
        descriptors.add(pathToDjlDependencyJar);
        this.descriptors = Collections.unmodifiableList(descriptors);

        final Set<Relationship> relationships = new HashSet<Relationship>();
        relationships.add(MY_RELATIONSHIP);
        this.relationships = Collections.unmodifiableSet(relationships);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return this.relationships;
    }

    @Override
    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return descriptors;
    }

    @OnScheduled
    public void onScheduled(final ProcessContext context) {

    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
        System.out.println(DjlDependencyClass.getMessage());
    }
}

This is how dependency inside pom is marked to have provided scope, so that the dependency jar will not be embedded inside nar:

   <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>djl-dependency</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>provided </scope>
    </dependency>

I am testing this processor as follows:

Configuration of the processor:

I am getting following exception:

2019-05-27 17:01:54,536 ERROR [Timer-Driven Process Thread-1] com.mycompany.djl.MyDjlProcessor MyDjlProcessor[id=f8fa5750-016a-1000-ecc3-c19732119332] MyDjlProcessor[id=f8fa5750-016a-1000-ecc3-c19732119332] failed to process due to java.lang.NoClassDefFoundError: com/mycompany/djldependency/DjlDependencyClass; rolling back session: {}
java.lang.NoClassDefFoundError: com/mycompany/djldependency/DjlDependencyClass
    at com.mycompany.djl.MyDjlProcessor.onTrigger(MyDjlProcessor.java:76)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1122)
    at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:147)
    at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:47)
    at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:128)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Am I doing something stupid here?

Please download both projects (nifi and dependency jar) here.


问:
file get content from iframe
I would like to get content of a iframe with id or class of that iframe.

```<code>$links = "https://www.amazon.co.uk/Book-Secret-Wisdom-Prophetic-Evolution/dp/599054314X/ref=pd_sbs_14_2/257-3608675-7951114?_encoding=UTF8&pd_rd_i=599054314X&pd_rd_r=f103ccc1-7985-11e9-987c-178a1a538946&pd_rd_w=E5xsZ&pd_rd_wg=206kw&pf_rd_p=18edf98b-139a-41ee-bb40-d725dd59d1d3&pf_rd_r=MV7NZ41V278ECZM1135G&psc=1&refRID=MV7NZ41V278ECZM1135G";

$res = @file_get_contents($links);

$dom = new DomDocument();

@$dom->loadHTML($res);

$xpath = new DOMXpath($dom);
</code>```

I would like to get content by id:

```<code>$dom->getElementById('iframeContent');
</code>```

However, it alway return a page, not content of that iframe.

Anyone meet that problem?, pls help.

答:
Iframes don't have content (well, they might, but it is alternative content for when iframes are not supported by the client).

They have a src attribute containing a URL pointing at an external document.

You need to read the src attribute value, resolve it to an absolute URL (if it isn't one already), then make an HTTP request to it, parse that, and extract the data from it.

OwnerDisplayName: the light

Title: file get content from iframe

Body:
I would like to get content of a iframe with id or class of that iframe.

$links = "https://www.amazon.co.uk/Book-Secret-Wisdom-Prophetic-Evolution/dp/599054314X/ref=pd_sbs_14_2/257-3608675-7951114?_encoding=UTF8&pd_rd_i=599054314X&pd_rd_r=f103ccc1-7985-11e9-987c-178a1a538946&pd_rd_w=E5xsZ&pd_rd_wg=206kw&pf_rd_p=18edf98b-139a-41ee-bb40-d725dd59d1d3&pf_rd_r=MV7NZ41V278ECZM1135G&psc=1&refRID=MV7NZ41V278ECZM1135G";

$res = @file_get_contents($links);

$dom = new DomDocument();

@$dom->loadHTML($res);

$xpath = new DOMXpath($dom);

I would like to get content by id:

$dom->getElementById('iframeContent');

However, it alway return a page, not content of that iframe.

Anyone meet that problem?, pls help.


问:
Python list creation with multiple loops
lets say I have one list ['A','B','C']

and the second [1,2]

I want to create a new list [(A,1), (A,2), (B,1)...]

Obviously it can be trivially done using a for loop like this:

```<code>a = ['A','B','C']
b = [1,2]
c = []
for x in a:
    for y in b:
        c.append((x,y))

c
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]
</code>```

but how can I do it using the [x for x in...] syntax ?

答:
You need the Cartesian Product of the two lists:

```<code>>>> from itertools import product

>>> list(product(a, b))
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]
</code>```

Unlike an explicit list comprehension, this is trivially scalable to any number of input iterables. See here for details.

Body:
lets say I have one list ['A','B','C']

and the second [1,2]

I want to create a new list [(A,1), (A,2), (B,1)...]

Obviously it can be trivially done using a for loop like this:

a = ['A','B','C']
b = [1,2]
c = []
for x in a:
    for y in b:
        c.append((x,y))

c
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

but how can I do it using the [x for x in...] syntax ?

Body:
You need the Cartesian Product of the two lists:

>>> from itertools import product

>>> list(product(a, b))
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

Unlike an explicit list comprehension, this is trivially scalable to any number of input iterables. See here for details.


问:
Extracting specific and latest data from http webserver using golang
I'm trying to make a simple blockchain and store the data to the webserver based on this tutorial https://github.com/mycoralhealth/blockchain-tutorial/tree/master/proof-work. I want to get the latest value by using get request but only the specific data not all the data, for example only the PrevHash and Data.

I tried this code to send a get request to the server.

```<code>package main

import (

"net/http"
"log"
"io/ioutil"
"fmt"
"encoding/json")

func main() {

MakeRequest()
}

func MakeRequest() {

resp, err := http.Get("http://localhost:5555/")
if err != nil {
    log.Fatalln(err)
}

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalln(err)
}

var data map[string]interface{}
    err = json.Unmarshal([]byte(body), &data)
    if err != nil {
        panic(err)
    }
    fmt.Println(data["Data"])
}
</code>```

But it gives the output:
panic: json: cannot unmarshal array into Go value of type map[string]interface {}

Update:
This is my data in webserver. I want to get the value of parameter "Data" based the newest NoBlock, which is always updated.

```<code>([]main.Block) (len=2 cap=2) {
(main.Block) {
NoBlock: (int) 0,
Timestamp: (string) (len=39) "2019-05-29 14:50:00.966201709 +0800 +08",
Data: (string) "",
Hash: (string) (len=64) "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
PrevHash: (string) "",
Difficulty: (int) 0,
Nonce: (string) ""
},
(main.Block) {
NoBlock: (int) 1,
Timestamp: (string) (len=39) "2019-05-29 14:50:12.891324534 +0800 +08",
Data: (string) (len=110) "3e19124ee3a459d5c6edcb9b2a37cf2c4febd2e3ab8a8628f1bfb197bdaf5accada8349d9a99cfbf7cdd1af003c14f7c5c004f53c1d231",
Hash: (string) (len=64) "b2aebe50c3ace8230cb8d839d4e36da8899a2d0f0a3c1dbc9e9c717f74ead464",
PrevHash: (string) (len=64) "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
Difficulty: (int) 0,
Nonce: (string) (len=1) "0"
 }
}
</code>```

Please help me, thank you.

答:
Your body data is a JSON array so the unmarshalling has to be to an array</p>

```<code>var data []map[string]interface{} // add this to declaration
err = json.Unmarshal([]byte(body), &data)
</code>```

Body:
I'm trying to make a simple blockchain and store the data to the webserver based on this tutorial https://github.com/mycoralhealth/blockchain-tutorial/tree/master/proof-work. I want to get the latest value by using get request but only the specific data not all the data, for example only the PrevHash and Data.

I tried this code to send a get request to the server.

package main

import (

"net/http"
"log"
"io/ioutil"
"fmt"
"encoding/json")

func main() {

MakeRequest()
}

func MakeRequest() {

resp, err := http.Get("http://localhost:5555/")
if err != nil {
    log.Fatalln(err)
}

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalln(err)
}

var data map[string]interface{}
    err = json.Unmarshal([]byte(body), &data)
    if err != nil {
        panic(err)
    }
    fmt.Println(data["Data"])
}

But it gives the output:
panic: json: cannot unmarshal array into Go value of type map[string]interface {}

Update:
This is my data in webserver. I want to get the value of parameter "Data" based the newest NoBlock, which is always updated.

([]main.Block) (len=2 cap=2) {
(main.Block) {
NoBlock: (int) 0,
Timestamp: (string) (len=39) "2019-05-29 14:50:00.966201709 +0800 +08",
Data: (string) "",
Hash: (string) (len=64) "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
PrevHash: (string) "",
Difficulty: (int) 0,
Nonce: (string) ""
},
(main.Block) {
NoBlock: (int) 1,
Timestamp: (string) (len=39) "2019-05-29 14:50:12.891324534 +0800 +08",
Data: (string) (len=110) "3e19124ee3a459d5c6edcb9b2a37cf2c4febd2e3ab8a8628f1bfb197bdaf5accada8349d9a99cfbf7cdd1af003c14f7c5c004f53c1d231",
Hash: (string) (len=64) "b2aebe50c3ace8230cb8d839d4e36da8899a2d0f0a3c1dbc9e9c717f74ead464",
PrevHash: (string) (len=64) "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
Difficulty: (int) 0,
Nonce: (string) (len=1) "0"
 }
}

Please help me, thank you.

Body:
Your body data is a JSON array so the unmarshalling has to be to an array

var data []map[string]interface{} // add this to declaration
err = json.Unmarshal([]byte(body), &data)


问:
Kotlin: data class private setter public getter
Is there any way I can make a private setter and a public getter in a Kotlin Data Class?</p>

```<code>data class Test(var attribute: String) {

    // attribute can be mutated inside this class

    // but outside only readable ?
}
</code>```

答:
To add some background to the other answer:

There's no way to do this directly in the constructor, though there have been several proposals as to how it could be added to the language; see here.

If it weren't a data class, I'd suggest this alternative:

```<code>class Test(_attribute: String) {
    var attribute = _attribute
        private set
}
</code>```

That only stores one value in the object, so is marginally more efficient.

But since this is a data class, that's not possible.  (Data classes can't have non-properties in their primary constructors.)  So the other answer's suggestion seems best.

Body:
Is there any way I can make a private setter and a public getter in a Kotlin Data Class?

data class Test(var attribute: String) {

    // attribute can be mutated inside this class

    // but outside only readable ?
}

Body:
To add some background to the other answer:

There's no way to do this directly in the constructor, though there have been several proposals as to how it could be added to the language; see here.

If it weren't a data class, I'd suggest this alternative:

class Test(_attribute: String) {
    var attribute = _attribute
        private set
}

That only stores one value in the object, so is marginally more efficient.

But since this is a data class, that's not possible.  (Data classes can't have non-properties in their primary constructors.)  So the other answer's suggestion seems best.


问:
How to pass "a pointer to a function with parameters" to another function
I have the following system function:

```<code>int sock_yield( void *s, void (*fn)() );
</code>```

to which I need to pass a function that takes 2 parameters:

```<code>void reset(char buf,udp_Socket sock) {

    if (-1 == udp_recv(&sock, &buf, sizeof(buf)));

    if(buf=='R')
    {

        printf("\nReceived-> %c",buf);

        forceSoftReset();

        forceWatchdogTimeout();

    }

}
</code>```

When calling sock_yield function I can only pass it the name of the function without its parameter:
sock_yield(sock, reset)

How to specify the parameters of reset to be passed to sock_yield?

答:
You cannot. C only knows raw pointer to functions. You can then give all the required parameters when you use the pointer. Example:

```<code>int double(int i) {
    return 2*1;
}

int exec_op(int param, int (*op)()) {
   return op(param);
}
</code>```

This works because in C a void parameter list means that the function can accept any parameters.

If in your use case sock_yield calls the function without parameters, the only option is to use a wrapper using global parameters:

```<code>char Buf;
udp_Socket Sock;

void reset_wrapper(void) {
    reset(Buf, Sock);
}
</code>```

and later use it that way:

```<code>    Buf = buf;
    Sock = sock;
    sock_yield(s, &reset_wrapper);
</code>```

Body:
I have the following system function:

int sock_yield( void *s, void (*fn)() );

to which I need to pass a function that takes 2 parameters:

void reset(char buf,udp_Socket sock) {

    if (-1 == udp_recv(&sock, &buf, sizeof(buf)));

    if(buf=='R')
    {

        printf("\nReceived-> %c",buf);

        forceSoftReset();

        forceWatchdogTimeout();

    }

}

When calling sock_yield function I can only pass it the name of the function without its parameter:
sock_yield(sock, reset)

How to specify the parameters of reset to be passed to sock_yield?

Body:
You cannot. C only knows raw pointer to functions. You can then give all the required parameters when you use the pointer. Example:

int double(int i) {
    return 2*1;
}

int exec_op(int param, int (*op)()) {
   return op(param);
}

This works because in C a void parameter list means that the function can accept any parameters.

If in your use case sock_yield calls the function without parameters, the only option is to use a wrapper using global parameters:

char Buf;
udp_Socket Sock;

void reset_wrapper(void) {
    reset(Buf, Sock);
}

and later use it that way:

    Buf = buf;
    Sock = sock;
    sock_yield(s, &reset_wrapper);


问:
HTML anchor within Javascript variable assigned dynamically to a dataTable cell is not rendered by the browser
I have implemented a dataTable on dynamic set of data.  There is a javascript variable that contains the following:

```<code>var path = "/<a href="http://demo.example.com/first.html">First</a>/<a href="http://demo.example.com/second.html">Second</a>/";
</code>```

This variable is supposed to have two anchors.  When I assign this variable dynamically to a cell of a dataTable as follows:

```<code>var tab = document.getElementById("sample_table");
var objCells = tab.rows.item(i).cells;
objCells[0].innerHTML = path;
</code>```

It is shown as plain text within the table cell and is not rendered as HTML by the browser:

```<code>/<a href="http://demo.example.com/first.html">First</a>/<a href="http://demo.example.com/second.html">Second</a>/
</code>```

and I want it like this:

/First/Second/

What should be done to render it correctly in the browser?

答:
You could use the draw method also</p>

```<code>
<html>
<body>

    <script type="text/javascript">
           $(document).ready(function () {
            var tab = $('#example').DataTable();
            var path = "/<a href='http://demo.example.com/first.html'>First</a>/<a href='http://demo.example.com/second.html'>Second</a>/";

            tab.cell(0, 0).data(path).draw();
        });
    </script>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
            </tr>
        </tbody>
    </table>
</body>

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

Body:
I have implemented a dataTable on dynamic set of data.  There is a javascript variable that contains the following:

var path = "/First/Second/";

This variable is supposed to have two anchors.  When I assign this variable dynamically to a cell of a dataTable as follows:

var tab = document.getElementById("sample_table");
var objCells = tab.rows.item(i).cells;
objCells[0].innerHTML = path;

It is shown as plain text within the table cell and is not rendered as HTML by the browser:

/First/Second/

and I want it like this:

/First/Second/

What should be done to render it correctly in the browser?

Body:
You could use the draw method also

<html>
<body>

    <script type="text/javascript">
           $(document).ready(function () {
            var tab = $('#example').DataTable();
            var path = "/<a href='http://demo.example.com/first.html'>First</a>/<a href='http://demo.example.com/second.html'>Second</a>/";

            tab.cell(0, 0).data(path).draw();
        });
    </script>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
            </tr>
        </tbody>
    </table>
</body>

</body>
</html>