问:
Why Consumer thread is not able to remove messages from Vector?
I am trying to create a solution for Producer/ Consumer problem where one thread is putting message in Vector and another is removing from it.

```<code>import java.util.Vector;
public class Producer implements Runnable {
    static final int MAXQUEUE = 5;
    private Vector<String> messages;

    public Producer(Vector<String> messages) {
        super();
        this.messages = messages;
    }

    @Override
    public void run() {
        try {
            while (true)
                putMessage();
        } catch (InterruptedException e) {
        }
    }

    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        notifyAll();
    }

    public static void main(String args[]) {
        Vector<String> messages = new Vector<String>();
        new Thread(new Producer(messages)).start();
        new Thread(new Consumer(messages)).start();
    }
}

class Consumer implements Runnable{
    public Consumer(Vector<String> messages) {
        super();
        this.messages = messages;
    }
    private Vector<String> messages;

    public synchronized String getMessage() throws InterruptedException {
        notifyAll();
        while (messages.size() == 0) {
            wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String message = getMessage();
                System.out.println("Got message: " + message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Whenever I am running the program, it is printing  put message 5 times. I don't understand even after notifyAll(), it is not giving lock to consumer.

答:
Logging to the console is very slow so if you do this without holding the lock you give the consumer a chance.

```<code>@Override
public void run() {
    try {
        while (true) {
            // slows the producer a little to give the consumer a chance to get the lock.
            System.out.println("put message");
            putMessage();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void putMessage() throws InterruptedException {
    synchronized  (messages) {
        while (messages.size() == MAXQUEUE) {
            messages.wait();
        }
        messages.addElement(new java.util.Date().toString());
        messages.notifyAll();
    }
}
</code>```

BTW on the consumer you can write this

```<code>public String getMessage() throws InterruptedException {
    synchronized (messages) {
        while (messages.isEmpty()) {
            messages.wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        messages.notifyAll();
        return messages.remove(0);
    }
}
</code>```

Body:
I am trying to create a solution for Producer/ Consumer problem where one thread is putting message in Vector and another is removing from it.

import java.util.Vector;
public class Producer implements Runnable {
    static final int MAXQUEUE = 5;
    private Vector<String> messages;

    public Producer(Vector<String> messages) {
        super();
        this.messages = messages;
    }

    @Override
    public void run() {
        try {
            while (true)
                putMessage();
        } catch (InterruptedException e) {
        }
    }

    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        notifyAll();
    }

    public static void main(String args[]) {
        Vector<String> messages = new Vector<String>();
        new Thread(new Producer(messages)).start();
        new Thread(new Consumer(messages)).start();
    }
}

class Consumer implements Runnable{
    public Consumer(Vector<String> messages) {
        super();
        this.messages = messages;
    }
    private Vector<String> messages;

    public synchronized String getMessage() throws InterruptedException {
        notifyAll();
        while (messages.size() == 0) {
            wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String message = getMessage();
                System.out.println("Got message: " + message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Whenever I am running the program, it is printing  put message 5 times. I don't understand even after notifyAll(), it is not giving lock to consumer.

Body:
Logging to the console is very slow so if you do this without holding the lock you give the consumer a chance.

@Override
public void run() {
    try {
        while (true) {
            // slows the producer a little to give the consumer a chance to get the lock.
            System.out.println("put message");
            putMessage();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void putMessage() throws InterruptedException {
    synchronized  (messages) {
        while (messages.size() == MAXQUEUE) {
            messages.wait();
        }
        messages.addElement(new java.util.Date().toString());
        messages.notifyAll();
    }
}

BTW on the consumer you can write this

public String getMessage() throws InterruptedException {
    synchronized (messages) {
        while (messages.isEmpty()) {
            messages.wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        messages.notifyAll();
        return messages.remove(0);
    }
}


来源: stackexchange

问:
Adjust LocalTime according to ZoneId
Given a LocalTime in a given ZoneId, how can I find the adjusted LocalTime on UTC?

I am looking for something similar to .atZone from LocalDateTime, but couldn't find anything.

I suspect I can use it with atOffset, but I don't really understand how to use it.

So for example:

```<code>LocalTime: 15:00
ZoneId: America/Sao_Paulo (GMT -3)
Output: 18:00
</code>```

答:
A ZoneId does not make sense because the date is missing but you can use a ZoneOffset this way:

```<code>LocalTime time = LocalTime.of(15, 0);
ZoneOffset offset = ZoneOffset.ofHours(-3);
LocalTime utc =
    OffsetTime.of(time, offset).withOffsetSameInstant(ZoneOffset.UTC).toLocalTime();
System.out.println(utc); // 18:00
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adjust LocalTime according to ZoneId

Body:
Given a LocalTime in a given ZoneId, how can I find the adjusted LocalTime on UTC?

I am looking for something similar to .atZone from LocalDateTime, but couldn't find anything.

I suspect I can use it with atOffset, but I don't really understand how to use it.

So for example:

LocalTime: 15:00
ZoneId: America/Sao_Paulo (GMT -3)
Output: 18:00

Body:
A ZoneId does not make sense because the date is missing but you can use a ZoneOffset this way:

LocalTime time = LocalTime.of(15, 0);
ZoneOffset offset = ZoneOffset.ofHours(-3);
LocalTime utc =
    OffsetTime.of(time, offset).withOffsetSameInstant(ZoneOffset.UTC).toLocalTime();
System.out.println(utc); // 18:00


问:
pandas adding new rows to dataframe based on dataframe values
I have transactional data for users as follows:

```<code>userid accountid weeknumber amount_spent
1      a         1          100
1      a         2          200
1      a         4          500
1      b         1          500
...
9      z         1          350
</code>```

The data only captured weeks where the user had transactions. I need to go through the data and add rows for when the user didn't spend any money.

E.g. I need to add rows like:

```<code>userid accountid weeknumber amount_spent
1      a         3          0
</code>```

Currently I do it as follows:

```<code># get all user-account pairs
for user_acct_pair in df.groupby(['userid', 'accountid']).groups.iterkeys():
    userid = user_acct_pair[0]
    acctid = user_acct_pair[1]

# get the weeks that we have recorded for this user
weeks_recorded = df.xs((userid, acctid), axis=0, level=[0, 1], \
                              drop_level=True).index.values

for i in range(1, MAX_WEEK_NUMBER):
    if i not in weeks_recorded:
        # add the row for the week without transactions
        df.loc[(userid, acctid, i), 'amount_spent'] = 0

# convert back to df from groupby object
df = df.reset_index()
</code>```

This seems to be incredibly slow when I run on a dataset with ~90,000 rows.
I think that there is a high cost in finding a row in a multilevel index when the row doesn't exist yet.

Are there more efficient ways to do this, or perhaps built in functionalities to achieve what I'm trying to do?

答:
Here is my solution : </p>

```<code>#Grouby accountid
for i in df.groupby(['userid', 'accountid']).max().itertuples():
    print(i)
    #Get range of weeks
    r = [i for i in range(1,i.weeknumber+1)]
    #find all unique weeks
    unique = df[(df.accountid == i.Index[1]) & (df.userid == i.Index[0])].weeknumber.unique()
    #Substract the one that are already here
    missing = [e for e in r if e not in unique]
    #append them to the dataframe
    for m in missing:
        line = pd.DataFrame({'userid':[i.Index[0]],"weeknumber":[m], "amount_spent":[0], "accountid":i.Index[1]})
        df = df.append(line)
</code>```

<p>Should be faster, but on small sample it's hard to tell </p>

Body:
I have transactional data for users as follows:

userid accountid weeknumber amount_spent
1      a         1          100
1      a         2          200
1      a         4          500
1      b         1          500
...
9      z         1          350

The data only captured weeks where the user had transactions. I need to go through the data and add rows for when the user didn't spend any money.

E.g. I need to add rows like:

userid accountid weeknumber amount_spent
1      a         3          0

Currently I do it as follows:

# get all user-account pairs
for user_acct_pair in df.groupby(['userid', 'accountid']).groups.iterkeys():
    userid = user_acct_pair[0]
    acctid = user_acct_pair[1]

# get the weeks that we have recorded for this user
weeks_recorded = df.xs((userid, acctid), axis=0, level=[0, 1], \
                              drop_level=True).index.values

for i in range(1, MAX_WEEK_NUMBER):
    if i not in weeks_recorded:
        # add the row for the week without transactions
        df.loc[(userid, acctid, i), 'amount_spent'] = 0

# convert back to df from groupby object
df = df.reset_index()

This seems to be incredibly slow when I run on a dataset with ~90,000 rows.
I think that there is a high cost in finding a row in a multilevel index when the row doesn't exist yet.

Are there more efficient ways to do this, or perhaps built in functionalities to achieve what I'm trying to do?

Body:
Here is my solution :

#Grouby accountid
for i in df.groupby(['userid', 'accountid']).max().itertuples():
    print(i)
    #Get range of weeks
    r = [i for i in range(1,i.weeknumber+1)]
    #find all unique weeks
    unique = df[(df.accountid == i.Index[1]) & (df.userid == i.Index[0])].weeknumber.unique()
    #Substract the one that are already here
    missing = [e for e in r if e not in unique]
    #append them to the dataframe
    for m in missing:
        line = pd.DataFrame({'userid':[i.Index[0]],"weeknumber":[m], "amount_spent":[0], "accountid":i.Index[1]})
        df = df.append(line)

Should be faster, but on small sample it's hard to tell


问:
How do i programatically find the exact place of a control on a form/page

Function RequiredFieldsMissing(frm As Form) As Boolean
Dim foundEmpty As Boolean
Dim txt As TextBox
Dim cmb As ComboBox
Dim pge As Page
Dim Ctrl As Control
Dim formName As String`

    foundEmpty = False
    formName = frm.Name
    For Each Ctrl In frm.Controls
        If Len(Ctrl.Name) > 6 Then
            If left(Ctrl.Name, 3) = "txt" And right(Ctrl.Name, 3) = "Req" Then
                Set txt = Ctrl
                If IsNull(txt.value) Then
                    foundEmpty = True
                    txt.BackColor = constLngRed
                    'Form_Clients.TabClientData.Pages(1).SetFocus
                    txt.SetFocus
                Else
                    If Len(txt.value) = 0 Then
                        foundEmpty = True
                        txt.BackColor = constLngRed
                    End If
                End If
            End If
            If left(Ctrl.Name, 3) = "cmb" And right(Ctrl.Name, 3) = "Req" Then
                Set cmb = Ctrl
                If IsNull(cmb.value) Then
                    foundEmpty = True
                    cmb.BackColor = constLngRed
                Else
                    If Len(cmb.value) = 0 Then
                        foundEmpty = True
                        cmb.BackColor = constLngRed
                    End If
                End If
            End If
        End If
    Next Ctrl

    RequiredFieldsMissing = foundEmpty
End Function
```

The function above will colour and highlight the control that does not have data...the problem is that i need to set focus to the control but sometimes the control resides on a sub form and on a page.
If i do txt.setfocus, then it will set focus to that control but not move to the residing page. Also the only variable I pass is the form.

My question is as follows...

How can i set focus to that control that resides on a page when i only pass the form name?

答: You have to call SetFocus twice: once to set the focus to the subform (on the main form), and once to set the focus to the control on the subform.</p>

Body:
Function RequiredFieldsMissing(frm As Form) As Boolean
Dim foundEmpty As Boolean
Dim txt As TextBox
Dim cmb As ComboBox
Dim pge As Page
Dim Ctrl As Control
Dim formName As String`

    foundEmpty = False
    formName = frm.Name
    For Each Ctrl In frm.Controls
        If Len(Ctrl.Name) > 6 Then
            If left(Ctrl.Name, 3) = "txt" And right(Ctrl.Name, 3) = "Req" Then
                Set txt = Ctrl
                If IsNull(txt.value) Then
                    foundEmpty = True
                    txt.BackColor = constLngRed
                    'Form_Clients.TabClientData.Pages(1).SetFocus
                    txt.SetFocus
                Else
                    If Len(txt.value) = 0 Then
                        foundEmpty = True
                        txt.BackColor = constLngRed
                    End If
                End If
            End If
            If left(Ctrl.Name, 3) = "cmb" And right(Ctrl.Name, 3) = "Req" Then
                Set cmb = Ctrl
                If IsNull(cmb.value) Then
                    foundEmpty = True
                    cmb.BackColor = constLngRed
                Else
                    If Len(cmb.value) = 0 Then
                        foundEmpty = True
                        cmb.BackColor = constLngRed
                    End If
                End If
            End If
        End If
    Next Ctrl

    RequiredFieldsMissing = foundEmpty
End Function

The function above will colour and highlight the control that does not have data...the problem is that i need to set focus to the control but sometimes the control resides on a sub form and on a page.
If i do txt.setfocus, then it will set focus to that control but not move to the residing page. Also the only variable I pass is the form.

My question is as follows...

How can i set focus to that control that resides on a page when i only pass the form name?


问:
If checkbox is checked, change only style of that item
I'm making a checkbox list and when someone checks a checkbox, I need it to change text from pending to done and also change the background to green. I've managed to make all that work with jQuery.

Except it styles every checkbox container and not just the one checked. How can I fix that? And how can I make it change back to its original style if someone unchecks the checkbox again after?

This is my code so far:

$('.custom-control-input').click(function(){
    if (this.checked) {
        $('.pending').css('display', 'none')
        $('.done').css('display', 'block')
        $('.list-group-item').css('background-color','#4CAF50')
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.done {
  display: none;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

```

答:
Add $(this).closest('.list-group-item') to change background of the only the parent of the checkedcheckbox

$('.custom-control-input').click(function(){
        $(this).closest('.list-group-item').find('.pending').css('display', (this.checked)?'none':'block')
        $(this).closest('.list-group-item').find('.done').css('display', (this.checked)?'block':'none')
        $(this).closest('.list-group-item').css('background-color',(this.checked)?'#4CAF50':'')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.done {
  display: none;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

```

Body:
I'm making a checkbox list and when someone checks a checkbox, I need it to change text from pending to done and also change the background to green. I've managed to make all that work with jQuery.

Except it styles every checkbox container and not just the one checked. How can I fix that? And how can I make it change back to its original style if someone unchecks the checkbox again after?

This is my code so far:

$('.custom-control-input').click(function(){
    if (this.checked) {
        $('.pending').css('display', 'none')
        $('.done').css('display', 'block')
        $('.list-group-item').css('background-color','#4CAF50')
    }
})

.done {
  display: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

Body:
Add $(this).closest('.list-group-item') to change background of the only the parent of the checkedcheckbox

$('.custom-control-input').click(function(){
        $(this).closest('.list-group-item').find('.pending').css('display', (this.checked)?'none':'block')
        $(this).closest('.list-group-item').find('.done').css('display', (this.checked)?'block':'none')
        $(this).closest('.list-group-item').css('background-color',(this.checked)?'#4CAF50':'')
})

.done {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<ul class="list-group">
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
</div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
  </div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
  </div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
</div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
</ul>


问:
Is there a level limit in dojo treegrid?
I've trying to get the treegrid using forestmodel to work the last several days. It seems to me that there is a limit to the number of level can be displayed using programmatically created treegrid.
I modified dojo's "dojox/grid/tests/test_treegrid_model2.html", once I add another level under "Ottwa", I got a "dojo.data.ItemFileReadStore: Invalid item argument." error.

...
{ id: 'CA', name:'Canada', type:'country',  population:'33 million', area:'9,984,670 sq km',
     children:[{_reference:'Ottawa'},
               {_reference:'Toronto'}]},
{ id: 'Ottawa', name:'Ottawa', type:'city', population:'0.9 million', timezone:'-5 UTC',
      children:[{_reference:'Ottawa1'}]},
{ id: 'Ottawa1', name:'Ottawa1', type:'city1', population:'0.9 million', timezone:'-5 UTC'},
...

If I add the 2 new cities to Canada, it works just fine.
...
{ id: 'CA', name:'Canada', type:'country',  population:'33 million', area:'9,984,670 sq km',
 children:[{_reference:'Ottawa'},
          {_reference:'Toronto'},
      {_reference:'Ottawa1'},
      {_reference:'Ottawa2'}] },
{ id: 'Ottawa', name:'Ottawa', type:'city', population:'0.9 million', timezone:'-5 UTC'},
{ id: 'Ottawa1', name:'Ottawa1', type:'city1', population:'0.9 million', timezone:'-5 UTC'},
{ id: 'Ottawa2', name:'Ottawa2', type:'city1', population:'0.9 million', timezone:'-5 UTC'},
...

Is there a limit to the number of level can be displayed in TreeGrid?
Thanks,

David

答: OK, I'm answering my own question, and hopefully it'll be useful for other people. It is a confirmed bug, the bug fix is scheduled to be released with 1.6. But if you check out the most recent trunk(http://svn.dojotoolkit.org/src/), and just update your TreeGrid.js, it should fix the problem.</p>

ContentLicense: CC BY-SA 2.5


问:
How show json data with database in symfony
I have a little problem, because I have to show json date with database in Symfony3.

My controller

```<code>/**
     * @Route("/api/rest", name="rest_api")
     *
     *
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();

    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}
</code>```

And this is my layout in html.twig

```<code>{% for comments in comment %}
           {{ comments }}
{% endfor %}
</code>```

But I don't know why nothing show.
Help me please :)

答:
json_encode return a string.

Twig

```<code>{{ dump(comments) }}
</code>```

Body:
I have a little problem, because I have to show json date with database in Symfony3.

My controller

/**
     * @Route("/api/rest", name="rest_api")
     *
     *
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();

    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}

And this is my layout in html.twig

{% for comments in comment %}
           {{ comments }}
{% endfor %}

But I don't know why nothing show.
Help me please :)

Body:
json_encode return a string.

Twig

{{ dump(comments) }}


问:
Error in Math.random() for arrayList
I'm sure this is a small, stupid error that I just can't see.

I'm getting a compiling error in this code:

```<code>private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
</code>```

in my length.

Compiling error is:

"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList  "

How can I fix this?  I do want to use Math.random();

Also not sure if this makes a difference, but this is is being done within a String method.

Thanks in advance!

答:
The code has three problems:

First, the variable "cities" is an ArrayList, as the compiller error wrote. ArrayList is a Collection which implements the interface List. The size of any implementations of List is accessable by method size(). Than, you should change cities.length by cities.size() or you turn cities as array.

Second, you defined the variable "match" as an int value but method floor from Math return a double. If you really want "match" to be a int, than you can use the cast against the method floor, that is, you code become: int match = (int) Math.random()*cities.size();

Third, your method requires an String as return, than you should return the String object correctly.

Title: Error in Math.random() for arrayList

Body:
I'm sure this is a small, stupid error that I just can't see.

I'm getting a compiling error in this code:

private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }

in my length.

Compiling error is:

"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList  "

How can I fix this?  I do want to use Math.random();

Also not sure if this makes a difference, but this is is being done within a String method.

Thanks in advance!


问:
Clipping of HALF plane in OpenGL
I would like to make a clipping half plane, but I am quite unacquainted with OpenGL.

For now, I use a wrapper to OpenGL's glClipPlane

```<code>    void gle::setClipPlane(GLenum glp, Vector3 const& dir, Vector3 const& pos)
{
    GLdouble eq[4] = { dir.XX, dir.YY, dir.ZZ, -dir*pos };
    glClipPlane(glp, eq);
}
</code>```

But I would actually like to do a clipping half-plane, e.g. the plane with normal 0 1 0, but only for x>0 and y>0.
Is it possible to do it in a simple way ?

答:
x>0 and y>0 are conditions that represent two half-spaces. You can set them by glClipPlane(planeE, equ)with a different planeE for each half-space.

glClipPlaneis a command for old OpenGL, or new with a compatibility-context profile. For modern OGL, core-context profile, you must implement this clipping inside shaders.

Title: Clipping of HALF plane in OpenGL

Body:
I would like to make a clipping half plane, but I am quite unacquainted with OpenGL.

For now, I use a wrapper to OpenGL's glClipPlane

    void gle::setClipPlane(GLenum glp, Vector3 const& dir, Vector3 const& pos)
{
    GLdouble eq[4] = { dir.XX, dir.YY, dir.ZZ, -dir*pos };
    glClipPlane(glp, eq);
}

But I would actually like to do a clipping half-plane, e.g. the plane with normal 0 1 0, but only for x>0 and y>0.
Is it possible to do it in a simple way ?


问:
How to check radio button status on UI (whether it is enabled or disabled)- robot framework
How to check whether a radio button status (is enabled or disabled). Is there any selenium2 keyword for this? Please help.</p>

答:
In case you mearly want to test if a radio button has a certain value set, then you should use 1 Radio Button Should be Set To Documentation

In case you have logic that enables an entire radio button group, and want to test for that then the standard keyword Element Should be Enabled is more appropriate. Documentation


问:
Request.GetOwinContext().Get<T> return null in APIControler
I Could not retrieve the data from OwinContext Environment that I store it after authenticate by token.

this is the Code:

[ValidateClientAuthentication]
In thins Code I validate the ClientID of the User and then store the data of ApplicationClient in OwinContext in this line

```<code>public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        ...
        ApplicationClient App = new ApplicationClient();
        App.Id = clientId;
        App.ClientSecretHash = clientSecret;
        // Storing Client Data
        context.OwinContext.Set<ApplicationClient>("oauth:client", App);
        context.Validated(clientId);
    }
</code>```

[GrantResourceOwnerCredentials]
Here I Validate User Credentials and Add Climes to the Token

```<code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    ...
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    if (Membership.ValidateUser(username, password))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
        identity.AddClaim(new Claim(ClaimTypes.Name, username));
        context.Validated(identity);
    }
    else
    {
        context.SetError("Login Field", "Error username or password");
    }
}
</code>```

[ControlerCode] Now Here is My Problem

```<code>[Authorize]
public class MyController : ApiController
{
    public IEnumerable<SelectedMenu> GetAllMenus() // Resturants ID
    {
        // client is Null
        ApplicationClient client = HttpContext.Current.GetOwinContext().Get<ApplicationClient>("oauth:client");
    }
}
</code>```

答:
You should really only add the clientId inside your token, so you may retrieve it anytime after the login process.

```<code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    // ...
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    if (Membership.ValidateUser(username, password))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
        identity.AddClaim(new Claim(ClaimTypes.Name, username));
        identity.AddClaim(new Claim("oauth-client", context.ClientId));
        context.Validated(identity);
    }
    else
    {
        context.SetError("Login Field", "Error username or password");
    }
}
</code>```

You may also create an extension method to help you in retrieving the clientId:

```<code>public static class PrincipalExtensions
{
    public static string GetClientId(this IPrincipal principal)
    {
        return (principal.Identity as ClaimsIdentity)?
            .Claims
            .FirstOrDefault(c => c.Type == "oauth-client")?
            .Value;
    }
}
</code>```

And inside your controller:

```<code>[Authorize]
public class MyController : ApiController
{
    public IEnumerable<SelectedMenu> GetAllMenus() // Resturants ID
    {
        var clientId = User.GetClientId();
    }
}
</code>```

Regarding the token size: if your clientId string is too long I suggest you to use another one and store any other client information (including a longer id if is needed) inside the database. The client identifier should be a small and unique string easy to transmit.

Body:
I Could not retrieve the data from OwinContext Environment that I store it after authenticate by token.

this is the Code:

[ValidateClientAuthentication]
In thins Code I validate the ClientID of the User and then store the data of ApplicationClient in OwinContext in this line

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        ...
        ApplicationClient App = new ApplicationClient();
        App.Id = clientId;
        App.ClientSecretHash = clientSecret;
        // Storing Client Data
        context.OwinContext.Set<ApplicationClient>("oauth:client", App);
        context.Validated(clientId);
    }

[GrantResourceOwnerCredentials]
Here I Validate User Credentials and Add Climes to the Token

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    ...
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    if (Membership.ValidateUser(username, password))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
        identity.AddClaim(new Claim(ClaimTypes.Name, username));
        context.Validated(identity);
    }
    else
    {
        context.SetError("Login Field", "Error username or password");
    }
}

[ControlerCode] Now Here is My Problem

[Authorize]
public class MyController : ApiController
{
    public IEnumerable<SelectedMenu> GetAllMenus() // Resturants ID
    {
        // client is Null
        ApplicationClient client = HttpContext.Current.GetOwinContext().Get<ApplicationClient>("oauth:client");
    }
}

Body:
You should really only add the clientId inside your token, so you may retrieve it anytime after the login process.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    // ...
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    if (Membership.ValidateUser(username, password))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
        identity.AddClaim(new Claim(ClaimTypes.Name, username));
        identity.AddClaim(new Claim("oauth-client", context.ClientId));
        context.Validated(identity);
    }
    else
    {
        context.SetError("Login Field", "Error username or password");
    }
}

You may also create an extension method to help you in retrieving the clientId:

public static class PrincipalExtensions
{
    public static string GetClientId(this IPrincipal principal)
    {
        return (principal.Identity as ClaimsIdentity)?
            .Claims
            .FirstOrDefault(c => c.Type == "oauth-client")?
            .Value;
    }
}

And inside your controller:

[Authorize]
public class MyController : ApiController
{
    public IEnumerable<SelectedMenu> GetAllMenus() // Resturants ID
    {
        var clientId = User.GetClientId();
    }
}

Regarding the token size: if your clientId string is too long I suggest you to use another one and store any other client information (including a longer id if is needed) inside the database. The client identifier should be a small and unique string easy to transmit.


问:
proper way to configure d3 to work with angular2 and typescript
trying to include d3 library into an angular2 typescript project. I added d3 via npm install d3 and the typings via typing install d3 --save, the project local server doesn't start (tsc && concurrently "npm
run tsc:w" "npm run lite"), with the following error:

```<code>typings/browser/definitions/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.
</code>```

these are my config files:

typings.json:

```<code>{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b",
    "gapi": "github:DefinitelyTyped/DefinitelyTyped/gapi.auth2/gapi.auth2.d.ts"
  },
  "dependencies": {
    "d3": "registry:npm/d3#3.0.0+20160211003958"
  }
}
</code>```

package.json:

```<code>{
  "name": "session-explorer",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "systemjs": "0.19.26",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.10",
    "d3": "^3.0.0"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^0.7.12"
  }
}
</code>```

答:
The 2017 Update

Installation

Installing types for d3 v3:

```<code>npm install d3@3.x --save
npm install @types/d3@3.x --save-dev
</code>```

Installing types for the latest d3 version (at the moment of writing v4):

```<code>npm install d3 --save
npm install @types/d3 --save-dev
</code>```

Usage

```<code>import * as d3 from 'd3';
</code>```

Body:
trying to include d3 library into an angular2 typescript project. I added d3 via npm install d3 and the typings via typing install d3 --save, the project local server doesn't start (tsc && concurrently "npm
run tsc:w" "npm run lite"), with the following error:

typings/browser/definitions/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.

these are my config files:

typings.json:

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b",
    "gapi": "github:DefinitelyTyped/DefinitelyTyped/gapi.auth2/gapi.auth2.d.ts"
  },
  "dependencies": {
    "d3": "registry:npm/d3#3.0.0+20160211003958"
  }
}

package.json:

{
  "name": "session-explorer",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "systemjs": "0.19.26",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.10",
    "d3": "^3.0.0"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^0.7.12"
  }
}

Body:
The 2017 Update

Installation

Installing types for d3 v3:

npm install d3@3.x --save
npm install @types/d3@3.x --save-dev

Installing types for the latest d3 version (at the moment of writing v4):

npm install d3 --save
npm install @types/d3 --save-dev

Usage

import * as d3 from 'd3';


问:
npm install error ( npm install -g angular-cli ) in windows 10

node -v

v4.5.0

npm -v

5.0.1

Has anyone faced this kind of issue while installing angular-cli in windows 10?

答:
try this : </p>

```<code>$ npm remove -g angular-cli
$ npm cache clean
$ npm install -g angular-cli
</code>```

ContentLicense: CC BY-SA 4.0

Body:
try this :

$ npm remove -g angular-cli
$ npm cache clean
$ npm install -g angular-cli


问:
Can CSS3 Filter be applied to options inside <select> ?
I would like to blur the options inside a select dropdown when opened. I could blur the selected option but not the ones inside it.

```<code>select option {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}
</code>```

Here's a codepen to test:

https://codepen.io/santalurr/pen/LLVWBB

答:
You can add a class on your blured option and do

```<code><select>
    <option class="blur">tatata</option>
</select>
</code>```

And do that in your css

```<code>select option.blur {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}
</code>```

Or just do

```<code>select option:checked {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}
</code>```

Source: https://www.w3.org/TR/selectors/#checked

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and  checked attributes

So, this CSS works, although styling is not possible in every browser.

You can take a look here too before click on -1...

CSS :selected pseudo class similar to :checked, but for <select> elements

Body:
I would like to blur the options inside a select dropdown when opened. I could blur the selected option but not the ones inside it.

select option {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}

Here's a codepen to test:

https://codepen.io/santalurr/pen/LLVWBB

Body:
You can add a class on your blured option and do

<select>
    <option class="blur">tatata</option>
</select>

And do that in your css

select option.blur {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}

Or just do

select option:checked {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}

Source: https://www.w3.org/TR/selectors/#checked

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and  checked attributes

So, this CSS works, although styling is not possible in every browser.

You can take a look here too before click on -1...

CSS :selected pseudo class similar to :checked, but for <select> elements


问:
What can make Class::Loader fail where "use" and "new" do not?
I'm working on a very large CGI application that uses Crypt::RSA, which is properly installed.  I get a "attempted to call a null reference as a function" type of error (I can't go back to get the exact error right now because we had to rollback for a release date) when I try to run any the embedded library.  I trace the null reference to Crypt::RSA's constructor, which uses Class::Loader to enable Crypt::RSA::ES::OAEP.

I replaced the class loader with a "use" and a "new", and that part works fine, though the library still fails in many points.  Obviously something is wrong with my environment.  I'm just not certain as to what.  Can anyone give me any leads?

答:
Ok, after 12 hours of digging into it, I got this working.

Here's what was going on (but not why).  Whenever I called eval() on a quoted use or require statement (as occurs in Class::Loader, but also in other locations in the Crypt:: framwork), it failed to see paths that were otherwise included as Perl classpaths.  Since most quoted use/require objects simply assume the class will be there, very few useful errors were thrown out at me.  I would dump @INC to file, outside an eval block, and everything would be there.

Ironically, I used the same setup in dev vs staging, and it worked in dev, but not in staging.  I must also point out that FindBin (I shouldn't be using it in CGI, I know, but Crypt uses it) was flailing up and down about /dev/null in staging, but not in development.

Since I can't easily compare versions or global configs, that's where my quest ends.

How I resolved the issue for myself in Crypt::RSA was to disable all commands tied to FindBin, and hard-code require references for anything my code would ever access.  I did a require in Crypt::RSA for Crypt::RSA::ES::OAEP and one in Crypt::Random::Generator for Crypt::Random::Provider::rand

Hope this helps anyone in the future who has the problem.  Anyone who can suggest the why of it, please respond and I'll add it to complete the post.

LastEditorDisplayName: brian d foy


问:
Stack trace for sql query execution? (Zend Framework)
Is there a way to get the stack trace for each sql query using the db profiler?

I'm using the profiler like so:

foreach($profiler->getQueryProfiles()
  as $query) {

}

Which is fine as I can get elapsed seconds, actual query etc but I want to know where this query was called from so I need the last 3 or 4 items in the stack trace.

Any ideas?

答: Extend Zend_Db_Profiler and use debug_backtrace() in the queryEnd method.


问:
How to change Content-Type:application/json into html in response header
I am setting up symfony 3 apache 2.4 and mysql environment for API development... I have just started and the index.html.twig page appears like this:

and my response header looks json format instead of html

my config.yml has FOSRest Configuration as:

```<code># FOSRest Configuration
fos_rest:
    body_listener: true
    format_listener:
        rules:
            - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true

# Nelmio CORS Configuration
nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
        max_age: 3600
        hosts: []
        origin_regex: false
</code>```

my question: how can I make my page rendered as html ?

答:
In your FOSRest configuration, you tell him to handle the response when the URL match ^/ which is every URLs.

If you want to use FOSRest formatting for everything but the main page, you can configure it as follow :

```<code>fos_rest:
    # ...
    format_listener:
            rules:
                - { path: '^/.+', priorities: ['json'], fallback_format: json, prefer_extension: false }
                - { path: '^/', stop: true }
</code>```

Body:
I am setting up symfony 3 apache 2.4 and mysql environment for API development... I have just started and the index.html.twig page appears like this:

and my response header looks json format instead of html

my config.yml has FOSRest Configuration as:

# FOSRest Configuration
fos_rest:
    body_listener: true
    format_listener:
        rules:
            - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true

# Nelmio CORS Configuration
nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
        max_age: 3600
        hosts: []
        origin_regex: false

my question: how can I make my page rendered as html ?

Body:
In your FOSRest configuration, you tell him to handle the response when the URL match ^/ which is every URLs.

If you want to use FOSRest formatting for everything but the main page, you can configure it as follow :

fos_rest:
    # ...
    format_listener:
            rules:
                - { path: '^/.+', priorities: ['json'], fallback_format: json, prefer_extension: false }
                - { path: '^/', stop: true }


问:
Need to change date variable with drop down menu selection dynamically in PHP
I have a php file (index.php) which has a titlebar, the titlebar holds date as (MM YYYY). The dates are pulled from another php file titled latest_update.php. The dates are listed in the latest_update file using the following syntax

```<code>$latest_run="April 2017";
$latest_run2="May 2017";
</code>```

The $latest_run date is stripped from the file and passed to a variable using the following.

```<code>include_once "scripts/latest_update.php";
$mainTitle = "Content Title";
$secondaryTitle = $latest_run;
$thirdTitle = $latest_run2;
</code>```

The title and date are held in a div using span

```<code>   <div class="titleBar">
   <span class="mainTitle"><?php echo $mainTitle ?></span></br>
   <span Class="secondaryTitle"><?php echo $secondaryTitle ?></span>
   </div>
</code>```

I have a selection menu and when I change the selection menu I want the option of the secondaryTitle to change. So if I select Run2 as the option I want the title to change to reflect May 2017 which corresponds to $thirdTitle. If I select Run1 I want it to change to the Secondarytitle referring to April 2017. The select menu is held within a form.

```<code> <form id="myForm">
 <select style="visibility:visible;position:relative;left:0px;top:1px;font-size:12px" name="selmenu" id="selmenu">
 <option value="Run1">Run1</option>
 <option value="Run2">Run2</option>
 <option value="Run3">Run3</option>
 </select>
 </form>
</code>```

I am new to php and have not been able to find a solution to complete this action. Any help would be appreciated.

答:
To change the content of the "secondaryTitle" you have to use javascript below:

```<code>function setTitle(select) {
        var value = select.options[select.selectedIndex].value;

        if (value == "Run2") {
            var secondTitle = document.getElementsByClassName('secondaryTitle')[0].innerHTML;
            document.getElementsByClassName('mainTitle')[0].innerHTML = secondTitle;
        }
    }
</code>```

and change the select tag to:

```<code><select style="visibility:visible;position:relative;left:0px;top:1px;font-size:12px" name="selmenu" id="selmenu" onchange="setTitle(this);">
    <option value="Run1">Run1</option>
    <option value="Run2">Run2</option>
    <option value="Run3">Run3</option>
</select>
</code>```

Body:
I have a php file (index.php) which has a titlebar, the titlebar holds date as (MM YYYY). The dates are pulled from another php file titled latest_update.php. The dates are listed in the latest_update file using the following syntax

$latest_run="April 2017";
$latest_run2="May 2017";

The $latest_run date is stripped from the file and passed to a variable using the following.

include_once "scripts/latest_update.php";
$mainTitle = "Content Title";
$secondaryTitle = $latest_run;
$thirdTitle = $latest_run2;

The title and date are held in a div using span

   <?php echo $mainTitle ?>

   <?php echo $secondaryTitle ?>

I have a selection menu and when I change the selection menu I want the option of the secondaryTitle to change. So if I select Run2 as the option I want the title to change to reflect May 2017 which corresponds to $thirdTitle. If I select Run1 I want it to change to the Secondarytitle referring to April 2017. The select menu is held within a form.

 <form id="myForm">
 <select style="visibility:visible;position:relative;left:0px;top:1px;font-size:12px" name="selmenu" id="selmenu">
 <option value="Run1">Run1</option>
 <option value="Run2">Run2</option>
 <option value="Run3">Run3</option>
 </select>
 </form>

I am new to php and have not been able to find a solution to complete this action. Any help would be appreciated.

Body:
To change the content of the "secondaryTitle" you have to use javascript below:

function setTitle(select) {
        var value = select.options[select.selectedIndex].value;

        if (value == "Run2") {
            var secondTitle = document.getElementsByClassName('secondaryTitle')[0].innerHTML;
            document.getElementsByClassName('mainTitle')[0].innerHTML = secondTitle;
        }
    }

and change the select tag to:

<select style="visibility:visible;position:relative;left:0px;top:1px;font-size:12px" name="selmenu" id="selmenu" onchange="setTitle(this);">
    <option value="Run1">Run1</option>
    <option value="Run2">Run2</option>
    <option value="Run3">Run3</option>
</select>


问:
Unit Test Custom MVC AuthorizationAttribute
This question is pretty much a duplicate of ASP.NET MVC unit testing custom AuthorizeAttribute - however I cannot get my code to run without hitting the same NullReferenceException

Something is clearly missing when I mock up my controller.

My attribute is simple - looks like this:

```<code>public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (!base.AuthorizeCore(filterContext.HttpContext))
    {
        filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
    }
    base.OnAuthorization(filterContext);
}
</code>```

My most recent attempt is below. I also tried the code from the question on that referenced link, including adding items to the context.

```<code> // Arrange
        Mock<IPrincipal> userMock = new Mock<IPrincipal>();
        Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>();
        responseMock.SetupGet(res => res.Cache).Returns(new Mock<HttpCachePolicyBase>().Object);

        Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(MockBehavior.Strict);
        contextMock.SetupGet(cm => cm.User).Returns(userMock.Object);
        contextMock.SetupGet(cm => cm.Response).Returns(responseMock.Object);
        contextMock.SetupGet(cm => cm.Items).Returns(new Mock<IDictionary>().Object);

        Mock<ControllerContext> controllerContextMock = new Mock<ControllerContext>();
        controllerContextMock.SetupGet(ctx => ctx.HttpContext).Returns(contextMock.Object);

        Mock<ActionDescriptor> actionDesMock = new Mock<ActionDescriptor>();
        actionDesMock.Setup(action => action.GetCustomAttributes(typeof(AllowAnonymousAttribute), true)).Returns(new object[0]);

        // Act
        CustomAuthorizationAttribute cusAtr = new CustomAuthorizationAttribute() { Roles = "TestRole" };

        // Assert
        cusAtr.OnAuthorization(new AuthorizationContext(controllerContextMock.Object, actionDesMock.Object));
</code>```

I've also checked out the source code for AuthorizeCore.

When ran, the test fails on base.AuthorizeCore(filterContext.HttpContext) with a NullReferenceException

Can't figure what's missing.

any idea?

For the sake of ease, code from the other question, adjusted to suit our models is:

```<code>    // Arrange
    var httpContext = new Mock<HttpContextBase>();
    Dictionary<object, object> dictionary = new Dictionary<object, object>();
    httpContext.SetupGet(cm => cm.Items).Returns(dictionary);
    Mock<IPrincipal> userMock = new Mock<IPrincipal>();
    httpContext.SetupGet(c => c.User).Returns(() => userMock.Object);
    var requestBase = new Mock<HttpRequestBase>();
    var headers = new NameValueCollection
    {
       {"Special-Header-Name", "false"}
    };
    requestBase.Setup(x => x.Headers).Returns(headers);
    requestBase.Setup(x => x.HttpMethod).Returns("GET");
    requestBase.Setup(x => x.Url).Returns(new Uri("http://localhost/"));
    requestBase.Setup(x => x.RawUrl).Returns("~/Maintenance/UnExistingMaster");
    requestBase.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(() => "~/Maintenance/UnExistingMaster");
    requestBase.Setup(x => x.IsAuthenticated).Returns(() => true);
    httpContext.Setup(x => x.Request).Returns(requestBase.Object);
    var controller = new Mock<ControllerBase>();
    var actionDescriptor = new Mock<ActionDescriptor>();
    var controllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller.Object);

    CustomAuthorizationAttribute cusAtr = new CustomAuthorizationAttribute() { Roles = "TestRole" };

    // Act
    cusAtr.OnAuthorization(new AuthorizationContext(controllerContext, actionDescriptor.Object));
</code>```

答:
You referenced the source code. Have you taken a look at what it needs and what you have setup? You set a principal mock. great. but the identity is not set. in checking user is calls

```<code>if (!user.Identity.IsAuthenticated) //<-- Identity would be null.
</code>```

Which will null out because an Identity was not arranged.

Just create a generic principal and use that. All the necessary dependencies would be initialized for you.

```<code>//...

IPrincipal principal = new GenericPrincipal(new GenericIdentity("TestName"), new[] { "TestRole" });

httpContext.SetupGet(c => c.User).Returns(() => principal);

//...
</code>```

This will get you past your initial hurdle. You may still have to review your arrangement for any other dependencies that were not arranged properly.

Body:
This question is pretty much a duplicate of ASP.NET MVC unit testing custom AuthorizeAttribute - however I cannot get my code to run without hitting the same NullReferenceException

Something is clearly missing when I mock up my controller.

My attribute is simple - looks like this:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (!base.AuthorizeCore(filterContext.HttpContext))
    {
        filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
    }
    base.OnAuthorization(filterContext);
}

My most recent attempt is below. I also tried the code from the question on that referenced link, including adding items to the context.

 // Arrange
        Mock<IPrincipal> userMock = new Mock<IPrincipal>();
        Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>();
        responseMock.SetupGet(res => res.Cache).Returns(new Mock<HttpCachePolicyBase>().Object);

        Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(MockBehavior.Strict);
        contextMock.SetupGet(cm => cm.User).Returns(userMock.Object);
        contextMock.SetupGet(cm => cm.Response).Returns(responseMock.Object);
        contextMock.SetupGet(cm => cm.Items).Returns(new Mock<IDictionary>().Object);

        Mock<ControllerContext> controllerContextMock = new Mock<ControllerContext>();
        controllerContextMock.SetupGet(ctx => ctx.HttpContext).Returns(contextMock.Object);

        Mock<ActionDescriptor> actionDesMock = new Mock<ActionDescriptor>();
        actionDesMock.Setup(action => action.GetCustomAttributes(typeof(AllowAnonymousAttribute), true)).Returns(new object[0]);

        // Act
        CustomAuthorizationAttribute cusAtr = new CustomAuthorizationAttribute() { Roles = "TestRole" };

        // Assert
        cusAtr.OnAuthorization(new AuthorizationContext(controllerContextMock.Object, actionDesMock.Object));

I've also checked out the source code for AuthorizeCore.

When ran, the test fails on base.AuthorizeCore(filterContext.HttpContext) with a NullReferenceException

Can't figure what's missing.

any idea?

For the sake of ease, code from the other question, adjusted to suit our models is:

    // Arrange
    var httpContext = new Mock<HttpContextBase>();
    Dictionary<object, object> dictionary = new Dictionary<object, object>();
    httpContext.SetupGet(cm => cm.Items).Returns(dictionary);
    Mock<IPrincipal> userMock = new Mock<IPrincipal>();
    httpContext.SetupGet(c => c.User).Returns(() => userMock.Object);
    var requestBase = new Mock<HttpRequestBase>();
    var headers = new NameValueCollection
    {
       {"Special-Header-Name", "false"}
    };
    requestBase.Setup(x => x.Headers).Returns(headers);
    requestBase.Setup(x => x.HttpMethod).Returns("GET");
    requestBase.Setup(x => x.Url).Returns(new Uri("http://localhost/"));
    requestBase.Setup(x => x.RawUrl).Returns("~/Maintenance/UnExistingMaster");
    requestBase.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(() => "~/Maintenance/UnExistingMaster");
    requestBase.Setup(x => x.IsAuthenticated).Returns(() => true);
    httpContext.Setup(x => x.Request).Returns(requestBase.Object);
    var controller = new Mock<ControllerBase>();
    var actionDescriptor = new Mock<ActionDescriptor>();
    var controllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller.Object);

    CustomAuthorizationAttribute cusAtr = new CustomAuthorizationAttribute() { Roles = "TestRole" };

    // Act
    cusAtr.OnAuthorization(new AuthorizationContext(controllerContext, actionDescriptor.Object));

Body:
You referenced the source code. Have you taken a look at what it needs and what you have setup? You set a principal mock. great. but the identity is not set. in checking user is calls

if (!user.Identity.IsAuthenticated) //<-- Identity would be null.

Which will null out because an Identity was not arranged.

Just create a generic principal and use that. All the necessary dependencies would be initialized for you.

//...

IPrincipal principal = new GenericPrincipal(new GenericIdentity("TestName"), new[] { "TestRole" });

httpContext.SetupGet(c => c.User).Returns(() => principal);

//...

This will get you past your initial hurdle. You may still have to review your arrangement for any other dependencies that were not arranged properly.


问:
Print Raw Bytes Using Variable
In the python 2 command line by running:

```<code>>>> print r"\x72"
\x72
</code>```

python will return: \x72
But if I do:

```<code>>>> a = "\x72"
>>> print a
r
</code>```

it will print "r". I am also aware that if I do:

```<code>>>> a = r"\x72"
>>> print a
\x72
</code>```

But what I want to be able to do is to take:

```<code>>>> a = "\x72"
</code>```

and make it so I can print it as if it were:

```<code>r"\x73"
</code>```

How do I convert that?

答:
This might be a duplicate of python : how to convert string literal to raw string literal?

I think what you want is to escape your escape sequence from being interpreted.

```<code>a = '\\x72'
</code>```

In order to have it print the full \x72

Title: Print Raw Bytes Using Variable

Body:
In the python 2 command line by running:

>>> print r"\x72"
\x72

python will return: \x72
But if I do:

>>> a = "\x72"
>>> print a
r

it will print "r". I am also aware that if I do:

>>> a = r"\x72"
>>> print a
\x72

But what I want to be able to do is to take:

>>> a = "\x72"

and make it so I can print it as if it were:

r"\x73"

How do I convert that?

Body:
This might be a duplicate of python : how to convert string literal to raw string literal?

I think what you want is to escape your escape sequence from being interpreted.

a = '\\x72'

In order to have it print the full \x72


问:
Not able to launch URL from ionic2 Cordova InAppBrowser Plugin
I am using InAppBrowser Plugin for launching a link from my application.But when i do click then it goes to localhost:/URL/..

What am i doing wrong?

INTERNET:
{{navigateUrl}}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> launch(url)
  {
    this.platform.ready().then(()=>{
      cordova.InAppBrowser.open(url,"_system","location=true");
    });
  }</code>```

答:
I was able to resolve the issue..

i used the following code

 launch()
  {
    this.platform.ready().then(()=>{
      // cordova.InAppBrowser.open(url,"_system","location=true");
      let browser=new InAppBrowser(this.navigateUrl,'_blank');
    });
  }```

It will open up a new tab in chrome as well...

Body:
I am using InAppBrowser Plugin for launching a link from my application.But when i do click then it goes to localhost:/URL/..

What am i doing wrong?

INTERNET:
{{navigateUrl}}

 launch(url)
  {
    this.platform.ready().then(()=>{
      cordova.InAppBrowser.open(url,"_system","location=true");
    });
  }

Body:
I was able to resolve the issue..

i used the following code

 launch()
  {
    this.platform.ready().then(()=>{
      // cordova.InAppBrowser.open(url,"_system","location=true");
      let browser=new InAppBrowser(this.navigateUrl,'_blank');
    });
  }

It will open up a new tab in chrome as well...


问:
Check if a value is within a range of numbers
I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.

The range is 0.001-0.009. I know how to use multiple if to check this, but I want to know if there is any way to check it in a single if statement.

答:
I like Pointy's between function so I wrote a similar one that worked well for my scenario.

```<code>/**
 * Checks if an integer is within ±x another integer.
 * @param {int} op - The integer in question
 * @param {int} target - The integer to compare to
 * @param {int} range - the range ±
 */
function nearInt(op, target, range) {
    return op < target + range && op > target - range;
}
</code>```

so if you wanted to see if x was within ±10 of y:

```<code>var x = 100;
var y = 115;
nearInt(x,y,10) = false
</code>```

I'm using it for detecting a long-press on mobile:

```<code>//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
</code>```

Body:
I like Pointy's between function so I wrote a similar one that worked well for my scenario.

/**
 * Checks if an integer is within ±x another integer.
 * @param {int} op - The integer in question
 * @param {int} target - The integer to compare to
 * @param {int} range - the range ±
 */
function nearInt(op, target, range) {
    return op < target + range && op > target - range;
}

so if you wanted to see if x was within ±10 of y:

var x = 100;
var y = 115;
nearInt(x,y,10) = false

I'm using it for detecting a long-press on mobile:

//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);


问:
Convert.DateTime
What Convert.DateTime will convert the date 7/25/2010 12:00:00 it's current format is(MM/dd/yyyy HH:mm:ss)?

When I convert this string format to date time I am getting the error "string was not recognized as valid DateTime"

答:
None. Dates are not stored internally as a certain format.

If you want to parse a string into a date, use DateTime.ParseExact or DateTime.TryParseExact (the former will throw an exception if the conversion fails, the second uses an out parameter):

```<code>DateTime myDate = DateTime.ParseExact("7/25/2010 12:00:00",
                                      "MM/dd/yyyy HH:mm:ss",
                                      CultureInfo.InvariantCulture);
</code>```

If you want to display a certain format, use ToString with the format string.

So, if you have a date object that represents midday of the 25th of July 2010 (doesn't matter how it is represented internally) and you want to format it with the format string "MM/dd/yyyy HH:mm:ss" you do the following:

```<code>string formattedDate = myDate.ToString("MM/dd/yyyy HH:mm:ss");
</code>```

Title: Convert.DateTime

Body:
None. Dates are not stored internally as a certain format.

If you want to parse a string into a date, use DateTime.ParseExact or DateTime.TryParseExact (the former will throw an exception if the conversion fails, the second uses an out parameter):

DateTime myDate = DateTime.ParseExact("7/25/2010 12:00:00",
                                      "MM/dd/yyyy HH:mm:ss",
                                      CultureInfo.InvariantCulture);

If you want to display a certain format, use ToString with the format string.

So, if you have a date object that represents midday of the 25th of July 2010 (doesn't matter how it is represented internally) and you want to format it with the format string "MM/dd/yyyy HH:mm:ss" you do the following:

string formattedDate = myDate.ToString("MM/dd/yyyy HH:mm:ss");


问:
Migrate hibernate 3 to hibernate 5. alternate way of getHibernateTemplate() and HibernateCallback
The following code is developed by hibernate 3. i want to migrate this to hibernate 5. getHibernateTemplate() and HibernateCallback is show error how to fix this error.</p>

```<code>public List<Employee> getAllSalaryPersons () {
    List<Employee> empSalList= super.getHibernateTemplate().execute(new HibernateCallback<List<Employee>>(){
        public List<Employee> doInHibernate(Session session) throws HibernateException  {

            Criteria criteria  = session.createCriteria(Salary.class, "sclass")
                    .createAlias("salary", "salary")
                    .add(Restrictions.le("sclass.salary", 25000))
                    .add(Restrictions.gt("sclass.salary", 99000))
                    .setProjection(
                            Projections.projectionList().addOrder( Order.asc("sclass.experiance") );

            criteria.setResultTransformer( new AliasToBeanResultTransformer(Employee.class));

            return criteria.list();
        }
    });
    return empSalList;
}
</code>```

答:
I would avoid HibernateTemplate entirely (whose package name changes with each major Hibernate version) and instead use SessionFactory.

That way, you won't have to change the code again when you eventually upgrade to Hibernate 6 or 7...

```<code>@Autowired
private SessionFactory sessionFactory;

public List<Employee> getAllSalaryPersons () {
    Criteria criteria  = sessionFactory.getCurrentSession().createCriteria(Salary.class, "sclass")
            .createAlias("salary", "salary")
            .add(Restrictions.le("sclass.salary", 25000))
            .add(Restrictions.gt("sclass.salary", 99000))
            .setProjection(Projections.projectionList())
            .addOrder(Order.asc("sclass.experiance")) ;
    criteria.setResultTransformer( new AliasToBeanResultTransformer(Employee.class));
    return criteria.list();
}
</code>```

Body:
The following code is developed by hibernate 3. i want to migrate this to hibernate 5. getHibernateTemplate() and HibernateCallback is show error how to fix this error.

public List<Employee> getAllSalaryPersons () {
    List<Employee> empSalList= super.getHibernateTemplate().execute(new HibernateCallback<List<Employee>>(){
        public List<Employee> doInHibernate(Session session) throws HibernateException  {

            Criteria criteria  = session.createCriteria(Salary.class, "sclass")
                    .createAlias("salary", "salary")
                    .add(Restrictions.le("sclass.salary", 25000))
                    .add(Restrictions.gt("sclass.salary", 99000))
                    .setProjection(
                            Projections.projectionList().addOrder( Order.asc("sclass.experiance") );

            criteria.setResultTransformer( new AliasToBeanResultTransformer(Employee.class));

            return criteria.list();
        }
    });
    return empSalList;
}

Body:
I would avoid HibernateTemplate entirely (whose package name changes with each major Hibernate version) and instead use SessionFactory.

That way, you won't have to change the code again when you eventually upgrade to Hibernate 6 or 7...

@Autowired
private SessionFactory sessionFactory;

public List<Employee> getAllSalaryPersons () {
    Criteria criteria  = sessionFactory.getCurrentSession().createCriteria(Salary.class, "sclass")
            .createAlias("salary", "salary")
            .add(Restrictions.le("sclass.salary", 25000))
            .add(Restrictions.gt("sclass.salary", 99000))
            .setProjection(Projections.projectionList())
            .addOrder(Order.asc("sclass.experiance")) ;
    criteria.setResultTransformer( new AliasToBeanResultTransformer(Employee.class));
    return criteria.list();
}


问:
Combine multiple XML files with PHP and wrap in new root element
I'm trying to combine multiple XML files that have the same structure into one file.

This is the structure of my XML files:

file1.xml:

```<code><root information="file1">
 <items>
  <item>FOO</item>
  <item>BAR</item>
 </items>
</root>
</code>```

file2.xml:

```<code><root information="file2">
 <items>
  <item>BAR</item>
  <item>FOO</item>
 </items>
</root>
</code>```

Using this code I've been able to combine them:

```<code>$files= array(
  'file1.xml',
  'file2.xml'
);

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));

foreach ($files as $filename) {
  $addDom = new DOMDocument();

  $addDom->load($filename);
  if ($addDom->documentElement) {
    foreach ($addDom->documentElement->childNodes as $node) {
      $dom->documentElement->appendChild(
        $dom->importNode($node, TRUE)
      );

    }

  }
}

$dom->save('output.xml');
</code>```

This works partly but removes the original root element which has the information attribute that I still need. So I would like to keep all the existing root elements but wrap them in a new root  element. This is what I would like to end up with:

```<code><files>
 <root information="file1">
  <items>
   <item>FOO</item>
   <item>BAR</item>
  </items>
 </root>
 <root information="file2">
  <items>
   <item>BAR</item>
   <item>FOO</item>
  </items>
 </root>
</files>
</code>```

But I can't figure out how to append the file. Whatever I try it only ends up at the bottom of the output file instead of appending all old root elements. I'm guessing this is simple as hell but I just can't figure it out. Help much appreciated!

答:
Consider XSLT the special-purpose language designed to transform XML files. XSLT maintains the document() function to parse from external files at paths relative to script. PHP can run XSLT 1.0 scripts with its php-xsl class. Be sure to enable this extension in .ini file.

Should your files be very numerous such as hundreds, consider building the XSLT script on the fly in PHP loop. As information, XSLT is a well-formed XML file, so can be parsed from file or string.

XSLT (save as .xsl file in same directory as all XML files)

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <files>
            <xsl:copy-of select="root"/>
            <xsl:copy-of select="document('file2.xml')/root"/>
            <xsl:copy-of select="document('file3.xml')/root"/>
            <xsl:copy-of select="document('file4.xml')/root"/>
            <!-- add more as needed -->
        </files>
    </xsl:template>

</xsl:stylesheet>
</code>```

PHP (load first XML and XSL scripts, then transform/output)

```<code>// LOAD XML SOURCE
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->load('file1.xml');                  // ONLY LOAD FIRST XML

// LOAD XSL SOURCE
$xsl = new DOMDocument('1.0', 'UTF-8');
$xsl->load('XSLT_Script.xsl');

// TRANSFORM XML
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
$newXML = $proc->transformToXML($xml);

// SAVE NEW XML
file_put_contents('Output.xml', $newXML);
</code>```

Body:
I'm trying to combine multiple XML files that have the same structure into one file.

This is the structure of my XML files:

file1.xml:

<root information="file1">
 <items>
  <item>FOO</item>
  <item>BAR</item>
 </items>
</root>

file2.xml:

<root information="file2">
 <items>
  <item>BAR</item>
  <item>FOO</item>
 </items>
</root>

Using this code I've been able to combine them:

$files= array(
  'file1.xml',
  'file2.xml'
);

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));

foreach ($files as $filename) {
  $addDom = new DOMDocument();

  $addDom->load($filename);
  if ($addDom->documentElement) {
    foreach ($addDom->documentElement->childNodes as $node) {
      $dom->documentElement->appendChild(
        $dom->importNode($node, TRUE)
      );

    }

  }
}

$dom->save('output.xml');

This works partly but removes the original root element which has the information attribute that I still need. So I would like to keep all the existing root elements but wrap them in a new root  element. This is what I would like to end up with:

<files>
 <root information="file1">
  <items>
   <item>FOO</item>
   <item>BAR</item>
  </items>
 </root>
 <root information="file2">
  <items>
   <item>BAR</item>
   <item>FOO</item>
  </items>
 </root>
</files>

But I can't figure out how to append the file. Whatever I try it only ends up at the bottom of the output file instead of appending all old root elements. I'm guessing this is simple as hell but I just can't figure it out. Help much appreciated!

Body:
Consider XSLT the special-purpose language designed to transform XML files. XSLT maintains the document() function to parse from external files at paths relative to script. PHP can run XSLT 1.0 scripts with its php-xsl class. Be sure to enable this extension in .ini file.

Should your files be very numerous such as hundreds, consider building the XSLT script on the fly in PHP loop. As information, XSLT is a well-formed XML file, so can be parsed from file or string.

XSLT (save as .xsl file in same directory as all XML files)

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <files>
            <xsl:copy-of select="root"/>
            <xsl:copy-of select="document('file2.xml')/root"/>
            <xsl:copy-of select="document('file3.xml')/root"/>
            <xsl:copy-of select="document('file4.xml')/root"/>
            <!-- add more as needed -->
        </files>
    </xsl:template>

</xsl:stylesheet>

PHP (load first XML and XSL scripts, then transform/output)

// LOAD XML SOURCE
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->load('file1.xml');                  // ONLY LOAD FIRST XML

// LOAD XSL SOURCE
$xsl = new DOMDocument('1.0', 'UTF-8');
$xsl->load('XSLT_Script.xsl');

// TRANSFORM XML
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
$newXML = $proc->transformToXML($xml);

// SAVE NEW XML
file_put_contents('Output.xml', $newXML);