问:
Powershell - Replace "umlauts" in whole array
I have got a csv with ";" delimiters which i imported with import-csv -delimiter ';'
having done that i get an array with 3 Rows (class name name2)
now the problem is: i need to remove "umlauts" from the array
I already tried it like that

```<code>$csv1 = Import-Csv $PSScriptRoot\csvfile.csv -Delimiter ';'
$csv1.name2 = $csv1.Familienname -ireplace 'ä', 'ae'
$csv1.name2
</code>```

to no avail, the output still remains the same (i.e ä stays ä and is not replaced by ae)

another idea I had was to write a loop that replaces the umlauts but I cant wrap my head around how to do that:
 could i do it somewhat like that

```<code>foreach ( ä,ö,ü in $csv1.name2)
{ replace with a,oe,ue}
</code>```

I would already be very thankful for just some links that get me in the right direction.

答:
Here is the solution that worked for me: </p>

```<code>$csv = (gc $PSScriptRoot\csvfile.csv -raw) -ireplace 'ä', 'ae' -ireplace 'ö', 'oe' -ireplace 'ü', 'ue' -ireplace 'ß', 'ss' | ConvertFrom-Csv -Delimiter ';'
</code>```

Body:
I have got a csv with ";" delimiters which i imported with import-csv -delimiter ';'
having done that i get an array with 3 Rows (class name name2)
now the problem is: i need to remove "umlauts" from the array
I already tried it like that

$csv1 = Import-Csv $PSScriptRoot\csvfile.csv -Delimiter ';'
$csv1.name2 = $csv1.Familienname -ireplace 'ä', 'ae'
$csv1.name2

to no avail, the output still remains the same (i.e ä stays ä and is not replaced by ae)

another idea I had was to write a loop that replaces the umlauts but I cant wrap my head around how to do that:
 could i do it somewhat like that

foreach ( ä,ö,ü in $csv1.name2)
{ replace with a,oe,ue}

I would already be very thankful for just some links that get me in the right direction.

Body:
Here is the solution that worked for me:

$csv = (gc $PSScriptRoot\csvfile.csv -raw) -ireplace 'ä', 'ae' -ireplace 'ö', 'oe' -ireplace 'ü', 'ue' -ireplace 'ß', 'ss' | ConvertFrom-Csv -Delimiter ';'


来源: stackexchange

问:
Accessing TempData variables
I'm using ajax to make a post request to my server side, I am creating a file, once that file has been created, I need to display it in my browser, I've read that using ajax is not possible to display that file, but I can use my success event in my ajax function to call another method in my server side, I've been trying to store that file as an array of bytes in memory using TempData or even Session variables, and then read them on the other method I'm calling on ajax success(called DisplayFile) , but the TempData variables are always null when the DisplayFile method is called... If you have different suggestions to do this are welcome,  I've been thinking in send the array of bytes to JQuery and then make another request passing it as a parameter but it is a very long array of bytes.., I'm not sure why the TempData value is null when DisplayFile method is called from client side...

```<code>$.ajax({ url: "/FileManagement/Files",
         type: 'post',
         data: formData,
         success: function(result){
           window.location = "/FileManagement/DisplayFile"
}
})

public JsonResult Files(//parameters...)
{
//...some code
 TempData["BytesArray"] = fileBytes; //fileBytes is an array of bytes
 TempData["FileName"] = fileName;
}

public ActionResult DisplayFile()
{
var file = TempData["BytesArray"];  //null
var fileName = TempData["FileName"];
}
</code>```

UPDATE
It's working now with Session variables instead of TempData, maybe it's because this controller is inside the Areas folder? This controller is not inside the Controllers folder, maybe it has to do with that, in order for Session to work I had to use the complete path to it like: System.Web.HttpContext.Current.Session["test"] = "asasa"; I'm still trying to figure out why with TempData the value is null when the second method is called...

答:
I finally ended up using Session variables, I'm using a controller inside Areas folder, so maybe because of that TempData isn't working the way I expect, for Session variables in order to work on this controller I have to use the complete path to it, while in a controller inside a Controllers folder I don't need to use that path..

```<code>public JsonResult Files(//parameters...)
{
//...some code
  System.Web.HttpContext.Current.Session["FileInBytes"] = bytesArray; //fileBytes is an array of bytes
  System.Web.HttpContext.Current.Session["FileName"] = fileName;;
}

public ActionResult DisplayFile()
{
   var fileInBytes = Session["FileInBytes"] as byte[];
   var fileName = Session["FileName"] as string;
   Session.Remove("FileInBytes");
   Session.Remove("FileName");
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Accessing TempData variables

Body:
I'm using ajax to make a post request to my server side, I am creating a file, once that file has been created, I need to display it in my browser, I've read that using ajax is not possible to display that file, but I can use my success event in my ajax function to call another method in my server side, I've been trying to store that file as an array of bytes in memory using TempData or even Session variables, and then read them on the other method I'm calling on ajax success(called DisplayFile) , but the TempData variables are always null when the DisplayFile method is called... If you have different suggestions to do this are welcome,  I've been thinking in send the array of bytes to JQuery and then make another request passing it as a parameter but it is a very long array of bytes.., I'm not sure why the TempData value is null when DisplayFile method is called from client side...

$.ajax({ url: "/FileManagement/Files",
         type: 'post',
         data: formData,
         success: function(result){
           window.location = "/FileManagement/DisplayFile"
}
})

public JsonResult Files(//parameters...)
{
//...some code
 TempData["BytesArray"] = fileBytes; //fileBytes is an array of bytes
 TempData["FileName"] = fileName;
}

public ActionResult DisplayFile()
{
var file = TempData["BytesArray"];  //null
var fileName = TempData["FileName"];
}

UPDATE
It's working now with Session variables instead of TempData, maybe it's because this controller is inside the Areas folder? This controller is not inside the Controllers folder, maybe it has to do with that, in order for Session to work I had to use the complete path to it like: System.Web.HttpContext.Current.Session["test"] = "asasa"; I'm still trying to figure out why with TempData the value is null when the second method is called...

Body:
I finally ended up using Session variables, I'm using a controller inside Areas folder, so maybe because of that TempData isn't working the way I expect, for Session variables in order to work on this controller I have to use the complete path to it, while in a controller inside a Controllers folder I don't need to use that path..

public JsonResult Files(//parameters...)
{
//...some code
  System.Web.HttpContext.Current.Session["FileInBytes"] = bytesArray; //fileBytes is an array of bytes
  System.Web.HttpContext.Current.Session["FileName"] = fileName;;
}

public ActionResult DisplayFile()
{
   var fileInBytes = Session["FileInBytes"] as byte[];
   var fileName = Session["FileName"] as string;
   Session.Remove("FileInBytes");
   Session.Remove("FileName");
}


问:
Checkbox doesnt update on react on child even if the parent state update?
This is the code from the parent:

```<code>_handleSelectedTodo(e) {
  e.preventDefault();
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
// render () { ...
<ul>
{todos.map((todo,todoIndex) => // The map method has default argument on second index, the index of the current todo in map execution. We use it so we do not have to use findIndex when we need to dispatch action that needs index of a specific todo
  <Todo
    key={todo.id}
    {...todo} // pass all the todo property
    onClick={() => onTodoClick(todo.id)}
    onTrashClick={() => onDeleteClick(todoIndex)}
    handleSelectedTodo = {this._handleSelectedTodo}
    checked={Boolean(this.state.checkedIds.includes(todo.id))}
  />
)}
</code>```

This is what I tried since assigning props on checkbox doesn't update on the Child Todo code, checked can be true or false that will depend on props:

```<code>componentWillMount() {
  this.setState({ checked: this.props.checked })
}
// render() { ...
<input
  checked={this.state.checked}
  onChange={handleSelectedTodo}
  type="checkbox"
  value={id}
></input>
</code>```

Checking on the checkbox updates the parent component state but the checkbox on child is not checked. help?

答:
Reason is, componentWillMount will get called only before the initial rendering not after that, when you are updating the state of parent component, state of child component is not getting updated.

Use componentWillReceiveProps method to update the state of child component:

```<code>componentWillReceiveProps(nextProps){
   if(nextProps.checked != this.state.checked)
        this.setState({checked: nextProps.checked})
}
</code>```

Or simplest solution will be don't save the value in state of child component, directly use the props values, Like this:

```<code><input
    checked={this.props.checked}      //here use this.props.checked directly
    onChange={handleSelectedTodo}
    type="checkbox"
    value={id}
>
</input>
</code>```

componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component
  receives new props. If you need to update the state in response to
  prop changes (for example, to reset it), you may compare this.props
  and nextProps and perform state transitions using this.setState() in
  this method.

componentWillMount:

componentWillMount() is invoked immediately before mounting occurs. It
  is called before render().

Body:
This is the code from the parent:

_handleSelectedTodo(e) {
  e.preventDefault();
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
// render () { ...

{todos.map((todo,todoIndex) => // The map method has default argument on second index, the index of the current todo in map execution. We use it so we do not have to use findIndex when we need to dispatch action that needs index of a specific todo
  <Todo
    key={todo.id}
    {...todo} // pass all the todo property
    onClick={() => onTodoClick(todo.id)}
    onTrashClick={() => onDeleteClick(todoIndex)}
    handleSelectedTodo = {this._handleSelectedTodo}
    checked={Boolean(this.state.checkedIds.includes(todo.id))}
  />
)}

This is what I tried since assigning props on checkbox doesn't update on the Child Todo code, checked can be true or false that will depend on props:

componentWillMount() {
  this.setState({ checked: this.props.checked })
}
// render() { ...
<input
  checked={this.state.checked}
  onChange={handleSelectedTodo}
  type="checkbox"
  value={id}
></input>

Checking on the checkbox updates the parent component state but the checkbox on child is not checked. help?

Body:
Reason is, componentWillMount will get called only before the initial rendering not after that, when you are updating the state of parent component, state of child component is not getting updated.

Use componentWillReceiveProps method to update the state of child component:

componentWillReceiveProps(nextProps){
   if(nextProps.checked != this.state.checked)
        this.setState({checked: nextProps.checked})
}

Or simplest solution will be don't save the value in state of child component, directly use the props values, Like this:

<input
    checked={this.props.checked}      //here use this.props.checked directly
    onChange={handleSelectedTodo}
    type="checkbox"
    value={id}
>
</input>

componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component
  receives new props. If you need to update the state in response to
  prop changes (for example, to reset it), you may compare this.props
  and nextProps and perform state transitions using this.setState() in
  this method.

componentWillMount:

componentWillMount() is invoked immediately before mounting occurs. It
  is called before render().


问:
How to authorize webapp with ebay?
I am making a django app that can hold info about items i have on ebay.
So, each user would have multiple ebay accounts.
For example:
user1 would have access to ebay1, ebay2, ebay3 account.
How can I get appid, certid, devid and token for each account?
The best would be to click 'add ebay account' and in new window with ebay sign in page and authorize by inserting username/password.

I had a look to:

https://github.com/timotheus/ebaysdk-python

https://developer.ebay.com/devzone/xml/docs/reference/ebay/FetchToken.html

but it is not clear to me.
Can anyone provide me some step-by-step or any guidelines?

Thanks in advance

答:
I used code from this repo: https://github.com/luke-dixon/django-ebay-accounts
with fix from: here it works great</p>

Title: How to authorize webapp with ebay?


问:
RxJS Keep Subject/Observable Subscription Active After Error
Is there a way to prevent a subscription to a stream (either observable or subject) from completing after calling the error function on the observable/subject?

```<code>var subject = new Rx.Subject();
subject.subscribe(function(){alert("OnNext")}, function(){alert("OnError")});

var next = document.querySelector("#next").addEventListener('click', function(){
  subject.next();
})
var error = document.querySelector("#error").addEventListener('click', function(){
  subject.error();
});
</code>```

From what I understand, calling subject.error() completes the event stream. So keeping the observable open would break the contract of the Observable object. So how can I handle the lifecycle of the observable in such a way that would recreate the subscription after an error occurs? Here is a plnkr demonstrating the behavior.

答:
Simply said, you can't. At least not with Subjects.

Subjects have internal state and when they emit or receive error notification they mark themself as stopped and will never ever emit anything.

Otherwise, you could use catch() or retry() operators that resubscribe to their source Observable but this wouldn't help you when using Subjects.

Body:
Is there a way to prevent a subscription to a stream (either observable or subject) from completing after calling the error function on the observable/subject?

var subject = new Rx.Subject();
subject.subscribe(function(){alert("OnNext")}, function(){alert("OnError")});

var next = document.querySelector("#next").addEventListener('click', function(){
  subject.next();
})
var error = document.querySelector("#error").addEventListener('click', function(){
  subject.error();
});

From what I understand, calling subject.error() completes the event stream. So keeping the observable open would break the contract of the Observable object. So how can I handle the lifecycle of the observable in such a way that would recreate the subscription after an error occurs? Here is a plnkr demonstrating the behavior.


问:
Responsive Image Resize Issue
I have looked everywhere on the site and tried every method I have come across, but still am not having any luck with getting this image to be responsive and scale properly. It stays at its default size no matter what code I enter. I resize the browser and use a mobile phone emulator and it stays the same size.

HTML

```<code><section class="image">
<div>
<img class="info" src="jewelry-large-info.png">
</div>
</section>
</code>```

CSS

```<code>.image {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
}
.info {
height: auto;
width: auto;
max-width: 1500px;
max-height: 666px;
}
</code>```

If anyone can help it would be very greatly appreciated, and chances are I probably have just overlooked something.

答: What you need to do is give the image a width of 100% and a height of auto. This will make it stay proportional and be as wide as the parent. </p>

Title: Responsive Image Resize Issue

Body:
I have looked everywhere on the site and tried every method I have come across, but still am not having any luck with getting this image to be responsive and scale properly. It stays at its default size no matter what code I enter. I resize the browser and use a mobile phone emulator and it stays the same size.

HTML

CSS

.image {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
}
.info {
height: auto;
width: auto;
max-width: 1500px;
max-height: 666px;
}

If anyone can help it would be very greatly appreciated, and chances are I probably have just overlooked something.


问:
SQL Server Stored Procedure Conversion failed when converting date and/or time from character string
I know that this question has been asked a few times, but the suggestions don't seem to be working for me.  I have an 83 line stored procedure that I need to call and pass a start and an end date into it.  The procedure works great if I hard code the dates; however, when I try to pass the dates as variables I receive the error:

Conversion failed when converting date and/or time from character string

I am calling my stored procedure as follows:

```<code>exec dbo.CreateReport @startDate = '10/01/2013', @endDate = '12/31/2013'
</code>```

I am creating my stored procedure as follows:

```<code>create procedure dbo.CreateReport
    @startDate smalldatetime = NULL,
    @endDate smalldatetime = NULL
</code>```

The block of code where the error is occurring:

```<code>declare vp_laboraccount_timesheetitem_cursor cursor for
            select a.laborleveldsc1,a.laborleveldsc2,a.laboracctid, sum(b.durationsecsqty)/3600 as totalhours
            from vp_laboraccount a, timesheetitem b
            where a.laboracctid=b.laboracctid and b.eventdtm >=''' + @@startDate + ''' and b.eventdtm <= ''' + @@endDate + ''' and employeeid = @personid
            group by a.laborleveldsc1,a.laborleveldsc2,a.laboracctid
            open vp_laboraccount_timesheetitem_cursor
            fetch next from vp_laboraccount_timesheetitem_cursor into @laborleveldsc1,@laborleveldsc2,@laboracctid,@totalhours
            while @@fetch_status=0
            begin
            --print results
                select @message = @personid + ',' + @personcstmdatatxt + ',' + @searchfullnm + ',' + @prdohh + ',' + @prjob1 + ',' + @laborleveldsc1 + ',' + @laborleveldsc2 + ',' + @laboracctid + ',' + @totalhours + ',' + @companhiredtm
                --print @message
                insert into dbo.tabResults (messages) Values(@message)
            fetch next from vp_laboraccount_timesheetitem_cursor into @laborleveldsc1,@laborleveldsc2,@laboracctid,@totalhours
            end
            close vp_laboraccount_timesheetitem_cursor
            deallocate vp_laboraccount_timesheetitem_cursor
</code>```

The specific line where the error is occurring:

```<code>where a.laboracctid=b.laboracctid and b.eventdtm >=''' + @@startDate + ''' and b.eventdtm <= ''' + @@endDate + ''' and employeeid = @personid
</code>```

The two variables in question are the @@startDate and the @@endDate.

I have tried several things, including passing my variables in as varchar, as well as doing both a convert and a cast on the variables, but nothing seems to be working for me.  I have tried both a single @ and a double @@ sign because those often give me problems.  I have tried different date formats, but every time I get a variation of the same error message.  If I hard code my date strings into the code it works as expected, and without errors.

I think that I am being very obtuse, and the solution will be obvious once somebody hits me over the head with a shovel, but after a week of trying various things I am ready to ask for help.

What am I doing wrong, and what do I have to do to fix this?

Thank you.

答:
The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

Use the single @ for your variable.

```<code>exec dbo.CreateReport @startDate='20131001', @endDate='20131231'
</code>```

And your where clause should be like so:

```<code>where a.laboracctid=b.laboracctid
  and b.eventdtm >= @startDate
  and b.eventdtm <= @endDate
  and employeeid = @personid
</code>```

Also, you should use proper joins instead of old-style joins and use meaningful aliases.

Bad habits to kick : using old-style JOINs - Aaron Bertrand

Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3) - Aaron Bertrand

Body:
I know that this question has been asked a few times, but the suggestions don't seem to be working for me.  I have an 83 line stored procedure that I need to call and pass a start and an end date into it.  The procedure works great if I hard code the dates; however, when I try to pass the dates as variables I receive the error:

Conversion failed when converting date and/or time from character string

I am calling my stored procedure as follows:

exec dbo.CreateReport @startDate = '10/01/2013', @endDate = '12/31/2013'

I am creating my stored procedure as follows:

create procedure dbo.CreateReport
    @startDate smalldatetime = NULL,
    @endDate smalldatetime = NULL

The block of code where the error is occurring:

declare vp_laboraccount_timesheetitem_cursor cursor for
            select a.laborleveldsc1,a.laborleveldsc2,a.laboracctid, sum(b.durationsecsqty)/3600 as totalhours
            from vp_laboraccount a, timesheetitem b
            where a.laboracctid=b.laboracctid and b.eventdtm >=''' + @@startDate + ''' and b.eventdtm <= ''' + @@endDate + ''' and employeeid = @personid
            group by a.laborleveldsc1,a.laborleveldsc2,a.laboracctid
            open vp_laboraccount_timesheetitem_cursor
            fetch next from vp_laboraccount_timesheetitem_cursor into @laborleveldsc1,@laborleveldsc2,@laboracctid,@totalhours
            while @@fetch_status=0
            begin
            --print results
                select @message = @personid + ',' + @personcstmdatatxt + ',' + @searchfullnm + ',' + @prdohh + ',' + @prjob1 + ',' + @laborleveldsc1 + ',' + @laborleveldsc2 + ',' + @laboracctid + ',' + @totalhours + ',' + @companhiredtm
                --print @message
                insert into dbo.tabResults (messages) Values(@message)
            fetch next from vp_laboraccount_timesheetitem_cursor into @laborleveldsc1,@laborleveldsc2,@laboracctid,@totalhours
            end
            close vp_laboraccount_timesheetitem_cursor
            deallocate vp_laboraccount_timesheetitem_cursor

The specific line where the error is occurring:

where a.laboracctid=b.laboracctid and b.eventdtm >=''' + @@startDate + ''' and b.eventdtm <= ''' + @@endDate + ''' and employeeid = @personid

The two variables in question are the @@startDate and the @@endDate.

I have tried several things, including passing my variables in as varchar, as well as doing both a convert and a cast on the variables, but nothing seems to be working for me.  I have tried both a single @ and a double @@ sign because those often give me problems.  I have tried different date formats, but every time I get a variation of the same error message.  If I hard code my date strings into the code it works as expected, and without errors.

I think that I am being very obtuse, and the solution will be obvious once somebody hits me over the head with a shovel, but after a week of trying various things I am ready to ask for help.

What am I doing wrong, and what do I have to do to fix this?

Thank you.

Body:
The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

Use the single @ for your variable.

exec dbo.CreateReport @startDate='20131001', @endDate='20131231'

And your where clause should be like so:

where a.laboracctid=b.laboracctid
  and b.eventdtm >= @startDate
  and b.eventdtm <= @endDate
  and employeeid = @personid

Also, you should use proper joins instead of old-style joins and use meaningful aliases.

Bad habits to kick : using old-style JOINs - Aaron Bertrand

Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3) - Aaron Bertrand

ContentLicense: CC BY-SA 4.0


问:
Customizing properties dialog screen in IBM Content Navigator
I need to develop a functionality in IBM Content Navigator where after search for an item, right click it-> Properties, I need to either:

1 - add a button in properties dialog screen that will call a service and open another dialog;

2 - or extend the Save button functionality to also call a service and open another dialog;

What's quickest way to achieve that ?

答: Have a look @ ecm.widget.dialog.EditPropertiesDialog and onSave() method. This might help you to extend save button functionality.</p>


问:
Java toString() using reflection?
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.

Getting the field names is fairly simple, here is what a co-worker came up with:

```<code>public static List initFieldArray(String className) throws ClassNotFoundException {

    Class c = Class.forName(className);
    Field field[] = c.getFields();
    List<String> classFields = new ArrayList(field.length);

    for (int i = 0; i < field.length; i++) {
        String cf = field[i].toString();
        classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
    }

    return classFields;
}
</code>```

Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.

Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.

答:
Apache commons-lang ReflectionToStringBuilder does this for you. </p>

```<code>import org.apache.commons.lang3.builder.ReflectionToStringBuilder

// your code goes here

public String toString() {
   return ReflectionToStringBuilder.toString(this);
}
</code>```

OwnerDisplayName: nemo

ContentLicense: CC BY-SA 2.5

Title: Java toString() using reflection?

Body:
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.

Getting the field names is fairly simple, here is what a co-worker came up with:

public static List initFieldArray(String className) throws ClassNotFoundException {

    Class c = Class.forName(className);
    Field field[] = c.getFields();
    List<String> classFields = new ArrayList(field.length);

    for (int i = 0; i < field.length; i++) {
        String cf = field[i].toString();
        classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
    }

    return classFields;
}

Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.

Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.

Body:
Apache commons-lang ReflectionToStringBuilder does this for you.

import org.apache.commons.lang3.builder.ReflectionToStringBuilder

// your code goes here

public String toString() {
   return ReflectionToStringBuilder.toString(this);
}

OwnerDisplayName: krosenvold


问:
PHP Code: usage of this keyword
```<code>public function __construct($template = '', array $data = array())
{
    if ($template !== '') {
        $this->setTemplate($template);
    }
    if (!empty($data)) {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
}
</code>```

Got this from the devshed composite view tutorial (http://www.devshed.com/c/a/PHP/PHP-Composite-View-Design-Pattern-Introducing-the-Key-Concepts/1/). Anyway, I'm a bit confuse on, $this->$name = $value; statement.

I usually use $this for class's properties and/or when invoking class's methods within the said class. Plus the statement have two $'s. Which is weird! So is $this->$name = $value referring to the $name defined in the foreach loop? If so can someone explain this usage or logic behind this?

Thank you in advance.

答:
Let as assume that the current value of $name is "foo".
then $this->name will return exactly the same as $this->foo.</p>

Title: PHP Code: usage of this keyword

Body:
public function __construct($template = '', array $data = array())
{
    if ($template !== '') {
        $this->setTemplate($template);
    }
    if (!empty($data)) {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
}

Got this from the devshed composite view tutorial (http://www.devshed.com/c/a/PHP/PHP-Composite-View-Design-Pattern-Introducing-the-Key-Concepts/1/). Anyway, I'm a bit confuse on, $this->$name = $value; statement.

I usually use $this for class's properties and/or when invoking class's methods within the said class. Plus the statement have two $'s. Which is weird! So is $this->$name = $value referring to the $name defined in the foreach loop? If so can someone explain this usage or logic behind this?

Thank you in advance.


问:
Component does not stop nested dependencies
I bumped into a following problem while using the component library - whenever a given component depends on another, the associated dependency in the system map does not release it's resources (i.e. is not stopped) on 'stop-system'.

I would assume that both lifecycle methods work in the dependency order and call start / stop for each component and its dependencies in a tree traversal of the dependency graph.

I haven't yet looked in detail, but I made a simple application that reproduces the problem in a simple unit test (call lein test):

https://github.com/fbielejec/component-app

答:
FWIW, if you add printlns to the start and stop methods you will see this:

On system/start:

```<code>db start
message handler start
</code>```

On system/stop:

```<code>message handler stop
db stop
</code>```

I don't know why the database reference in the message handler isn't updated.

Body:
FWIW, if you add printlns to the start and stop methods you will see this:

On system/start:

db start
message handler start

On system/stop:

message handler stop
db stop

I don't know why the database reference in the message handler isn't updated.


问:
Where to fetch user roles using ADFS service
I'm newbie to ADFS and I need to enable my web application developed with Spring Security to use ADFS service for user authentication and authorization, I've figured out the authentication process but it's the authorization piece is blocking me, actually, I'm confused, from where to get user roles? Because my datastore (mongoDB) neither have user info and roles which is required for securing my rest resources, can someone enlighten me how to implement same.  </p>

答:
In the ADFS wizard, you configure claims rules which place AD attributes in the token.

Some of these attributes can be roles which you can then use for authorisation.

That's assuming that there are some roles in the AD?

You can also use the claims rules to get attributes from your DB.


问:
How to use dynamic Linq with List<dynamic> object
I have a List of dynamic objects that I am trying to use dynamic Linq on. I am using dynamic objects because I do not know the properties that will be coming into the object. Linq works on my dynamic object, but, to avoid giant hard coding if statements, I would like to use dynamic Linq to search my list. The top half of the code snippet works but I need it to work dynamically so I can create a query string from my properties and filter that way.

```<code>public List<dynamic> GetFilteredLocationData(List<dynamic> locationData, string searchTerm){

                //Does work
                List<dynamic> totalResults = locationData.Where(x => x.Street.ToLower().Contains(searchTerm.ToLower()) ||
                    x.Street.ToLower().Contains(searchTerm.ToLower()) ||
                    x.Zip.ToLower().Contains(searchTerm.ToLower()));

                //Does not work
                var testQueryString = "(Street == \"king\")";
                var testResult = locationData.Where(testQueryString);

                return totalResults;
            }
</code>```

The runtime error I receive: No property or field 'Street' exists in type 'Object'

That error makes sense as object by default doesn't contain 'Street' but I'd expect the dynamic Linq to behave like the code above it. Is there something I am doing wrong here, or should I take a different approach? I can provide more detail if needed.

Thanks in advance!

答:
Finally I got a working solution! It may not be the most efficient but it works for my needs and allows me to keep the dynamic nature I was hoping to retain. The solution was to drop Linq entirely and use a good old for-each loop. The Important part was the IDictionary which allowed me to search each row for the key value pair. This is the same functionality I was going for, just ditched linq.</p>

```<code>public List<dynamic> GetFilteredLocationData(List<dynamic> locationData, string searchTerm){
                List<dynamic> totalResults = new List<dynamic>();
                List<string> locationProperties = new List<string> {"dynamic properties here, this was filled by call to DB for info pertaining to certain location combined with unique data"}
                foreach (var locData in locationData)
                {
                    var currentLoc = locData;
                    var currentLocDict = (IDictionary<string, object>)currentLoc;

                    bool containsSearchTerm = CheckIfLocationContainsSearch(currentLocDict, allLocationProperties, searchTerm);
                    if (containsSearchTerm)
                    {
                        totalResults.Add(locData);
                    }
                }
            }

            public bool CheckIfLocationContainsSearch(IDictionary<string,object> location, List<string> locationProperties, string searchTerm){

            foreach (var locProp in locationProperties)
            {
                if (location[locProp].ToString().ToLower().Contains(searchTerm))
                {
                    return true;
                }
            }
            return false;
        }
</code>```

Body:
I have a List of dynamic objects that I am trying to use dynamic Linq on. I am using dynamic objects because I do not know the properties that will be coming into the object. Linq works on my dynamic object, but, to avoid giant hard coding if statements, I would like to use dynamic Linq to search my list. The top half of the code snippet works but I need it to work dynamically so I can create a query string from my properties and filter that way.

public List<dynamic> GetFilteredLocationData(List<dynamic> locationData, string searchTerm){

                //Does work
                List<dynamic> totalResults = locationData.Where(x => x.Street.ToLower().Contains(searchTerm.ToLower()) ||
                    x.Street.ToLower().Contains(searchTerm.ToLower()) ||
                    x.Zip.ToLower().Contains(searchTerm.ToLower()));

                //Does not work
                var testQueryString = "(Street == \"king\")";
                var testResult = locationData.Where(testQueryString);

                return totalResults;
            }

The runtime error I receive: No property or field 'Street' exists in type 'Object'

That error makes sense as object by default doesn't contain 'Street' but I'd expect the dynamic Linq to behave like the code above it. Is there something I am doing wrong here, or should I take a different approach? I can provide more detail if needed.

Thanks in advance!

Body:
Finally I got a working solution! It may not be the most efficient but it works for my needs and allows me to keep the dynamic nature I was hoping to retain. The solution was to drop Linq entirely and use a good old for-each loop. The Important part was the IDictionary which allowed me to search each row for the key value pair. This is the same functionality I was going for, just ditched linq.

public List<dynamic> GetFilteredLocationData(List<dynamic> locationData, string searchTerm){
                List<dynamic> totalResults = new List<dynamic>();
                List<string> locationProperties = new List<string> {"dynamic properties here, this was filled by call to DB for info pertaining to certain location combined with unique data"}
                foreach (var locData in locationData)
                {
                    var currentLoc = locData;
                    var currentLocDict = (IDictionary<string, object>)currentLoc;

                    bool containsSearchTerm = CheckIfLocationContainsSearch(currentLocDict, allLocationProperties, searchTerm);
                    if (containsSearchTerm)
                    {
                        totalResults.Add(locData);
                    }
                }
            }

            public bool CheckIfLocationContainsSearch(IDictionary<string,object> location, List<string> locationProperties, string searchTerm){

            foreach (var locProp in locationProperties)
            {
                if (location[locProp].ToString().ToLower().Contains(searchTerm))
                {
                    return true;
                }
            }
            return false;
        }


问:
google page insights api screenshot - Laravel
Im having trouble getting the Google API PageSpeed Insights screenshot that they provide of the website when hitting the API. I have looked at other examples, but none seem to work for me.

This is what I get back when hitting the API.

And this is my controller:

```<code>   public function fetch() {

        $key = env('GOOGLE_ANALYTICS_KEY');
        $website = request('website_url');

        $client = new \GuzzleHttp\Client();

        $res = $client->request('GET', 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=http://' .$website. '&key=' . $key . '&screenshot=true');

        if ($res->getStatusCode() == 200) {
            $result = json_decode($res->getBody());

            $data    = str_replace('_','/',$result->screenshot->data);
            $data    = str_replace('-','+',$data);
            $decoded = base64_decode($data);

            return view('api.index', compact('result', 'decoded'));

        } else {
            return redirect()->back();
        }
    }
</code>```

I try to call it in the front end like this:

```<code><img src="data:image/jpeg;base64,'{{ $decoded }}">
// And like this
<img src="{{ $decoded }}">
</code>```

But just get an empty src=""

答:
I figured it out.

This is what I did in my controller (not much changing):

```<code>$result = json_decode($res->getBody());

            $data    = str_replace('_','/',$result->screenshot->data);
            $data    = str_replace('-','+',$data);
</code>```

This is how I called it in front-end:

```<code> <img src="data:image/jpeg;base64,{{ $data }}">
</code>```

Body:
Im having trouble getting the Google API PageSpeed Insights screenshot that they provide of the website when hitting the API. I have looked at other examples, but none seem to work for me.

This is what I get back when hitting the API.

And this is my controller:

   public function fetch() {

        $key = env('GOOGLE_ANALYTICS_KEY');
        $website = request('website_url');

        $client = new \GuzzleHttp\Client();

        $res = $client->request('GET', 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=http://' .$website. '&key=' . $key . '&screenshot=true');

        if ($res->getStatusCode() == 200) {
            $result = json_decode($res->getBody());

            $data    = str_replace('_','/',$result->screenshot->data);
            $data    = str_replace('-','+',$data);
            $decoded = base64_decode($data);

            return view('api.index', compact('result', 'decoded'));

        } else {
            return redirect()->back();
        }
    }

I try to call it in the front end like this:

// And like this

But just get an empty src=""

Body:
I figured it out.

This is what I did in my controller (not much changing):

$result = json_decode($res->getBody());

            $data    = str_replace('_','/',$result->screenshot->data);
            $data    = str_replace('-','+',$data);

This is how I called it in front-end:

 <img src="data:image/jpeg;base64,{{ $data }}">


问:
Move UITextField up when keyboard is overlapped
There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

```<code>ViewA
  -> UIButton

subView
  -> UIScrollView
        -> UITextField
        -> UITextField

   ViewA
 -----------
|           |
|           |
|  Button   |
|           |
|           |
 -----------

   subView
 --------------
|              |
|              |
|  UITextField |
|  UITextField |
|              |
 --------------
</code>```

I have registered keyboard notification

```<code>    - (void) viewWillAppear:(BOOL)animated {

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardDidShow:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }

- (void) keyboardDidShow:(NSNotification *)notification {

            NSDictionary* info = [notification userInfo];
            CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
            self.scrollViewIb.contentInset = contentInsets;
            self.scrollViewIb.scrollIndicatorInsets = contentInsets;

            CGRect aRect = self.viewSelf.frame;
            aRect.size.height -= kbRect.size.height;
            CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];
            if (!CGRectContainsPoint(aRect, frame.origin) ) {
                [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];
            }
    }

- (void) keyboardWillBeHidden:(NSNotification *)notification {

        self.scrollViewIb.scrollEnabled = true;

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollViewIb.scrollIndicatorInsets = contentInsets;
        [self.scrollViewIb setContentOffset:CGPointZero animated:false];

}
</code>```

答:
I think the problem is that you are always scrolling up, no matter if the keyboard overlaps your textfield or not.

You would have to get the frame of the textfield, calculate the distance to the bottom of the screen and check if the keyboard height (plus possible toolbar on top of it) would overlap your textfield and only then scroll up.

Anyways, I personally gave up on implementing scroll up behavior again and again. I now switched to using IQKeyboardManager. Simply install it as a Pod in your project and call IQKeyboardManager.sharedManager().enable = true in application(didFinishLaunchingWithOptions) and you are all set.

You even get a toolbar with next/previous and done button for free.

Body:
There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

ViewA
  -> UIButton

subView
  -> UIScrollView
        -> UITextField
        -> UITextField

   ViewA
 -----------
|           |
|           |
|  Button   |
|           |
|           |
 -----------

   subView
 --------------
|              |
|              |
|  UITextField |
|  UITextField |
|              |
 --------------

I have registered keyboard notification

    - (void) viewWillAppear:(BOOL)animated {

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardDidShow:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }

- (void) keyboardDidShow:(NSNotification *)notification {

            NSDictionary* info = [notification userInfo];
            CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
            self.scrollViewIb.contentInset = contentInsets;
            self.scrollViewIb.scrollIndicatorInsets = contentInsets;

            CGRect aRect = self.viewSelf.frame;
            aRect.size.height -= kbRect.size.height;
            CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];
            if (!CGRectContainsPoint(aRect, frame.origin) ) {
                [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];
            }
    }

- (void) keyboardWillBeHidden:(NSNotification *)notification {

        self.scrollViewIb.scrollEnabled = true;

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollViewIb.scrollIndicatorInsets = contentInsets;
        [self.scrollViewIb setContentOffset:CGPointZero animated:false];

}


问:
How to read the JSON String
Kindly need your help as this really taking me long time to try. From JSP, I passed the stingnify JSON object as a String to the Java action, it like

String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"Dealer ABC"},
{"dealerID":"VARSSTH008","dealerName":"Dealer XYZ"}]

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help...

答:
You probably need a JSON library for Java which can parse the string into an object / collection.

I'm not a Java expert myselft, but this list might have somethng suitable: http://www.json.org/java/

Title: How to read the JSON String


答:
You cannot use clarity-etl-1.0.0-SNAPSHOT.jar as a regular jar dependency. Notice that the classes in this jar are under BOOT-INF/classes, which is used by Spring Boot but ignored by the Java compiler.

If your goal is to test the Spring Boot application (as opposed to using the jar as a dependency), then Spring Boot provides easy ways to do it.
 See, for example https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html.

If, on the other hand, it is important to include the classes in another application, then How to add a dependency to a Spring Boot Jar in another project? might help as you pointed out in the comments.

Title: Maven: Package Does Not Exist. Dependencies Seem Correct


问:
gSOAP soapcpp2 #import: Cannot open file “soap12.h” for reading
I'm in the process of moving from gSOAP 2.7 to 2.8.

soapcpp2 is returning the error "#import: Cannot open file “soap12.h” for reading."

I've found a similar post called "#import: Cannot open file “soap12.h” for reading gSoap in VS 2010" but my situation does not seem to be the same. In that case the application was including the .h file generated by wsdl2h and causing an error that caused the developer to change his wsdl2h options and that caused the error. The solution was to not include that .h file

This is what I did that worked in gSOAP 2.7

```<code>wsdl2h -s -t TypeMap.dat -o SOAP.h <multiple WSDL file names>

soapcpp2 -C SOAP.h
</code>```

The wsdl2h execution gives some warnings that are new to 2.8. They are about multiple bindings being found and being collected as one service. I don't think they are important here

What is this SOAP12.h file it thinks it needs to import. TypeMap.dat does not contain an import like that

答:
The answer is this. gSOAP 2.8 requires the specification of a path to the import library in the gSOAP files in the execution of soapcpp2

This is done with the -I option

Body:
I'm in the process of moving from gSOAP 2.7 to 2.8.

soapcpp2 is returning the error "#import: Cannot open file “soap12.h” for reading."

I've found a similar post called "#import: Cannot open file “soap12.h” for reading gSoap in VS 2010" but my situation does not seem to be the same. In that case the application was including the .h file generated by wsdl2h and causing an error that caused the developer to change his wsdl2h options and that caused the error. The solution was to not include that .h file

This is what I did that worked in gSOAP 2.7

wsdl2h -s -t TypeMap.dat -o SOAP.h <multiple WSDL file names>

soapcpp2 -C SOAP.h

The wsdl2h execution gives some warnings that are new to 2.8. They are about multiple bindings being found and being collected as one service. I don't think they are important here

What is this SOAP12.h file it thinks it needs to import. TypeMap.dat does not contain an import like that


问:
Use Picasso to load images in RecyclerView with DataObject
I want to use picasso lib in a "RecyclerViewAdapter". I want to display different images for each entry. It worked for my when I only use text...
I parse a JSON file with the data I use in getDataSet().

At the moment I have no idea how I can use the picasso function to add the images to the dataSet.

WRONG => int imageUrl = Picasso.

CardViewActivity.java

```<code>public class CardViewActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";

    // url to make request - Hole fixe Coupons (max. 100)
    private static String url = "http://json.file";

    // JSON Node names
    private static final String TAG_FIXES = "result";
    private static final String TAG_TITEL = "titel";
    private static final String TAG_BESCHREIBUNG = "beschreibung";

    // contacts JSONArray
    JSONArray fixes = null;

    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_view);
        /*
        image = (ImageView) findViewById(R.id.image_view);

        Picasso.with(getApplicationContext())
                .load("http://1UVZ8A9DRLH/bild.jpg")
                .placeholder(R.drawable.logo)
                .fit().centerCrop().into(image);
        */
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);

        // Code to Add an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);

        // Code to remove an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
                .MyClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
            }
        });
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of fixes
            fixes = json.getJSONArray(TAG_FIXES);

            // looping through All Contacts
            for(int i = 0; i < fixes.length(); i++){
                JSONObject f = fixes.getJSONObject(i);

                // Storing each json item in variable
                String titel = f.getString(TAG_TITEL);
                String description = f.getString(TAG_BESCHREIBUNG);
                int imageUrl = Picasso.with(getApplicationContext())
                        .load("http://1UVZ8A9DRLH/bild.jpg")
                        .placeholder(R.drawable.logo)
                        .fit().centerCrop().into(image);

                DataObject obj = new DataObject(
                        titel,
                        description,
                        imageUrl
                );
                results.add(i, obj);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return results;
    }
}
</code>```

DataObject.java

```<code>public class DataObject {
    private String mText1;
    private String mText2;
    private int imageUrl;

    DataObject(String text1, String text2, int imageUrl){
        mText1 = text1;
        mText2 = text2;
        imageUrl = imageUrl;
    }

    public String getmText1() { return mText1;  }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) { this.mText2 = mText2; }

    public int getImageUrl() { return imageUrl; }

    public void getImageUrl(int imageUrl) {
        this.imageUrl = imageUrl;
    }
}
</code>```

MyRecyclerViewAdapter

```<code>public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView label;
        ImageView imgViewIcon;
        TextView description;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            imgViewIcon = (ImageView) itemView.findViewById(R.id.image_view);
            description = (TextView) itemView.findViewById(R.id.textView2);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.label.setText(mDataset.get(position).getmText1());
        holder.imgViewIcon.setImageResource(mDataset.get(position).getImageUrl());
        holder.description.setText(mDataset.get(position).getmText2());
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}
</code>```

答:
In your onBindViewHolder call Picasso to load an image to your ImageView. Like this:

```<code>Picasso.with(context).load("url").into(imageView);
</code>```

Body:
I want to use picasso lib in a "RecyclerViewAdapter". I want to display different images for each entry. It worked for my when I only use text...
I parse a JSON file with the data I use in getDataSet().

At the moment I have no idea how I can use the picasso function to add the images to the dataSet.

WRONG => int imageUrl = Picasso.

CardViewActivity.java

public class CardViewActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";

    // url to make request - Hole fixe Coupons (max. 100)
    private static String url = "http://json.file";

    // JSON Node names
    private static final String TAG_FIXES = "result";
    private static final String TAG_TITEL = "titel";
    private static final String TAG_BESCHREIBUNG = "beschreibung";

    // contacts JSONArray
    JSONArray fixes = null;

    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_view);
        /*
        image = (ImageView) findViewById(R.id.image_view);

        Picasso.with(getApplicationContext())
                .load("http://1UVZ8A9DRLH/bild.jpg")
                .placeholder(R.drawable.logo)
                .fit().centerCrop().into(image);
        */
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);

        // Code to Add an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);

        // Code to remove an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
                .MyClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
            }
        });
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of fixes
            fixes = json.getJSONArray(TAG_FIXES);

            // looping through All Contacts
            for(int i = 0; i < fixes.length(); i++){
                JSONObject f = fixes.getJSONObject(i);

                // Storing each json item in variable
                String titel = f.getString(TAG_TITEL);
                String description = f.getString(TAG_BESCHREIBUNG);
                int imageUrl = Picasso.with(getApplicationContext())
                        .load("http://1UVZ8A9DRLH/bild.jpg")
                        .placeholder(R.drawable.logo)
                        .fit().centerCrop().into(image);

                DataObject obj = new DataObject(
                        titel,
                        description,
                        imageUrl
                );
                results.add(i, obj);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return results;
    }
}

DataObject.java

public class DataObject {
    private String mText1;
    private String mText2;
    private int imageUrl;

    DataObject(String text1, String text2, int imageUrl){
        mText1 = text1;
        mText2 = text2;
        imageUrl = imageUrl;
    }

    public String getmText1() { return mText1;  }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) { this.mText2 = mText2; }

    public int getImageUrl() { return imageUrl; }

    public void getImageUrl(int imageUrl) {
        this.imageUrl = imageUrl;
    }
}

MyRecyclerViewAdapter

public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView label;
        ImageView imgViewIcon;
        TextView description;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            imgViewIcon = (ImageView) itemView.findViewById(R.id.image_view);
            description = (TextView) itemView.findViewById(R.id.textView2);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.label.setText(mDataset.get(position).getmText1());
        holder.imgViewIcon.setImageResource(mDataset.get(position).getImageUrl());
        holder.description.setText(mDataset.get(position).getmText2());
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}

Body:
In your onBindViewHolder call Picasso to load an image to your ImageView. Like this:

Picasso.with(context).load("url").into(imageView);


问:
Is there dynamic module discovery in JDK9?
In the upcoming Java 9, is there a way to dynamically discover which modules are available?

E.g.:

Run some app with some module path

While the app is running, add a few more modules into the module path (e.g. copy into module directories)

From within the app, query "give me all available modules" (perhaps with a filter, such as those providing an alternate implementation of the same service)

I can't quite tell from the documentation.

答:
It depends to which lengths you are willing to go...

By default the module system is hidden quite well from user code and there is no API to tell the module system to reevaluate the given command line (e.g. --module-path, --add-exports, ...). So the immediate answer is "No, you can not change the app by modifying the module path."

What you can do, though, is create a new layer, which contains an entirely new module graph. When launching the JVM, it will create a single layer from the command line flags and the module path content. With the existing API, you can then create new layers on top of that one.

To learn about layers, have a look at The State of the Module System and the Javadoc for ModuleLayer.


问:
aspx submit form error
Im working with asp.net  framework 4.0 and I have this code:

form id="form1" runat="server" method="get" action="Profile.aspx"

```<code> // some code
</code>```

asp:Button runat="server" ID="SubmitButton" Text="Submit"

Each time i click the submit button i get this error:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that  configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

any idea how to fix it ???

答:
If you want to send post back to your current page, remove in form tag method="get" action="Profile.aspx" attributes. And handle in codebehind post data from your page.

If your want to send data you another page like Profile.aspx, use PostBackUrl attribute of the button control, like Stilgar wrote for you. And then in Profile.aspx codebehind to get access to control from your current page use somethink like this:

```<code>If(Page.PreviousPage != null)
{
    var textBox = Page.PreviousPage.FindControl("ControlID") as TextBox;
    if(textBox != null)
    {
        //Use your logic here
    }
}
</code>```

Hope it will be helpful for you!

Best regards, Dima.

Title: aspx submit form error

Body:
Im working with asp.net  framework 4.0 and I have this code:

form id="form1" runat="server" method="get" action="Profile.aspx"

 // some code

asp:Button runat="server" ID="SubmitButton" Text="Submit"

Each time i click the submit button i get this error:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that  configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

any idea how to fix it ???

Body:
If you want to send post back to your current page, remove in form tag method="get" action="Profile.aspx" attributes. And handle in codebehind post data from your page.

If your want to send data you another page like Profile.aspx, use PostBackUrl attribute of the button control, like Stilgar wrote for you. And then in Profile.aspx codebehind to get access to control from your current page use somethink like this:

If(Page.PreviousPage != null)
{
    var textBox = Page.PreviousPage.FindControl("ControlID") as TextBox;
    if(textBox != null)
    {
        //Use your logic here
    }
}

Hope it will be helpful for you!

Best regards, Dima.


问:
Creating new Customised field so it appear in Sales Order import scenario in Order Nbr.> section
I would like to create a new customised field on the Sales Order summary screen so that it appears in the Import Scenario for Sales Order in the Order Nbr.-> Section. Is it possible?

Like by default we have Order Nbr.-> Order Nbr or Order Nbr.-> Customer Order

The final goal is to be able to select this newly added field in "Order Nbr. ->" prefix in the Import Scenario.

The reason I need this field is that I am creating import Scenarios to import the Salesforce Opportunity as Sales Order in Acumatica. For this, I have to create two Import scenarios, One for Order Summary and 2nd for Order details as the data in Salesforce is in two different tables.

Currently I am using the “Customer Order” field on the Order summary to store the Opportunity ID and then in my 2nd import Scenario, I am using  Order Nbr. ->Customer Order field to pickup the relevant Opportunity where the details should be imported. Client would like to use Customer Order for the actual Customer Order number so I am thinking of either using the External Reference or a new field to import the Opportunity ID.

答:
When you inspect fields with the "Order Nbr. ->" prefix in their names, those are the columns found inside the Order Nbr. selector drop-down:

Any custom field added for the SOOrder DAC and placed somewhere on the Sales Orders header form should be accessible for an integration scenario. For example, the Custom Text Field I added for Sales Orders was immediately accessible within the Import Scenarios screen:

There is nothing complicated in adding the External Reference and a new custom field in the Order Nbr. selector drop-down:

You should simply add the External Reference and a new custom field to the Customize Selector Columns dialog and, if needed, reorder the columns:

And to enable searching by the External Reference and a new custom field within the Order Nbr. selector drop-down, you should add CustomerRefNbr and custom field name in the GridProperties -> FastFilterFields property of the Order Nbr. selector:


问:
How to force Devel::Cover to ignore a folder when using perl-helpers via Travis CI
The MetaCPAN Travis CI coverage builds are quite slow.  See https://travis-ci.org/metacpan/metacpan-web/builds/238884497  This is likely in part because we're not successfully ignoring the /local folder that gets created by Carton as part of our build.  See  https://coveralls.io/builds/11809290

We're using perl-helpers to help with our Travis configuration.  I thought I should be able to use the DEVEL_COVER_OPTIONS environment variable in order to fix this, but I guess I don't have the correct incantation.  I've included the entire config below because a few snippets out of context seemed misleading.

```<code>language: perl
perl:
  - "5.22"

matrix:
  fast_finish: true
  allow_failures:
    - env: COVERAGE=1 USE_CPANFILE_SNAPSHOT=true
    - env: USE_CPANFILE_SNAPSHOT=false HARNESS_VERBOSE=1
env:
  global:
    # Carton --deployment only works on the same version of perl
    # that the snapshot was built from.
    - DEPLOYMENT_PERL_VERSION=5.22
    - DEVEL_COVER_OPTIONS="-ignore ^local/"
  matrix:

    # Get one passing run with coverage and one passing run with Test::Vars
    # checks.  If run together they more than double the build time.
    - COVERAGE=1 USE_CPANFILE_SNAPSHOT=true
    - USE_CPANFILE_SNAPSHOT=false HARNESS_VERBOSE=1
    - USE_CPANFILE_SNAPSHOT=true

before_install:
  - git clone git://github.com/travis-perl/helpers ~/travis-perl-helpers
  - source ~/travis-perl-helpers/init

  - npm install -g less js-beautify
  # Pre-install from backpan to avoid upgrade breakage.
  - cpanm -n http://cpan.metacpan.org/authors/id/M/ML/MLEHMANN/common-sense-3.6.tar.gz
  - cpanm -n App::cpm Carton

install:
  - cpan-install --coverage   # installs converage prereqs, if enabled
  - 'cpm install `test "${USE_CPANFILE_SNAPSHOT}" = "false" && echo " --resolver metadb" || echo " --resolver snapshot"`'

before_script:
  - coverage-setup

script:
  # Devel::Cover isn't in the cpanfile
  # but if it's installed into the global dirs this should work.
  - carton exec prove -lr -j$(test-jobs) t

after_success:
  - coverage-report

notifications:
  email:
    recipients:
      - olaf@seekrit.com
    on_success: change
    on_failure: always
  irc: "irc.perl.org#metacpan-travis"

# Use newer travis infrastructure.
sudo: false
cache:
  directories:
    - local
</code>```

答:
The syntax for the Devel::Cover options on the command line is weird. You need to put stuff comma-separated. At least when you use PERL5OPT.

```<code>DEVEL_COVER_OPTIONS="-ignore,^local/"
</code>```

See for example https://github.com/simbabque/AWS-S3/blob/master/.travis.yml#L26, where it's a whole lot of stuff with commas.

```<code>PERL5OPT=-MDevel::Cover=-ignore,"t/",+ignore,"prove",-coverage,statement,branch,condition,path,subroutine prove -lrs t
</code>```

Body:
The MetaCPAN Travis CI coverage builds are quite slow.  See https://travis-ci.org/metacpan/metacpan-web/builds/238884497  This is likely in part because we're not successfully ignoring the /local folder that gets created by Carton as part of our build.  See  https://coveralls.io/builds/11809290

We're using perl-helpers to help with our Travis configuration.  I thought I should be able to use the DEVEL_COVER_OPTIONS environment variable in order to fix this, but I guess I don't have the correct incantation.  I've included the entire config below because a few snippets out of context seemed misleading.

language: perl
perl:
  - "5.22"

matrix:
  fast_finish: true
  allow_failures:
    - env: COVERAGE=1 USE_CPANFILE_SNAPSHOT=true
    - env: USE_CPANFILE_SNAPSHOT=false HARNESS_VERBOSE=1
env:
  global:
    # Carton --deployment only works on the same version of perl
    # that the snapshot was built from.
    - DEPLOYMENT_PERL_VERSION=5.22
    - DEVEL_COVER_OPTIONS="-ignore ^local/"
  matrix:

    # Get one passing run with coverage and one passing run with Test::Vars
    # checks.  If run together they more than double the build time.
    - COVERAGE=1 USE_CPANFILE_SNAPSHOT=true
    - USE_CPANFILE_SNAPSHOT=false HARNESS_VERBOSE=1
    - USE_CPANFILE_SNAPSHOT=true

before_install:
  - git clone git://github.com/travis-perl/helpers ~/travis-perl-helpers
  - source ~/travis-perl-helpers/init

  - npm install -g less js-beautify
  # Pre-install from backpan to avoid upgrade breakage.
  - cpanm -n http://cpan.metacpan.org/authors/id/M/ML/MLEHMANN/common-sense-3.6.tar.gz
  - cpanm -n App::cpm Carton

install:
  - cpan-install --coverage   # installs converage prereqs, if enabled
  - 'cpm install `test "${USE_CPANFILE_SNAPSHOT}" = "false" && echo " --resolver metadb" || echo " --resolver snapshot"`'

before_script:
  - coverage-setup

script:
  # Devel::Cover isn't in the cpanfile
  # but if it's installed into the global dirs this should work.
  - carton exec prove -lr -j$(test-jobs) t

after_success:
  - coverage-report

notifications:
  email:
    recipients:
      - olaf@seekrit.com
    on_success: change
    on_failure: always
  irc: "irc.perl.org#metacpan-travis"

# Use newer travis infrastructure.
sudo: false
cache:
  directories:
    - local

Body:
The syntax for the Devel::Cover options on the command line is weird. You need to put stuff comma-separated. At least when you use PERL5OPT.

DEVEL_COVER_OPTIONS="-ignore,^local/"

See for example https://github.com/simbabque/AWS-S3/blob/master/.travis.yml#L26, where it's a whole lot of stuff with commas.

PERL5OPT=-MDevel::Cover=-ignore,"t/",+ignore,"prove",-coverage,statement,branch,condition,path,subroutine prove -lrs t


问:
appengine service to service queries not working
I followed those instructions

I have an appengine where 2 services (let's call them A and B) are deployed. The appengine is configured with IAP. (Identity Aware Proxy)

I can't get B to query A. If I call it simply with urlfetch.fetch, the call get's redirected with a 302 to what seems to be a login a page. The call is not logged in A so it seems to be intercepted elsewhere.

From what I understand this should work...

Anyway, I tried a using an Authorization header like we need to do when we want to query a google API. Still no luck, then I get a 401 with {'www-authenticate': 'Bearer error="invalid id token"'}

What should I do? Must I use a key? Activate an API switch somewhere to allow inter-services communications?

Also, they mention X-Appengine-Inbound-Appid needing to be there. How can I know if it's being added automatically or not? I set follow_redirects to false as the doc mentions it but I don't know how to see the outgoing traffic to confirm whether it's working or not.

答:
Two things need to be done.

In the IAP config page, you need to allow the app itself. So, in the right pane, click "Add", and add the app. (Something like <app-id>@appspot.gserviceaccount.com)

You need to add the proper "Authorization" : "Bearer <>" header to the requests. You can follow Authenticating from a service account to get the token_response['id_token'] to put in the header. And yes, it's quite a lot of code.

Note that even though I added the new access, it's still not being displayed in the right pane. It may be related to the fact that IAP is still in beta.


问:
yii2 from validation on array form elements
I've a form containing array elements and I've to validate it. i cant validate it by using the in-built validation rules, because the elements are not present in the database. i'm serialising the data and save them in a single field in database. so i tried to do the validation with custom validation.
my actual problem is the array field is validating but it doesn't shows the validation error message in the corresponding field.

This is the form

    <?php Portlet::begin(['title' => t('Shipper')]) ?>

    <?= $form->field($model, 'shipper[name]')
        ->textInput(['maxlength' => true])->label(t('Name'))?>

            <?= $form->field($model, 'shipper[address_line1]')
                ->textInput(['maxlength' => true])->label(t('Address Line 1')) ?>

            <?= $form->field($model, 'shipper[address_line2]')
                ->textInput(['maxlength' => true])->label(t('Address Line 2')) ?>

             <?= $form->field($model, 'shipper[city]')
                ->textInput(['maxlength' => true])->label(t('City')) ?>

             <?= $form->field($model, 'shipper[pin]')
                ->textInput(['maxlength' => true])->label(t('Pin Code')) ?>

```
</div>
</div>
</p>

<p><strong>Model</strong></p>

```.....
['shipper', function ($attribute, $params) {
   if (!filter_var($this->{$attribute}['email'], FILTER_VALIDATE_EMAIL)) {
         $this->addError('shipper', 'The email format is invalid!');
  }
}],
....
```

答:
You could add attributes to your model class like the following:

```<code>class MyModel extends \yii\db\ActiveRecord {
    public $shipperAddressLine1;
    public $shipperAddressLine2;
    public $shipperCity;
    public $shipperPin;
    ...
}
</code>```

Then you can add validation rules for them just like your database attributes.

Body:
I've a form containing array elements and I've to validate it. i cant validate it by using the in-built validation rules, because the elements are not present in the database. i'm serialising the data and save them in a single field in database. so i tried to do the validation with custom validation.
my actual problem is the array field is validating but it doesn't shows the validation error message in the corresponding field.

This is the form

    <?php Portlet::begin(['title' => t('Shipper')]) ?>

    <?= $form->field($model, 'shipper[name]')
        ->textInput(['maxlength' => true])->label(t('Name'))?>

            <?= $form->field($model, 'shipper[address_line1]')
                ->textInput(['maxlength' => true])->label(t('Address Line 1')) ?>

            <?= $form->field($model, 'shipper[address_line2]')
                ->textInput(['maxlength' => true])->label(t('Address Line 2')) ?>

             <?= $form->field($model, 'shipper[city]')
                ->textInput(['maxlength' => true])->label(t('City')) ?>

             <?= $form->field($model, 'shipper[pin]')
                ->textInput(['maxlength' => true])->label(t('Pin Code')) ?>

Model

.....
['shipper', function ($attribute, $params) {
   if (!filter_var($this->{$attribute}['email'], FILTER_VALIDATE_EMAIL)) {
         $this->addError('shipper', 'The email format is invalid!');
  }
}],
....

Body:
You could add attributes to your model class like the following:

class MyModel extends \yii\db\ActiveRecord {
    public $shipperAddressLine1;
    public $shipperAddressLine2;
    public $shipperCity;
    public $shipperPin;
    ...
}

Then you can add validation rules for them just like your database attributes.


答:
I didn't go to the link you posted but reading the code.

I will give you an example:

```<code>// If $data has the following values
array(
    'firstname' => 'my first name',
    'surname'  => 'my surname'
)
</code>```

The code will have 'firstname' and 'surname' as a public property of the class. The values for $this->firstname will be 'my first name'. The value of $this->surname will be 'my surname'.

Title: PHP Code: usage of this keyword

Body:
I didn't go to the link you posted but reading the code.

I will give you an example:

// If $data has the following values
array(
    'firstname' => 'my first name',
    'surname'  => 'my surname'
)

The code will have 'firstname' and 'surname' as a public property of the class. The values for $this->firstname will be 'my first name'. The value of $this->surname will be 'my surname'.


问:
how to inject Environment on application context
I'm currently working with legacy code and I wanna read some properties from the Environment. I know this would be easily done using spring boot with:

```<code>@Autowired
Environment environment;
</code>```

But, since I'm wiring all the components using an application-context.xml file, I don't know how to wire the Environment there,

```<code><bean name="myBean" class="com.acme.MyClass">
???
</bean>
</code>```

答:
Thanks for your help @volveira89 @rmlan

Using the xml file, this is working:

```<code><bean name="myBean" class="com.acme.MyClass">
   <constructor-arg ref="environment"/>
</bean>
</code>```

Body:
I'm currently working with legacy code and I wanna read some properties from the Environment. I know this would be easily done using spring boot with:

@Autowired
Environment environment;

But, since I'm wiring all the components using an application-context.xml file, I don't know how to wire the Environment there,

<bean name="myBean" class="com.acme.MyClass">
???
</bean>

Body:
Thanks for your help @volveira89 @rmlan

Using the xml file, this is working:

<bean name="myBean" class="com.acme.MyClass">
   <constructor-arg ref="environment"/>
</bean>


问:
¿Why does not the recyclerView update the data obtained from Firebase instantly?
I'm using a recyclerView that inflates two types of views, to be able to do a chat, everything is fine but it is not sent or received instantly
When I send a message, it is not received unless I click on my edit text,
Which is wrong, because in a chat should show instantly...

My adapter:

```<code>     public class ChatRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public Context context;
    public ArrayList<ChatPersonal> items = new ArrayList<>();
    private String mId;
    private static final int CHAT_RIGHT = 1;
    private static final int CHAT_LEFT = 2;

    public ChatRecyclerAdapter (Context context, ArrayList<ChatPersonal> items, String mId){
        this.context = context;
        this.items = items;
        this.mId = mId;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder holder = null;
        switch (viewType){
            case CHAT_RIGHT:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_right, parent, false);
                holder = new ChatPersonalHolderSender(view);
                break;
            case CHAT_LEFT:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_left, parent, false);
                holder = new ChatPersonalHolder(view);
                break;
        }

        return  holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ChatPersonal mObject = items.get(position);
        int itemViewType = getItemViewType(position);
        switch(itemViewType){
            case CHAT_RIGHT:
                ((ChatPersonalHolderSender) holder).mMENSAJE.setText(mObject.getMessage());
                ((ChatPersonalHolderSender) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
                break;
            case CHAT_LEFT:
                ((ChatPersonalHolder) holder).mMENSAJE.setText(mObject.getMessage());
                ((ChatPersonalHolder) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
                break;

        }
    }

    @Override
    public int getItemViewType(int position) {
        if(items.get(position).getId().equals(mId)){
            return CHAT_RIGHT;
        }else{
            return CHAT_LEFT;
        }
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

}
</code>```

And this is the relevant code of my chatClass:

```<code>   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

     linearLayoutManager = new LinearLayoutManager(ActivityChat.this);
            linearLayoutManager.setStackFromEnd(true);
            mRecyclerView.setLayoutManager(linearLayoutManager);
            mRecyclerView.setHasFixedSize(false);
            adapter = new ChatRecyclerAdapter(getApplicationContext(), items, mId);
            adapter.notifyDataSetChanged();
            mRecyclerView.setAdapter(adapter);

          // send message

        mSentMensaje.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String message = mEditText.getText().toString();
                    if (!message.isEmpty()) {
                        mChat.setMessage(message);
                        mChat.setHour(System.currentTimeMillis());
                        mChat.setId(mId);

                        if(mUser != null){
                            if(mUser.getIDchat() != null){
                                FirebaseUtils.getCHATT(mUser.getIDchat()).push().setValue(mChat).addOnSuccessListener(ActivityChat.this, new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        mRecyclerView.scrollToPosition(items.size() -1);
                                        adapter.notifyDataSetChanged();
                                        mEditText.setText("");
                                    }
                                });
                            }}

    // retreive message
        if(mUser != null){
        if(mUser.getIDchat() != null){
            FirebaseUtils.getCHATT(mUser.getIDchat()).limitToFirst(50).addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                        try{
                            ChatPersonal model = dataSnapshot.getValue(ChatPersonal.class);
                            items.add(model);
                        } catch (Exception ex) {
                            Log.e(TAG, ex.getMessage());
                        }
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

// status

 @Override
protected void onStart() {
    super.onStart();

    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            mRecyclerView.scrollToPosition(adapter.getItemCount() - 1);
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    adapter.notifyDataSetChanged();

}

@Override
protected void onPostResume() {
    super.onPostResume();
    adapter.notifyDataSetChanged();
}

  }
</code>```

答:
If you want the data to be synced with Firebase automatically, you need to use FirebaseRecyclerAdapter
Reference: https://github.com/firebase/FirebaseUI-Android/blob/master/database/src/main/java/com/firebase/ui/database/FirebaseRecyclerAdapter.java

Body:
I'm using a recyclerView that inflates two types of views, to be able to do a chat, everything is fine but it is not sent or received instantly
When I send a message, it is not received unless I click on my edit text,
Which is wrong, because in a chat should show instantly...

My adapter:

     public class ChatRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public Context context;
    public ArrayList<ChatPersonal> items = new ArrayList<>();
    private String mId;
    private static final int CHAT_RIGHT = 1;
    private static final int CHAT_LEFT = 2;

    public ChatRecyclerAdapter (Context context, ArrayList<ChatPersonal> items, String mId){
        this.context = context;
        this.items = items;
        this.mId = mId;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder holder = null;
        switch (viewType){
            case CHAT_RIGHT:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_right, parent, false);
                holder = new ChatPersonalHolderSender(view);
                break;
            case CHAT_LEFT:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_left, parent, false);
                holder = new ChatPersonalHolder(view);
                break;
        }

        return  holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ChatPersonal mObject = items.get(position);
        int itemViewType = getItemViewType(position);
        switch(itemViewType){
            case CHAT_RIGHT:
                ((ChatPersonalHolderSender) holder).mMENSAJE.setText(mObject.getMessage());
                ((ChatPersonalHolderSender) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
                break;
            case CHAT_LEFT:
                ((ChatPersonalHolder) holder).mMENSAJE.setText(mObject.getMessage());
                ((ChatPersonalHolder) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
                break;

        }
    }

    @Override
    public int getItemViewType(int position) {
        if(items.get(position).getId().equals(mId)){
            return CHAT_RIGHT;
        }else{
            return CHAT_LEFT;
        }
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

}

And this is the relevant code of my chatClass:

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

     linearLayoutManager = new LinearLayoutManager(ActivityChat.this);
            linearLayoutManager.setStackFromEnd(true);
            mRecyclerView.setLayoutManager(linearLayoutManager);
            mRecyclerView.setHasFixedSize(false);
            adapter = new ChatRecyclerAdapter(getApplicationContext(), items, mId);
            adapter.notifyDataSetChanged();
            mRecyclerView.setAdapter(adapter);

          // send message

        mSentMensaje.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String message = mEditText.getText().toString();
                    if (!message.isEmpty()) {
                        mChat.setMessage(message);
                        mChat.setHour(System.currentTimeMillis());
                        mChat.setId(mId);

                        if(mUser != null){
                            if(mUser.getIDchat() != null){
                                FirebaseUtils.getCHATT(mUser.getIDchat()).push().setValue(mChat).addOnSuccessListener(ActivityChat.this, new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        mRecyclerView.scrollToPosition(items.size() -1);
                                        adapter.notifyDataSetChanged();
                                        mEditText.setText("");
                                    }
                                });
                            }}

    // retreive message
        if(mUser != null){
        if(mUser.getIDchat() != null){
            FirebaseUtils.getCHATT(mUser.getIDchat()).limitToFirst(50).addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                        try{
                            ChatPersonal model = dataSnapshot.getValue(ChatPersonal.class);
                            items.add(model);
                        } catch (Exception ex) {
                            Log.e(TAG, ex.getMessage());
                        }
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

// status

 @Override
protected void onStart() {
    super.onStart();

    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            mRecyclerView.scrollToPosition(adapter.getItemCount() - 1);
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    adapter.notifyDataSetChanged();

}

@Override
protected void onPostResume() {
    super.onPostResume();
    adapter.notifyDataSetChanged();
}

  }


问:
Jquery Input field when user finishes making changes
I am wondering if their is a way to get what the user entered into an input field once they have click on another field(are done input into that field).  I tried .change, but that works for every letter the user inputs.  Is their a way for when the user is done entering text into the input field(clicks on another field)?

答: Yes, you can use <code>.blur()</code> for that. </p>

Body: Yes, you can use .blur() for that.


问:
Disabling/enabled textbox in GridViewRow
I have a checkbox and a textbox in a GridView (for every row), and I'd like to be able to write some javascript that would enable and disable the textbox depending on the state of the checkbox (checked or unchecked). I guess I'd have to give JS the row index somehow. Is this possible?</p>

答:
If you are ready to use jquery then this can be very easily accomplished as follows:

```<code>$(document).ready(function() {

   $('.grid tr').each(function() {
      var r = $(this);
      var c = r.find('.check');
      var t = r.find('.text');
      var f = function(c1, t1) { return function() {
            if (c1.attr('checked')) {
               t1.removeAttr('disabled');
            }
            else {
               t1.attr('disabled', 'disabled');
            }
         };
      };
      c.click(f(c, t)); // attach click event handler
      f(c, t); // set initial state
   });
});
</code>```

Above script is assuming that the gridview table is decorated with grid css class and each textbox and checkbox  are decorated with check and text css class respectively.

Body:
If you are ready to use jquery then this can be very easily accomplished as follows:

$(document).ready(function() {

   $('.grid tr').each(function() {
      var r = $(this);
      var c = r.find('.check');
      var t = r.find('.text');
      var f = function(c1, t1) { return function() {
            if (c1.attr('checked')) {
               t1.removeAttr('disabled');
            }
            else {
               t1.attr('disabled', 'disabled');
            }
         };
      };
      c.click(f(c, t)); // attach click event handler
      f(c, t); // set initial state
   });
});

Above script is assuming that the gridview table is decorated with grid css class and each textbox and checkbox  are decorated with check and text css class respectively.


问:
Indentation errors with code block?
I tried to define the following functions, but I keep getting:

error 000989 : Python syntax error: <value>.

So apparently my code has improper syntax. I've tried the following:

```<code>def yieldCalc(value):
 if (value=1):
     return 6.2
  elif (value=2):
     return 7.9
  else:
     return 8.21
</code>```

Also

```<code>def yieldCalc(value):
 if (value=1):
     return 6.2
  elif (value=2):
     return 7.9
 else:
     return 8.21
</code>```

And

```<code>def yieldCalc(value):
 if (value=1):
     return 6.2
 elif (value=2):
     return 7.9
 else:
     return 8.21
</code>```

What is the proper way to indent the python code block?

答:
Thanks to everyone who responded, as it turns out what I had wrong was - as all of you pointed out - the syntax used for declaring the logical test in my if.

I used == instead of = and kept the indentation as suggested by Larry.

It works and I saved a lot of time.

Title: Indentation errors with code block?

Body:
I tried to define the following functions, but I keep getting:

error 000989 : Python syntax error: <value>.

So apparently my code has improper syntax. I've tried the following:

def yieldCalc(value):
 if (value=1):
     return 6.2
  elif (value=2):
     return 7.9
  else:
     return 8.21

Also

def yieldCalc(value):
 if (value=1):
     return 6.2
  elif (value=2):
     return 7.9
 else:
     return 8.21

And

def yieldCalc(value):
 if (value=1):
     return 6.2
 elif (value=2):
     return 7.9
 else:
     return 8.21

What is the proper way to indent the python code block?