问:
How to pass argument for function in controller from view
I have function in controller with one argument and now I want to pass value for it from view through url.

courses.php

```<code>public function index($id){
   print_r();
   exit;
}
</code>```

coursesview.php

```<code><a class="jscroll-next" href="<?php echo base_url(); ?>/courses/index?page=<?php echo $nextPage; ?>&id=<?php echo $parentId ?>">next page</a>
</code>```

How it possible?

答:
You are going to use minimum arguments in URL, here is my suggestions

```<code>1.<a class="jscroll-next" href="<?php echo base_url('courses/$nextPage/$parentId/'); ?>">next page</a> //controller followed by arguments -  if you call index method

(OR)

2.<a class="jscroll-next" href="<?php echo base_url('courses/methodname/$nextPage/$parentId/'); ?>">next page</a> //controller,method name and followed by arguments
</code>```

How to get those arguments in controller
Example:

```<code>$nextPage =  $this->uri->segment(3);
$parentId =  $this->uri->segment(4);
</code>```

Body:
I have function in controller with one argument and now I want to pass value for it from view through url.

courses.php

public function index($id){
   print_r();
   exit;
}

coursesview.php

<a class="jscroll-next" href="<?php echo base_url(); ?>/courses/index?page=<?php echo $nextPage; ?>&id=<?php echo $parentId ?>">next page

How it possible?

Body:
You are going to use minimum arguments in URL, here is my suggestions

1.<a class="jscroll-next" href="<?php echo base_url('courses/$nextPage/$parentId/'); ?>">next page</a> //controller followed by arguments -  if you call index method

(OR)

2.<a class="jscroll-next" href="<?php echo base_url('courses/methodname/$nextPage/$parentId/'); ?>">next page</a> //controller,method name and followed by arguments

How to get those arguments in controller
Example:

$nextPage =  $this->uri->segment(3);
$parentId =  $this->uri->segment(4);


来源: stackexchange

问:
How to restrict user to entering only "Y" or "N" in a single column
I want to restrict user entry in column A and column D.

In column A, the user should enter the values as R00yyyyyy where yyyyyy is a number between 000000 and 999999.

In column D they should only enter y or n.

My code below doesn't seem to work properly. The column A part works fine, just having issues with column D.

Can anyone suggest a way to enable restricting the entry in column D?

```<code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub
</code>```

答:
You can try this code below. It checks to see if the change was in either column A or column D and exits if neither column was changed.

Then you know that the change was in either column A or column D and check exactly which column. Then you do the appropriate check and show the appropriate message box depending on the input.

To check for a simple pattern like R00yyyyyy where y is a number you can use the Like operator and use # as a placeholder for 'any number'.

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rngCell As Range

    ' exit if change was not in column A and not in column D
    If Intersect(Target, Range("A:A,D:D")) Is Nothing Then Exit Sub

    ' get first cell of change
    Set rngCell = Target.Cells(1, 1)

    ' disable events
    Application.EnableEvents = False

    ' now check if change in column A
    If rngCell.Column = 1 Then
        If Not rngCell.Value Like "R00######" Then
            MsgBox "Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999"
            rngCell.Clear
        End If
    Else 'must have been in column D
        If rngCell.Value <> "y" And rngCell.Value <> "n" Then
            MsgBox "The only allowable entry here is Y or N"
            rngCell.Clear
        End If
    End If

    ' re-enable events
    Application.EnableEvents = True

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to restrict user entry in column A and column D.

In column A, the user should enter the values as R00yyyyyy where yyyyyy is a number between 000000 and 999999.

In column D they should only enter y or n.

My code below doesn't seem to work properly. The column A part works fine, just having issues with column D.

Can anyone suggest a way to enable restricting the entry in column D?

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub

Body:
You can try this code below. It checks to see if the change was in either column A or column D and exits if neither column was changed.

Then you know that the change was in either column A or column D and check exactly which column. Then you do the appropriate check and show the appropriate message box depending on the input.

To check for a simple pattern like R00yyyyyy where y is a number you can use the Like operator and use # as a placeholder for 'any number'.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rngCell As Range

    ' exit if change was not in column A and not in column D
    If Intersect(Target, Range("A:A,D:D")) Is Nothing Then Exit Sub

    ' get first cell of change
    Set rngCell = Target.Cells(1, 1)

    ' disable events
    Application.EnableEvents = False

    ' now check if change in column A
    If rngCell.Column = 1 Then
        If Not rngCell.Value Like "R00######" Then
            MsgBox "Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999"
            rngCell.Clear
        End If
    Else 'must have been in column D
        If rngCell.Value <> "y" And rngCell.Value <> "n" Then
            MsgBox "The only allowable entry here is Y or N"
            rngCell.Clear
        End If
    End If

    ' re-enable events
    Application.EnableEvents = True

End Sub


问:
PHP substr but keep HTML tags?
I am wondering if there is an elegant way to trim some text but while being HTML tag aware?

For example, I have this string:

```<code>$data = '<strong>some title text here that could get very long</strong>';
</code>```

And let's say I need to return/output this string on a page but would like it to be no more than X characters.  Let's say 35 for this example.

Then I use:

```<code>$output = substr($data,0,20);
</code>```

But now I end up with:

```<code><strong>some title text here that
</code>```

which as you can see the closing strong tags are discarded thus breaking the HTML display.

Is there a way around this?  Also note that it is possible to have multiple tags in the string for example:

```<code><p>some text here <strong>and here</strong></p>
</code>```

答:
Using @newbieuser his function, I had the same issue, like @pablo-pazos, that it was (not) breaking when $limit fell into an html tag (in my case
 at the r)

Fixed with some code

```<code>if ( strlen($code) <= $limit ){
    return $code;
}

$html = substr($code, 0, $limit);

//We must find a . or > or space so we are sure not being in a html-tag!
//In my case there are only <br>
//If you have more tags, or html formatted text, you must do a little more and also use something like http://htmlpurifier.org/demo.php

$_find_last_char = strrpos($html, ".")+1;
if($_find_last_char > $limit/3*2){
    $html_break = $_find_last_char;
}else{
    $_find_last_char = strrpos($html, ">")+1;
    if($_find_last_char > $limit/3*2){
        $html_break = $_find_last_char;
    }else{
        $html_break = strrpos($html, " ");
    }
}

$html = substr($html, 0, $html_break);
preg_match_all ( "#<([a-zA-Z]+)#", $html, $result );
......
</code>```

Title: PHP substr but keep HTML tags?

Body:
I am wondering if there is an elegant way to trim some text but while being HTML tag aware?

For example, I have this string:

$data = 'some title text here that could get very long';

And let's say I need to return/output this string on a page but would like it to be no more than X characters.  Let's say 35 for this example.

Then I use:

$output = substr($data,0,20);

But now I end up with:

some title text here that

which as you can see the closing strong tags are discarded thus breaking the HTML display.

Is there a way around this?  Also note that it is possible to have multiple tags in the string for example:

some text here and here

Body:
Using @newbieuser his function, I had the same issue, like @pablo-pazos, that it was (not) breaking when $limit fell into an html tag (in my case <br /> at the r)

Fixed with some code

if ( strlen($code) <= $limit ){
    return $code;
}

$html = substr($code, 0, $limit);

//We must find a . or > or space so we are sure not being in a html-tag!
//In my case there are only <br>
//If you have more tags, or html formatted text, you must do a little more and also use something like http://htmlpurifier.org/demo.php

$_find_last_char = strrpos($html, ".")+1;
if($_find_last_char > $limit/3*2){
    $html_break = $_find_last_char;
}else{
    $_find_last_char = strrpos($html, ">")+1;
    if($_find_last_char > $limit/3*2){
        $html_break = $_find_last_char;
    }else{
        $html_break = strrpos($html, " ");
    }
}

$html = substr($html, 0, $html_break);
preg_match_all ( "#<([a-zA-Z]+)#", $html, $result );
......


问:
Typescript: Why am I able to allocate a string value to my declared (interface) number object parameter
I have declared an interface:

```<code>export interface DateArray {
    year    : number;
}
</code>```

and I am declaring a new variable in my component like so:

```<code>private dateArray: DateArray = {
    year: null
};
</code>```

and in my component I am assigning a value to dateArray.year like:

```<code>this.dateArray.year = this.megaData[0][3];
</code>```

Now what I do not understand is that no matter what the value of this.megaData[0][3] is (string, number, array), it gets assigned to this.dateArray.year without any problem.

When I do:

```<code> this.dateArray.year = "A"
</code>```

I get an error "can't assign string to number", but when the value of this.megaData[0][3] is "A", then I get no error, and the output of:

```<code>        this.dateArray.year = this.megaData[0][3];
        console.log("this.dateArray.year);
</code>```

is just A

this.megaData is just defined as <any> for now, is this maybe the problem?

答:
this.megaData is just defined as <any> for now, is this maybe the problem?

Correct as any means it could also be, or contain, a number (the declared type of property year) so the assignment will not generate a type mismatch error.

ContentLicense: CC BY-SA 4.0

Body:
I have declared an interface:

export interface DateArray {
    year    : number;
}

and I am declaring a new variable in my component like so:

private dateArray: DateArray = {
    year: null
};

and in my component I am assigning a value to dateArray.year like:

this.dateArray.year = this.megaData[0][3];

Now what I do not understand is that no matter what the value of this.megaData[0][3] is (string, number, array), it gets assigned to this.dateArray.year without any problem.

When I do:

 this.dateArray.year = "A"

I get an error "can't assign string to number", but when the value of this.megaData[0][3] is "A", then I get no error, and the output of:

        this.dateArray.year = this.megaData[0][3];
        console.log("this.dateArray.year);

is just A

this.megaData is just defined as <any> for now, is this maybe the problem?


问:
Angular 4 call function in another component
I have a search bar in a header component, that are supposed to search in a list in another component. How do i get the headerComponent to call a function in the BooksComponent?</p>

```<code>export class HeaderComponent {
    search(){
        searchBooks($(".header-search-input").val());
    }
}

export class BooksComponent {

  searchBooks(searchWord){
    ...
}
</code>```

答:
Create service with property type of Subject. Then inject it in both components. In HeaderComponent call Subject.next(val) when value in input change, in BooksComponent subscribe to this subject and call rest api.
Service with subject should be provided on module which declare both components.</p>

Body:
I have a search bar in a header component, that are supposed to search in a list in another component. How do i get the headerComponent to call a function in the BooksComponent?

export class HeaderComponent {
    search(){
        searchBooks($(".header-search-input").val());
    }
}

export class BooksComponent {

  searchBooks(searchWord){
    ...
}


问:
Project X targets '.NETStandard,Version=v1.6'. It cannot be referenced by a project that targets '.NETFramework,Version=v4.6.1'
I really wanted to be a good citizen... copied all my classes to .net standard 1.6 libraries. Just to find out that my test DLL can't use it. I get the following error

Project X targets '.NETStandard,Version=v1.6'. It cannot be referenced by a project that targets '.NETFramework,Version=v4.6.1'.

Of course, when I check .Net Standard (https://learn.microsoft.com/en-us/dotnet/articles/standard/library) it says that with 1.6 it can target 4.6.1.

I tried 4.6.2 without better luck. I installed the .net standard 1.6.1 NuGet package. Anyway, you guys are awesome, I'm sure you'll tell me which stupid mistake I'm making that is preventing me from doing something as basic as running unit tests with a .net standard library.

Thanks

P.S. I did find a work around (kind of) by using a .net core unit test project instead of a .net framework one. It doesn't solve my problem, so I can't mark that as an answer, but at least I can go back to coding...

答:
You need to upgrade to .Net Core SDK 2.x+

Once that is installed restart your machine and you should be able to reference NetStandard 1.6 in .Net Framework 4.6.1+

With .Net Core SDK 1.x you can only reference Net Standard 1.5 in .Net Framework 4.6.2

Best would be to upgrade your Net Standard project to version 2.0 if you can.


问:
How to replicate records using PLSQL in two tables
I have two existing tables and many records already added.

```<code>formula(formulaId,formulaName,formulaType)
and formula_detail(detailId,formulaId,fieldType,value)
</code>```

Now there is change in formula table and new column is being added , branchId as

```<code>formula(formulaId,formulaName,formulaType,branchId),

and branch table is branch(branchId,branchName)
</code>```

I want to copy and paste every existing record in formula table for every branch.
e.g if there are 3 existing records in formula table (with ID 1,2,3) and 2 branches. Then copy paste operation should produce total new (3*2)=6 records in formula table and also replicate records in formula_detail table for every newly created formula as follows

for formulaId 1 , If there were 5 records in formula_detail table, then copy paste in formual_detail table will have (2*5) new records added in formual_detail table.

I tried some solutions but number of are records huge and script is taking time. Please help. If need any test code I can add.

答:
First of all replicating same column in detail table is against the Normalized Form used in your Data model.

Still If you want to add the column anyway,

Add the column using ALTER statement in formula_detail table

Try using this Merge statement
.

MERGE INTO formula_detail fd
USING (SELECT formulaId, branchId from Formula) temp
ON (fd.formulaId=temp.formulaId)
WHEN MATCHED THEN
UPDATE SET fd.branchId=temp.branchId;

Body:
I have two existing tables and many records already added.

formula(formulaId,formulaName,formulaType)
and formula_detail(detailId,formulaId,fieldType,value)

Now there is change in formula table and new column is being added , branchId as

formula(formulaId,formulaName,formulaType,branchId),

and branch table is branch(branchId,branchName)

I want to copy and paste every existing record in formula table for every branch.
e.g if there are 3 existing records in formula table (with ID 1,2,3) and 2 branches. Then copy paste operation should produce total new (3*2)=6 records in formula table and also replicate records in formula_detail table for every newly created formula as follows

for formulaId 1 , If there were 5 records in formula_detail table, then copy paste in formual_detail table will have (2*5) new records added in formual_detail table.

I tried some solutions but number of are records huge and script is taking time. Please help. If need any test code I can add.


问:
Existing li gets overridden in todolist instead of adding a new li
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>spooky</h1>

<input type="text" class="input">
<ul>
  <li>1</li>
  <li>2</li>
</ul></code>```

答:
let input = document.querySelector(".input");
let ul = document.querySelector("ul");

let addNewFunc = function () {
  let addNew = document.createElement("li");
  addNew.innerHTML = input.value;
  let name = ul.appendChild(addNew);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>spooky</h1>
<input type="text" class="input"><button onclick='addNewFunc()'> add</button>
<ul>
    <li>1</li>
    <li>2</li>
</ul></code>```

Create new li element everytime on the function call, add value to it then append to ul element.

Body:
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};

spooky

<input type="text" class="input">

1

2

Body:
let input = document.querySelector(".input");
let ul = document.querySelector("ul");

let addNewFunc = function () {
  let addNew = document.createElement("li");
  addNew.innerHTML = input.value;
  let name = ul.appendChild(addNew);
};

<h1>spooky</h1>
<input type="text" class="input"><button onclick='addNewFunc()'> add</button>
<ul>
    <li>1</li>
    <li>2</li>
</ul>

Create new li element everytime on the function call, add value to it then append to ul element.


问:
How to replace/change the icon of an action bar item
I hope you can give me a hand on this one.

I have an Action bar item with a default icon set.(android:icon="@drawable/ic_action_volume_on")
but the thing is that i need to change it somehow programmatically at my method "onOptionsItemSelected"  and since I recently started with Android I'm a bit lost...

答:
You can do this simply by defining

```<code>private Menu menu;
</code>```

and in onCreateOptionMenu callback assign value to menu and get menu inflater like this

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu=menu;
    getMenuInflater().inflate(R.menu.menu_bar, menu);
    return true;
}
</code>```

And finally you can write this line to change icon in your preferred method

```<code>menu.findItem(R.id.item_id).setIcon(R.drawable.your_icon);
</code>```

Body:
You can do this simply by defining

private Menu menu;

and in onCreateOptionMenu callback assign value to menu and get menu inflater like this

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu=menu;
    getMenuInflater().inflate(R.menu.menu_bar, menu);
    return true;
}

And finally you can write this line to change icon in your preferred method

menu.findItem(R.id.item_id).setIcon(R.drawable.your_icon);


问:
Why does not onupdate run on iTween?
I'm implementing a card-matching game.

The event will be sent after the card is first deployed.

```<code>public void cardFlipStateUpdate()
{
    foreach (Card card in cardAllInformation[current_pageNumber])
    {
        GameObject card_gameObj = cardAllGameObject[current_pageNumber][card.cardIndex] as GameObject;

        int c_idx = card.cardIndex;
        int c_uidx = card.cardUniqueIndex;

        float delay_s = c_idx * 0.15f;
        float delay_r = 2.5f + c_idx * 0.15f;

        TouchEventManager.Instance.dispatch(c_idx, c_uidx, card_gameObj, card, true, "none", delay_s);
        TouchEventManager.Instance.dispatch(c_idx, c_uidx, card_gameObj, card, true, "cardSelectionCriteria", delay_r);
    }
}

public void onTuchHandler(object obj, EventArgs e)
{
    TouchEventTypes t_evt = e as TouchEventTypes;

    WordReviewUtil.cardFlipAnimation(t_evt.card_idx, t_evt.card_selectNum, t_evt.go, t_evt.card, t_evt.init, t_evt.complete, t_evt.delay);
}
</code>```

Here is the code for receiving the above event.

```<code>   public static void cardFlipAnimation(int card_idx, int card_selectNum, GameObject gobj, Card card, bool init = false, string complete = "cardDifferentiate", float delay = 0f)
    {
        Hashtable data = new Hashtable();
    //    Debug.Log("cardFlipAnimation Receive Param >> " + card_idx + " / " + card_selectNum + " / " + gobj + " / ");
    //    Debug.Log("cardFlipAnimation Receive Param >> " + card + " / " + init + " / " + complete + " / " + delay);
    //    Debug.Log("============================================================================================");
        data.Add("gobj", gobj);
        data.Add("card", card);

        Hashtable run_hash = new Hashtable();
        run_hash.Add("y", 0.5);
        run_hash.Add("time", 0.7);
        run_hash.Add("delay", delay);
        run_hash.Add("easetype", iTween.EaseType.easeInOutCubic);
        run_hash.Add("onupdate", "test");
        run_hash.Add("onupdatetarget", gobj);
        run_hash.Add("onupdateparams", data);
        run_hash.Add("oncomplete", complete);
        run_hash.Add("oncompletetarget", gobj);

        //Debug.Log("run_hash >> " + run_hash);

        iTween.RotateBy(gobj, run_hash);
    }
</code>```

I created a temporary function to check that the above code works well.
(("onupdate", "test");)

```<code>public void test()
{
   Debug.Log("hello Moto~~");
}
</code>```

But the log can't be verified.

I can't find the cause.

What did you write wrong? And how to solve it?

Your comments are valuable. Please help me.

答:
I believe you are creating the hashtable assuming that iTween uses the standard one, but it never worked for me. Try calling RotateBy using this instead:

```<code>iTween.RotateBy( gobj, iTween.Hash(
     "y", 0.5,
     "time", 0.7,
     "delay", delay,
     "easetype", iTween.EaseType.easeInOutCubic,
     "onupdate", "test",
     "onupdatetarget", gobj,
     "onupdateparams", data,
     "oncomplete", complete,
     "oncompletetarget", gobj
));
</code>```

EDIT: The method Test in the code has no parameters, while here you want to pass data as a param: that will break it.

Title: Why does not onupdate run on iTween?

Body:
I'm implementing a card-matching game.

The event will be sent after the card is first deployed.

public void cardFlipStateUpdate()
{
    foreach (Card card in cardAllInformation[current_pageNumber])
    {
        GameObject card_gameObj = cardAllGameObject[current_pageNumber][card.cardIndex] as GameObject;

        int c_idx = card.cardIndex;
        int c_uidx = card.cardUniqueIndex;

        float delay_s = c_idx * 0.15f;
        float delay_r = 2.5f + c_idx * 0.15f;

        TouchEventManager.Instance.dispatch(c_idx, c_uidx, card_gameObj, card, true, "none", delay_s);
        TouchEventManager.Instance.dispatch(c_idx, c_uidx, card_gameObj, card, true, "cardSelectionCriteria", delay_r);
    }
}

public void onTuchHandler(object obj, EventArgs e)
{
    TouchEventTypes t_evt = e as TouchEventTypes;

    WordReviewUtil.cardFlipAnimation(t_evt.card_idx, t_evt.card_selectNum, t_evt.go, t_evt.card, t_evt.init, t_evt.complete, t_evt.delay);
}

Here is the code for receiving the above event.

   public static void cardFlipAnimation(int card_idx, int card_selectNum, GameObject gobj, Card card, bool init = false, string complete = "cardDifferentiate", float delay = 0f)
    {
        Hashtable data = new Hashtable();
    //    Debug.Log("cardFlipAnimation Receive Param >> " + card_idx + " / " + card_selectNum + " / " + gobj + " / ");
    //    Debug.Log("cardFlipAnimation Receive Param >> " + card + " / " + init + " / " + complete + " / " + delay);
    //    Debug.Log("============================================================================================");
        data.Add("gobj", gobj);
        data.Add("card", card);

        Hashtable run_hash = new Hashtable();
        run_hash.Add("y", 0.5);
        run_hash.Add("time", 0.7);
        run_hash.Add("delay", delay);
        run_hash.Add("easetype", iTween.EaseType.easeInOutCubic);
        run_hash.Add("onupdate", "test");
        run_hash.Add("onupdatetarget", gobj);
        run_hash.Add("onupdateparams", data);
        run_hash.Add("oncomplete", complete);
        run_hash.Add("oncompletetarget", gobj);

        //Debug.Log("run_hash >> " + run_hash);

        iTween.RotateBy(gobj, run_hash);
    }

I created a temporary function to check that the above code works well.
(("onupdate", "test");)

public void test()
{
   Debug.Log("hello Moto~~");
}

But the log can't be verified.

I can't find the cause.

What did you write wrong? And how to solve it?

Your comments are valuable. Please help me.

Body:
I believe you are creating the hashtable assuming that iTween uses the standard one, but it never worked for me. Try calling RotateBy using this instead:

iTween.RotateBy( gobj, iTween.Hash(
     "y", 0.5,
     "time", 0.7,
     "delay", delay,
     "easetype", iTween.EaseType.easeInOutCubic,
     "onupdate", "test",
     "onupdatetarget", gobj,
     "onupdateparams", data,
     "oncomplete", complete,
     "oncompletetarget", gobj
));

EDIT: The method Test in the code has no parameters, while here you want to pass data as a param: that will break it.


问:
Access device compass from web app with Javascript
Is it possible to access the compass with Javascript on an iphone/ android device from a web app? Have been looking all over the net for hours I know you can access the accelerometer with

window.ondevicemotion = function(event)

Does anyone know if you can access the information from the compass??

答:
It looks to be cross platform now, check this excellent article by Ruadhán O'Donoghue.

For Android, it still uses window.addEventListener('deviceorientation', ...) but check for other event properties (event.alpha which is compass orientation ; beta and gamma are also available, which represent the tilting).

Here are the relevant parts (adapted) if the link becomes unavailable:

```<code>   if(window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', function(event) {
        var alpha;
        // Check for iOS property
        if(event.webkitCompassHeading) {
          alpha = event.webkitCompassHeading;
        }
        // non iOS
        else {
          alpha = event.alpha;
          if(!window.chrome) {
            // Assume Android stock
            alpha = alpha-270;
          }
        }
      }
    }
</code>```

Another usage example is available on CodePen.

Body:
It looks to be cross platform now, check this excellent article by Ruadhán O'Donoghue.

For Android, it still uses window.addEventListener('deviceorientation', ...) but check for other event properties (event.alpha which is compass orientation ; beta and gamma are also available, which represent the tilting).

Here are the relevant parts (adapted) if the link becomes unavailable:

   if(window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', function(event) {
        var alpha;
        // Check for iOS property
        if(event.webkitCompassHeading) {
          alpha = event.webkitCompassHeading;
        }
        // non iOS
        else {
          alpha = event.alpha;
          if(!window.chrome) {
            // Assume Android stock
            alpha = alpha-270;
          }
        }
      }
    }

Another usage example is available on CodePen.


问:
A computer with two network adapter is scanned by Arp
I've got a computer with two network adapter, both of them is assigned a different IP.(EX:192.168.81.90, 192.168.81.93)

And I use ARP scan from 192.168.81.1 to 192.168.81.255, I will get two different MAC addresses and two different IPs.

Is it possible to recognize these pairs of MAC address + IP belonging to the same host?

答: "Is it possible to recognize these pairs of mac address + IP belong to the same host?" - No, that's not possible unless there's a higher layer protocol providing this information. You can't go by IP address and MAC alone.</p>


问:
How to debug dylib with Xcode?
I have a Xcode project for library arith.
I could build it with debug configuration, and I need to debug it. How can I do that?

The ideal method would be to set up a test code to build an execution in a project file, and then set a breakpoint in a source code in arith library.

However, it seems that Xcode arith project doesn't allow to add another use_arith project that uses the arith library.

What method people use to debug a dynamic library in Xcode?

ADDED

I googled and found some ways to debug dll. Attaching to a running process can be one way of debugging dynamic library. And, for iPhone/iPad programming dynamic library is not allowed, so static library is used.

Attaching to a Running Process - http://gcc.gnu.org/onlinedocs/gnat_ugn_unw/Attaching-to-a-Running-Process.html

Debugging a library with Xcode - Debugging a library with Xcode

Easy, Modular Code Sharing Across iPhone Apps: Static Libraries and Cross-Project References - http://www.clintharris.net/2009/iphone-app-shared-libraries/

答:
I could find a way to debug dynamic library in Xcode.

Build

Make a library, I'll call this arith library. Debug build to make libarith.dylib.

Make a project to use the library, I'll call this usearith.

For userarith, Project->Add To Project, and add the arith library.

Open Project info, and open the Build tab.

Go to Search Paths/Library Search Paths, drag and drop the arith library. You should remove the library name as you need only specify the path. Specify the header directory with 'Header Search Paths'.

Go to Linking, set Other Linker Flags, add -larith

Running

Now, you should be able to link the execution binary to the library.
For running, you need to copy the dynamic library to the directory where the execution binary is located.

Debugging

You need to set the breakpoints both arith/usearith.
You can run debugger in arith and use the step into to debug the code in a arith project.

Title: How to debug dylib with Xcode?

ContentLicense: CC BY-SA 2.5


问:
How to copy the value of a cell that contains a formula into another cell?
In Column A, I use a API that goes out to the web and returns a stock price.

I want to then copy just the stock price (not the formula) automatically into the cell next to it.  I  know I can copy special but I want this to occur automatically.  I'm looking for a Macro to do this.

Thanks

答:
```<code> Sub Demo
 columns("a").copy
 range("b1").pastespecial xlpastevalues
End Sub
</code>```


问:
Angular 2 / Material - md-error not displayed with custom validator applied to parent FormGroup
I am having some trouble getting validation errors to display on a model driven form with Angular (v4.3.6).

In my model, I have the following:

```<code>this.registerForm = formBuilder.group({
        'email':[null,Validators.compose([Validators.required, ValidateEmail])],
        'firstName':[null, Validators.required],
        'lastName':[null, Validators.required],
        'passwordGroup': formBuilder.group({
            'password':[null, Validators.compose([Validators.required,Validators.minLength(8)])],
            'passwordConfirmation':[null, Validators.required],
        },{validator: ValidatePasswordConfirmation})
    });
</code>```

The ValidatePasswordConfirmation custom validator referenced is as follows:

```<code>export function ValidatePasswordConfirmation(group: FormGroup) {

    if(group.value.password !== group.value.passwordConfirmation){
        return { 'no-match':true };
    }

    return null;
}
</code>```

Lastly, in my template I have the following:

```<code><md-form-field>
  <input mdInput name="passwordConfirmation" placeholder="Confirm password" [formControl]="registerForm.controls['passwordGroup'].controls['passwordConfirmation']" [(ngModel)]="model.passwordConfirmation" type="password">

<md-error *ngIf="registerForm.controls['passwordGroup'].controls['passwordConfirmation'].hasError('required')">
    Password confirmation is required
  </md-error>

<md-error *ngIf="registerForm.controls['passwordGroup'].hasError('no-match')">
    Passwords don't match
  </md-error>

</md-form-field>
</code>```

However, the md-error governed by the 'no-match' error never shows up. So, to debug this on the page I added the following:

```<code>no-match = {{registerForm.controls['passwordGroup'].hasError('no-match')}}
invalid = {{registerForm.controls['passwordGroup'].invalid}}
</code>```

Unsurprisingly, the debug lines show true/false as you would expect. However, the 'md-error' is never displayed... except for when the 'required' error is shown. I have a feeling that the issue is due to the [formControl] referring to the passwordConfirmation FormControl, and so without that being invalid, the md-error is not shown. However, I would like this error to display when the outer FormGroup is invalid.

Any pointers on where I'm going wrong here would be really helpful!

Finally, I have tried a few other ways around this such as setting the error on the PasswordConfirmation FormControl, which works, but I would like to know why my current implementation is failing.

答:
I found that I was able to solve the exact same issue using a custom ErrorStateMatcher (the default one requires the control to be in an invalid state before showing any errors)

```<code>export class ParentErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = !!(form && form.submitted);
        const controlTouched = !!(control && (control.dirty || control.touched));
        const controlInvalid = !!(control && control.invalid);
        const parentInvalid = !!(control && control.parent && control.parent.invalid && (control.parent.dirty || control.parent.touched));

        return isSubmitted || (controlTouched && (controlInvalid || parentInvalid));
    }
}
</code>```

This is exposed as a variable on my page component like so...

```<code>@Component({
    templateUrl: 'register.page.component.html',
    styleUrls: ['register.page.styles.css']
})
export class RegisterPageComponent implements OnInit {
    registerForm: FormGroup;
    parentErrorStateMatcher = new ParentErrorStateMatcher();

    // Accessors
    get name() { return this.registerForm.get('name'); }
    get email() { return this.registerForm.get('email'); }
    get passwords() { return this.registerForm.get('passwords'); }
    get password() { return this.registerForm.get('passwords.password'); }
    get confirmPassword() { return this.registerForm.get('passwords.confirmPassword'); }
...
</code>```

With this form...

```<code>this.registerForm = this.formBuilder.group({
        name: ['', [
            Validators.required,
            Validators.maxLength(256)]
        ],
        email: ['', [
            Validators.email,
            Validators.required,
            Validators.maxLength(256)]
        ],
        passwords: this.formBuilder.group({
            password: ['', [
                Validators.required,
                Validators.maxLength(128)
            ]],
            confirmPassword: ['', [
                Validators.required
            ]]
        },
            {
                validator: CustomValidators.doNotMatch('password', 'confirmPassword')
            }),
    });
</code>```

And this mark-up for the password fields (see errorStateMatcher and the last mat-error for the confirmPassword input control)...

```<code><div formGroupName="passwords">
    <mat-form-field class="full-width">
        <input matInput placeholder="Password" type="password" name="password" id="password" formControlName="password" required/>
        <mat-error *ngIf="password.errors && password.errors.required">
            Please enter your password
        </mat-error>
        <mat-error *ngIf="password.errors && password.errors.maxLength">
            Password must be less than 128 characters long
        </mat-error>
    </mat-form-field>

    <mat-form-field class="full-width">
        <input matInput placeholder="Confirm Password" type="password" name="confirmPassword" id="confirmPassword" formControlName="confirmPassword" required
            [errorStateMatcher]="parentErrorStateMatcher"/>
        <mat-error *ngIf="confirmPassword.errors && confirmPassword.errors.required">
            Please confirm your password
        </mat-error>
        <mat-error *ngIf="passwords.errors && passwords.errors.doNotMatch">
            Passwords do not match
        </mat-error>
    </mat-form-field>
</div>
</code>```

Feels more marginally more confusing than when I wasn't using Material but I'm happy for the trade-off and really the only extra code is the custom matcher :)

Body:
I am having some trouble getting validation errors to display on a model driven form with Angular (v4.3.6).

In my model, I have the following:

this.registerForm = formBuilder.group({
        'email':[null,Validators.compose([Validators.required, ValidateEmail])],
        'firstName':[null, Validators.required],
        'lastName':[null, Validators.required],
        'passwordGroup': formBuilder.group({
            'password':[null, Validators.compose([Validators.required,Validators.minLength(8)])],
            'passwordConfirmation':[null, Validators.required],
        },{validator: ValidatePasswordConfirmation})
    });

The ValidatePasswordConfirmation custom validator referenced is as follows:

export function ValidatePasswordConfirmation(group: FormGroup) {

    if(group.value.password !== group.value.passwordConfirmation){
        return { 'no-match':true };
    }

    return null;
}

Lastly, in my template I have the following:

<md-form-field>
  <input mdInput name="passwordConfirmation" placeholder="Confirm password" [formControl]="registerForm.controls['passwordGroup'].controls['passwordConfirmation']" [(ngModel)]="model.passwordConfirmation" type="password">

<md-error *ngIf="registerForm.controls['passwordGroup'].controls['passwordConfirmation'].hasError('required')">
    Password confirmation is required
  </md-error>

<md-error *ngIf="registerForm.controls['passwordGroup'].hasError('no-match')">
    Passwords don't match
  </md-error>

</md-form-field>

However, the md-error governed by the 'no-match' error never shows up. So, to debug this on the page I added the following:

no-match = {{registerForm.controls['passwordGroup'].hasError('no-match')}}
invalid = {{registerForm.controls['passwordGroup'].invalid}}

Unsurprisingly, the debug lines show true/false as you would expect. However, the 'md-error' is never displayed... except for when the 'required' error is shown. I have a feeling that the issue is due to the [formControl] referring to the passwordConfirmation FormControl, and so without that being invalid, the md-error is not shown. However, I would like this error to display when the outer FormGroup is invalid.

Any pointers on where I'm going wrong here would be really helpful!

Finally, I have tried a few other ways around this such as setting the error on the PasswordConfirmation FormControl, which works, but I would like to know why my current implementation is failing.

Body:
I found that I was able to solve the exact same issue using a custom ErrorStateMatcher (the default one requires the control to be in an invalid state before showing any errors)

export class ParentErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = !!(form && form.submitted);
        const controlTouched = !!(control && (control.dirty || control.touched));
        const controlInvalid = !!(control && control.invalid);
        const parentInvalid = !!(control && control.parent && control.parent.invalid && (control.parent.dirty || control.parent.touched));

        return isSubmitted || (controlTouched && (controlInvalid || parentInvalid));
    }
}

This is exposed as a variable on my page component like so...

@Component({
    templateUrl: 'register.page.component.html',
    styleUrls: ['register.page.styles.css']
})
export class RegisterPageComponent implements OnInit {
    registerForm: FormGroup;
    parentErrorStateMatcher = new ParentErrorStateMatcher();

    // Accessors
    get name() { return this.registerForm.get('name'); }
    get email() { return this.registerForm.get('email'); }
    get passwords() { return this.registerForm.get('passwords'); }
    get password() { return this.registerForm.get('passwords.password'); }
    get confirmPassword() { return this.registerForm.get('passwords.confirmPassword'); }
...

With this form...

this.registerForm = this.formBuilder.group({
        name: ['', [
            Validators.required,
            Validators.maxLength(256)]
        ],
        email: ['', [
            Validators.email,
            Validators.required,
            Validators.maxLength(256)]
        ],
        passwords: this.formBuilder.group({
            password: ['', [
                Validators.required,
                Validators.maxLength(128)
            ]],
            confirmPassword: ['', [
                Validators.required
            ]]
        },
            {
                validator: CustomValidators.doNotMatch('password', 'confirmPassword')
            }),
    });

And this mark-up for the password fields (see errorStateMatcher and the last mat-error for the confirmPassword input control)...

<div formGroupName="passwords">
    <mat-form-field class="full-width">
        <input matInput placeholder="Password" type="password" name="password" id="password" formControlName="password" required/>
        <mat-error *ngIf="password.errors && password.errors.required">
            Please enter your password
        </mat-error>
        <mat-error *ngIf="password.errors && password.errors.maxLength">
            Password must be less than 128 characters long
        </mat-error>
    </mat-form-field>

    <mat-form-field class="full-width">
        <input matInput placeholder="Confirm Password" type="password" name="confirmPassword" id="confirmPassword" formControlName="confirmPassword" required
            [errorStateMatcher]="parentErrorStateMatcher"/>
        <mat-error *ngIf="confirmPassword.errors && confirmPassword.errors.required">
            Please confirm your password
        </mat-error>
        <mat-error *ngIf="passwords.errors && passwords.errors.doNotMatch">
            Passwords do not match
        </mat-error>
    </mat-form-field>
</div>

Feels more marginally more confusing than when I wasn't using Material but I'm happy for the trade-off and really the only extra code is the custom matcher :)


答:
You could move the search() function to a service and inject it into the component that need this function.

search.service.ts

```<code>@Injectable
export class SearchService {
  search() {
    ...
  }
}
</code>```

Injection

```<code>import { SearchService } from './search.service.ts';

export class HeaderComponent {
  constructor(public searchService SearchService) {}

  search() {
    this.searchService.search();
  }
}
</code>```

Title: Angular 4 call function in another component

Body:
You could move the search() function to a service and inject it into the component that need this function.

search.service.ts

@Injectable
export class SearchService {
  search() {
    ...
  }
}

Injection

import { SearchService } from './search.service.ts';

export class HeaderComponent {
  constructor(public searchService SearchService) {}

  search() {
    this.searchService.search();
  }
}


问:
Creating a New Animation Clip in unity?
I need to know how to make a simple animation video by using the unity game engine by using Animator Component, Animator Controller, Animation Clips.</p>

答:
My personal best way of doing so is selecting all the sprites you wish to animate at the hirerchy and dragging them to the editor scene.
Good luck!</p>

Title: Creating a New Animation Clip in unity?


问:
Laravel Undefined Property Error with Google Pagespeed API
I'm a beginner in using laravel. For my webapp I want to use the Google API PageSpeed. When visiting /pagespeed, it gives me this error: ErrorException (E_NOTICE)
Undefined property: stdClass::$ruleScore

Also I'm not sure if i made a correct return. I just want to show the meassured data on the /pagespeed page.

Couldn't really find an answer for my problem, I hope you can help.

I used the pagespeed.php code from https://gist.github.com/typhonius/6259822/revisions and put this in my PagespeedController:

```<code>public function pageSpeed(){
$url = 'https://www.facebook.com';
$key = 'my API key';
// View https://developers.google.com/speed/docs/insights/v1/getting_started#before_starting to get a key
$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&key=$key"));
$dat = $data->formattedResults->ruleResults;
foreach($dat as $d) {
  $name = $d->localizedRuleName;
  $score = $d->ruleScore;
  print "\nTest: " . $name . "\n";
  print "Score: " . $score . "\n";
  if ($score != 100) {
    if (isset($d->urlBlocks[0]->header->args)) {
      $advice_header = replace_placeholders($d->urlBlocks[0]->header->format, $d->urlBlocks[0]->header->args);
    }
    else {
      $advice_header = $d->urlBlocks[0]->header->format;
    }
    print "Advice: " . $advice_header . "\n";
    foreach ($d->urlBlocks[0]->urls as $url) {
      $advice = replace_placeholders($url->result->format, $url->result->args);
      print $advice . "\n";
    }
  }
};
function replace_placeholders($format, $args) {
  $i = 1;
  foreach ($args as $arg) {
    $format = str_replace("\$" . $i, "$arg->value", $format);
    $i++;
  }
  return view('pagespeed')->with('format');
}
</code>```

This is in my views folder: pagespeed.blade.php:

```<code>@extends('layouts.app')
@section('content')
<h1>Page Speed</h1>
@endsection
</code>```

This is my Route in web.php:

```<code>Route::get('/pagespeed', 'PagespeedController@pageSpeed');
</code>```

答:
Change this

```<code>$score = $d->ruleScore;
</code>```

to

```<code>$score = $d->score;
</code>```

Body:
I'm a beginner in using laravel. For my webapp I want to use the Google API PageSpeed. When visiting /pagespeed, it gives me this error: ErrorException (E_NOTICE)
Undefined property: stdClass::$ruleScore

Also I'm not sure if i made a correct return. I just want to show the meassured data on the /pagespeed page.

Couldn't really find an answer for my problem, I hope you can help.

I used the pagespeed.php code from https://gist.github.com/typhonius/6259822/revisions and put this in my PagespeedController:

public function pageSpeed(){
$url = 'https://www.facebook.com';
$key = 'my API key';
// View https://developers.google.com/speed/docs/insights/v1/getting_started#before_starting to get a key
$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&key=$key"));
$dat = $data->formattedResults->ruleResults;
foreach($dat as $d) {
  $name = $d->localizedRuleName;
  $score = $d->ruleScore;
  print "\nTest: " . $name . "\n";
  print "Score: " . $score . "\n";
  if ($score != 100) {
    if (isset($d->urlBlocks[0]->header->args)) {
      $advice_header = replace_placeholders($d->urlBlocks[0]->header->format, $d->urlBlocks[0]->header->args);
    }
    else {
      $advice_header = $d->urlBlocks[0]->header->format;
    }
    print "Advice: " . $advice_header . "\n";
    foreach ($d->urlBlocks[0]->urls as $url) {
      $advice = replace_placeholders($url->result->format, $url->result->args);
      print $advice . "\n";
    }
  }
};
function replace_placeholders($format, $args) {
  $i = 1;
  foreach ($args as $arg) {
    $format = str_replace("\$" . $i, "$arg->value", $format);
    $i++;
  }
  return view('pagespeed')->with('format');
}

This is in my views folder: pagespeed.blade.php:

@extends('layouts.app')
@section('content')

Page Speed

@endsection

This is my Route in web.php:

Route::get('/pagespeed', 'PagespeedController@pageSpeed');

Body:
Change this

$score = $d->ruleScore;

to

$score = $d->score;


答:
As mentioned in the comments, some labels in y_test don't appear in y_pred. Specifically in this case, label '2' is never predicted:

```<code>>>> set(y_test) - set(y_pred)
{2}
</code>```

This means that there is no F-score to calculate for this label, and thus the F-score for this case is considered to be 0.0. Since you requested an average of the score, you must take into account that a score of 0 was included in the calculation, and this is why scikit-learn is showing you that warning.

This brings me to you not seeing the error a second time. As I mentioned, this is a warning, which is treated differently from an error in python. The default behavior in most environments is to show a specific warning only once. This behavior can be changed:

```<code>import warnings
warnings.filterwarnings('always')  # "error", "ignore", "always", "default", "module" or "once"
</code>```

If you set this before importing the other modules, you will see the warning every time you run the code.

There is no way to avoid seeing this warning the first time, aside for setting warnings.filterwarnings('ignore'). What you can do, is decide that you are not interested in the scores of labels that were not predicted, and then explicitly specify the labels you are interested in (which are labels that were predicted at least once):

```<code>>>> metrics.f1_score(y_test, y_pred, average='weighted', labels=np.unique(y_pred))
0.91076923076923078
</code>```

The warning will be gone.

Body:
I'm getting this weird error:

classification.py:1113: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
'precision', 'predicted', average, warn_for)`

but then it also prints the f-score the first time I run:

metrics.f1_score(y_test, y_pred, average='weighted')

The second time I run, it provides the score without error. Why is that?

>>> y_pred = test.predict(X_test)
>>> y_test
array([ 1, 10, 35,  9,  7, 29, 26,  3,  8, 23, 39, 11, 20,  2,  5, 23, 28,
       30, 32, 18,  5, 34,  4, 25, 12, 24, 13, 21, 38, 19, 33, 33, 16, 20,
       18, 27, 39, 20, 37, 17, 31, 29, 36,  7,  6, 24, 37, 22, 30,  0, 22,
       11, 35, 30, 31, 14, 32, 21, 34, 38,  5, 11, 10,  6,  1, 14, 12, 36,
       25,  8, 30,  3, 12,  7,  4, 10, 15, 12, 34, 25, 26, 29, 14, 37, 23,
       12, 19, 19,  3,  2, 31, 30, 11,  2, 24, 19, 27, 22, 13,  6, 18, 20,
        6, 34, 33,  2, 37, 17, 30, 24,  2, 36,  9, 36, 19, 33, 35,  0,  4,
        1])
>>> y_pred
array([ 1, 10, 35,  7,  7, 29, 26,  3,  8, 23, 39, 11, 20,  4,  5, 23, 28,
       30, 32, 18,  5, 39,  4, 25,  0, 24, 13, 21, 38, 19, 33, 33, 16, 20,
       18, 27, 39, 20, 37, 17, 31, 29, 36,  7,  6, 24, 37, 22, 30,  0, 22,
       11, 35, 30, 31, 14, 32, 21, 34, 38,  5, 11, 10,  6,  1, 14, 30, 36,
       25,  8, 30,  3, 12,  7,  4, 10, 15, 12,  4, 22, 26, 29, 14, 37, 23,
       12, 19, 19,  3, 25, 31, 30, 11, 25, 24, 19, 27, 22, 13,  6, 18, 20,
        6, 39, 33,  9, 37, 17, 30, 24,  9, 36, 39, 36, 19, 33, 35,  0,  4,
        1])
>>> metrics.f1_score(y_test, y_pred, average='weighted')
C:\Users\Michael\Miniconda3\envs\snowflakes\lib\site-packages\sklearn\metrics\classification.py:1113: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
  'precision', 'predicted', average, warn_for)
0.87282051282051276
>>> metrics.f1_score(y_test, y_pred, average='weighted')
0.87282051282051276
>>> metrics.f1_score(y_test, y_pred, average='weighted')
0.87282051282051276

Also, why is there a trailing 'precision', 'predicted', average, warn_for) error message? There is no open parenthesis so why does it end with a closing parenthesis? I am running sklearn 0.18.1 using Python 3.6.0 in a conda environment on Windows 10.

I also looked at here and I don't know if it's the same bug. This SO post doesn't have solution either.

Body:
As mentioned in the comments, some labels in y_test don't appear in y_pred. Specifically in this case, label '2' is never predicted:

>>> set(y_test) - set(y_pred)
{2}

This means that there is no F-score to calculate for this label, and thus the F-score for this case is considered to be 0.0. Since you requested an average of the score, you must take into account that a score of 0 was included in the calculation, and this is why scikit-learn is showing you that warning.

This brings me to you not seeing the error a second time. As I mentioned, this is a warning, which is treated differently from an error in python. The default behavior in most environments is to show a specific warning only once. This behavior can be changed:

import warnings
warnings.filterwarnings('always')  # "error", "ignore", "always", "default", "module" or "once"

If you set this before importing the other modules, you will see the warning every time you run the code.

There is no way to avoid seeing this warning the first time, aside for setting warnings.filterwarnings('ignore'). What you can do, is decide that you are not interested in the scores of labels that were not predicted, and then explicitly specify the labels you are interested in (which are labels that were predicted at least once):

>>> metrics.f1_score(y_test, y_pred, average='weighted', labels=np.unique(y_pred))
0.91076923076923078

The warning will be gone.


问:
ASP.Net MVC Usage confusion
I'm in a situation where I would like to take a value from a page using JQuery, update the model with that value, call a method to update a different value in a model. Then call the controller to return a view with the new model.

I'm new to this so I imagine this is the wrong approach.

This is the View I have so far:

```<code>@using Cubic.OSS.SNMPMessageDuggerWebApplication.Models
@model SnmpModel
@{
   ViewBag.Title = "SNMP Message Debugger";
}

@section scripts
{

<script src="~/Scripts/jquery-1.7.1.js"></script>

<script type="text/javascript">

    $(document).ready(function() {

        $("#input-button").click(function () {
            // This is where I want the process to start.
        });

    });

</script>

}

<h2>@ViewBag.Title.</h2>
<div class="container-bar">
    <div id="input-bar">
        <p class="input-label">Enter SNMP Message: </p>
        <textarea rows="10" cols="300" id="input-area"></textarea>
        <br />
        <button id="input-button">Convert</button>
    </div>
    <div id="output-bar">
        <p class="output-label">Result: </p>
        <textarea rows="10" cols="300" id="output-area"></textarea>
    </div>
</div>
</code>```

My model looks like this:

```<code>public class SnmpModel
{

    public string SnmpMessageInput { get; set; }
    public string SnmpMessageOutout { get; set; }

   // I Imagine a method would be added here to transform the input

}
</code>```

And this is the controller so far:

```<code>public class SNMPController : Controller
{
    // GET: SNMP
    public ActionResult Index()
    {
        return View();
    }

}
</code>```

What I don't know how to do is: update the model with the returned JQuery, then refresh the page with the new model using the controller.

The input would be taken from the input text area, then transformed using code that was written in C# previously. This would be a method in the model I image. I have to use the code written in C# so I can't do the algorithm in js.

Thanks.

答:
Dont do the page/view reload. Just update the desired value like this:

```<code> function onChangeNumber() {
    var changedText = $("#PhoneNo").val();
    var CountryVal = $("#CountryCode").val();
    var CountryName = $("#appSelected option:selected").text();
    var ProductVal = $('#appSelected option:selected').val();
    url = '/controller/PhoneTextChanged';
    var data_to_send = {
        changed: changedText, ProductValue: CountryName
    };
    alert(changedText + CountryName);
    $.ajax({
        url: url,
        type: "POST",
        async: true,
        dataType: "json",
        data: data_to_send,
        success: function (data, textStatus, jqXHR) {
            if (data == "Invalid Number format") {
                alert("Invalid Number format");
            }

            else if (data == "hide") {
                $("#hiddenDiv").hide();
            }
            else {
                $("#hiddenDiv").show();
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Server error! try back later.");

        }
    });
};
</code>```

In this code what im doing is, I am hiding or unhiding a  depending upon the result returned by the method i created in my controller i.e PhoneTextChanged.

I pass parameters to this method PhoneTextChanged and then i evaluate my results and then return the result from controller like this :

```<code> return Json("no hide");
</code>```

I hope you want to do the same stuff at your end. Let me know if you want to know more.

Title: ASP.Net MVC Usage confusion

Body:
I'm in a situation where I would like to take a value from a page using JQuery, update the model with that value, call a method to update a different value in a model. Then call the controller to return a view with the new model.

I'm new to this so I imagine this is the wrong approach.

This is the View I have so far:

@using Cubic.OSS.SNMPMessageDuggerWebApplication.Models
@model SnmpModel
@{
   ViewBag.Title = "SNMP Message Debugger";
}

@section scripts
{

}

@ViewBag.Title.

Enter SNMP Message:

        <textarea rows="10" cols="300" id="input-area"></textarea>

        <button id="input-button">Convert</button>

Result:

        <textarea rows="10" cols="300" id="output-area"></textarea>

My model looks like this:

public class SnmpModel
{

    public string SnmpMessageInput { get; set; }
    public string SnmpMessageOutout { get; set; }

   // I Imagine a method would be added here to transform the input

}

And this is the controller so far:

public class SNMPController : Controller
{
    // GET: SNMP
    public ActionResult Index()
    {
        return View();
    }

}

What I don't know how to do is: update the model with the returned JQuery, then refresh the page with the new model using the controller.

The input would be taken from the input text area, then transformed using code that was written in C# previously. This would be a method in the model I image. I have to use the code written in C# so I can't do the algorithm in js.

Thanks.

Body:
Dont do the page/view reload. Just update the desired value like this:

 function onChangeNumber() {
    var changedText = $("#PhoneNo").val();
    var CountryVal = $("#CountryCode").val();
    var CountryName = $("#appSelected option:selected").text();
    var ProductVal = $('#appSelected option:selected').val();
    url = '/controller/PhoneTextChanged';
    var data_to_send = {
        changed: changedText, ProductValue: CountryName
    };
    alert(changedText + CountryName);
    $.ajax({
        url: url,
        type: "POST",
        async: true,
        dataType: "json",
        data: data_to_send,
        success: function (data, textStatus, jqXHR) {
            if (data == "Invalid Number format") {
                alert("Invalid Number format");
            }

            else if (data == "hide") {
                $("#hiddenDiv").hide();
            }
            else {
                $("#hiddenDiv").show();
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Server error! try back later.");

        }
    });
};

In this code what im doing is, I am hiding or unhiding a  depending upon the result returned by the method i created in my controller i.e PhoneTextChanged.

I pass parameters to this method PhoneTextChanged and then i evaluate my results and then return the result from controller like this :

 return Json("no hide");

I hope you want to do the same stuff at your end. Let me know if you want to know more.


问:
batch convert xml to json Mac
This is my first post here so please be forgiving.
I have about 56gb of xml files (trade documents) i need to convert in to json format.
Are there any tools out there that might do this for me?</p>

答: xml2json.js is a js library for converting xml files to json format, you can craete a small program using this script, or try my online xml to json converter https://xmltojson.tk/ , you can convert multiple xml files in a single click, Very easy to use, created with xml2json.js

Title: batch convert xml to json Mac


问:
How to produce XML signature with no whitespaces and line-breaks in Java?
I work with the brazilian "Nota Fiscal Eletronica" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there are absolutely no whitespaces between tags, including signature tags (*).

We happen to use apache's XMLSignature and I can't seem to produce an unindented signature.

If I remove the whitespaces after signing, the signature gets broken.

I cannot change the canonicalizer / transformers set either, since they're predefined.

I couldn't find an option or parameter in the XMLSignature API to control indentation or whitespaces.

Below is the code:

```<code>    // the element where to insert the signature
    Element element = ...;
    X509Certificate cert = ...;
    PrivateKey privateKey = ...;

    XMLSignature signer =
            new XMLSignature(doc, "http://xml-security",
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    element.appendChild(signer.getElement());

    Transforms transforms = new Transforms(doc);

    // Define as regras de transformação e canonicalização do documento
    // XML, necessário para fazer a verificação do parsing e da
    // assinatura pelos destinatários
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //, xpath.getElementPlusReturns());

    transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); //,xpath.getElementPlusReturns());

    String id = "";

    id = ((Element) element.getElementsByTagName("infNFe").item(0)).getAttributeNode("Id").getNodeValue();

    signer.addDocument("#" + id, transforms,
                       Constants.ALGO_ID_DIGEST_SHA1);
    signer.addKeyInfo(cert);
    signer.sign(privateKey);
</code>```

And below is the resulting signature (snippet):

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#NFe43110189716583000165550010000076011492273645">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>fas0ra5uRskQgRHSrIYhEjFEjKQ=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
2RGltUZy0HfNoiKtVanAeN+JUPyglWDuQNnMudSgA7kESoHBZ/q/GMbc+xMSN1eV8u7+2PxSKl1T
Zl592FWmCSAkL8pwMujDxJ4iTLU20Hf0dNF7oGcyB+g9GgbipW2udq0kwJLz6HzXUD/Evf/0y+3T
NtsXeIaA6A29ttD/UEs=
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
MIIFqTCCBJGgAwIBAgIEQeNSuzANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJicjETMBEGA1UE
ChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNhIEZlZGVyYWwxFDASBgNVBAMT
C0FDIENBSVhBIFBKMB4XDTEwMDYwODE5MjQwNVoXDTExMDYwODE5NTQwNVowgYQxCzAJBgNVBAYT
AmJyMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSAwHgYDVQQLExdDYWl4YSBFY29ub21pY2EgRmVkZXJh
bDEUMBIGA1UECxMLQUMgQ0FJWEEgUEoxKDAmBgNVBAMTH0EgQlVITEVSIFNBIENVUlRVTUU6NDA5
NDI0OTAwMTAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOFxgvG35RQWgXec4zVrzoUHolnJ
fP76rpO2Vo40593W9Gf0WwHt36gVmli0ZeQitFmzFSoE5KhgXQGZg6RpV3WJUFcIrPBHPdqOSfiB
988kf962P+j8fZ38BNmo7TV9H9hMBkV9bD/QOe73wFDc+rT6/9io++Z+7/wup/3glKntAgMBAAGj
ggLOMIICyjAOBgNVHQ8BAf8EBAMCBeAwVwYDVR0gBFAwTjBMBgZgTAECAQkwQjBABggrBgEFBQcC
ARY0aHR0cDovL2ljcC5jYWl4YS5nb3YuYnIvcmVwb3NpdG9yaW8vZHBjYWNjYWl4YXBqLnBkZjAp
BgNVHSUEIjAgBggrBgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcUAgIwgbYGA1UdEQSBrjCBq4EV
YnVobGVyQGFidWhsZXIuY29tLmJyoD4GBWBMAQMEoDUEMzE0MDkxOTQ2NDA5NDI0OTAwMTAxMDg0
NDcwODE3NTAwMDAwODAzMjkyMjM1NlNTUCBSU6AeBgVgTAEDAqAVBBNOQUlSIEJVSExFUiBTQ0hO
RUNLoBkGBWBMAQMDoBAEDjg5NzE2NTgzMDAwMTY1oBcGBWBMAQMHoA4EDDAwMDAwMDAwMDAwMDCC
ATIGA1UdHwSCASkwggElMIGuoIGroIGohjJodHRwOi8vaWNwLmNhaXhhLmdvdi5ici9yZXBvc2l0
b3Jpby9BQ0NBSVhBUEoxLmNybIY0aHR0cDovL2ljcDIuY2FpeGEuZ292LmJyL3JlcG9zaXRvcmlv
Mi9BQ0NBSVhBUEoxLmNybIY8aHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNy
L2NhaXhhL0FDQ0FJWEFQSjEuY3JsMHKgcKBupGwwajELMAkGA1UEBhMCYnIxEzARBgNVBAoTCklD
UC1CcmFzaWwxIDAeBgNVBAsTF0NhaXhhIEVjb25vbWljYSBGZWRlcmFsMRQwEgYDVQQDEwtBQyBD
QUlYQSBQSjEOMAwGA1UEAxMFQ1JMNDEwHwYDVR0jBBgwFoAUjkAvCv4T1ao5oHZ0htO8fcfx5c8w
CQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDqDANBgkqhkiG9w0BAQUFAAOCAQEA
nZHUvdnZsiCIDjKm1zHehbtuDtDJha4O4FZ03J74Y+AxyAFs/4JED+xUvZ5jFuEsdqgA0V/dxUFy
Uz/ca10Ievd578GQdGwYl1GFhRtO/SlxeaOEf7eDdGOWXO3VmUA3NmNo0X8RRTIoifnhpDXu7RbN
5sijyH/uXyRFWX9XH2N0U/r3oJtNKXsvoUlbDrkalgkuLzLKsaEj0TkwisXO3cmMoWGuBpAZC+46
e4x/2vTqOvYkzZO+O9NLi0YWSYY7OJKiKBjMC6MzdlPM9VTkIwO9WvWEMdbU0/jhO2cMcVMzNZc1
r6ZmdTDrwqV3elSTkQtJ0RIZNgMJUn+Y8c7Aog==
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</code>```

Notice the (unwanted) line-breaks.

Any help would be greatly appreciated.

Thanks a lot in advance.

(*) Clarification: the new rule forbids whitespaces (or any other text) between element-only tags. As an example, this would be allowed:

```<code><a><b>
  text
  inside
  tag
</b></a>
</code>```

while this would be forbidden:

```<code><a>
<b>text</b>
</a>
</code>```

because on the latter case, the whitespaces (line-breaks) are between two tags, or, in other words, placed inside an element-only tag.

答:
the signature blocks are encoding binary information as Base64, which must follow some formating including line breaks (see http://en.wikipedia.org/wiki/Base64). So you simply can't remove them without alter the information.

a better way to redure network traffic, is to use comression before sending data.

Body:
I work with the brazilian "Nota Fiscal Eletronica" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there are absolutely no whitespaces between tags, including signature tags (*).

We happen to use apache's XMLSignature and I can't seem to produce an unindented signature.

If I remove the whitespaces after signing, the signature gets broken.

I cannot change the canonicalizer / transformers set either, since they're predefined.

I couldn't find an option or parameter in the XMLSignature API to control indentation or whitespaces.

Below is the code:

    // the element where to insert the signature
    Element element = ...;
    X509Certificate cert = ...;
    PrivateKey privateKey = ...;

    XMLSignature signer =
            new XMLSignature(doc, "http://xml-security",
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    element.appendChild(signer.getElement());

    Transforms transforms = new Transforms(doc);

    // Define as regras de transformação e canonicalização do documento
    // XML, necessário para fazer a verificação do parsing e da
    // assinatura pelos destinatários
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //, xpath.getElementPlusReturns());

    transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); //,xpath.getElementPlusReturns());

    String id = "";

    id = ((Element) element.getElementsByTagName("infNFe").item(0)).getAttributeNode("Id").getNodeValue();

    signer.addDocument("#" + id, transforms,
                       Constants.ALGO_ID_DIGEST_SHA1);
    signer.addKeyInfo(cert);
    signer.sign(privateKey);

And below is the resulting signature (snippet):

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#NFe43110189716583000165550010000076011492273645">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>fas0ra5uRskQgRHSrIYhEjFEjKQ=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
2RGltUZy0HfNoiKtVanAeN+JUPyglWDuQNnMudSgA7kESoHBZ/q/GMbc+xMSN1eV8u7+2PxSKl1T
Zl592FWmCSAkL8pwMujDxJ4iTLU20Hf0dNF7oGcyB+g9GgbipW2udq0kwJLz6HzXUD/Evf/0y+3T
NtsXeIaA6A29ttD/UEs=
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
MIIFqTCCBJGgAwIBAgIEQeNSuzANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJicjETMBEGA1UE
ChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNhIEZlZGVyYWwxFDASBgNVBAMT
C0FDIENBSVhBIFBKMB4XDTEwMDYwODE5MjQwNVoXDTExMDYwODE5NTQwNVowgYQxCzAJBgNVBAYT
AmJyMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSAwHgYDVQQLExdDYWl4YSBFY29ub21pY2EgRmVkZXJh
bDEUMBIGA1UECxMLQUMgQ0FJWEEgUEoxKDAmBgNVBAMTH0EgQlVITEVSIFNBIENVUlRVTUU6NDA5
NDI0OTAwMTAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOFxgvG35RQWgXec4zVrzoUHolnJ
fP76rpO2Vo40593W9Gf0WwHt36gVmli0ZeQitFmzFSoE5KhgXQGZg6RpV3WJUFcIrPBHPdqOSfiB
988kf962P+j8fZ38BNmo7TV9H9hMBkV9bD/QOe73wFDc+rT6/9io++Z+7/wup/3glKntAgMBAAGj
ggLOMIICyjAOBgNVHQ8BAf8EBAMCBeAwVwYDVR0gBFAwTjBMBgZgTAECAQkwQjBABggrBgEFBQcC
ARY0aHR0cDovL2ljcC5jYWl4YS5nb3YuYnIvcmVwb3NpdG9yaW8vZHBjYWNjYWl4YXBqLnBkZjAp
BgNVHSUEIjAgBggrBgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcUAgIwgbYGA1UdEQSBrjCBq4EV
YnVobGVyQGFidWhsZXIuY29tLmJyoD4GBWBMAQMEoDUEMzE0MDkxOTQ2NDA5NDI0OTAwMTAxMDg0
NDcwODE3NTAwMDAwODAzMjkyMjM1NlNTUCBSU6AeBgVgTAEDAqAVBBNOQUlSIEJVSExFUiBTQ0hO
RUNLoBkGBWBMAQMDoBAEDjg5NzE2NTgzMDAwMTY1oBcGBWBMAQMHoA4EDDAwMDAwMDAwMDAwMDCC
ATIGA1UdHwSCASkwggElMIGuoIGroIGohjJodHRwOi8vaWNwLmNhaXhhLmdvdi5ici9yZXBvc2l0
b3Jpby9BQ0NBSVhBUEoxLmNybIY0aHR0cDovL2ljcDIuY2FpeGEuZ292LmJyL3JlcG9zaXRvcmlv
Mi9BQ0NBSVhBUEoxLmNybIY8aHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNy
L2NhaXhhL0FDQ0FJWEFQSjEuY3JsMHKgcKBupGwwajELMAkGA1UEBhMCYnIxEzARBgNVBAoTCklD
UC1CcmFzaWwxIDAeBgNVBAsTF0NhaXhhIEVjb25vbWljYSBGZWRlcmFsMRQwEgYDVQQDEwtBQyBD
QUlYQSBQSjEOMAwGA1UEAxMFQ1JMNDEwHwYDVR0jBBgwFoAUjkAvCv4T1ao5oHZ0htO8fcfx5c8w
CQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDqDANBgkqhkiG9w0BAQUFAAOCAQEA
nZHUvdnZsiCIDjKm1zHehbtuDtDJha4O4FZ03J74Y+AxyAFs/4JED+xUvZ5jFuEsdqgA0V/dxUFy
Uz/ca10Ievd578GQdGwYl1GFhRtO/SlxeaOEf7eDdGOWXO3VmUA3NmNo0X8RRTIoifnhpDXu7RbN
5sijyH/uXyRFWX9XH2N0U/r3oJtNKXsvoUlbDrkalgkuLzLKsaEj0TkwisXO3cmMoWGuBpAZC+46
e4x/2vTqOvYkzZO+O9NLi0YWSYY7OJKiKBjMC6MzdlPM9VTkIwO9WvWEMdbU0/jhO2cMcVMzNZc1
r6ZmdTDrwqV3elSTkQtJ0RIZNgMJUn+Y8c7Aog==
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>

Notice the (unwanted) line-breaks.

Any help would be greatly appreciated.

Thanks a lot in advance.

(*) Clarification: the new rule forbids whitespaces (or any other text) between element-only tags. As an example, this would be allowed:

  text
  inside
  tag

while this would be forbidden:

text

because on the latter case, the whitespaces (line-breaks) are between two tags, or, in other words, placed inside an element-only tag.


问:
Find the inverse function in R
Is there a function in R that generates the inverse of a given function?
To be more specific: I have a polynomial of a third order and I need the inverse of it. It's strictly monotonously.

I read a few times that uniroot and/or polyroot can help. But how? Uniroot yields the root of a function and polyroot the zeros of a function. How can I use that for the inverse?
Maybe a dumb question but I don't get it..

答: The package investr is able to apply an inverse regression.</p>

Title: Find the inverse function in R


问:
Node js App integration with power bi rest Api
Is there a way using power bi rest API in node js, I watched video ,Ran Breuer and Arina Hantsis were showing the demo here,Setting up and Getting Started with Power BI Embedded I want to achieve same but using node js, in our development environment we do not use c#.
I found the Node SDK but it saying we no longer support node SDK,Node SDK

Do I have to change development structure from Node js to c#  in order to use power bi Rest API!!

答: They no longer support the Node SDK, but have you tried it? It might still be working. You are gonna want some sort of SDK - it seems that is not the easiest API to work with. </p>


问:
Calculating how long app runs in background
I'm building a VR experience using a GearVR and Samsung phone.

I've tried to figure out how long the app has been "in the background" when OnApplicationPause has been triggered, and subsequently OnApplicationFocus.

I know that the app doesn't process anything while in the background so doing a simple 'timer' wouldn't work, thus the following:

```<code>private float pausedAt;

void OnApplicationPause(bool pauseStatus)
{
    pausedAt = Time.realtimeSinceStartup;
}

void OnApplicationFocus(bool hasFocus)
{
    if (Time.realtimeSinceStartup > pausedAt + 60) { // 60 for 1 minute AFK
         ResetExperience();
    }
}
</code>```

This doesn't seem to be working, so any help would be appreciated.

答:
The problem with your current code is that you are not also getting the  pausedAt value in the OnApplicationFocus(false). You must do this as OnApplicationPause is called at certain times only. Also, do this with Time.time instead of Time.realtimeSinceStartup.

Get the the time with Time.time when the game pauses in the OnApplicationPause and  OnApplicationFocus(false) then get the time again when it resumes in OnApplicationFocus(true). Subtract them to get the actual time your app waited in the background.

```<code>float pauseBeginTime;
float focusTime;

float totalTimeInBackground;

void OnApplicationFocus(bool hasFocus)
{
    //Detect return to game
    if (hasFocus)
    {
        Debug.Log("Focused");

        focusTime = Time.time;
        //Calculate how much waited in the background
        totalTimeInBackground = focusTime - pauseBeginTime;

        Debug.Log("Stayed in Background for " + totalTimeInBackground);
    }

    //Detect on-screen keyboard is enabled
    else
    {
        setExitTime();
    }
}

void OnApplicationPause(bool pause)
{
    //Detect Home button on Android
    if (pause)
    {
        setExitTime();
    }
}

void setExitTime()
{
    Debug.Log("Paused");
    pauseBeginTime = Time.time;
}
</code>```

Body:
I'm building a VR experience using a GearVR and Samsung phone.

I've tried to figure out how long the app has been "in the background" when OnApplicationPause has been triggered, and subsequently OnApplicationFocus.

I know that the app doesn't process anything while in the background so doing a simple 'timer' wouldn't work, thus the following:

private float pausedAt;

void OnApplicationPause(bool pauseStatus)
{
    pausedAt = Time.realtimeSinceStartup;
}

void OnApplicationFocus(bool hasFocus)
{
    if (Time.realtimeSinceStartup > pausedAt + 60) { // 60 for 1 minute AFK
         ResetExperience();
    }
}

This doesn't seem to be working, so any help would be appreciated.

Body:
The problem with your current code is that you are not also getting the  pausedAt value in the OnApplicationFocus(false). You must do this as OnApplicationPause is called at certain times only. Also, do this with Time.time instead of Time.realtimeSinceStartup.

Get the the time with Time.time when the game pauses in the OnApplicationPause and  OnApplicationFocus(false) then get the time again when it resumes in OnApplicationFocus(true). Subtract them to get the actual time your app waited in the background.

float pauseBeginTime;
float focusTime;

float totalTimeInBackground;

void OnApplicationFocus(bool hasFocus)
{
    //Detect return to game
    if (hasFocus)
    {
        Debug.Log("Focused");

        focusTime = Time.time;
        //Calculate how much waited in the background
        totalTimeInBackground = focusTime - pauseBeginTime;

        Debug.Log("Stayed in Background for " + totalTimeInBackground);
    }

    //Detect on-screen keyboard is enabled
    else
    {
        setExitTime();
    }
}

void OnApplicationPause(bool pause)
{
    //Detect Home button on Android
    if (pause)
    {
        setExitTime();
    }
}

void setExitTime()
{
    Debug.Log("Paused");
    pauseBeginTime = Time.time;
}


问:
How to execute a same query for 7 days in Oracle sql developer
I have a query

```<code>select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);
</code>```

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

```<code>  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110
</code>```

Is it achievable ?

答:
Does this do what you need?</p>

```<code>select p.*
from purchases p
where client_id in (1, 54) and
      start_time >= sysdate - 7 days and
      start_time < start_time and
      to_char(start_time, 'HH24:MI') in ('00:01', '00:02');
</code>```

Body:
I have a query

select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110

Is it achievable ?

Body:
Does this do what you need?

select p.*
from purchases p
where client_id in (1, 54) and
      start_time >= sysdate - 7 days and
      start_time < start_time and
      to_char(start_time, 'HH24:MI') in ('00:01', '00:02');


问:
Reduce space between rows in CSS Grid
I'm wondering how to reduce the spacing between the rows? I've tried setting margins and paddings to 0, but nothing seems to be biting.

Destktop view on the left and mobile view on the right.

```<code>.content{
    margin: 0;
    padding: 0;
    width: 100%;
    display: grid;
    grid-gap: 5px;
    grid-template-columns: repeat(36, 1fr);
    justify-items: stretch;
    align-content: start;
    }

.one{
    grid-column: 1/37;
    width: 100%;
}

.two{
    grid-column: 1/11;

}
.three{
    grid-column: 12/24;
    justify-self: center;
    align-self: start;
    position: relative;
    bottom: 5px;
}
.four{
    grid-column: 25/37;
}
</code>```

Here's a link to a test site:
http://www.acm.no/test/valhall/

答:
The issue is coming from .ctrl. It's taking the space you need to decrease. It's position is relative and :

An element with position: relative; is positioned relative to its
normal position.

Setting the top, right, bottom, and left properties of a
relatively-positioned element will cause it to be adjusted away from
its normal position. Other content will not be adjusted to fit into
any gap left by the element.

You can add negative margin to fix this :

```<code>.ctrl {
    max-width: 30px;
    position: relative;
    bottom: 40px;
    color: black;
    text-align: left;
    padding-left: 1%;
    margin-bottom: -40px; /*added this line*/
}
</code>```

Or you can use absolute position and adjust the code like this :

```<code>.one,.two,.three {
   position:relative;
}
.ctrl {
    max-width: 30px;
    position: absolute;
    bottom: 10px;
    color: black;
    text-align: left;
    padding-left: 1%;
}
</code>```

Title: Reduce space between rows in CSS Grid

Body:
I'm wondering how to reduce the spacing between the rows? I've tried setting margins and paddings to 0, but nothing seems to be biting.

Destktop view on the left and mobile view on the right.

.content{
    margin: 0;
    padding: 0;
    width: 100%;
    display: grid;
    grid-gap: 5px;
    grid-template-columns: repeat(36, 1fr);
    justify-items: stretch;
    align-content: start;
    }

.one{
    grid-column: 1/37;
    width: 100%;
}

.two{
    grid-column: 1/11;

}
.three{
    grid-column: 12/24;
    justify-self: center;
    align-self: start;
    position: relative;
    bottom: 5px;
}
.four{
    grid-column: 25/37;
}

Here's a link to a test site:
http://www.acm.no/test/valhall/

Body:
The issue is coming from .ctrl. It's taking the space you need to decrease. It's position is relative and :

An element with position: relative; is positioned relative to its
normal position.

Setting the top, right, bottom, and left properties of a
relatively-positioned element will cause it to be adjusted away from
its normal position. Other content will not be adjusted to fit into
any gap left by the element.

You can add negative margin to fix this :

.ctrl {
    max-width: 30px;
    position: relative;
    bottom: 40px;
    color: black;
    text-align: left;
    padding-left: 1%;
    margin-bottom: -40px; /*added this line*/
}

Or you can use absolute position and adjust the code like this :

.one,.two,.three {
   position:relative;
}
.ctrl {
    max-width: 30px;
    position: absolute;
    bottom: 10px;
    color: black;
    text-align: left;
    padding-left: 1%;
}


问:
Existing li gets overridden in todolist instead of adding a new li
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>spooky</h1>

<input type="text" class="input">
<ul>
  <li>1</li>
  <li>2</li>
</ul></code>```

答:
Full code is </p>

```<code> let input = document.querySelector(".input");
 let ul = document.querySelector("ul");
 input.onchange=function(){
    let addNew = document.createElement("li");
    addNew.innerHTML=this.value;
    this.value="";
    ul.appendChild(addNew);
 }
</code>```

Body:
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};

spooky

<input type="text" class="input">

1

2

Body:
Full code is

 let input = document.querySelector(".input");
 let ul = document.querySelector("ul");
 input.onchange=function(){
    let addNew = document.createElement("li");
    addNew.innerHTML=this.value;
    this.value="";
    ul.appendChild(addNew);
 }


问:
Fit image to paragraph width
Let's say I have the following css

```<code>.text{
    position:absolute;
    padding: 0 25px;
    background: rgba(255,255,255,.6);
}
</code>```

And following html

```<code><div class = "row">
    <div class = "col-md-6">
        <div class = "text">
            <h3>Title 1</h3>
            <p>
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
            </p>
        </div>
        <img src = "https://i.pinimg.com/736x/51/d6/e3/51d6e3dcccd3bdac300202a5a3e99de0--pretty-cats-beautiful-cats.jpg">
    </div>
    <div class = "col-md-6">
        <div class = "text">
            <h3>Title 2</h3>
            <p>
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
            </p>
        </div>
        <img src = "https://i.pinimg.com/736x/51/d6/e3/51d6e3dcccd3bdac300202a5a3e99de0--pretty-cats-beautiful-cats.jpg">
    </div>
</div>
</code>```

How would I get the image to shrink or stretch to fit the width of the whole paragraph, and the height to remain centered on the image.

As an example
If image was 600 x 600 and paragraph took 300 x 150 pixels then the image would shrink down to 300 x 300 and the area that would be displayed would be starting at position (0, 50) and would be size of (300, 150).

I know that I haven't provided any example of what I tried, but if you can at least point me in right direction I would be ever so grateful.

答:
You can use background-image with url of your image and background-size set as "cover".
I think that (jsfiddle) should be what you are looking for:</p>

```<code>.background-img-cat {
  background-image:url('https://i.pinimg.com/736x/51/d6/e3/51d6e3dcccd3bdac300202a5a3e99de0--pretty-cats-beautiful-cats.jpg');
  background-size:cover;
}

<div class="row">
    <div class="col-md-6 background-img-cat">
        <div class="text">
            <h3>Title 1</h3>
            <p>
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
            </p>
        </div>
    </div>
    <div class="col-md-6 background-img-cat">
        <div class="text">
            <h3>Title 2</h3>
            <p>
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
            </p>
        </div>
    </div>
</div>
</code>```

Title: Fit image to paragraph width

Body:
Let's say I have the following css

.text{
    position:absolute;
    padding: 0 25px;
    background: rgba(255,255,255,.6);
}

And following html

Title 1

                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum

Title 2

                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum

How would I get the image to shrink or stretch to fit the width of the whole paragraph, and the height to remain centered on the image.

As an example
If image was 600 x 600 and paragraph took 300 x 150 pixels then the image would shrink down to 300 x 300 and the area that would be displayed would be starting at position (0, 50) and would be size of (300, 150).

I know that I haven't provided any example of what I tried, but if you can at least point me in right direction I would be ever so grateful.

Body:
You can use background-image with url of your image and background-size set as "cover".
I think that (jsfiddle) should be what you are looking for:

.background-img-cat {
  background-image:url('https://i.pinimg.com/736x/51/d6/e3/51d6e3dcccd3bdac300202a5a3e99de0--pretty-cats-beautiful-cats.jpg');
  background-size:cover;
}

<div class="row">
    <div class="col-md-6 background-img-cat">
        <div class="text">
            <h3>Title 1</h3>
            <p>
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
            </p>
        </div>
    </div>
    <div class="col-md-6 background-img-cat">
        <div class="text">
            <h3>Title 2</h3>
            <p>
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
                Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
            </p>
        </div>
    </div>
</div>


问:
Add Items using CSV file - Laravel
I am able to save products into my groups using the group id  using the save function
 but now i want to do that using an excel file. I am having issues with how to do that. Any help will be appreciated. Thank you.

Controller

```<code> public function save($id, Request $request)
 {
    $group = Group::whereId($id)->firstorFail();
    $product = new Product(array(
        'name'  => $request->get('name'),
        'price' => $request->get('price'),
    ));

    $group->products()->save($product);
}

public function import($id, Request $request)
{
   $group = Group::whereId($id)->firstorFail();

   if($request->file('imported-file'))
   {
             $path = $request->file('imported-file')->getRealPath();
             $data = Excel::load($path, function($reader)
       {
             })->get();

       if(!empty($data) && $data->count())
       {
         foreach ($data->toArray() as $row)
         {
           if(!empty($row))
           {
             $dataArray[] =
             [
               'name' => $row['name'],
               'price' => $row['price'],
             ];
           }
       }

       if(!empty($dataArray))
       {
          Item::insert($dataArray);

        }
      }
    }

}
</code>```

Route

```<code>Route::post('import/{id?}', 'ItemController@import');
</code>```

Model for Product
Product

```<code>  public function groups()
        {
            return $this->belongsToMany('App\Group','group_product','product_id','group_id')
            ->withTimestamps();

       }
</code>```

Model for group

Group

```<code> public function products()
{
    return $this->belongsToMany('App\Product','group_product','group_id','product_id')
  }
</code>```

答:
You need saveMany</p>

```<code>$dataArray[] =
             new App\Product([
               'name' => $row['name'],
               'price' => $row['price'],
             ]);

   $group->products()->saveMany($dataArray);
</code>```

Title: Add Items using CSV file - Laravel

Body:
I am able to save products into my groups using the group id  using the save function
 but now i want to do that using an excel file. I am having issues with how to do that. Any help will be appreciated. Thank you.

Controller

 public function save($id, Request $request)
 {
    $group = Group::whereId($id)->firstorFail();
    $product = new Product(array(
        'name'  => $request->get('name'),
        'price' => $request->get('price'),
    ));

    $group->products()->save($product);
}

public function import($id, Request $request)
{
   $group = Group::whereId($id)->firstorFail();

   if($request->file('imported-file'))
   {
             $path = $request->file('imported-file')->getRealPath();
             $data = Excel::load($path, function($reader)
       {
             })->get();

       if(!empty($data) && $data->count())
       {
         foreach ($data->toArray() as $row)
         {
           if(!empty($row))
           {
             $dataArray[] =
             [
               'name' => $row['name'],
               'price' => $row['price'],
             ];
           }
       }

       if(!empty($dataArray))
       {
          Item::insert($dataArray);

        }
      }
    }

}

Route

Route::post('import/{id?}', 'ItemController@import');

Model for Product
Product

  public function groups()
        {
            return $this->belongsToMany('App\Group','group_product','product_id','group_id')
            ->withTimestamps();

       }

Model for group

Group

 public function products()
{
    return $this->belongsToMany('App\Product','group_product','group_id','product_id')
  }

Body:
You need saveMany

$dataArray[] =
             new App\Product([
               'name' => $row['name'],
               'price' => $row['price'],
             ]);

   $group->products()->saveMany($dataArray);