问:
Display Timer on Screen in Assembly MASM 8086
I have to display the time passing on the screen, i've been looking online and found how to set up a time delay but i don't know how to display it on the screen
Here's what i got right now(I dont even know if this is the way to do it)</p>

```<code> delay proc

    mov ah, 00
    int 1Ah
    mov bx, dx
 jmp_delay:
    int 1Ah
    sub dx, bx
    cmp dl, delaytime
    jl jmp_delay
    ret
 delay endp
</code>```

答:
Time is a number and and you will need to convert it to string in order to display it. There are many procedures to do that, next I post one (procedure "dollars" is secondary but necessary) :

```<code>;------------------------------------------
;CONVERT A NUMBER IN STRING.
;ALGORITHM : EXTRACT DIGITS ONE BY ONE, STORE
;THEM IN STACK, THEN EXTRACT THEM IN REVERSE
;ORDER TO CONSTRUCT STRING (STR).
;PARAMETERS : AX = NUMBER TO CONVERT.
;             SI = POINTING WHERE TO STORE STRING.

proc number2string
;FILL BUF WITH DOLLARS.
  push si
  call dollars
  pop  si

  mov  bx, 10 ;DIGITS ARE EXTRACTED DIVIDING BY 10.
  mov  cx, 0 ;COUNTER FOR EXTRACTED DIGITS.
cycle1:
  mov  dx, 0 ;NECESSARY TO DIVIDE BY BX.
  div  bx ;DX:AX / 10 = AX:QUOTIENT DX:REMAINDER.
  push dx ;PRESERVE DIGIT EXTRACTED FOR LATER.
  inc  cx ;INCREASE COUNTER FOR EVERY DIGIT EXTRACTED.
  cmp  ax, 0  ;IF NUMBER IS
  jne  cycle1 ;NOT ZERO, LOOP.
;NOW RETRIEVE PUSHED DIGITS.
cycle2:
  pop  dx
  add  dl, 48 ;CONVERT DIGIT TO CHARACTER.
  mov  [ si ], dl
  inc  si
  loop cycle2

  ret
endp

;------------------------------------------
;FILLS VARIABLE WITH '$'.
;USED BEFORE CONVERT NUMBERS TO STRING, BECAUSE
;THE STRING WILL BE DISPLAYED.
;PARAMETER : SI = POINTING TO STRING TO FILL.

proc dollars
  mov  cx, 6
six_dollars:
  mov  bl, '$'
  mov  [ si ], bl
  inc  si
  loop six_dollars

  ret
endp
</code>```

With previous procedures you can display the time, next example shows how to use them, it also displays only seconds (I'm sure you will be able to display minutes and hours by yourself), notice there are two important variables that you will have to create in data segment :

```<code>seconds db ?         ;◄■■ IMPORTANT VARIABLES IN DATA SEGMENT.
buf     db 6 dup (?)

display_time:
;▼ GET SYSTEM TIME.
  mov  ah, 2ch
  int  21h       ;◄■■ SECONDS RETURN IN DH.
;▼ TIMER (1 SECOND).
  cmp  dh, seconds
  je   display_time  ;◄■■ REPEAT UNTIL 1 SECOND PASSED.
  mov  seconds, dh
;▼ CONVERT SECONDS TO STRING.
  xor  ax, ax  ;◄■■ NUMBER TO CONVERT TO STRING.
  mov  al, dh  ;◄■■ SECONDS IN AX.
  lea  si, buf  ;◄■■ VARIABLE WHERE STRING WILL BE STORED.
  call number2string  ;◄■■ CALL PROCEDURE THAT CONVERTS NUMBER TO STRING.
;▼ MOVE CURSOR TO 0,0.
  mov  dl, 0  ;◄■■ X.
  mov  dh, 0  ;◄■■ Y.
  mov  ah, 2
  mov  bh, 0
  int  10h
;▼ DISPLAY STRING.
  mov  ah, 9
  lea  dx, buf
  int  21h
  jmp  display_time
</code>```

Body:
I have to display the time passing on the screen, i've been looking online and found how to set up a time delay but i don't know how to display it on the screen
Here's what i got right now(I dont even know if this is the way to do it)

 delay proc

    mov ah, 00
    int 1Ah
    mov bx, dx
 jmp_delay:
    int 1Ah
    sub dx, bx
    cmp dl, delaytime
    jl jmp_delay
    ret
 delay endp

Body:
Time is a number and and you will need to convert it to string in order to display it. There are many procedures to do that, next I post one (procedure "dollars" is secondary but necessary) :

;------------------------------------------
;CONVERT A NUMBER IN STRING.
;ALGORITHM : EXTRACT DIGITS ONE BY ONE, STORE
;THEM IN STACK, THEN EXTRACT THEM IN REVERSE
;ORDER TO CONSTRUCT STRING (STR).
;PARAMETERS : AX = NUMBER TO CONVERT.
;             SI = POINTING WHERE TO STORE STRING.

proc number2string
;FILL BUF WITH DOLLARS.
  push si
  call dollars
  pop  si

  mov  bx, 10 ;DIGITS ARE EXTRACTED DIVIDING BY 10.
  mov  cx, 0 ;COUNTER FOR EXTRACTED DIGITS.
cycle1:
  mov  dx, 0 ;NECESSARY TO DIVIDE BY BX.
  div  bx ;DX:AX / 10 = AX:QUOTIENT DX:REMAINDER.
  push dx ;PRESERVE DIGIT EXTRACTED FOR LATER.
  inc  cx ;INCREASE COUNTER FOR EVERY DIGIT EXTRACTED.
  cmp  ax, 0  ;IF NUMBER IS
  jne  cycle1 ;NOT ZERO, LOOP.
;NOW RETRIEVE PUSHED DIGITS.
cycle2:
  pop  dx
  add  dl, 48 ;CONVERT DIGIT TO CHARACTER.
  mov  [ si ], dl
  inc  si
  loop cycle2

  ret
endp

;------------------------------------------
;FILLS VARIABLE WITH '$'.
;USED BEFORE CONVERT NUMBERS TO STRING, BECAUSE
;THE STRING WILL BE DISPLAYED.
;PARAMETER : SI = POINTING TO STRING TO FILL.

proc dollars
  mov  cx, 6
six_dollars:
  mov  bl, '$'
  mov  [ si ], bl
  inc  si
  loop six_dollars

  ret
endp

With previous procedures you can display the time, next example shows how to use them, it also displays only seconds (I'm sure you will be able to display minutes and hours by yourself), notice there are two important variables that you will have to create in data segment :

seconds db ?         ;◄■■ IMPORTANT VARIABLES IN DATA SEGMENT.
buf     db 6 dup (?)

display_time:
;▼ GET SYSTEM TIME.
  mov  ah, 2ch
  int  21h       ;◄■■ SECONDS RETURN IN DH.
;▼ TIMER (1 SECOND).
  cmp  dh, seconds
  je   display_time  ;◄■■ REPEAT UNTIL 1 SECOND PASSED.
  mov  seconds, dh
;▼ CONVERT SECONDS TO STRING.
  xor  ax, ax  ;◄■■ NUMBER TO CONVERT TO STRING.
  mov  al, dh  ;◄■■ SECONDS IN AX.
  lea  si, buf  ;◄■■ VARIABLE WHERE STRING WILL BE STORED.
  call number2string  ;◄■■ CALL PROCEDURE THAT CONVERTS NUMBER TO STRING.
;▼ MOVE CURSOR TO 0,0.
  mov  dl, 0  ;◄■■ X.
  mov  dh, 0  ;◄■■ Y.
  mov  ah, 2
  mov  bh, 0
  int  10h
;▼ DISPLAY STRING.
  mov  ah, 9
  lea  dx, buf
  int  21h
  jmp  display_time


来源: stackexchange

问:
captcha or not?
i hate captcha, do you think there is a better solution </p>

答:
there is a nice trick which you can use by setting an empty input displayed none to the user but visible to the bot.

and if that input filed !=="" empty, return false for the form.

there is more here http://klauskjeldsen.dk/avoid-html-form-spam-using-css/

ContentLicense: CC BY-SA 2.5

Title: captcha or not?


问:
Cannot install pip on Python 2.7
I'm a new Python user. I'm having issues installing new modules for python 2.7. When I try installing a new module from PyCharm, I get the following error

Error: Python packaging tool 'pip' not found

Moreover, I'm a bit confuse about which Python version I'm actually using...

This is what I get when I type the following commands in the terminal.

```<code>$ which python
/usr/bin/python
$ echo $PYTHONPATH
PYTHONPATH:/usr/local/lib/python3/dist-packages/
$ python -V
Python 2.7.6
</code>```

Everything seems a bit messed up to me...all the procedures I follow to install pip result in failure. The command

```<code>$ python get-pip.py
</code>```

returns

You are using pip version 7.1.0, however version 9.0.1 is available.
      You should consider upgrading via the 'pip install --upgrade pip' command

However, when I run that command, it tells me that there is no module named pip.
Please, how can I fix it? I need to work with Python 2.7 but I'm completely unable to install packages. Thanks.

EDIT I am using Ubuntu 14.04 LTS

答:
You may be trying to install pip wrong. Depending on your version of linux there are several install methods that can be found here

for your version judging by your use of get.

try this one:

```<code>sudo apt-get install python-pip
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cannot install pip on Python 2.7

Body:
I'm a new Python user. I'm having issues installing new modules for python 2.7. When I try installing a new module from PyCharm, I get the following error

Error: Python packaging tool 'pip' not found

Moreover, I'm a bit confuse about which Python version I'm actually using...

This is what I get when I type the following commands in the terminal.

$ which python
/usr/bin/python
$ echo $PYTHONPATH
PYTHONPATH:/usr/local/lib/python3/dist-packages/
$ python -V
Python 2.7.6

Everything seems a bit messed up to me...all the procedures I follow to install pip result in failure. The command

$ python get-pip.py

returns

You are using pip version 7.1.0, however version 9.0.1 is available.
      You should consider upgrading via the 'pip install --upgrade pip' command

However, when I run that command, it tells me that there is no module named pip.
Please, how can I fix it? I need to work with Python 2.7 but I'm completely unable to install packages. Thanks.

EDIT I am using Ubuntu 14.04 LTS

Body:
You may be trying to install pip wrong. Depending on your version of linux there are several install methods that can be found here

for your version judging by your use of get.

try this one:

sudo apt-get install python-pip


问:
Getting TokenMismatchException in VerifyCsrfToken.php line 53 in Laravel 5.1 while using csrf token
I am getting TokenMismatchException in VerifyCsrfToken.php line 53:
I am using {!!Form::open()!!}
{!!Form::close!!}. When I click the add Button in my form with empty field for the first time, it shows me error as I set the validation rule. But when I click the Add button again without refreshing the page, it shows me the TokenMismatchException error. I have checked with dd() and it shows me the token like this:

```<code> array:3 [▼
 "_token" => "5dXwRHbz4GNY1tx9OVeWPcOkirVIm0YtpkZufFbr"
 "menu_name" => ""
 "menu_price" => ""
</code>```

Here is my form code:

```<code>{!! Form::open(array('route' =>'upcoming.store', 'method'=>'POST')) !!}
                    <div class="col-lg-6 col-sm-offset-3 top-spacing">
                        <input type="text" name="menu_name" placeholder="Menu Name.." class="form-control">
                    </div>
                    <div class="col-lg-6 col-sm-offset-3 top-spacing">
                        <input type="text" name="menu_price" placeholder="Menu Price.." class="form-control">
                    </div>

                    <div class="col-sm-2 col-sm-offset-8 top-spacing">
                        <button class="btn btn-success">
                            Add +
                        </button>
                    </div>

                </div>
                {!! Form::close() !!}
</code>```

Here is my controller store function:

```<code>public function store(Request $request)
{
    dd($request->all());
    $this->validate($request, array(
        'menu_name'=>'required',
        'menu_price'=>'required',
        ));
    $upcoming = new Upcomingfood;
    $upcoming->menu_name=$request->menu_name;
    $upcoming->menu_price=$request->menu_price;
    $upcoming->save();
    Session::flash('success','Food Menu Added Successfullly');
    return redirect()->back();
}
</code>```

Can anyone help?

答:
I have solved this problem by going to

```<code>`VerifyCsrfToken.php`
</code>```

and then I have changed

throw new TokenMismatchException;
 by
else{
            return redirect()->back();
        }

But I am not sure am I right or wrong to apply this way. will it bring any problem in my future work in this project. anyone please make me sure. please.

Body:
I am getting TokenMismatchException in VerifyCsrfToken.php line 53:
I am using {!!Form::open()!!}
{!!Form::close!!}. When I click the add Button in my form with empty field for the first time, it shows me error as I set the validation rule. But when I click the Add button again without refreshing the page, it shows me the TokenMismatchException error. I have checked with dd() and it shows me the token like this:

 array:3 [▼
 "_token" => "5dXwRHbz4GNY1tx9OVeWPcOkirVIm0YtpkZufFbr"
 "menu_name" => ""
 "menu_price" => ""

Here is my form code:

{!! Form::open(array('route' =>'upcoming.store', 'method'=>'POST')) !!}

                        <input type="text" name="menu_name" placeholder="Menu Name.." class="form-control">

                        <input type="text" name="menu_price" placeholder="Menu Price.." class="form-control">

                        <button class="btn btn-success">
                            Add +
                        </button>

                {!! Form::close() !!}

Here is my controller store function:

public function store(Request $request)
{
    dd($request->all());
    $this->validate($request, array(
        'menu_name'=>'required',
        'menu_price'=>'required',
        ));
    $upcoming = new Upcomingfood;
    $upcoming->menu_name=$request->menu_name;
    $upcoming->menu_price=$request->menu_price;
    $upcoming->save();
    Session::flash('success','Food Menu Added Successfullly');
    return redirect()->back();
}

Can anyone help?

Body:
I have solved this problem by going to

`VerifyCsrfToken.php`

and then I have changed

throw new TokenMismatchException;
 by
else{
            return redirect()->back();
        }

But I am not sure am I right or wrong to apply this way. will it bring any problem in my future work in this project. anyone please make me sure. please.


问:
How can I find the specific interval (via list) within which a given value occurs, in order to return the corresponding value from a second list?
I am writing a python code to act as a gradebook. I have calculated the total number of points earned by each student and am now stuck on the last step of my code - assigning a letter grade to a student. The structure of my code is to define functions that evaluate a single student's performance, so that one "master function" can repeatedly call the functions by an index number corresponding to each student. As such, I was able to produce a working code that I am trying to condense and simplify. I've checked out similar questions in posts like these, but I haven't been able to adapt these approaches to my problem (I think because my for-loop screws up the indexing).

Working code:

```<code>import numpy as np

failing_score = 100
perfect_score = 200
letter_grades = ['A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']
grade_borders = np.linspace(perfect_score, failing_score, len(letter_grades))

print(grade_borders)
>> [ 200.          190.90909091  181.81818182  172.72727273  163.63636364
  154.54545455  145.45454545  136.36363636  127.27272727  118.18181818
  109.09090909  100.        ]

def get_letter_grade(student_grade, grade_borders=grade_borders):
    """
    perfect score = 200, failing score ≤ 100

    190.9 - 200:    A
    181.8 - 190.9:  A-
    172.7 - 181.8:  B+
    etc
    """
    if student_grade >= grade_borders[1]:
        letter = 'A'
    elif grade_borders[2] <= student_grade < grade_borders[1]:
        letter = 'A-'
    elif grade_borders[3] <= student_grade < grade_borders[2]:
        letter = 'B+'
    elif grade_borders[4] <= student_grade < grade_borders[3]:
        letter = 'B'
    elif grade_borders[5] <= student_grade < grade_borders[4]:
        letter = 'B-'
    elif grade_borders[6] <= student_grade < grade_borders[5]:
        letter = 'C+'
    elif grade_borders[7] <= student_grade < grade_borders[6]:
        letter = 'C'
    elif grade_borders[8] <= student_grade < grade_borders[7]:
        letter = 'C-'
    elif grade_borders[9] <= student_grade < grade_borders[8]:
        letter = 'D+'
    elif grade_borders[10] <= student_grade < grade_borders[9]:
        letter = 'D'
    elif grade_borders[11] <= student_grade < grade_borders[10]:
        letter = 'D-'
    elif student_grade < grade_borders[11]:
        letter = 'F'
    return letter

print(get_letter_grade(182))
>> A-
</code>```

I don't like having to specify each index and each letter grade using so many if/elif loops. So I tried to modify my approach by using a for-loop; the values at the boundaries (A and F) are handled separately while the grades in-between can be handled by the same code as functions of index.

Unsuccessful attempt:

```<code>def assign_letter_grade(student_score, grade_borders=grade_borders, letter_grades=letter_grades):
    """
    This is my unsuccessful attempt at replicating the function above.
    """
    res = 0 # not including this line ==> UnboundLocalError: local variable 'res' referenced before assignment
    for idx in range(len(grade_borders)):
        if idx == 0:
            if student_score >= grade_borders[1]:
                res = letter_grades[idx]
                print("--", res)
        elif idx > 0 and idx < len(letter_grades)-1:
            if (student_score >= grade_borders[idx+1]) and (student_score < grade_borders[idx]) is True:
                res = letter_grades[idx]
                print("--", res)
        elif idx == len(letter_grades)-1:
            if student_score < grade_borders[len(grade_borders)-1]:
                res = letter_grades[idx]
                print("--", res)
    return res

print(assign_letter_grade(182))
</code>```

Question:
What is my mistake in the code just above? Is this a dumb approach (and why /why not?) I've thought about another alternate method that uses a histogram to find the non-zero interval corresponding to a student's grade, but I'm not sure about the efficiency and implementation.

答:
For interval search, you can use numpy's searchsorted. Things will be more smooth if you sort the values from smallest the largest though.

```<code>letter_grades = np.array(letter_grades[::-1])
grade_borders = grade_borders[::-1]

def assign_letter_grade(student_score, grade_borders=grade_borders, letter_grades=letter_grades):
    return letter_grades[np.searchsorted(grade_borders, student_score)]
</code>```

A few example on this function:

```<code>assign_letter_grade(95)
Out: 'F'

assign_letter_grade(105)
Out: 'D-'

assign_letter_grade(182)
Out: 'A-'
</code>```

The same can be done with Python's bisect module.

```<code>import bisect

bisect.bisect(grade_borders, 182)
Out: 10

letter_grades[bisect.bisect(grade_borders, 182)]
Out: 'A-'
</code>```

The advantage of the numpy function is that it is vectorized so you can pass an array of scores:

```<code>assign_letter_grade([95, 110, 135, 157, 189, 198])
Out:
array(['F', 'D', 'C-', 'B-', 'A-', 'A'],
      dtype='<U2')
</code>```

Of course the same can be done with bisect in a loop but numpy's version will probably be faster.

Body:
I am writing a python code to act as a gradebook. I have calculated the total number of points earned by each student and am now stuck on the last step of my code - assigning a letter grade to a student. The structure of my code is to define functions that evaluate a single student's performance, so that one "master function" can repeatedly call the functions by an index number corresponding to each student. As such, I was able to produce a working code that I am trying to condense and simplify. I've checked out similar questions in posts like these, but I haven't been able to adapt these approaches to my problem (I think because my for-loop screws up the indexing).

Working code:

import numpy as np

failing_score = 100
perfect_score = 200
letter_grades = ['A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']
grade_borders = np.linspace(perfect_score, failing_score, len(letter_grades))

print(grade_borders)
>> [ 200.          190.90909091  181.81818182  172.72727273  163.63636364
  154.54545455  145.45454545  136.36363636  127.27272727  118.18181818
  109.09090909  100.        ]

def get_letter_grade(student_grade, grade_borders=grade_borders):
    """
    perfect score = 200, failing score ≤ 100

    190.9 - 200:    A
    181.8 - 190.9:  A-
    172.7 - 181.8:  B+
    etc
    """
    if student_grade >= grade_borders[1]:
        letter = 'A'
    elif grade_borders[2] <= student_grade < grade_borders[1]:
        letter = 'A-'
    elif grade_borders[3] <= student_grade < grade_borders[2]:
        letter = 'B+'
    elif grade_borders[4] <= student_grade < grade_borders[3]:
        letter = 'B'
    elif grade_borders[5] <= student_grade < grade_borders[4]:
        letter = 'B-'
    elif grade_borders[6] <= student_grade < grade_borders[5]:
        letter = 'C+'
    elif grade_borders[7] <= student_grade < grade_borders[6]:
        letter = 'C'
    elif grade_borders[8] <= student_grade < grade_borders[7]:
        letter = 'C-'
    elif grade_borders[9] <= student_grade < grade_borders[8]:
        letter = 'D+'
    elif grade_borders[10] <= student_grade < grade_borders[9]:
        letter = 'D'
    elif grade_borders[11] <= student_grade < grade_borders[10]:
        letter = 'D-'
    elif student_grade < grade_borders[11]:
        letter = 'F'
    return letter

print(get_letter_grade(182))
>> A-

I don't like having to specify each index and each letter grade using so many if/elif loops. So I tried to modify my approach by using a for-loop; the values at the boundaries (A and F) are handled separately while the grades in-between can be handled by the same code as functions of index.

Unsuccessful attempt:

def assign_letter_grade(student_score, grade_borders=grade_borders, letter_grades=letter_grades):
    """
    This is my unsuccessful attempt at replicating the function above.
    """
    res = 0 # not including this line ==> UnboundLocalError: local variable 'res' referenced before assignment
    for idx in range(len(grade_borders)):
        if idx == 0:
            if student_score >= grade_borders[1]:
                res = letter_grades[idx]
                print("--", res)
        elif idx > 0 and idx < len(letter_grades)-1:
            if (student_score >= grade_borders[idx+1]) and (student_score < grade_borders[idx]) is True:
                res = letter_grades[idx]
                print("--", res)
        elif idx == len(letter_grades)-1:
            if student_score < grade_borders[len(grade_borders)-1]:
                res = letter_grades[idx]
                print("--", res)
    return res

print(assign_letter_grade(182))

Question:
What is my mistake in the code just above? Is this a dumb approach (and why /why not?) I've thought about another alternate method that uses a histogram to find the non-zero interval corresponding to a student's grade, but I'm not sure about the efficiency and implementation.

Body:
For interval search, you can use numpy's searchsorted. Things will be more smooth if you sort the values from smallest the largest though.

letter_grades = np.array(letter_grades[::-1])
grade_borders = grade_borders[::-1]

def assign_letter_grade(student_score, grade_borders=grade_borders, letter_grades=letter_grades):
    return letter_grades[np.searchsorted(grade_borders, student_score)]

A few example on this function:

assign_letter_grade(95)
Out: 'F'

assign_letter_grade(105)
Out: 'D-'

assign_letter_grade(182)
Out: 'A-'

The same can be done with Python's bisect module.

import bisect

bisect.bisect(grade_borders, 182)
Out: 10

letter_grades[bisect.bisect(grade_borders, 182)]
Out: 'A-'

The advantage of the numpy function is that it is vectorized so you can pass an array of scores:

assign_letter_grade([95, 110, 135, 157, 189, 198])
Out:
array(['F', 'D', 'C-', 'B-', 'A-', 'A'],
      dtype='<U2')

Of course the same can be done with bisect in a loop but numpy's version will probably be faster.


问:
Using a Document Listener to display search results in real time?
I've a list of 'people' displayed in a JTable and stored in a database. I'd quite like users to have the results narrowed in that table as they type into a search area.

So for example typing 'S' would narrow the displayed names to 'Susan', 'Stephen', 'Steve', which would be narrowed down to just 'Susan' as soon as you type 'Su'

I was thinking of using the DocumentListener methods .removeUpdate(e) and .insertUpdate(e) to call the method that searches the underlying database and updates the table view - but this seems pretty wasteful.

In effect I'd be creating a new database connection, and other db objects, and refreshing the table every time any character was typed. I'm not sure if this is just poor design, or something that will actively cause me problems? Is there a better way of approaching this? or should I just stick to a normal search button?

答:
I've a list of 'people' displayed in a JTable

If all the people are displayed in a JTable then you can use the filtering feature of the JTable to display a subset of the rows in the table.

Read the section from the Swing tutorial on Sorting and Filtering for more information and working examples.


问:
When does the UIColletionView calls his datasource and delegate methods
I created a UICollectionView with a custom cell. In the viewDidLoad() method I was registering my cellclass.

```<code>   collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: cellId)
  collectionView?.reloadData()
</code>```

While debugging my code to check the behavior I saw that in the line where I was registering my collectionView and called collectionView.reloadData()  with the custom Cellclass none of the datasource and delegate methods got executed like cellForItem at etc.. ? Why is that so ?

答:
viewDidLoad() is called when your view has finished loading but before the view is laid out i.e. before its frame is properly set.

Judging from my observations a collection view calls its data source methods (like cellForItem(at:)) lazily during the layout process. After all, it doesn't need to call the data source methods at all if its size is .zero or if its position is currently off-screen!

So to put it short:

There is no reason why your collection view's data source methods should be called in viewDidLoad().

As far as I know calling reloadData() only discards all visible cells and decoration views so that they must be reloaded during the next layout pass. When the collection view is currently visible a new layout pass is triggered immediately but in viewDidLoad() the collection view isn't even on screen yet. (viewDidAppear() has not been called yet.)

Body:
I created a UICollectionView with a custom cell. In the viewDidLoad() method I was registering my cellclass.

   collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: cellId)
  collectionView?.reloadData()

While debugging my code to check the behavior I saw that in the line where I was registering my collectionView and called collectionView.reloadData()  with the custom Cellclass none of the datasource and delegate methods got executed like cellForItem at etc.. ? Why is that so ?


问:
Remove duplicate values from JS array
I have a very simple JavaScript array that may or may not contain duplicates.

```<code>var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
</code>```

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

答:
Solution 1

```<code>Array.prototype.unique = function() {
    var a = [];
    for (i = 0; i < this.length; i++) {
        var current = this[i];
        if (a.indexOf(current) < 0) a.push(current);
    }
    return a;
}
</code>```

Solution 2 (using Set)

```<code>Array.prototype.unique = function() {
    return Array.from(new Set(this));
}
</code>```

Test

```<code>var x=[1,2,3,3,2,1];
x.unique() //[1,2,3]
</code>```

Performance

When I tested both implementation (with and without Set) for performance in chrome, I found that the one with Set is much much faster!

Array.prototype.unique1 = function() {
    var a = [];
    for (i = 0; i < this.length; i++) {
        var current = this[i];
        if (a.indexOf(current) < 0) a.push(current);
    }
    return a;
}

Array.prototype.unique2 = function() {
    return Array.from(new Set(this));
}

var x=[];
for(var i=0;i<10000;i++){
 x.push("x"+i);x.push("x"+(i+1));
}

console.time("unique1");
console.log(x.unique1());
console.timeEnd("unique1");

console.time("unique2");
console.log(x.unique2());
console.timeEnd("unique2");```

ContentLicense: CC BY-SA 4.0

Title: Remove duplicate values from JS array

Body:
I have a very simple JavaScript array that may or may not contain duplicates.

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Body:
Solution 1

Array.prototype.unique = function() {
    var a = [];
    for (i = 0; i < this.length; i++) {
        var current = this[i];
        if (a.indexOf(current) < 0) a.push(current);
    }
    return a;
}

Solution 2 (using Set)

Array.prototype.unique = function() {
    return Array.from(new Set(this));
}

Test

var x=[1,2,3,3,2,1];
x.unique() //[1,2,3]

Performance

When I tested both implementation (with and without Set) for performance in chrome, I found that the one with Set is much much faster!

Array.prototype.unique1 = function() {
    var a = [];
    for (i = 0; i < this.length; i++) {
        var current = this[i];
        if (a.indexOf(current) < 0) a.push(current);
    }
    return a;
}

Array.prototype.unique2 = function() {
    return Array.from(new Set(this));
}

var x=[];
for(var i=0;i<10000;i++){
 x.push("x"+i);x.push("x"+(i+1));
}

console.time("unique1");
console.log(x.unique1());
console.timeEnd("unique1");

console.time("unique2");
console.log(x.unique2());
console.timeEnd("unique2");


问:
How do I use ASP.NET Core App Settings with Simple Injector
I am new to ASP.NET Core and need some direction. I am trying to figure out a simple scenario with using app settings in ASP.NET Core while also using Simple Injector.

I first set up my Strongly-Type configuration settings as explained here by Rick Strahl. This works great.

```<code>  public class MySettings
  {
    public string ApplicationName { get; set; }
  }
</code>```

appsetting.json

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "MySettings": {
    "ApplicationName": "Test Service"
  }
}
</code>```

Startup.cs

```<code>    public void ConfigureServices(IServiceCollection services)
    {
      // Add framework services.
      services.AddMvc();

      // Add Options
      services.AddOptions();

      // Add our Config object so it can be injected
      services.Configure<MySettings>(Configuration.GetSection("MySettings"));
      services.AddSingleton(GetTestBroker(container));

      //Simple Injector
      //services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(container));
      //services.AddSingleton<IViewComponentActivator>(new SimpleInjectorViewComponentActivator(container));

  }
</code>```

In our other projects were are using Simple Injector for DI. After adding the Simple Injector package and configuring it per the instructions I see that my IOptions configuration breaks.

What I'd like to know is what would be best practice for implementing a configuration in ASP.NET Core and using another DI library like Simple Injector together?

答:
I am the Author of ExistAll.SimpleConfig. SimpleConfig is exactly what is needed for Configuration / Settings in a DI environment.

Take a look to see if it's what you need

Body:
I am new to ASP.NET Core and need some direction. I am trying to figure out a simple scenario with using app settings in ASP.NET Core while also using Simple Injector.

I first set up my Strongly-Type configuration settings as explained here by Rick Strahl. This works great.

  public class MySettings
  {
    public string ApplicationName { get; set; }
  }

appsetting.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "MySettings": {
    "ApplicationName": "Test Service"
  }
}

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
      // Add framework services.
      services.AddMvc();

      // Add Options
      services.AddOptions();

      // Add our Config object so it can be injected
      services.Configure<MySettings>(Configuration.GetSection("MySettings"));
      services.AddSingleton(GetTestBroker(container));

      //Simple Injector
      //services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(container));
      //services.AddSingleton<IViewComponentActivator>(new SimpleInjectorViewComponentActivator(container));

  }

In our other projects were are using Simple Injector for DI. After adding the Simple Injector package and configuring it per the instructions I see that my IOptions configuration breaks.

What I'd like to know is what would be best practice for implementing a configuration in ASP.NET Core and using another DI library like Simple Injector together?


问:
Using Windows Phone 7 pinching in XNA
I'm trying to figure out how to implement pinch-to-zoom functionality. My problem is I'm not sure how to do it algorithmically.

I have the pinch positions of both fingers and the amount they've moved since the last frame. At first I tried making the pinch amount the delta of the distance between the two fingers however every way I've done it around this concept has been unyieldly.

Even if I manage to get the pinching working semi-decently I still have the problem of the zoom direction and how to make the image zoom in on the center of the pinch area...

Is there a proper way of implementing such functionality?

答:
I found few links of 3rd-party solution...

1) Dual-Touch SDK for Resistive Screens V1.0 Beta, Rotation Alpha

2) SciLor's HD2 / Leo Multitouch .NET CF DLL

I tried using Dual-Touch SDKs which were working fine for Resistive screen mobiles but not for Capacitive Screen mobiles.

Title: Using Windows Phone 7 pinching in XNA


问:
Why is my sqlalchemy model not callable?
I'm following the official sqlalchemy tutorial on getting started, yet when I try to instantiate the User class below, I'm told by the interpreter that it's not callable. I have no idea why. Anyone have any idea?

__init__.py

```<code>from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
</code>```

user.py

```<code>from sqlalchemy import Column, Integer, String

from __init__ import Base

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
</code>```

user_api.py

```<code>from flask import request
from flask.views import MethodView

from src.main.model.user import User

class UserAPI(MethodView):
    def post(self):
        usr = User(**request.form)
        return usr
</code>```

__main__.py

```<code>import flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from src.main.endpoints.user_api import UserAPI
from src.main.model import Base

def database_stuff():
    engine = create_engine('sqlite:///:memory:', echo=True)
    Session = sessionmaker(bind=engine)
    Base.metadata.create_all(engine)

if __name__ == "__main__":
    database_stuff()
    app = flask.Flask(__name__)
    user_view = UserAPI.as_view("users")
    app.add_url_rule("/users/", defaults={"user_id": None}, view_func=user_view, methods=["GET"])
    app.add_url_rule("/users/", view_func=user_view, methods=["POST"])
    app.add_url_rule("/users/<int:user_id>", view_func=user_view, methods=["GET"])
    app.run()
</code>```

When attempting to do a post request to the Flask server, this is what I'm getting in the logs:

```<code>Traceback (most recent call last):
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1740, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\wrappers.py", line 885, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\test.py", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'User' object is not callable
127.0.0.1 - - [05/Jun/2017 20:44:32] "POST /users/ HTTP/1.1" 500 -
</code>```

答: It actually has nothing to do with sqlalchemy. The object is indeed callable and instantiable. The error actually comes with attempting to return the object as a response. You can't just return any old object from a Flask endpoint. If I convert the object dict to json, then the error is no longer applicable.</p>

Body:
I'm following the official sqlalchemy tutorial on getting started, yet when I try to instantiate the User class below, I'm told by the interpreter that it's not callable. I have no idea why. Anyone have any idea?

__init__.py

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

user.py

from sqlalchemy import Column, Integer, String

from __init__ import Base

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

user_api.py

from flask import request
from flask.views import MethodView

from src.main.model.user import User

class UserAPI(MethodView):
    def post(self):
        usr = User(**request.form)
        return usr

__main__.py

import flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from src.main.endpoints.user_api import UserAPI
from src.main.model import Base

def database_stuff():
    engine = create_engine('sqlite:///:memory:', echo=True)
    Session = sessionmaker(bind=engine)
    Base.metadata.create_all(engine)

if __name__ == "__main__":
    database_stuff()
    app = flask.Flask(__name__)
    user_view = UserAPI.as_view("users")
    app.add_url_rule("/users/", defaults={"user_id": None}, view_func=user_view, methods=["GET"])
    app.add_url_rule("/users/", view_func=user_view, methods=["POST"])
    app.add_url_rule("/users/<int:user_id>", view_func=user_view, methods=["GET"])
    app.run()

When attempting to do a post request to the Flask server, this is what I'm getting in the logs:

Traceback (most recent call last):
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1740, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\wrappers.py", line 885, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\test.py", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'User' object is not callable
127.0.0.1 - - [05/Jun/2017 20:44:32] "POST /users/ HTTP/1.1" 500 -


问:
VBA for Excel, how to load a .js file as Jscript Scriptcontrol object
I know it's a bit silly to load a js into VBA, but I need to load the libphonenumber library by Google to perform an analysis of a big bunch of phone numbers.

I tried to adapt the following code borrowed from here, but the compiled library is to big to be inserted into the Vba code.

Is there any way to load the .js library from a file instead?
Thanks!

```<code>Function encodeURL(str As String)
   Dim ScriptEngine As ScriptControl
   Set ScriptEngine = New ScriptControl

   ScriptEngine.Language = "JScript"
   ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
   Dim encoded As String

   encoded = ScriptEngine.Run("encode", str)
   encodeURL = encoded
End Function
</code>```

UPDATE.

This should be a working code, but for some reason doesn't works:

```<code>Function loabdjs(x As String)

    Dim fso As Scripting.FileSystemObject
    Set fso = New Scripting.FileSystemObject

    Dim script As String
    Dim fs As Scripting.TextStream

    ''' CODE : "function encode(str) {return encodeURIComponent(str);}"
    Set fs = fso.OpenTextFile("test.js", ForReading, False)
    MsgBox ("Never reached this point")

    script = fs.ReadAll

    fs.Close

    Dim ScriptEngine As ScriptControl
    Set ScriptEngine = New ScriptControl

    Dim output As String

    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode script

    output = ScriptEngine.Run("encode", x)
    loadjs = output
End Function
</code>```

Any ideas?

答:
Read the library from the filesystem into a string:</p>

```<code>Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject

Dim fs As Scripting.TextStream
Set fs = fso.OpenTextFile( "libphonenumber.js", ForReading, False )

Dim script As String
script = fs.ReadAll

fs.Close()

scriptEngine.AddCode script
</code>```

Body:
I know it's a bit silly to load a js into VBA, but I need to load the libphonenumber library by Google to perform an analysis of a big bunch of phone numbers.

I tried to adapt the following code borrowed from here, but the compiled library is to big to be inserted into the Vba code.

Is there any way to load the .js library from a file instead?
Thanks!

Function encodeURL(str As String)
   Dim ScriptEngine As ScriptControl
   Set ScriptEngine = New ScriptControl

   ScriptEngine.Language = "JScript"
   ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
   Dim encoded As String

   encoded = ScriptEngine.Run("encode", str)
   encodeURL = encoded
End Function

UPDATE.

This should be a working code, but for some reason doesn't works:

Function loabdjs(x As String)

    Dim fso As Scripting.FileSystemObject
    Set fso = New Scripting.FileSystemObject

    Dim script As String
    Dim fs As Scripting.TextStream

    ''' CODE : "function encode(str) {return encodeURIComponent(str);}"
    Set fs = fso.OpenTextFile("test.js", ForReading, False)
    MsgBox ("Never reached this point")

    script = fs.ReadAll

    fs.Close

    Dim ScriptEngine As ScriptControl
    Set ScriptEngine = New ScriptControl

    Dim output As String

    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode script

    output = ScriptEngine.Run("encode", x)
    loadjs = output
End Function

Any ideas?

Body:
Read the library from the filesystem into a string:

Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject

Dim fs As Scripting.TextStream
Set fs = fso.OpenTextFile( "libphonenumber.js", ForReading, False )

Dim script As String
script = fs.ReadAll

fs.Close()

scriptEngine.AddCode script


问:
Canvas wont work
```<code> var canvas = document.getElementById("mycanvas");

 var ctx = canvas.getContext("2d");

var ball = function() {

this.x = Math.floor((Math.random() * 10) + 1);
this.y = Math.floor((Math.random() * 10) + 1);
this.xSpeed = Math.floor((Math.random() * 10) + 1);
this.ySpeed = Math.floor((Math.random() * 10) + 1);

};

  var balls =[];

for(i = 0 ; i < 10 ; i++) {

balls[i] = new ball();

}

  function draw() {
 for( i = 0; i < 10 ; i++) {

var ball = balls[i]

ctx.beginPath()

if(ball.x < 0 || ball.x > 400) {

ball.xSpeed = -ball.xSpeed;
}

if(ball.y < 0 || ball.y > 400 ) {

ball.ySpeed = -ball.ySpeed;
}

ball.x += ball.xSpeed;

ball.y += ball.ySpeed;

ctx.arc(ball.x , ball.y , 2 , 0 , Math.PI * 2 , false);
ctx.stroke();

ctx.fill();
}
}

  function bounce() {

setInterval(draw , 10);

}
</code>```

It should draw more than one ball but it's not drawing any. please help. I can provide html if needed. i have this issue right now. Please help me right now. i It's not drawing any balls. This is unlucky

答:
Call your draw function.
Add: bounce(); at the bottom.

Title: Canvas wont work

Body:
 var canvas = document.getElementById("mycanvas");

 var ctx = canvas.getContext("2d");

var ball = function() {

this.x = Math.floor((Math.random() * 10) + 1);
this.y = Math.floor((Math.random() * 10) + 1);
this.xSpeed = Math.floor((Math.random() * 10) + 1);
this.ySpeed = Math.floor((Math.random() * 10) + 1);

};

  var balls =[];

for(i = 0 ; i < 10 ; i++) {

balls[i] = new ball();

}

  function draw() {
 for( i = 0; i < 10 ; i++) {

var ball = balls[i]

ctx.beginPath()

if(ball.x < 0 || ball.x > 400) {

ball.xSpeed = -ball.xSpeed;
}

if(ball.y < 0 || ball.y > 400 ) {

ball.ySpeed = -ball.ySpeed;
}

ball.x += ball.xSpeed;

ball.y += ball.ySpeed;

ctx.arc(ball.x , ball.y , 2 , 0 , Math.PI * 2 , false);
ctx.stroke();

ctx.fill();
}
}

  function bounce() {

setInterval(draw , 10);

}

It should draw more than one ball but it's not drawing any. please help. I can provide html if needed. i have this issue right now. Please help me right now. i It's not drawing any balls. This is unlucky


问:
Excel - Rather complex SUM IF criteria
I have roughly the following setup:

Values:

```<code>MONTH | DURATION | VALUE |
  5   |     3    |  120  |
  6   |     1    |  100  |
</code>```

Expected outcome for totals:

```<code>MONTH | TOTAL
  5   |  120
  6   |  220
  7   |  120
</code>```

What I would like to do, is to be able to sum in another table the total values for each month. The logic would be to SUM every value where the total table's month is equal or higher than that of the values, but lower than the value's month + duration.

Does that make any sense? Is that possible? I'm cracking my head and I can't seem to find a way to solve it.

Thank you very much.

答:
The easiest solution is probably to make another column with the end month. And then use SUMIFS to check if month is >= starting month and <= ending month.</p>

```<code>=SUMIFS(<Range of Values>,<Range of starting>,"<="& "Target month",<Range of ending>,">="& <Target month>)
</code>```

Title: Excel - Rather complex SUM IF criteria

Body:
I have roughly the following setup:

Values:

MONTH | DURATION | VALUE |
  5   |     3    |  120  |
  6   |     1    |  100  |

Expected outcome for totals:

MONTH | TOTAL
  5   |  120
  6   |  220
  7   |  120

What I would like to do, is to be able to sum in another table the total values for each month. The logic would be to SUM every value where the total table's month is equal or higher than that of the values, but lower than the value's month + duration.

Does that make any sense? Is that possible? I'm cracking my head and I can't seem to find a way to solve it.

Thank you very much.

Body:
The easiest solution is probably to make another column with the end month. And then use SUMIFS to check if month is >= starting month and <= ending month.

=SUMIFS(<Range of Values>,<Range of starting>,"<="& "Target month",<Range of ending>,">="& <Target month>)


问:
How do I get the value of the first occurrence of array_walk_recursive in php
I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

```<code>Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)
</code>```

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

```<code>array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));
</code>```

The above returns submodel is LXsubmodel is LX.

Bonus Question!!
How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

答:
array_walk_recursive() has the defect of not allowing to return matching results however in PHP 7 you could use an anonymous function and a variable to store the matching value.</p>

```<code>$matching = null;
$wanted = "submodel";

array_walk_recursive ($array, function ($item, $key) use ($wanted, $matching) {
    if (($key === $wanted) && is_null($matching)) {
        $matching = $item;
    }
});
</code>```

Body:
I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));

The above returns submodel is LXsubmodel is LX.

Bonus Question!!
How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

Body:
array_walk_recursive() has the defect of not allowing to return matching results however in PHP 7 you could use an anonymous function and a variable to store the matching value.

$matching = null;
$wanted = "submodel";

array_walk_recursive ($array, function ($item, $key) use ($wanted, $matching) {
    if (($key === $wanted) && is_null($matching)) {
        $matching = $item;
    }
});


问:
Call a function when it is stored as dictionary value
```<code>def test():
     print "printing from test func"

dic = {'a':1,'b':2,'c':test}
if len(dic) == 3:
     print (dic['c'])

output:
<function test at 0x106887578>
</code>```

This code prints the function object as output, how to get the print statement from test function as output.

答: Simply call dic['c']() to run your function. Hope I helped!

Body:
def test():
     print "printing from test func"

dic = {'a':1,'b':2,'c':test}
if len(dic) == 3:
     print (dic['c'])

output:
<function test at 0x106887578>

This code prints the function object as output, how to get the print statement from test function as output.


问:
getting data from a partial view onto main view
I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers

Tool Model

```<code>  public class Tool
{
  public int Id { get; set; }
  public string ToolId { get; set; }
  public string Adapter { get; set; }
  public string Description { get; set; }
  public string TNumber { get; set; }
  public List<string> ComponentList { get; set; }
  public List<string> AccessoryList { get; set; }
  public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
  public List<string> toolList = new List<string>();

}
</code>```

Partial View Controller

```<code>public ActionResult PartialView()
  {
     Tool newTool = new Tool();
     List<string> tools = new List<string>();
     tools = backgroundLoad();
     newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     foreach (string tool in tools)
     {
        newTool.ToolIdDescription = GetToolDescription(tool);
     }

     return View(newTool);
  }
</code>```

Controller to recieve Datasets

```<code>public ActionResult GetDataSet(string id)
  {
     Tool selectedTool = new Tool();
     if (id != null)
     {
        var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
        XmlDocument xml = new XmlDocument();
        Stream aResponsestream;
        string aResult = "";
        using (aResponsestream = request.GetResponse().GetResponseStream())
        using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
        {
           aResult = aReader.ReadToEnd();
           aResponsestream.Close();
        }
        xml.LoadXml(aResult);
        var Description =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
        if (Description != null) selectedTool.Description =
Description.InnerText;
        var Adapter =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
        if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
        var TNumber =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
        if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
        var ToolId =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
        if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;

        return View(selectedTool);
     }
     else return View();

  }
</code>```

View which contains the list

```<code>@model  MiniWeb.Models.Tool

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   <link href="~/Content/Site.css" rel="stylesheet" />
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
   <table class="table table-hover">
      <thead>
      <tr>
         <th>Id</th>
         <th>Description</th>
      </tr>
      </thead>
      @foreach (var item in Model.ToolIdDescription)
      {

         <tbody>
         <tr>
            <td>@Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })</td>
            <td>@Html.DisplayFor(modelItem => item.Value)</td>
         </tr>
         </tbody>
      }
   </table>
</div>
</body>
</html>

@Html.Partial("GetDataSet", new MiniWeb.Models.Tool())
</code>```

View which displays the tool information

```<code>@model MiniWeb.Models.Tool

@{
    ViewBag.Title = "GetDataSet";
}
@{
   ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<h2>Tool Selection </h2>
<div class="Tool">
   <span id ="id">
         @Html.LabelFor(m => Model.ToolId)
         @Html.TextBoxFor(modelItem => Model.ToolId)
   </span>
   <br/>
   <span id="Description">
         @Html.LabelFor(m => Model.Description)
         @Html.TextBoxFor(modelItem => Model.Description)
   </span>
   <br/>
   <span id="Adapter">
         @Html.LabelFor(m=> Model.Adapter)
         @Html.TextBoxFor(modelItem => Model.Adapter)

   </span>
   <br/>
   <span id="Adapter">
         @Html.LabelFor(m => Model.TNumber)
         @Html.TextBoxFor(modelItem => Model.TNumber)
   </span>
   <span>
      <button> Save </button>
   </span>
</div>
</code>```

Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.

答:
With some more research I was able to figure out how to solve my problem. Turns out all I needed was some AJAX. I used an Ajax.Actionlink instead of an HTML action link and was able to load up my partial view in a div on the page. Here is my new view and controller. The partial view stayed the same.

View

```<code>@model  MiniWeb.Models.Tool

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

   <link href="~/Content/Site.css" rel="stylesheet" />
   <script src="~/Scripts/jquery-3.1.1.min.js"></script>
   <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
   <table class="table table-hover">
      <thead>
      <tr>
         <th>Id</th>
         <th>Description</th>
      </tr>
      </thead>
      @foreach (var item in Model.ToolIdDescription)
      {

         <tbody>
         <tr>
            <td>@Ajax.ActionLink(item.Key, "_Partially", new { id = item.Key },new AjaxOptions()
                {
                   HttpMethod = "GET",
                   UpdateTargetId = "ToolInfo",
                   InsertionMode = InsertionMode.Replace,

                })

            </td>

            <td>@Html.DisplayFor(modelItem => item.Value)</td>
         </tr>
         </tbody>
      }
   </table>
</div>
</body>
</html>
<div id="ToolInfo">

</div>
</code>```

and my new controller which is returns a PartialView looks like this

Partial View Controller

```<code>public PartialViewResult _Partially(string id)
      {
         Tool selectedTool = new Tool();
         if (id != null)
         {
            var request = (HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);

            XmlDocument xml = new XmlDocument();
            Stream aResponsestream;
            string aResult = "";
            using (aResponsestream = request.GetResponse().GetResponseStream())
            using (StreamReader aReader = new StreamReader(aResponsestream, Encoding.UTF8))

            {
               aResult = aReader.ReadToEnd();
               aResponsestream.Close();
            }
            xml.LoadXml(aResult);
            var Description = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
            if (Description != null) selectedTool.Description = Description.InnerText;
            var Adapter = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
            if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
            var TNumber = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
            if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
            var ToolId = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
            if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;

            return PartialView("_Partially", selectedTool);
         }
         return PartialView();

      }
</code>```

Hopefully this answer will help others like me in the future. Thanks for reading.

Body:
I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers

Tool Model

  public class Tool
{
  public int Id { get; set; }
  public string ToolId { get; set; }
  public string Adapter { get; set; }
  public string Description { get; set; }
  public string TNumber { get; set; }
  public List<string> ComponentList { get; set; }
  public List<string> AccessoryList { get; set; }
  public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
  public List<string> toolList = new List<string>();

}

Partial View Controller

public ActionResult PartialView()
  {
     Tool newTool = new Tool();
     List<string> tools = new List<string>();
     tools = backgroundLoad();
     newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
     foreach (string tool in tools)
     {
        newTool.ToolIdDescription = GetToolDescription(tool);
     }

     return View(newTool);
  }

Controller to recieve Datasets

public ActionResult GetDataSet(string id)
  {
     Tool selectedTool = new Tool();
     if (id != null)
     {
        var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
        XmlDocument xml = new XmlDocument();
        Stream aResponsestream;
        string aResult = "";
        using (aResponsestream = request.GetResponse().GetResponseStream())
        using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
        {
           aResult = aReader.ReadToEnd();
           aResponsestream.Close();
        }
        xml.LoadXml(aResult);
        var Description =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
        if (Description != null) selectedTool.Description =
Description.InnerText;
        var Adapter =
   xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
        if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
        var TNumber =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
        if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
        var ToolId =
        xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
        if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;

        return View(selectedTool);
     }
     else return View();

  }

View which contains the list

@model  MiniWeb.Models.Tool

<!DOCTYPE html>

   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

   <link href="~/Content/Site.css" rel="stylesheet" />

Tool List

         Id
         Description

      @foreach (var item in Model.ToolIdDescription)
      {

            @Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })
            @Html.DisplayFor(modelItem => item.Value)

      }

@Html.Partial("GetDataSet", new MiniWeb.Models.Tool())

View which displays the tool information

@model MiniWeb.Models.Tool

@{
    ViewBag.Title = "GetDataSet";
}
@{
   ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />

Tool Selection

         @Html.LabelFor(m => Model.ToolId)
         @Html.TextBoxFor(modelItem => Model.ToolId)

         @Html.LabelFor(m => Model.Description)
         @Html.TextBoxFor(modelItem => Model.Description)

         @Html.LabelFor(m=> Model.Adapter)
         @Html.TextBoxFor(modelItem => Model.Adapter)

         @Html.LabelFor(m => Model.TNumber)
         @Html.TextBoxFor(modelItem => Model.TNumber)

      <button> Save </button>

Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.

Body:
With some more research I was able to figure out how to solve my problem. Turns out all I needed was some AJAX. I used an Ajax.Actionlink instead of an HTML action link and was able to load up my partial view in a div on the page. Here is my new view and controller. The partial view stayed the same.

View

@model  MiniWeb.Models.Tool

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

   <link href="~/Content/Site.css" rel="stylesheet" />
   <script src="~/Scripts/jquery-3.1.1.min.js"></script>
   <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
   <table class="table table-hover">
      <thead>
      <tr>
         <th>Id</th>
         <th>Description</th>
      </tr>
      </thead>
      @foreach (var item in Model.ToolIdDescription)
      {

         <tbody>
         <tr>
            <td>@Ajax.ActionLink(item.Key, "_Partially", new { id = item.Key },new AjaxOptions()
                {
                   HttpMethod = "GET",
                   UpdateTargetId = "ToolInfo",
                   InsertionMode = InsertionMode.Replace,

                })

            </td>

            <td>@Html.DisplayFor(modelItem => item.Value)</td>
         </tr>
         </tbody>
      }
   </table>
</div>
</body>
</html>
<div id="ToolInfo">

</div>

and my new controller which is returns a PartialView looks like this

Partial View Controller

public PartialViewResult _Partially(string id)
      {
         Tool selectedTool = new Tool();
         if (id != null)
         {
            var request = (HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);

            XmlDocument xml = new XmlDocument();
            Stream aResponsestream;
            string aResult = "";
            using (aResponsestream = request.GetResponse().GetResponseStream())
            using (StreamReader aReader = new StreamReader(aResponsestream, Encoding.UTF8))

            {
               aResult = aReader.ReadToEnd();
               aResponsestream.Close();
            }
            xml.LoadXml(aResult);
            var Description = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
            if (Description != null) selectedTool.Description = Description.InnerText;
            var Adapter = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
            if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
            var TNumber = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
            if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
            var ToolId = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
            if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;

            return PartialView("_Partially", selectedTool);
         }
         return PartialView();

      }

Hopefully this answer will help others like me in the future. Thanks for reading.


问:
SAS VA Merge two tables (using GUI)
Im trying to merge two tables together into one, using the SAS VA user interface. But I only have the option to join (left,right,inner,full). Is this just not possible through the GUI?

答:
Yes, data prep runs on sql, but it doesn't have to. In theory, you can hack the code in data prep to accomplish what you want. First, create a "dummy" query in data prep by pulling any dataset into the design tab (use one from the same library as the others just to make it simple. you could even use one of the two you have selected already), select a column or two to produce results, go to the "outputs" tab and give it the actual name you want it to have in the end. Then click on the "code" tab. You'll see some pre-populated code. Down at the bottom you'll see a proc sql statement querying the dataset and pulling in the columns you selected followed by the code to drop any existing datasets by that name and then a data step to create the table in the lasr library. will look something like this, i called my output testtable_01...

```<code>proc sql noprint;
create table TEMP_LASR_VIEW_0 as
SELECT
    library.column_1 length=8 format=16. AS column_1,
    library.column_2 length=8 format=10. AS column_2
FROM
    library.table;
quit;
/* Drop existing table */
%vdb_dt(LASRLIB.testtable_01);
data LASRLIB.testtable_01 (   );
set TEMP_LASR_VIEW_0 (  );
run;
</code>```

Now preview the results of the query (just to make sure it will work, which it should because it's a simple select statement). Next you'll save the query. This will generate the last piece of code you need... the registertable macro. This will create the reposid and tableid assigned to the output tablename you have it at the start. should look something like this..

```<code>/* Synchronize table registration */
%registerTable(
 LIBRARY=%nrstr(/Shared Data/SAS Visual Analytics/Public/Visual Analytics Public LASR)
, REPOSID=%str(A5UHNO19)
, TABLEID=%str(A5UHN019.BF003CB7));
</code>```

Now that you have this piece of code you can click the "unlock for manual editing" button (looks like a little padlock at the top left of the code window). Once you click it there is no turning back. If you screw up you'll have to start from scratch. But now you'll be able to modify the code. Replace the proc sql with whatever code you want to merge the two datasets you actually want to use. for example.

```<code>DATA TEMP_LASR_VIEW_0;
MERGE library.TABLE_01
      library.TABLE_02;
BY COLUMN_01;
RUN;
/* Drop existing table */
%vdb_dt(LASRLIB.testtable_01);
data LASRLIB.testtable_01 (   );
set TEMP_LASR_VIEW_0 (  );
run;
/* Synchronize table registration */
%registerTable(
 LIBRARY=%nrstr(/Shared Data/SAS Visual Analytics/Public/Visual Analytics Public LASR)
, REPOSID=%str(A5UHNO19)
, TABLEID=%str(A5UHN019.BF003CB7));
</code>```

Now save the query and run it. Again, in theory this should work. Might need to tweak it a bit. Will probably take a few attempts before getting it perfect.

Title: SAS VA Merge two tables (using GUI)

Body:
Yes, data prep runs on sql, but it doesn't have to. In theory, you can hack the code in data prep to accomplish what you want. First, create a "dummy" query in data prep by pulling any dataset into the design tab (use one from the same library as the others just to make it simple. you could even use one of the two you have selected already), select a column or two to produce results, go to the "outputs" tab and give it the actual name you want it to have in the end. Then click on the "code" tab. You'll see some pre-populated code. Down at the bottom you'll see a proc sql statement querying the dataset and pulling in the columns you selected followed by the code to drop any existing datasets by that name and then a data step to create the table in the lasr library. will look something like this, i called my output testtable_01...

proc sql noprint;
create table TEMP_LASR_VIEW_0 as
SELECT
    library.column_1 length=8 format=16. AS column_1,
    library.column_2 length=8 format=10. AS column_2
FROM
    library.table;
quit;
/* Drop existing table */
%vdb_dt(LASRLIB.testtable_01);
data LASRLIB.testtable_01 (   );
set TEMP_LASR_VIEW_0 (  );
run;

Now preview the results of the query (just to make sure it will work, which it should because it's a simple select statement). Next you'll save the query. This will generate the last piece of code you need... the registertable macro. This will create the reposid and tableid assigned to the output tablename you have it at the start. should look something like this..

/* Synchronize table registration */
%registerTable(
 LIBRARY=%nrstr(/Shared Data/SAS Visual Analytics/Public/Visual Analytics Public LASR)
, REPOSID=%str(A5UHNO19)
, TABLEID=%str(A5UHN019.BF003CB7));

Now that you have this piece of code you can click the "unlock for manual editing" button (looks like a little padlock at the top left of the code window). Once you click it there is no turning back. If you screw up you'll have to start from scratch. But now you'll be able to modify the code. Replace the proc sql with whatever code you want to merge the two datasets you actually want to use. for example.

DATA TEMP_LASR_VIEW_0;
MERGE library.TABLE_01
      library.TABLE_02;
BY COLUMN_01;
RUN;
/* Drop existing table */
%vdb_dt(LASRLIB.testtable_01);
data LASRLIB.testtable_01 (   );
set TEMP_LASR_VIEW_0 (  );
run;
/* Synchronize table registration */
%registerTable(
 LIBRARY=%nrstr(/Shared Data/SAS Visual Analytics/Public/Visual Analytics Public LASR)
, REPOSID=%str(A5UHNO19)
, TABLEID=%str(A5UHN019.BF003CB7));

Now save the query and run it. Again, in theory this should work. Might need to tweak it a bit. Will probably take a few attempts before getting it perfect.


问:
Match row value in df1 with column name in df2 to return same row value of df2
This question is similar to what I found here: Multiply rows (with row names) in one data frame with matching column names in another

But instead of matching rows and multiplying, I want to match a column's values from df1 with a column name in df2 and return the corresponding row values of df2 in a new df3.

```<code>df1 <- data.frame(V1=c(1:6),V2=c("X3", "X3_8", "NA", "X5", "X4_5", "X3_8"))
df1
    V1 V2
  1 1  X3
  2 2  X3_8
  3 3  NA
  4 4  X5
  5 5  X4_5
  6 6  X3_8

df2 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  X3=c(0.5, 1.2, 0.75, 3.1, 2.0, 1.1),
                  X5=c(1.0, 2.3, 4.2, 5, 1.1, 3.0),
                  X3_8=c(0.6, 1.0, 2.0, 1.0, 0.7, 1.4),
                  X4_5=c(0.4, 0.3, 3.0, 1.0, 2.0, 0.9))
df2
     name   X3    X5    X3_8  X4_5
  1  John   0.5   1.0   0.6   0.4
  2  Mary   1.2   2.3   1.0   0.3
  3  Joe    0.75  4.2   2.0   3.0
  4  Tim    3.1   5.0   1.0   1.0
  5  Bob    2.0   1.1   0.7   2.0
  6  Pat    1.1   3.0   1.4   0.9
</code>```

This is what I want:

```<code>df3 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  values=c(0.5, 1.0, NA, 5.0, 1.0, 1.4))
    name values
  1 John    0.5
  2 Mary    1.0
  3  Joe     NA
  4  Tim    5.0
  5  Bob    1.0
  6  Pat    1.4
</code>```

In my real df1 and df2 there are 64 rows, where "V1" in df1 corresponds to a numeric index for the "name" column in df2. In my df2, there are 22 columns, i.e., one with "name" and another 21 with "X*" to match "V2" in df1. I tried converting "V2" to row names, but this doesn't work because there are NA's and repeating values.

Bonus but not necessary: I have 10 df1s and 10 df2s and need to do this for each pair of df1s and df2s where the names of the df1s and the df2s contain common years. For example, I need to match df1_2004 with df2_2004, create df3_2004, and move on to df1_2005 and df2_2005, and so on. I'm sure there's an elegant way to do this without a for loop and an if statement.

Thanks for any assistance. I'm sure there's a simple base R or tidyrverse solution to this, but I'm struggling to put the pieces together. Forgive my newbie understanding of indexing in R.

答:
The less functional procedure of the world:

```<code>n_row <- nrow(df1)
# corce the variable V1 in a factor with the name variables of the
# df2
df1$V1 <- factor(df1$V1, labels = df2$name)
# coerce the variable V2 into a character vector or use 'stringsAsFactors = FALSE'
# when you read the data frame
df1$V2 <- as.character(df1$V2)
# create a copy of df1 to impute values of the V2 col
df3 <- df1
for (i in 1:n_row) {
  col_index <- which(df1[i, "V2"] == names(df2), arr.ind = TRUE)
  row_index <- which(df1[i, "V1"] == df2$name, arr.ind = TRUE)
  if (length(col_index) == 0) {
    df3[i, "V2"] <- NA
  } else {
    df3[i, "V2"] <- df2[row_index, col_index]
  }
}
names(df3) <- c("name", "values")
</code>```

gives:

```<code>#>df3
   name  values
 1 John  0.5
 2 Mary    1
 3  Joe <NA>
 4  Tim    5
 5  Bob    2
 6  Pat  1.4
</code>```

Body:
This question is similar to what I found here: Multiply rows (with row names) in one data frame with matching column names in another

But instead of matching rows and multiplying, I want to match a column's values from df1 with a column name in df2 and return the corresponding row values of df2 in a new df3.

df1 <- data.frame(V1=c(1:6),V2=c("X3", "X3_8", "NA", "X5", "X4_5", "X3_8"))
df1
    V1 V2
  1 1  X3
  2 2  X3_8
  3 3  NA
  4 4  X5
  5 5  X4_5
  6 6  X3_8

df2 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  X3=c(0.5, 1.2, 0.75, 3.1, 2.0, 1.1),
                  X5=c(1.0, 2.3, 4.2, 5, 1.1, 3.0),
                  X3_8=c(0.6, 1.0, 2.0, 1.0, 0.7, 1.4),
                  X4_5=c(0.4, 0.3, 3.0, 1.0, 2.0, 0.9))
df2
     name   X3    X5    X3_8  X4_5
  1  John   0.5   1.0   0.6   0.4
  2  Mary   1.2   2.3   1.0   0.3
  3  Joe    0.75  4.2   2.0   3.0
  4  Tim    3.1   5.0   1.0   1.0
  5  Bob    2.0   1.1   0.7   2.0
  6  Pat    1.1   3.0   1.4   0.9

This is what I want:

df3 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  values=c(0.5, 1.0, NA, 5.0, 1.0, 1.4))
    name values
  1 John    0.5
  2 Mary    1.0
  3  Joe     NA
  4  Tim    5.0
  5  Bob    1.0
  6  Pat    1.4

In my real df1 and df2 there are 64 rows, where "V1" in df1 corresponds to a numeric index for the "name" column in df2. In my df2, there are 22 columns, i.e., one with "name" and another 21 with "X*" to match "V2" in df1. I tried converting "V2" to row names, but this doesn't work because there are NA's and repeating values.

Bonus but not necessary: I have 10 df1s and 10 df2s and need to do this for each pair of df1s and df2s where the names of the df1s and the df2s contain common years. For example, I need to match df1_2004 with df2_2004, create df3_2004, and move on to df1_2005 and df2_2005, and so on. I'm sure there's an elegant way to do this without a for loop and an if statement.

Thanks for any assistance. I'm sure there's a simple base R or tidyrverse solution to this, but I'm struggling to put the pieces together. Forgive my newbie understanding of indexing in R.

Body:
The less functional procedure of the world:

n_row <- nrow(df1)
# corce the variable V1 in a factor with the name variables of the
# df2
df1$V1 <- factor(df1$V1, labels = df2$name)
# coerce the variable V2 into a character vector or use 'stringsAsFactors = FALSE'
# when you read the data frame
df1$V2 <- as.character(df1$V2)
# create a copy of df1 to impute values of the V2 col
df3 <- df1
for (i in 1:n_row) {
  col_index <- which(df1[i, "V2"] == names(df2), arr.ind = TRUE)
  row_index <- which(df1[i, "V1"] == df2$name, arr.ind = TRUE)
  if (length(col_index) == 0) {
    df3[i, "V2"] <- NA
  } else {
    df3[i, "V2"] <- df2[row_index, col_index]
  }
}
names(df3) <- c("name", "values")

gives:

#>df3
   name  values
 1 John  0.5
 2 Mary    1
 3  Joe <NA>
 4  Tim    5
 5  Bob    2
 6  Pat  1.4


问:
Angular - Apply style to element depending on sibling RouterLinkActive?
I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive?

menu.html

```<code><menu>
  <a routerLink="page1" routerLinkActive="active">
      option1
  </a>
  <a routerLink="page2" routerLinkActive="active">
      option2
  </a>
</menu>
</code>```

This menu works great. But what I'm asking is how can I take advantage of routerLinkActive property placed in other HTML Tag. like:

main.html

```<code><main>
    <span class="title" routerLinkActive="active">My sub child part</span>
</main>
</code>```

答:
you can apply the RouterLinkActive directive to an ancestor of a
  RouterLink.

```<code><div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>
</code>```

More details here.

Hope this helps!!

Body:
I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive?

menu.html

<menu>

      option1

      option2

</menu>

This menu works great. But what I'm asking is how can I take advantage of routerLinkActive property placed in other HTML Tag. like:

main.html

    My sub child part

Body:
you can apply the RouterLinkActive directive to an ancestor of a
  RouterLink.

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>

More details here.

Hope this helps!!


问:
How to stopPropagation() w/ Hammer.js 2.0?
I have a parent and child div.  Panning/dragging on the child should not affect the parent.  This is a similar question but was asked a year ago, and I'm using a newer version of Hammer.js w/ the jQuery wrapper.

My assumption was that I'd have to somehow stopPropagation() but I'm not really sure how to use it.

I've mocked up a demo showing my problem on JsFiddle.  I've also commented out the couple things I've tried.

```<code>$(".outer-box").hammer().bind("panright", function(event){
    // do stuff when panning
    // panning here should move both boxes
});
$(".outer-box").hammer().bind("panend", function(event){
    // do stuff when panning ends
});

$(".inner-box").hammer().bind("panright", function(event){
    // do stuff when panning
    // panning here should only affect the inner box
});
$(".inner-box").hammer().bind("panend", function(event){
    // do stuff when panning ends
});
</code>```

Any suggestions or tips?  Thanks!

答:
Had the same issue, however was able to handle this by enabling domEvents.

```<code>Hammer.defaults.domEvents = true;
</code>```

Once enabled, event.stopPropagation(); worked fine.

Body:
I have a parent and child div.  Panning/dragging on the child should not affect the parent.  This is a similar question but was asked a year ago, and I'm using a newer version of Hammer.js w/ the jQuery wrapper.

My assumption was that I'd have to somehow stopPropagation() but I'm not really sure how to use it.

I've mocked up a demo showing my problem on JsFiddle.  I've also commented out the couple things I've tried.

$(".outer-box").hammer().bind("panright", function(event){
    // do stuff when panning
    // panning here should move both boxes
});
$(".outer-box").hammer().bind("panend", function(event){
    // do stuff when panning ends
});

$(".inner-box").hammer().bind("panright", function(event){
    // do stuff when panning
    // panning here should only affect the inner box
});
$(".inner-box").hammer().bind("panend", function(event){
    // do stuff when panning ends
});

Any suggestions or tips?  Thanks!

Body:
Had the same issue, however was able to handle this by enabling domEvents.

Hammer.defaults.domEvents = true;

Once enabled, event.stopPropagation(); worked fine.


问:
GRAILS - How to start using Twitter Bootstrap in Grails 3.2.9 and what's the best way to do it?
What's the way to use Bootstrap in Grails 3.2.9? How to start? Should I use any plugins?</p>

答:
To follow best practices use the Grails Asset Pipeline. It may take a bit of practice to understand how the pipeline works but the general ideas are highlighted well in this SO Answer. The pipeline will create folders for your assets, (css, javascript, images for example) and you need to place your bootstrap files in the proper locations. Make sure you remember that Bootstrap requires jQuery.

Please note that all JavaScript plugins require jQuery...

So be sure to include jQuery in your javascript folder. The other concept to grasp is creating the manifest file. For javascript assets it might look similar to:

Example file path:

```<code>grails-app/assets/javascripts/application.js
</code>```

Example file contents:

```<code>//This is a JavaScript file with its top level require directives
//= require jquery
//= require app/models.js
//= require_tree views
//= require_self
console.log("This is my javascript manifest");
</code>```

Then in the view you would like to uses the assets in, include the bootstrap assets by declaring:

```<code><head>
    <asset:stylesheet href="application.css"/> //This assumes the standard pipeline path
    <asset:javascript src="application.js"/>
    <asset:link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
</head>
</code>```

Hopefully that helps you get started with loading Bootstrap via the asset pipeline.

Body:
To follow best practices use the Grails Asset Pipeline. It may take a bit of practice to understand how the pipeline works but the general ideas are highlighted well in this SO Answer. The pipeline will create folders for your assets, (css, javascript, images for example) and you need to place your bootstrap files in the proper locations. Make sure you remember that Bootstrap requires jQuery.

Please note that all JavaScript plugins require jQuery...

So be sure to include jQuery in your javascript folder. The other concept to grasp is creating the manifest file. For javascript assets it might look similar to:

Example file path:

grails-app/assets/javascripts/application.js

Example file contents:

//This is a JavaScript file with its top level require directives
//= require jquery
//= require app/models.js
//= require_tree views
//= require_self
console.log("This is my javascript manifest");

Then in the view you would like to uses the assets in, include the bootstrap assets by declaring:

<head>
    <asset:stylesheet href="application.css"/> //This assumes the standard pipeline path
    <asset:javascript src="application.js"/>
    <asset:link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
</head>

Hopefully that helps you get started with loading Bootstrap via the asset pipeline.


问:
How does the following class have to look for desired output?
```<code>class Answer{
  //insert code here
}

let answer = new Answer();

console.log( +answer === 20 ); //this should return true
</code>```

What do I have to write in my class in order to get the desired output?

答:
Ahh yes, good old valueOf. The valueOf property when defined converts an object into a number when called upon.

In your situation all you have to do is create a valueOf function in your Answer class and have it return 20. e.g.

```<code>class Answer{

   valueOf () {
       return 20;
   }
}

let answer = new Answer();

console.log( +answer === 20 ); //this should re
</code>```

Hope that helps!

Body:
class Answer{
  //insert code here
}

let answer = new Answer();

console.log( +answer === 20 ); //this should return true

What do I have to write in my class in order to get the desired output?

Body:
Ahh yes, good old valueOf. The valueOf property when defined converts an object into a number when called upon.

In your situation all you have to do is create a valueOf function in your Answer class and have it return 20. e.g.

class Answer{

   valueOf () {
       return 20;
   }
}

let answer = new Answer();

console.log( +answer === 20 ); //this should re

Hope that helps!


问:
Not receiving a response from Dynamics CRM Server web Api
I am not getting a response from a Dynamics CRM web server, and was wondering if there is anything wrong with my below code. I am building a JSON payload and sending the request to a server using WEB API endpoint</p>

```<code>using (HttpClient httpClient = new HttpClient()) {
    Uri requesturi = new Uri(string.Format("{0}/api/data/v8.2",url));
    httpClient.BaseAddress = requesturi;
    httpClient.Timeout = new TimeSpan(0, 10, 0);  // 10 minutes
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, string.Format("/contacts",contact));
    request.Content = new StringContent(props.ToString(), Encoding.UTF8, "application/json");
    HttpResponseMessage createResponse1 = await httpClient.SendAsync(request);
    return createResponse1.StatusCode;
}
</code>```

答:
Lower the following line.

Old

```<code>httpClient.Timeout = new TimeSpan(0, 10, 0); // 10 minutes
</code>```

New

```<code>httpClient.Timeout = new TimeSpan(0, 0, 10); // 10 seconds
</code>```

10 minutes is an amazingly long time to wait for request to complete. 30 seconds is an eternity for a web service request.

As you have specified such a long timeout if there is a transient error or lookup issue you will need to wait 10 minutes for it to timeout.

Chances are you will now get an error or exception from the code.

Body:
I am not getting a response from a Dynamics CRM web server, and was wondering if there is anything wrong with my below code. I am building a JSON payload and sending the request to a server using WEB API endpoint

using (HttpClient httpClient = new HttpClient()) {
    Uri requesturi = new Uri(string.Format("{0}/api/data/v8.2",url));
    httpClient.BaseAddress = requesturi;
    httpClient.Timeout = new TimeSpan(0, 10, 0);  // 10 minutes
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, string.Format("/contacts",contact));
    request.Content = new StringContent(props.ToString(), Encoding.UTF8, "application/json");
    HttpResponseMessage createResponse1 = await httpClient.SendAsync(request);
    return createResponse1.StatusCode;
}

Body:
Lower the following line.

Old

httpClient.Timeout = new TimeSpan(0, 10, 0); // 10 minutes

New

httpClient.Timeout = new TimeSpan(0, 0, 10); // 10 seconds

10 minutes is an amazingly long time to wait for request to complete. 30 seconds is an eternity for a web service request.

As you have specified such a long timeout if there is a transient error or lookup issue you will need to wait 10 minutes for it to timeout.

Chances are you will now get an error or exception from the code.


问:
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.

答:
$name contain the name of property nothing else

instead of just mentioning the property statically it is pointing to the variable which contain the name of property

```<code>$name='someproperty';

$this->$name;
</code>```

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.

Body:
$name contain the name of property nothing else

instead of just mentioning the property statically it is pointing to the variable which contain the name of property

$name='someproperty';

$this->$name;


问:
Notice unread messages
Im trying to notice the new unreaded messages on my chat. I'm using a bundle  and I create my own friendlist.Then on my chat view I can choice which user I want to chat with. I will show you my code cause I didn't get errors and I'm not sure why this don't work.

I got a column on my table called reading that works with a boolean and set a 0 if its an unread message.

ChatController.php

On my indexAction I made this :

```<code>` $userConnected= $this->container->get('security.token_storage')->getToken()->getUser();

    $friends= $em->getRepository(Agenda::class)->findByIdUsuari($userConnected);

    $messages=  $em->getRepository(Messages::class)->findByAddressee($userConnected);

    $newmessage= array();
    foreach ($messages as $value) {
        if ($value->getReading() == 0) {
            $newmessage= $value->getAuthor()->getId();
        }
     }
</code>```

On my view I print the users and form.

That's where I print Users :

```<code> <div id="selectUser">
        {% for user in users %}
            {% if user.id != currentUser.id %}
                <a href="" onclick="return false;" data-number="{{ user.id }}" class="changeUser" >{{ user.username }}</a>
            {% endif %}
        {% endfor %}
    </div>
</code>```

How can I implement that if the User's id of my list are the same as I saved on my variable $newmessage ???. I want that if got the same id, that means that got a 0 and he don't read the message so if I can check that I'll implement a class that will change the color of user's name.

UPDATE :

It seems that didnt work cause it sets Reading value to 1 and I don't know why cause on AjaxController it sets on 0 when I Send the message and change to 1 when user read it.

Controller:

https://pastebin.com/6LZ1FVG2

答:
When you render your page inside your controller, you need to pass the variable into an array like this:

```<code>$this->render('default/index.html.twig', array(
    'newmessage' => $newmessage,
));
</code>```

After in your twig you can use newmessage variable like this for example

```<code>{% if user.id == newmessage %}
</code>```

Title: Notice unread messages

Body:
Im trying to notice the new unreaded messages on my chat. I'm using a bundle  and I create my own friendlist.Then on my chat view I can choice which user I want to chat with. I will show you my code cause I didn't get errors and I'm not sure why this don't work.

I got a column on my table called reading that works with a boolean and set a 0 if its an unread message.

ChatController.php

On my indexAction I made this :

` $userConnected= $this->container->get('security.token_storage')->getToken()->getUser();

    $friends= $em->getRepository(Agenda::class)->findByIdUsuari($userConnected);

    $messages=  $em->getRepository(Messages::class)->findByAddressee($userConnected);

    $newmessage= array();
    foreach ($messages as $value) {
        if ($value->getReading() == 0) {
            $newmessage= $value->getAuthor()->getId();
        }
     }

On my view I print the users and form.

That's where I print Users :

        {% for user in users %}
            {% if user.id != currentUser.id %}
                {{ user.username }}
            {% endif %}
        {% endfor %}

How can I implement that if the User's id of my list are the same as I saved on my variable $newmessage ???. I want that if got the same id, that means that got a 0 and he don't read the message so if I can check that I'll implement a class that will change the color of user's name.

UPDATE :

It seems that didnt work cause it sets Reading value to 1 and I don't know why cause on AjaxController it sets on 0 when I Send the message and change to 1 when user read it.

Controller:

https://pastebin.com/6LZ1FVG2

Body:
When you render your page inside your controller, you need to pass the variable into an array like this:

$this->render('default/index.html.twig', array(
    'newmessage' => $newmessage,
));

After in your twig you can use newmessage variable like this for example

{% if user.id == newmessage %}