问:
When brew installing opencv3 I get warning that formula has no --with-contrib option
My intent is to install opencv for use with C++ on macOs 10.12.6 (16G29). It seems the suggested method is using homebrew to install.

I am following this tutorial: https://www.pyimagesearch.com/2016/12/19/install-opencv-3-on-macos-with-homebrew-the-easy-way/

I used this command to install:

brew install opencv3 --with-contrib --c++11

and everything finished without error but I received the following warnings:

Warning: opencv: this formula has no --c++11 option so it will be ignored!
Warning: opencv: this formula has no --with-contrib option so it will be ignored!

From brew info opencv3:

$ brew info opencv3
opencv: stable 3.3.1 (bottled)
Open source computer vision library
https://opencv.org/
/usr/local/Cellar/opencv/3.3.1_1 (519 files, 95.9MB) *
  Poured from bottle on 2017-11-21 at 08:11:10
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/opencv.rb
==> Dependencies
Build: cmake ✘, pkg-config ✘
Required: eigen ✔, ffmpeg ✔, jpeg ✔, libpng ✔, libtiff ✔, openexr ✔, numpy ✔, tbb ✔
==> Requirements
Required: python ✔, python3 ✔

Has anyone had success installing opencv3 for c++ development on macOs?

答:
I was getting the same error. Take a look at the output of "brew info opencv". It turns out that the opencv was moved to homebrew-core:

```<code>https://github.com/Homebrew/homebrew-core/blob/master/Formula/opencv.rb
</code>```

To show the list of available '--with-*' options allowed to be passed to homebrew during an install, use:

```<code>brew options opencv
</code>```

I would assume that it returns nothing, since the formula does not define any such options anymore.

Installing Opencv

If you have not installed opencv, install with:

```<code>brew install opencv
</code>```

This should just install from source by downloading and compiling opencv with the packages listed in the homebrew formula. Since there are currently no options in the opencv formula, passing in something like --with-*, for example --with-contrib, will not be recognized as a valid option. However the formula actually happens to install certain things like contrib by default now.

If you already have opencv installed, try reinstalling:

```<code>brew reinstall opencv
</code>```

This will reinstall from source as well.

(Fyi, recompile takes about 10-20 minutes)

Body:
I was getting the same error. Take a look at the output of "brew info opencv". It turns out that the opencv was moved to homebrew-core:

https://github.com/Homebrew/homebrew-core/blob/master/Formula/opencv.rb

To show the list of available '--with-*' options allowed to be passed to homebrew during an install, use:

brew options opencv

I would assume that it returns nothing, since the formula does not define any such options anymore.

Installing Opencv

If you have not installed opencv, install with:

brew install opencv

This should just install from source by downloading and compiling opencv with the packages listed in the homebrew formula. Since there are currently no options in the opencv formula, passing in something like --with-*, for example --with-contrib, will not be recognized as a valid option. However the formula actually happens to install certain things like contrib by default now.

If you already have opencv installed, try reinstalling:

brew reinstall opencv

This will reinstall from source as well.

(Fyi, recompile takes about 10-20 minutes)


来源: stackexchange

问:
I've been trying to return numbers to a multidimensional int array in Java
I have been trying to code a game for my comp. sci. class and I've been having trouble

getting values to transfer between methods for a 2D int array.

The code I've currently have is as follows:

```<code>public int assignDeck(){
    int k = 1;
    int[][] deckNum = new int[4][13];
    for (int i=0;i<4;i++){
        for (int j=0;j<13;j++){
            deckNum[i][j] = k;
        }
        k++;
    }
    return new int[][]deckNum;
}
</code>```

As it stands, my program is telling me "incompatible types: int[] cannot be converted to int" on the return line, as well as an error from the bracket below from what I assume is the return statement not being acknowledged as proper code.

I'm not sure how to get each value to transfer to the array in my main method:

```<code>int [][] deckNum = assignDeck();
</code>```

This line of code is getting "non-static method assignDeck() cannot be referenced from a static context" as an error. All I need it to do is transfer the values for my array from "assignDeck" to my main method.

Thanks in advance.

答:
Use static and declare arrays as return type.</p>

```<code>public static int[][] assignDeck() {
   ...
   return deckNum;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to code a game for my comp. sci. class and I've been having trouble

getting values to transfer between methods for a 2D int array.

The code I've currently have is as follows:

public int assignDeck(){
    int k = 1;
    int[][] deckNum = new int[4][13];
    for (int i=0;i<4;i++){
        for (int j=0;j<13;j++){
            deckNum[i][j] = k;
        }
        k++;
    }
    return new int[][]deckNum;
}

As it stands, my program is telling me "incompatible types: int[] cannot be converted to int" on the return line, as well as an error from the bracket below from what I assume is the return statement not being acknowledged as proper code.

I'm not sure how to get each value to transfer to the array in my main method:

int [][] deckNum = assignDeck();

This line of code is getting "non-static method assignDeck() cannot be referenced from a static context" as an error. All I need it to do is transfer the values for my array from "assignDeck" to my main method.

Thanks in advance.

Body:
Use static and declare arrays as return type.

public static int[][] assignDeck() {
   ...
   return deckNum;
}


问:
how to make condition on update query
i made a query which which have a condition inside update.

```<code>UPDATE tbl_delivery SET amount_paid = 700000, amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END, transaction_status = IF(amount_remaining = 0, transaction_status = 'accepted', transaction_status='pending'), payment_status = CASE WHEN amount_remaining = 0 THEN payment_status = 'paid' ELSE payment_status = 'unpaid' END, modified = '2017-12-05 12:14:02' WHERE id = '1' AND user_id = '201720000003'

UPDATE tbl_delivery SET amount_paid = 700000, amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END, transaction_status = CASE WHEN amount_remaining = 0 THEN transaction_status = 'accepted' ELSE transaction_status = 'pending' END, payment_status = CASE WHEN amount_remaining = 0 THEN payment_status = 'paid' ELSE payment_status = 'unpaid' END, modified = '2017-12-05 12:01:17' WHERE id = '1' AND user_id = '201720000003'
</code>```

this is the queries i test to get the right result but what happen is it is not getting the result that i wanted to get..

my problem lies on this field

```<code>    transaction_status = CASE WHEN amount_remaining = 0 THEN transaction_status = 'accepted' ELSE transaction_status = 'pending' END,
 transaction_status = IF(amount_remaining = 0, transaction_status = 'accepted', transaction_status='pending'),
</code>```

instead of getting the result accepted or pending what i get was 0.

答:
you only need this:

```<code>transaction_status = CASE WHEN amount_remaining = 0 THEN 'accepted' ELSE 'pending' END
</code>```

that is, you do not have to repeat "transaction_status ="

```<code>UPDATE tbl_delivery
SET
        amount_paid = 700000
      , amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END
      , transaction_status = IF(amount_remaining = 0, 'accepted','pending')
      , payment_status = CASE WHEN amount_remaining = 0 THEN 'paid' ELSE 'unpaid' END
      , modified = '2017-12-05 12:14:02'
WHERE id = '1'
AND user_id = '201720000003'
</code>```

Personally I prefer to use case expressions and I would not like to encourage use of IF() and CASE in the same query, which I think is just confusing.

Title: how to make condition on update query

Body:
i made a query which which have a condition inside update.

UPDATE tbl_delivery SET amount_paid = 700000, amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END, transaction_status = IF(amount_remaining = 0, transaction_status = 'accepted', transaction_status='pending'), payment_status = CASE WHEN amount_remaining = 0 THEN payment_status = 'paid' ELSE payment_status = 'unpaid' END, modified = '2017-12-05 12:14:02' WHERE id = '1' AND user_id = '201720000003'

UPDATE tbl_delivery SET amount_paid = 700000, amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END, transaction_status = CASE WHEN amount_remaining = 0 THEN transaction_status = 'accepted' ELSE transaction_status = 'pending' END, payment_status = CASE WHEN amount_remaining = 0 THEN payment_status = 'paid' ELSE payment_status = 'unpaid' END, modified = '2017-12-05 12:01:17' WHERE id = '1' AND user_id = '201720000003'

this is the queries i test to get the right result but what happen is it is not getting the result that i wanted to get..

my problem lies on this field

    transaction_status = CASE WHEN amount_remaining = 0 THEN transaction_status = 'accepted' ELSE transaction_status = 'pending' END,
 transaction_status = IF(amount_remaining = 0, transaction_status = 'accepted', transaction_status='pending'),

instead of getting the result accepted or pending what i get was 0.

Body:
you only need this:

transaction_status = CASE WHEN amount_remaining = 0 THEN 'accepted' ELSE 'pending' END

that is, you do not have to repeat "transaction_status ="

UPDATE tbl_delivery
SET
        amount_paid = 700000
      , amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END
      , transaction_status = IF(amount_remaining = 0, 'accepted','pending')
      , payment_status = CASE WHEN amount_remaining = 0 THEN 'paid' ELSE 'unpaid' END
      , modified = '2017-12-05 12:14:02'
WHERE id = '1'
AND user_id = '201720000003'

Personally I prefer to use case expressions and I would not like to encourage use of IF() and CASE in the same query, which I think is just confusing.


问:
No rule to make target `/Makefile', needed by `Makefile'
I'm trying to 'make' using a pretty simple makefile. My makefile is named 'Makefile' so I'm simply using the command 'make'.

I get this strange error:

make: *** No rule to make target `/Makefile', needed by `Makefile'.  Stop.

If, however, I use
make -f "full-path-to-makefile" it actually does run (with odd consequences...). I should say that I'm running all this from the directory where the Makefile lies, of course.

I'm working on Mac OSX, using tcsh.

Edit:

I'm working in the LLVM framework, trying to compile a pass function and this is  the associated makefile:

```
LEVEL = ../../../
LIBRARYNAME = FunctionName
LOADABLE_MODULE = 1
include $(LEVEL)/Makefile.common
```

Any ideas will be appreciated :)

答:
Since your include line reads:

```<code>include $(LEVEL)/Makefile.common
</code>```

it is puzzling that you are not getting an error about /Makefile.common.  If you were, then I'd suggest that maybe you have a trailing blank after the definition of LEVEL.

Could there be a line in Makefile.common that itself includes $(SOMEMACRO)/Makefile and you have not set the value of SOMEMACRO?

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to 'make' using a pretty simple makefile. My makefile is named 'Makefile' so I'm simply using the command 'make'.

I get this strange error:

make: *** No rule to make target `/Makefile', needed by `Makefile'.  Stop.

If, however, I use
make -f "full-path-to-makefile" it actually does run (with odd consequences...). I should say that I'm running all this from the directory where the Makefile lies, of course.

I'm working on Mac OSX, using tcsh.

Edit:

I'm working in the LLVM framework, trying to compile a pass function and this is  the associated makefile:

LEVEL = ../../../
LIBRARYNAME = FunctionName
LOADABLE_MODULE = 1
include $(LEVEL)/Makefile.common

Any ideas will be appreciated :)

Body:
Since your include line reads:

include $(LEVEL)/Makefile.common

it is puzzling that you are not getting an error about /Makefile.common.  If you were, then I'd suggest that maybe you have a trailing blank after the definition of LEVEL.

Could there be a line in Makefile.common that itself includes $(SOMEMACRO)/Makefile and you have not set the value of SOMEMACRO?


问:
How to check if there is a string equal to your variable in a csv file line
I have a variable (aTerm) which contains an 8 digit random number which im using to uniquely identify each individual line of a csv file.

Here is the code I wrote to remove the line which has the corresponding number:

```<code>def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not aTerm in line:
                newFile.write(line)
return
</code>```

The only trouble is that it doesn't work at all unless I type out the 8 digit number as a string in the if statement. So this works perfectly:

```<code>def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not "45893243" in line:
                newFile.write(line)
return
</code>```

I don't understand and would greatly appreciate the help thanks

答:
You need to cast aTerm to str in order to compare it to a str:

```<code>def rebuildFile(aTerm, aFile):
    sTerm = str(aTerm)
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not sTerm in line:
                newFile.write(line)
</code>```

Body:
I have a variable (aTerm) which contains an 8 digit random number which im using to uniquely identify each individual line of a csv file.

Here is the code I wrote to remove the line which has the corresponding number:

def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not aTerm in line:
                newFile.write(line)
return

The only trouble is that it doesn't work at all unless I type out the 8 digit number as a string in the if statement. So this works perfectly:

def rebuildFile(aTerm, aFile):
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not "45893243" in line:
                newFile.write(line)
return

I don't understand and would greatly appreciate the help thanks

Body:
You need to cast aTerm to str in order to compare it to a str:

def rebuildFile(aTerm, aFile):
    sTerm = str(aTerm)
    with open(aFile, 'r') as oldFile, open('static\\new.csv', 'w') as newFile:
        for line in oldFile:
            if not sTerm in line:
                newFile.write(line)


问:
Decoration view not getting removed after deleting entire row in collection view
I have added decoration view to the UICollectionView by sub classing UICollectionViewFlowLayout. Im placing decoration view under each row in collection view. Its works fine. Decoration views appearing. But the problem is decoration views are not getting removed from the collection view after deleting one entire row of items. But the the header and footer views are repositioned correctly it's not handled by me. I dont know where to remove decoration view after deletion. help me. My calculation of decoration view in prepareLayout is fine there number of decoration views and frame is correct

(Fig 1) Before deletion  (Fig2) After deletion

答:
Use methods in UICollectionViewLayout to remove supplementary/decoration View:

```<code>func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem])

func indexPathsToDeleteForSupplementaryView(ofKind elementKind: String) -> [IndexPath]

func indexPathsToInsertForDecorationView(ofKind elementKind: String) -> [IndexPath]
</code>```

if you're not familiar with them, well, you should read the document really carefully

Body:
Use methods in UICollectionViewLayout to remove supplementary/decoration View:

func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem])

func indexPathsToDeleteForSupplementaryView(ofKind elementKind: String) -> [IndexPath]

func indexPathsToInsertForDecorationView(ofKind elementKind: String) -> [IndexPath]

if you're not familiar with them, well, you should read the document really carefully


问:
How do you write the sql to delete a line from a database in a detailsView control using VB?
Using a DetailsView control on a web page coding in VB.Net Framework 4.5.2 on Visual Studio (Think its VS 2014).  Need it to delete an item from a database (.mdf file format).  The database is provided by the class, but the auto generation option for the Edit, Delete, and New keys is locked out for some reason.

I have the Edit, and New buttons working, as I could get that out of the book and it was easy to adjust them for this database.  What I can't get to work is the line for delete.  Here is what I have (Adjusted from the book I'm using):

```<code>DELETE FROM Schedule WHERE (ID = @ID)
</code>```

When I go to debug it, I get the following error:

Must declare the scalar variable "@ID".
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@ID".

I don't know where to go from here.

答:
```<code>dim cmd as new sqlcommand("Delete from tablename where ID=@id",constring)
cmd.parameters.add("@id", idno.text)
cmd.executenonquery
</code>```

This is how u should do it

Body:
Using a DetailsView control on a web page coding in VB.Net Framework 4.5.2 on Visual Studio (Think its VS 2014).  Need it to delete an item from a database (.mdf file format).  The database is provided by the class, but the auto generation option for the Edit, Delete, and New keys is locked out for some reason.

I have the Edit, and New buttons working, as I could get that out of the book and it was easy to adjust them for this database.  What I can't get to work is the line for delete.  Here is what I have (Adjusted from the book I'm using):

DELETE FROM Schedule WHERE (ID = @ID)

When I go to debug it, I get the following error:

Must declare the scalar variable "@ID".
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@ID".

I don't know where to go from here.

Body:
dim cmd as new sqlcommand("Delete from tablename where ID=@id",constring)
cmd.parameters.add("@id", idno.text)
cmd.executenonquery

This is how u should do it


问:
NHibernate updates row before deleting it?
I'm having a strange behavior with nhibernate. The problem is that
nhibernate performs an update before it deletes an entity.
I have a Category class and a Product class. Category has a bag of
products. When I remove a product from Category, nhibernate does the
following:

It updates the product entity which I removed from collection

It deletes the product entity from database.

Here's mapping

```<code>  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="all-delete-orphan" lazy="false"
inverse="false">
      <key column="CategoryId" />
      <one-to-many class="Product" />
    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>
</code>```

Here's the code

```<code>    using (var session = NHibernateHelper.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        var c1 = session.Load<Category>(32768);
        c1.Ps.RemoveAt(0);

        session.SaveOrUpdate(c1);
        transaction.Commit();
    }
</code>```

and here's the result:

```<code>exec sp_executesql N'UPDATE Product SET CategoryId = null WHERE
CategoryId = @p0 AND Id = @p1',N'@p0 int,@p1 int',@p0=32768,@p1=65537
go

exec sp_executesql N'DELETE FROM Product WHERE Id = @p0',N'@p0
int',@p0=65537
go
</code>```

Anyone can explain this strange behavior?

Thanks.

答:
This behavior looks normal to me.  I have little experience with NHibernate, but in order to delete a record I believe you typically call the ISession.Delete method, passing in the object that represents the record you want to delete.

In your case, you might be able to do the following:

```<code>// delete a product
session.Delete(c1.Ps[0]);
</code>```

Or, to be more clear:

```<code>// find the product that I want to delete
var product = c1.Ps[0];

// now delete it
session.Delete(product);
</code>```

Your code appears to be taking a roundabout way of deleting the Product record.  Your code is not explicitly deleting the product, rather it is disassociating that Product record with that Category record.  That's why NHibernate is doing the update.

Notice that in your Category class you've defined the "cascade" attribute of the relationship to the Product class as the following:  cascade="all-delete-orphan".  Because your update statement causes that Product record to be orphaned, NHibernate probably recognizes that the Product record should be deleted, according to your cascade setting, and so I assume that's why it decides to execute the delete statement.

Body:
I'm having a strange behavior with nhibernate. The problem is that
nhibernate performs an update before it deletes an entity.
I have a Category class and a Product class. Category has a bag of
products. When I remove a product from Category, nhibernate does the
following:

It updates the product entity which I removed from collection

It deletes the product entity from database.

Here's mapping

  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="all-delete-orphan" lazy="false"
inverse="false">
      <key column="CategoryId" />
      <one-to-many class="Product" />
    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>

Here's the code

    using (var session = NHibernateHelper.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        var c1 = session.Load<Category>(32768);
        c1.Ps.RemoveAt(0);

        session.SaveOrUpdate(c1);
        transaction.Commit();
    }

and here's the result:

exec sp_executesql N'UPDATE Product SET CategoryId = null WHERE
CategoryId = @p0 AND Id = @p1',N'@p0 int,@p1 int',@p0=32768,@p1=65537
go

exec sp_executesql N'DELETE FROM Product WHERE Id = @p0',N'@p0
int',@p0=65537
go

Anyone can explain this strange behavior?

Thanks.

Body:
This behavior looks normal to me.  I have little experience with NHibernate, but in order to delete a record I believe you typically call the ISession.Delete method, passing in the object that represents the record you want to delete.

In your case, you might be able to do the following:

// delete a product
session.Delete(c1.Ps[0]);

Or, to be more clear:

// find the product that I want to delete
var product = c1.Ps[0];

// now delete it
session.Delete(product);

Your code appears to be taking a roundabout way of deleting the Product record.  Your code is not explicitly deleting the product, rather it is disassociating that Product record with that Category record.  That's why NHibernate is doing the update.

Notice that in your Category class you've defined the "cascade" attribute of the relationship to the Product class as the following:  cascade="all-delete-orphan".  Because your update statement causes that Product record to be orphaned, NHibernate probably recognizes that the Product record should be deleted, according to your cascade setting, and so I assume that's why it decides to execute the delete statement.


问:
jQuery how to replace text node for children of elements
I want to replace all text of children of elements.

such as this, I replace all text children of II.Maybe has other tag.
not only
 and
.

I

II

A

B

1

2

3

C

III

I want get like this:

I

II

test: A

test: B

test: 1

test: 2

test: 3

test: C

III

I try code it, but I fail.

Why the .find('*') is failure?

<!DOCTYPE html>

I

II

A

B

1

2

3

C

III

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

<p>I can not modify this HTML because it is not the code I wrote.
so I use js to modify it.</p>

<p>Thank!</p>

<h1>update</h1>

<p>I solve it, Thank anyone!</p>

<p>Text Node is not a <code>Elements</code>, so <code>find('*')</code> can not <strong>capture</strong> it. I find <code>contents()</code> can <strong>capture</strong> it.
This is My code</p>

```    $('ul.level-2').find('*').contents().filter(function () {
        return this.nodeType === 3 && !!this.textContent.trim();
    }).each(function () {
        this.textContent = 'test'+this.textContent
    });
```

答:
What you need is recursion:

```<code>function recursivelyChangeText($node, transformFunc) {
  var children = $node.children()
  if(children.length > 0) {
    for(var i = 0; i < children.length; i++) {
      recursivelyChangeText($(children[i]), transformFunc)
    }
  } else {
    $node.text(transformFunc($node.text()))
  }
}

recursivelyChangeText($('ul.level-2'), function(text) {
  return `test: ${text}`
})
</code>```

here's a codepen:
SO Answer - Recursively Change Dom Content with jQuery by Matt Black (@mattblackdev) on CodePen.

Body:
I want to replace all text of children of elements.

such as this, I replace all text children of II.Maybe has other tag.
not only
 and
.

I

II

A

B

1

2

3

C

III

I want get like this:

I

II

test: A

test: B

test: 1

test: 2

test: 3

test: C

III

I try code it, but I fail.

Why the .find('*') is failure?

<!DOCTYPE html>

I

II

A

B

1

2

3

C

III

I can not modify this HTML because it is not the code I wrote.
so I use js to modify it.

Thank!

update

I solve it, Thank anyone!

Text Node is not a Elements, so find('*') can not capture it. I find contents() can capture it.
This is My code

    $('ul.level-2').find('*').contents().filter(function () {
        return this.nodeType === 3 && !!this.textContent.trim();
    }).each(function () {
        this.textContent = 'test'+this.textContent
    });

Body:
What you need is recursion:

function recursivelyChangeText($node, transformFunc) {
  var children = $node.children()
  if(children.length > 0) {
    for(var i = 0; i < children.length; i++) {
      recursivelyChangeText($(children[i]), transformFunc)
    }
  } else {
    $node.text(transformFunc($node.text()))
  }
}

recursivelyChangeText($('ul.level-2'), function(text) {
  return `test: ${text}`
})

here's a codepen:
SO Answer - Recursively Change Dom Content with jQuery by Matt Black (@mattblackdev) on CodePen.


问:
Exception Value:failed to find libmagic. Check your installation in windows 7
When I am trying to open django admin panel this error is showing:

```<code>ImportError at /admin/
failed to find libmagic.  Check your installation
Request Method: GET
Request URL:    Django Version: 1.5.1
Exception Type: ImportError
Exception Value:    failed to find libmagic.  Check your installation
Exception Location: C:\Python27\lib\site-packages\magic.py in <module>, line 131
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\Users\\farhan\\Downloads\\dist\\Django-1.5.1\\django\\bin\\mysite',
 'C:\\Python27\\lib\\site-packages\\distribute-0.6.49-py2.7.egg',
 'C:\\Windows\\system32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages',
 'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info']
Server time:    Thu, 22 Aug 2013 13:19:01 +0600
</code>```

Here is my traceback

答:
Go here and then:

For Windoes 32bit, download the file "python_magic_bin-0.4.14-py2.py3-none-win32.whl" and run

```<code>pip install python_magic_bin-0.4.14-py2.py3-none-win32.whl
</code>```

For Windows 64bit, download "python_magic_bin-0.4.14-py2.py3-none-win_amd64.whl" and run

```<code>pip install python_magic_bin-0.4.14-py2.py3-none-win_amd64.whl
</code>```

now python-magic works

EDIT:
As suggested in the comments, this also works:

```<code>pip install python-magic-bin==0.4.14
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I am trying to open django admin panel this error is showing:

ImportError at /admin/
failed to find libmagic.  Check your installation
Request Method: GET
Request URL:    Django Version: 1.5.1
Exception Type: ImportError
Exception Value:    failed to find libmagic.  Check your installation
Exception Location: C:\Python27\lib\site-packages\magic.py in <module>, line 131
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\Users\\farhan\\Downloads\\dist\\Django-1.5.1\\django\\bin\\mysite',
 'C:\\Python27\\lib\\site-packages\\distribute-0.6.49-py2.7.egg',
 'C:\\Windows\\system32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages',
 'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info']
Server time:    Thu, 22 Aug 2013 13:19:01 +0600

Here is my traceback

Body:
Go here and then:

For Windoes 32bit, download the file "python_magic_bin-0.4.14-py2.py3-none-win32.whl" and run

pip install python_magic_bin-0.4.14-py2.py3-none-win32.whl

For Windows 64bit, download "python_magic_bin-0.4.14-py2.py3-none-win_amd64.whl" and run

pip install python_magic_bin-0.4.14-py2.py3-none-win_amd64.whl

now python-magic works

EDIT:
As suggested in the comments, this also works:

pip install python-magic-bin==0.4.14


问:
Printing rectangle from instance method
I am having trouble with an instance method that uses a nested for loop to print a rectangle of asterisks.  When the code is executed, once it hits the print method the output in the console disappears and the program continues running.

    public class Rectangle {

```<code>private int length;
private int width;

//Constructor for a rectangle with no parameters
public Rectangle() {

    //create a square rectangle with length of 1
    length = 1;
    width = 1;
</code>```

}//End Rectangle0

```<code>//Constructor for a rectangle with 2 parameters
public Rectangle(int len, int wid) {

    //create a rectangle with given parameters
    length = len;
    width = wid;

}//end Rectangle2

//method to print rectangle
public void print() {

    //loop to print rectangle
    for(int i = 0; i <= length; i++) {
        for(int j = 0; j <= width; i++) {

            System.out.print("*");//prints row

        }//end nested for loop

        System.out.println();//begin new line

    }//end for loop
}//End method print
</code>```

}//End class rectangle

 If the length = 3 and width = 4, output should be three rows of asterisks all with 4 columns of asterisks

 Instead of that result, once it begins to print the rectangle, all output disappears from the console and the program does not stop running.

答:
You are incrementing 'i' in the inner j loop, Change that to j++.
Also since you are using i <= length so start the loop from i=1 instead of i=0. Same for inner j loop.
Hope this helps.</p>

Title: Printing rectangle from instance method

Body:
I am having trouble with an instance method that uses a nested for loop to print a rectangle of asterisks.  When the code is executed, once it hits the print method the output in the console disappears and the program continues running.

    public class Rectangle {

private int length;
private int width;

//Constructor for a rectangle with no parameters
public Rectangle() {

    //create a square rectangle with length of 1
    length = 1;
    width = 1;

}//End Rectangle0

//Constructor for a rectangle with 2 parameters
public Rectangle(int len, int wid) {

    //create a rectangle with given parameters
    length = len;
    width = wid;

}//end Rectangle2

//method to print rectangle
public void print() {

    //loop to print rectangle
    for(int i = 0; i <= length; i++) {
        for(int j = 0; j <= width; i++) {

            System.out.print("*");//prints row

        }//end nested for loop

        System.out.println();//begin new line

    }//end for loop
}//End method print

}//End class rectangle

 If the length = 3 and width = 4, output should be three rows of asterisks all with 4 columns of asterisks

 Instead of that result, once it begins to print the rectangle, all output disappears from the console and the program does not stop running.


问:
Data returning from api call through service to component is an object and seems to need to be an Array for Angular
I have data returned to me that works just fine

working data is

data: Array(16)

Data that is NOT working is like this

data:  Menu1Items: Array(5)  > 0 { .... }    etc

I am using Angular 5, and so service returns data like this

```<code>  .map((response: Response) => {
            return response;
</code>```

Then the component intercepts it and console.log works fine

```<code>this.arsSevice.getMenu()
        .subscribe(
            result => {
                this.testing = result;
                console.log('menu',result);
            })
</code>```

problem is with the data,  this screenshot shows the problem, i just don't understand how to fix it with the object vs array?

error message ONLY because of the HTML TEMPLATE

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML Template

```<code><li *ngFor="let item of testing">
</code>```

Image showing that a call that is similar in architecture with html template loop,  component , service  the working call is the BOTTOM , component  notice the different compared to the one called menu that I'm having trouble with?

答:
With HttpClient angular automatically parses the reponse into an object. It doesn't know what type of object that is, so it's just a normal object that doesn't know its array properties.

That's because while HttpClient parsed the JSON response into an Object, it doesn't know what shape that object is.

But you can tell angular what type the returning object is so it is cast properly. For example if you get back an array of strings you could do something like this.

```<code>return this.http.get<string[]>(apiUrl)
</code>```

You can read more here, they are describing a similar problem, just with a little different structure.

Body:
I have data returned to me that works just fine

working data is

data: Array(16)

Data that is NOT working is like this

data:  Menu1Items: Array(5)  > 0 { .... }    etc

I am using Angular 5, and so service returns data like this

  .map((response: Response) => {
            return response;

Then the component intercepts it and console.log works fine

this.arsSevice.getMenu()
        .subscribe(
            result => {
                this.testing = result;
                console.log('menu',result);
            })

problem is with the data,  this screenshot shows the problem, i just don't understand how to fix it with the object vs array?

error message ONLY because of the HTML TEMPLATE

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML Template

Image showing that a call that is similar in architecture with html template loop,  component , service  the working call is the BOTTOM , component  notice the different compared to the one called menu that I'm having trouble with?

Body:
With HttpClient angular automatically parses the reponse into an object. It doesn't know what type of object that is, so it's just a normal object that doesn't know its array properties.

That's because while HttpClient parsed the JSON response into an Object, it doesn't know what shape that object is.

But you can tell angular what type the returning object is so it is cast properly. For example if you get back an array of strings you could do something like this.

return this.http.get<string[]>(apiUrl)

You can read more here, they are describing a similar problem, just with a little different structure.


问:
Test if a promise is resolved or rejected with Jasmine in Nodejs
I know how to do it in Mocha but want to know how to do it with Jasmine.
I tried this

describe('test promise with jasmine', function() {
    it('expects a rejected promise', function() {
        var promise = getRejectedPromise();

        // return expect(promise).toBe('rejected');
        return expect(promise.inspect().state).toBe('rejected');
    });
});
```

However, the state is always pending and, of course, the test fails. I couldn't find any example online that I could make it work.

Can someone please help me with this?

Thanks.

答:
@Leonid's answer is correct, but you can simplify like so, and use only promises:</p>

```<code>it('test promise with jasmine', function() {

    return getRejectedPromise().then(function() {
      // Promise should not be resolved, so we reject it
      return Promise.reject(new Error('Promise should not be resolved'));
    })
    .catch(function(err){
       if(!/Promise should not be resolved/.test(err && err.message)){
          return Promise.reject(err);
       }
    })
})
</code>```

Body:
I know how to do it in Mocha but want to know how to do it with Jasmine.
I tried this

describe('test promise with jasmine', function() {
    it('expects a rejected promise', function() {
        var promise = getRejectedPromise();

        // return expect(promise).toBe('rejected');
        return expect(promise.inspect().state).toBe('rejected');
    });
});

However, the state is always pending and, of course, the test fails. I couldn't find any example online that I could make it work.

Can someone please help me with this?

Thanks.

Body:
@Leonid's answer is correct, but you can simplify like so, and use only promises:

it('test promise with jasmine', function() {

    return getRejectedPromise().then(function() {
      // Promise should not be resolved, so we reject it
      return Promise.reject(new Error('Promise should not be resolved'));
    })
    .catch(function(err){
       if(!/Promise should not be resolved/.test(err && err.message)){
          return Promise.reject(err);
       }
    })
})


问:
scroll effect with labels using delay C#
I have a problem. I need to create a scroll effect with labels. The essence is to put the value to label with 1 sec delay.
I have a function which generates for each label number of the array. But it occurs immediately and I tried to make a delay. I used Timer but it doesn't give me any results or I just don't know how to use it correctly. Also tried to use Thread.Sleep() but it doesn't give me expected result.

```<code>public void generator() // присваивание текстбоксам значений
    {
        int[] array = getUniqueRandomArray(1, 81, 20).ToArray();
        green = 0;

        for (int i = 0; i < array.Length; i++)
        {
            panel1.Controls[i].Text = array[i].ToString();
            Thread.Sleep(350);
            panel1.Controls[i].Refresh();

            foreach (DataGridViewRow currentRow in dataGridView1.Rows)
            {
                foreach (DataGridViewCell currentCell in currentRow.Cells)
                {
                    if (Convert.ToInt32(currentCell.Value) == array[i] && currentCell.Style.BackColor == Color.Yellow)
                    {
                        currentCell.Style.BackColor = Color.Green;
                        green++;
                        panel1.Controls[i].BackColor = Color.Green;
                    }

                }
            }
        }
    }
</code>```

getUniqueRandomArray(1, 81, 20) - this function generates an array from 1 to 80 and returns 20 numbers.

When I use Thread.Sleep(350) I press the button and the form is freezing then each label gets a value from an array with delay 350ms. If I press this button one more time the current value replaces previous value without cleaning previous values though I clean them with:

```<code>for (int i = 0; i < panel1.Controls.Count; i++)
        {
            panel1.Controls[i].BackColor = Color.White;
            panel1.Controls[i].Text = null;
        }
</code>```

It is my actual result. But I expect to do described instructions without freezing from and in another thread that will allow me to use form while such circle is run.

And finally I'll try to explain more clearly:

I have 20 labels and 20 numbers. I need to assign each label the number with some delay - label1 = "1" -> (wait 1s) -> label2 = "2" -> (wait 1s) ... etc.

I would be grateful for help :)

答:
You can do this with a Timer control on the form.  The trick is to let the timer Tick event replace the outer loop, such that each "tick" of the timer performs one iteration.  Follow these steps:

Add a Timer control to your form.  I'll assume here it is called timer1.

In the timer properties, set the Interval to 1000.  This will cause it to "tick" once per second.  Be sure the Enabled property is set to False.

Add a couple of private fields to your form to keep track of the generated array of numbers and the index of the next label to be populated:

```<code>private int[] generatedArray;
private int nextControlIndex = 0;
</code>```

Double-click on the timer in the form to add a Tick event handler.  In the handler, add the following code:

```<code>private void timer1_Tick(object sender, EventArgs e)
{
    int i = nextControlIndex++;
    if (i < panel1.Controls.Count && i < generatedArray.Length)
    {
        panel1.Controls[i].Text = generatedArray[i].ToString();

        foreach (DataGridViewRow currentRow in dataGridView1.Rows)
        {
            foreach (DataGridViewCell currentCell in currentRow.Cells)
            {
                if (Convert.ToInt32(currentCell.Value) == generatedArray[i] &&
                    currentCell.Style.BackColor == Color.Yellow)
                {
                    currentCell.Style.BackColor = Color.Green;
                    green++;
                    panel1.Controls[i].BackColor = Color.Green;
                }
            }
        }
    }
    else
    {
        timer1.Stop();
    }
}
</code>```

Finally, change the code for your generator() method to set up the private fields and start the timer:

```<code>public void generator() // присваивание текстбоксам значений
{
    generatedArray = getUniqueRandomArray(1, 81, 20).ToArray();
    nextControlIndex = 0;
    green = 0;
    timer1.Start();
}
</code>```

And that's it.  Now the labels should get populated incrementally whenever you call the generator() function.

Body:
I have a problem. I need to create a scroll effect with labels. The essence is to put the value to label with 1 sec delay.
I have a function which generates for each label number of the array. But it occurs immediately and I tried to make a delay. I used Timer but it doesn't give me any results or I just don't know how to use it correctly. Also tried to use Thread.Sleep() but it doesn't give me expected result.

public void generator() // присваивание текстбоксам значений
    {
        int[] array = getUniqueRandomArray(1, 81, 20).ToArray();
        green = 0;

        for (int i = 0; i < array.Length; i++)
        {
            panel1.Controls[i].Text = array[i].ToString();
            Thread.Sleep(350);
            panel1.Controls[i].Refresh();

            foreach (DataGridViewRow currentRow in dataGridView1.Rows)
            {
                foreach (DataGridViewCell currentCell in currentRow.Cells)
                {
                    if (Convert.ToInt32(currentCell.Value) == array[i] && currentCell.Style.BackColor == Color.Yellow)
                    {
                        currentCell.Style.BackColor = Color.Green;
                        green++;
                        panel1.Controls[i].BackColor = Color.Green;
                    }

                }
            }
        }
    }

getUniqueRandomArray(1, 81, 20) - this function generates an array from 1 to 80 and returns 20 numbers.

When I use Thread.Sleep(350) I press the button and the form is freezing then each label gets a value from an array with delay 350ms. If I press this button one more time the current value replaces previous value without cleaning previous values though I clean them with:

for (int i = 0; i < panel1.Controls.Count; i++)
        {
            panel1.Controls[i].BackColor = Color.White;
            panel1.Controls[i].Text = null;
        }

It is my actual result. But I expect to do described instructions without freezing from and in another thread that will allow me to use form while such circle is run.

And finally I'll try to explain more clearly:

I have 20 labels and 20 numbers. I need to assign each label the number with some delay - label1 = "1" -> (wait 1s) -> label2 = "2" -> (wait 1s) ... etc.

I would be grateful for help :)

Body:
You can do this with a Timer control on the form.  The trick is to let the timer Tick event replace the outer loop, such that each "tick" of the timer performs one iteration.  Follow these steps:

Add a Timer control to your form.  I'll assume here it is called timer1.

In the timer properties, set the Interval to 1000.  This will cause it to "tick" once per second.  Be sure the Enabled property is set to False.

Add a couple of private fields to your form to keep track of the generated array of numbers and the index of the next label to be populated:

private int[] generatedArray;
private int nextControlIndex = 0;

Double-click on the timer in the form to add a Tick event handler.  In the handler, add the following code:

private void timer1_Tick(object sender, EventArgs e)
{
    int i = nextControlIndex++;
    if (i < panel1.Controls.Count && i < generatedArray.Length)
    {
        panel1.Controls[i].Text = generatedArray[i].ToString();

        foreach (DataGridViewRow currentRow in dataGridView1.Rows)
        {
            foreach (DataGridViewCell currentCell in currentRow.Cells)
            {
                if (Convert.ToInt32(currentCell.Value) == generatedArray[i] &&
                    currentCell.Style.BackColor == Color.Yellow)
                {
                    currentCell.Style.BackColor = Color.Green;
                    green++;
                    panel1.Controls[i].BackColor = Color.Green;
                }
            }
        }
    }
    else
    {
        timer1.Stop();
    }
}

Finally, change the code for your generator() method to set up the private fields and start the timer:

public void generator() // присваивание текстбоксам значений
{
    generatedArray = getUniqueRandomArray(1, 81, 20).ToArray();
    nextControlIndex = 0;
    green = 0;
    timer1.Start();
}

And that's it.  Now the labels should get populated incrementally whenever you call the generator() function.


问:
What's wrong when use mypy to check type
```<code>from typing import Dict, List, Any, AnyStr, TypeVar
def abc(xyz: str) -> Dict[AnyStr, Any]:
    return {"abc": 1}
</code>```

And I use mypy to check this file. It's giving an Error.

Below is the Error message

"Dict entry 0 has incompatible type "str": "int"; expected "bytes":
  "Any""

But I don't know why

答:
The issue is that AnyStr is actually an alias for a typevar. This means your program is actually exactly equivalent to writing:

```<code>from typing import Dict, Any, AnyStr, TypeVar

T = TypeVar('T', str, bytes)

def abc(xyz: str) -> Dict[T, Any]:
    return {"abc": 1}
</code>```

This, however, presents us with a problem: how is mypy supposed to infer which of the two possible alternatives you wanted for T?

There are three possible fixes. You can either...

Find some way of using AnyStr at least two or more times within your type signature. For example, perhaps you decide this is really more what you meant?

```<code>def abc(xyz: AnyStr) -> Dict[AnyStr, Any]:
    # etc
</code>```

Use Union[str, bytes] instead of AnyStr:

```<code>from typing import Union, Dict, Any

def abc(xyz: str) -> Dict[Union[str, bytes], Any]:
    # etc
</code>```

If the type signature is starting to get uncomfortably long, you can shorten it by using a type alias:

```<code>from typing import Union, Dict, Any

# Note: this isn't a great type alias name, but whatever
UnionStr = Union[str, bytes]

def abc(xyz: str) -> Dict[UnionStr, Any]:
    # etc
</code>```

Body:
from typing import Dict, List, Any, AnyStr, TypeVar
def abc(xyz: str) -> Dict[AnyStr, Any]:
    return {"abc": 1}

And I use mypy to check this file. It's giving an Error.

Below is the Error message

"Dict entry 0 has incompatible type "str": "int"; expected "bytes":
  "Any""

But I don't know why

Body:
The issue is that AnyStr is actually an alias for a typevar. This means your program is actually exactly equivalent to writing:

from typing import Dict, Any, AnyStr, TypeVar

T = TypeVar('T', str, bytes)

def abc(xyz: str) -> Dict[T, Any]:
    return {"abc": 1}

This, however, presents us with a problem: how is mypy supposed to infer which of the two possible alternatives you wanted for T?

There are three possible fixes. You can either...

Find some way of using AnyStr at least two or more times within your type signature. For example, perhaps you decide this is really more what you meant?

def abc(xyz: AnyStr) -> Dict[AnyStr, Any]:
    # etc

Use Union[str, bytes] instead of AnyStr:

from typing import Union, Dict, Any

def abc(xyz: str) -> Dict[Union[str, bytes], Any]:
    # etc

If the type signature is starting to get uncomfortably long, you can shorten it by using a type alias:

from typing import Union, Dict, Any

# Note: this isn't a great type alias name, but whatever
UnionStr = Union[str, bytes]

def abc(xyz: str) -> Dict[UnionStr, Any]:
    # etc


问:
Passing values to functions in React Native from Array
I am extracting data from a JSON Array and creating objects out of it and setting the string values that I need from the array within the objects I am creating using a for loop:

```<code>var gamesList = [];
gamesList = this.props.navigation.state.params.gamesList;
var gameIconList = [];

for(var i=0;i<3;i++){
  var provider = gamesList[i].provider;
  var gameId = gamesList[i].gameId.toString();

  gameIconList.push(
    <TouchableOpacity onPress={(provider,gameId) => this.launchGame(provider,gameId)}>
      <ResponsiveImage source={{uri: gamesList[i].imageUrl}}
      initWidth="200" initHeight="120" defaultSource={require('./splash-tile2.png')} />
    </TouchableOpacity>
  );
}
</code>```

This is all happening within the render() function and the {gameIconList} will be called in the return() function as below:

```<code>return(
 <ScrollView horizontal={true}>
    {gameIconList}
 </ScrollView>
);
</code>```

As you can see I am setting the string values into the onPress function call via the loop and when I click the image within the TouchableOpacity I want the string values I am setting to be sent back to the function above which is:

```<code>  launchGame = (provider, gameId) => {

  params = {
    Provider: provider.nativeEvent.text,
    Platform: this.state.Platform,
    Environment: this.state.Environment,
    GameId: gameId,
    IsDemo: this.state.IsDemo
  };

  request = {
    method: 'POST',
    headers:{
      "Content-Type": "application/json"
    },
    body: params
  };

}
</code>```

But the problem is I have tried so many different methods and I always end up getting a Proxy object sent back to me when it comes to the provider value and an undefined sent to me when it comes to the gameId value.

I have tried the calling method of event.target.value and event.nativeEvent.text but to no avail.

What am I missing?
And if this is not the correct way of sending values to the function, can I get a guide on how to do it properly?

答:
The onPress prop for TouchableOpacity takes a callback function that is called when that element is "pressed".

This function is supposed to be an event handler. It is conventional that an event handler is called with an event object. I think you are misunderstanding how callback functions are called. Please go through this.

So, your function is called with the event object (proxy event object in React) in the first argument and undefined as the second argument.

Do this instead:

```<code><TouchableOpacity onPress={() => this.launchGame(provider, gameId)}>
</code>```

But there is more. This probably won't work properly because of how closures work. See here.

Basically, you are changing the value in provider and gameId on each loop. The callback functions have these variables in its closure, but they do not store the exact value that was there when these functions were defined (basically, you'll get the last value stored in provide and gameId when pressing on all of the TouchableOpacity). This is also because you are using var, instead of let or const, which had function scope and not block scope.

You can do this instead:

```<code><TouchableOpacity onPress={() => {
  var provider = gamesList[i].provider;
  var gameId = gamesList[i].gameId.toString();
  this.launchGame(provider, gameId)
}}>
  <ResponsiveImage
    source={{uri: gamesList[i].imageUrl}}
    initWidth="200"
    initHeight="120"
    defaultSource={require('./splash-tile2.png')}
  />
</TouchableOpacity>
</code>```

This way you are defining these variables in each callback's scope directly. (Or, if you can use let or const, change var to const when defining provider and gameId and your code should work.)

Body:
I am extracting data from a JSON Array and creating objects out of it and setting the string values that I need from the array within the objects I am creating using a for loop:

var gamesList = [];
gamesList = this.props.navigation.state.params.gamesList;
var gameIconList = [];

for(var i=0;i<3;i++){
  var provider = gamesList[i].provider;
  var gameId = gamesList[i].gameId.toString();

  gameIconList.push(
    <TouchableOpacity onPress={(provider,gameId) => this.launchGame(provider,gameId)}>
      <ResponsiveImage source={{uri: gamesList[i].imageUrl}}
      initWidth="200" initHeight="120" defaultSource={require('./splash-tile2.png')} />
    </TouchableOpacity>
  );
}

This is all happening within the render() function and the {gameIconList} will be called in the return() function as below:

return(
 <ScrollView horizontal={true}>
    {gameIconList}
 </ScrollView>
);

As you can see I am setting the string values into the onPress function call via the loop and when I click the image within the TouchableOpacity I want the string values I am setting to be sent back to the function above which is:

  launchGame = (provider, gameId) => {

  params = {
    Provider: provider.nativeEvent.text,
    Platform: this.state.Platform,
    Environment: this.state.Environment,
    GameId: gameId,
    IsDemo: this.state.IsDemo
  };

  request = {
    method: 'POST',
    headers:{
      "Content-Type": "application/json"
    },
    body: params
  };

}

But the problem is I have tried so many different methods and I always end up getting a Proxy object sent back to me when it comes to the provider value and an undefined sent to me when it comes to the gameId value.

I have tried the calling method of event.target.value and event.nativeEvent.text but to no avail.

What am I missing?
And if this is not the correct way of sending values to the function, can I get a guide on how to do it properly?

Body:
The onPress prop for TouchableOpacity takes a callback function that is called when that element is "pressed".

This function is supposed to be an event handler. It is conventional that an event handler is called with an event object. I think you are misunderstanding how callback functions are called. Please go through this.

So, your function is called with the event object (proxy event object in React) in the first argument and undefined as the second argument.

Do this instead:

<TouchableOpacity onPress={() => this.launchGame(provider, gameId)}>

But there is more. This probably won't work properly because of how closures work. See here.

Basically, you are changing the value in provider and gameId on each loop. The callback functions have these variables in its closure, but they do not store the exact value that was there when these functions were defined (basically, you'll get the last value stored in provide and gameId when pressing on all of the TouchableOpacity). This is also because you are using var, instead of let or const, which had function scope and not block scope.

You can do this instead:

<TouchableOpacity onPress={() => {
  var provider = gamesList[i].provider;
  var gameId = gamesList[i].gameId.toString();
  this.launchGame(provider, gameId)
}}>
  <ResponsiveImage
    source={{uri: gamesList[i].imageUrl}}
    initWidth="200"
    initHeight="120"
    defaultSource={require('./splash-tile2.png')}
  />
</TouchableOpacity>

This way you are defining these variables in each callback's scope directly. (Or, if you can use let or const, change var to const when defining provider and gameId and your code should work.)


问:
What should I use instead of a "for" loop when appending a number?
I have heard that the for(){...} loop in JavaScript is passé and should not be used in favor of other, clearer alternatives.  JSLint goes so far as to throw an error when it encounters one (unless you override it, of course).  I understand using Array.prototype.forEach() when the situation allows, but in this instance what alternative could I use that would be "clearer"?

```<code>var number = 5;
for (var i=0; i <= number; i++){
    log("somestring" + i);
}
</code>```

In C# I would use a foreach(){...} over Enumerable.Range(0, 5) - but I know of no such alternative in JavaScript. I could create an array of digits 0...5 but that seems like going the long way for no gain.

Edit 1

I am not looking for an alternative plugin to implement this like lodash or jQuery, and my question really isn't about "why does JSLint...".  What native JavaScript alternative would I use?

答:
If you're using an array to store your numbers, use .reduce():

```<code>const num = [1, 2, 3, 4, 5]
const val = num.reduce((acc, curr) => `${acc}${curr}`, 'somestring')
console.log(val)
</code>```

Edit: The thing is, if you don't want to use an array then the for loop would be the most readable. My advice is to just ignore what JSLint says.

I'll just post another suggestion. It uses the array indexes to generate an array:

```<code>[...Array(5).keys()].reduce((acc, curr) => `${acc}${curr + 1}`, 'somestring')
</code>```

Body:
I have heard that the for(){...} loop in JavaScript is passé and should not be used in favor of other, clearer alternatives.  JSLint goes so far as to throw an error when it encounters one (unless you override it, of course).  I understand using Array.prototype.forEach() when the situation allows, but in this instance what alternative could I use that would be "clearer"?

var number = 5;
for (var i=0; i <= number; i++){
    log("somestring" + i);
}

In C# I would use a foreach(){...} over Enumerable.Range(0, 5) - but I know of no such alternative in JavaScript. I could create an array of digits 0...5 but that seems like going the long way for no gain.

Edit 1

I am not looking for an alternative plugin to implement this like lodash or jQuery, and my question really isn't about "why does JSLint...".  What native JavaScript alternative would I use?

Body:
If you're using an array to store your numbers, use .reduce():

const num = [1, 2, 3, 4, 5]
const val = num.reduce((acc, curr) => `${acc}${curr}`, 'somestring')
console.log(val)

Edit: The thing is, if you don't want to use an array then the for loop would be the most readable. My advice is to just ignore what JSLint says.

I'll just post another suggestion. It uses the array indexes to generate an array:

[...Array(5).keys()].reduce((acc, curr) => `${acc}${curr + 1}`, 'somestring')


问:
When does a hexidecimal number pivot to letters rather than numbers
Assume this number 173250103518582539668252657343418508842, if I wanted to convert it to a hexadecimal number such that a 10 = F, 11 = E, etc. where are the breaks/how does that work?

I've done a bit of research online and I can't seem to find the answer. It's a really low-level question, I know.

6 characters in there's a 10, would that be flipped to an F or would that get missed because whatever triggers the flip in the int -> string hexadecimal conversion happens another way?

答:
Hexadecimal is an encoding used to express binary data in base-16 where the ascending sequence is 0-9a-f (upper or lower case a-f), once character per 4-bits (4-bits has 16 possible values). Thus 2 hex characters per byte.

binary bits (msb on left) and hexadecimal:

```<code>0000 0
0001 1
0010 2
0011 3
...
1001 9
1010 a
...
1111 f
</code>```

To say "10 = F, 11 = E" is not hexadecimal.

To encode the decimal number 173250103518582539668252657343418508842 convert it is a Big Integer and then hexadecimal encode the underlying bytes to hexadecimal.

or

To encode the ASCI string "173250103518582539668252657343418508842" to hexadecimal convert each letter to the underlying ASCII binary code and then encode that into hexadecimal: "313733323530313033353138353832353339363638323532363537333433343138353038383432".

See Hexadecimal and ASCII.

Aside: My first day as a programmer I had to know hex, binary and ASCII encoding, funny how things change.

Body:
Hexadecimal is an encoding used to express binary data in base-16 where the ascending sequence is 0-9a-f (upper or lower case a-f), once character per 4-bits (4-bits has 16 possible values). Thus 2 hex characters per byte.

binary bits (msb on left) and hexadecimal:

0000 0
0001 1
0010 2
0011 3
...
1001 9
1010 a
...
1111 f

To say "10 = F, 11 = E" is not hexadecimal.

To encode the decimal number 173250103518582539668252657343418508842 convert it is a Big Integer and then hexadecimal encode the underlying bytes to hexadecimal.

or

To encode the ASCI string "173250103518582539668252657343418508842" to hexadecimal convert each letter to the underlying ASCII binary code and then encode that into hexadecimal: "313733323530313033353138353832353339363638323532363537333433343138353038383432".

See Hexadecimal and ASCII.

Aside: My first day as a programmer I had to know hex, binary and ASCII encoding, funny how things change.


问:
Compute 3 Month return for dataframe of monthly returns
I have a dataframe of monthly stock returns:

```<code>d<-data.frame(replicate(5,sample(rnorm(1),6,rep=TRUE)))
</code>```

Now I would like to transform these returns to n-month returns in the following manner (e.g. for n=3):

```<code>d[1,1]=(1+d[1,1])*(1+d[2,1])*(1+d[3,1])
d[2,1]=(1+d[2,1])*(1+d[3,1])*(1+d[4,1])
d[3,1]=(1+d[3,1])*(1+d[4,1])*(1+d[5,1])
</code>```

And then the same for the next column:

```<code>d[1,2]=(1+d[1,2])*(1+d[2,2])*(1+d[3,2])
d[2,2]=(1+d[2,2])*(1+d[3,2])*(1+d[4,2])
d[3,2]=(1+d[3,2])*(1+d[4,2])*(1+d[5,2])
</code>```

I think you get the idea.

Now, the way I was thinking to proceed is as follows:

```<code>apply(d, 2, fun)
</code>```

where fun is defined as:

```<code>fun<-function(df_column)
{
  # Loop over df_column rows
 for (row in 1:nrow(df_column)) {
   d[row]=(1+d[row])*(1+d[row+1])*(1+d[row+2])
 }
}
</code>```

Does this approach make sense or is there a more elegant way?

答:
You can use purrr::map_df and dplyr::lead to achieve what you are after.

```<code>library(dplyr)
library(purrr)

set.seed(42)

df <- data.frame(replicate(5, rnorm(6)))

df %>%
  map_df(function(x) {

    (1 + x) * (1 + lead(x, 1)) * (1 + lead(x, 2))

  })

# # A tibble: 6 x 5
#          X1       X2         X3         X4         X5
#       <dbl>    <dbl>      <dbl>      <dbl>      <dbl>
# 1 1.4068610 6.863243 -0.2430606 -2.3172461  1.2246900
# 2 0.9688954 2.561324  1.0225645 -1.2568729 -0.3228241
# 3 3.1256224 6.520767  1.0148172 -0.4485965 -0.8276191
# 4 2.0496361 7.100212 -1.9395879 -1.4328679 -0.4011510
# 5        NA       NA         NA         NA         NA
# 6        NA       NA         NA         NA         NA
</code>```

N.B. As you are looking ahead two records, note that the final two rows will only produce NA. You could add na.omit or tidyr::drop_na to your pipe if you want them to be excluded.

Body:
I have a dataframe of monthly stock returns:

d<-data.frame(replicate(5,sample(rnorm(1),6,rep=TRUE)))

Now I would like to transform these returns to n-month returns in the following manner (e.g. for n=3):

d[1,1]=(1+d[1,1])*(1+d[2,1])*(1+d[3,1])
d[2,1]=(1+d[2,1])*(1+d[3,1])*(1+d[4,1])
d[3,1]=(1+d[3,1])*(1+d[4,1])*(1+d[5,1])

And then the same for the next column:

d[1,2]=(1+d[1,2])*(1+d[2,2])*(1+d[3,2])
d[2,2]=(1+d[2,2])*(1+d[3,2])*(1+d[4,2])
d[3,2]=(1+d[3,2])*(1+d[4,2])*(1+d[5,2])

I think you get the idea.

Now, the way I was thinking to proceed is as follows:

apply(d, 2, fun)

where fun is defined as:

fun<-function(df_column)
{
  # Loop over df_column rows
 for (row in 1:nrow(df_column)) {
   d[row]=(1+d[row])*(1+d[row+1])*(1+d[row+2])
 }
}

Does this approach make sense or is there a more elegant way?

Body:
You can use purrr::map_df and dplyr::lead to achieve what you are after.

library(dplyr)
library(purrr)

set.seed(42)

df <- data.frame(replicate(5, rnorm(6)))

df %>%
  map_df(function(x) {

    (1 + x) * (1 + lead(x, 1)) * (1 + lead(x, 2))

  })

# # A tibble: 6 x 5
#          X1       X2         X3         X4         X5
#       <dbl>    <dbl>      <dbl>      <dbl>      <dbl>
# 1 1.4068610 6.863243 -0.2430606 -2.3172461  1.2246900
# 2 0.9688954 2.561324  1.0225645 -1.2568729 -0.3228241
# 3 3.1256224 6.520767  1.0148172 -0.4485965 -0.8276191
# 4 2.0496361 7.100212 -1.9395879 -1.4328679 -0.4011510
# 5        NA       NA         NA         NA         NA
# 6        NA       NA         NA         NA         NA

N.B. As you are looking ahead two records, note that the final two rows will only produce NA. You could add na.omit or tidyr::drop_na to your pipe if you want them to be excluded.


问:
Python-magic installation error - ImportError: failed to find libmagic
I am trying to install python-magic for Windows and I have followed all the instructions in https://github.com/ahupp/python-magic and repeated the process several times but I am still getting this error:

```<code>ImportError: failed to find libmagic. Check your installation
</code>```

I have magic1.dll (along with the two other files the docs specified) in C:\Windows\System32 so I am not sure what the issue is. I would appreciate any help or workarounds.

答:
Go here and download the file "python_magic_bin-0.4.14-py2.py3-none-win32.whl", then

```<code>pip install python_magic_bin-0.4.14-py2.py3-none-win32.whl
</code>```

now python-magic works

Body:
I am trying to install python-magic for Windows and I have followed all the instructions in https://github.com/ahupp/python-magic and repeated the process several times but I am still getting this error:

ImportError: failed to find libmagic. Check your installation

I have magic1.dll (along with the two other files the docs specified) in C:\Windows\System32 so I am not sure what the issue is. I would appreciate any help or workarounds.

Body:
Go here and download the file "python_magic_bin-0.4.14-py2.py3-none-win32.whl", then

pip install python_magic_bin-0.4.14-py2.py3-none-win32.whl

now python-magic works


问:
Incompatible types error when assigning inheriting class to inherited interface
So I was looking into how to use the RuntimeTypeAdapterFactory from the gson extras branch and seem to have run into a peculiar issue. My IDE doesn't show that this is an error, however, when I compile the project I get error: incompatible types: RuntimeTypeAdapterFactory cannot be converted to TypeAdapterFactory. Is there a specific reason that I cannot assign to inherited class?

```<code>public class Main {
    public static void main(String... args) {
        TypeAdapterFactory factory = new RuntimeTypeAdapterFactory<Number>()
    }
}

public final RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {}
</code>```

EDIT 1

I have made the example more clear and the exact error is:
error: incompatible types: RuntimeTypeAdapterFactory cannot be converted to TypeAdapterFactory
        return factory;

It's also worth noting that I am using IntelliJ IDEA 2017.2.5 and Gradle 4.3.1.

答: Ok, so moving some of the classes around I've determined that it's most likely an issue with gradle module configuration. Will have to look into that more, but I've essentially solved the problem by moving the class from one module to another.</p>

Body:
So I was looking into how to use the RuntimeTypeAdapterFactory from the gson extras branch and seem to have run into a peculiar issue. My IDE doesn't show that this is an error, however, when I compile the project I get error: incompatible types: RuntimeTypeAdapterFactory cannot be converted to TypeAdapterFactory. Is there a specific reason that I cannot assign to inherited class?

public class Main {
    public static void main(String... args) {
        TypeAdapterFactory factory = new RuntimeTypeAdapterFactory<Number>()
    }
}

public final RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {}

EDIT 1

I have made the example more clear and the exact error is:
error: incompatible types: RuntimeTypeAdapterFactory cannot be converted to TypeAdapterFactory
        return factory;

It's also worth noting that I am using IntelliJ IDEA 2017.2.5 and Gradle 4.3.1.


问:
reportviewer hide exporting to word and excel options
i am using visual studio 2012 and I have a rdlc report. I want to hide word and excel in the export option in ssrs ReportViewer. I Have tried couple of things but nothing seems to work! if any body can help i'd be so grateful :)

Thanks

答:
Simple Jquery trick to hide Word and Excel options from RDLC Report Viewer:</p>

```<code>$(document).ready(function() {
 $("a[title='Excel']").parent().hide(); // Remove Excel from export dropdown.
 $("a[title='Word']").parent().hide(); // Remove Word from export dropdown.
}
</code>```

Body:
Simple Jquery trick to hide Word and Excel options from RDLC Report Viewer:

$(document).ready(function() {
 $("a[title='Excel']").parent().hide(); // Remove Excel from export dropdown.
 $("a[title='Word']").parent().hide(); // Remove Word from export dropdown.
}


问:
Trying to get background-image filesize in greasemonkey
I would like to get the filesize of a submit button's background-image with javascript/greasemonkey.

<s>P.s. I don't want to reload the page or make new calls to the image. Since the image is different each load.</s>

The image is not different each time, only the name and url are :D

Sorry about that.. :/

Thanks, all, I solved the rest of my problem myself :)

答:
"I don't want to reload the page or make new calls to the image. Since the image is different each load."

There is no way to get this information in JavaScript or Greasemonkey without a second call to the server.   You would need to write your own add-on/extension to get that programmatically on the first call.

However, you can see background-image, filesize, right now.  Just right-click on the page and select View Page Info (Firefox) and then click the Media tab.

Also, you can install the Web Developer add-on.  It can show image information, including BG image, filesize.


问:
Laravel: Passing variable from Blade to relationship not working
I am trying to modify a Laravel relationship to return the related case against a question.

My question model has the following relationship entry:

```<code>/**
 * A Question has one Case Detail
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasOne
 */
public function casedetail( $caseId ) {

    return $this->hasOne( 'App\CaseDetail' )->where( 'test_case_id', $caseId );

}
</code>```

However, trying to access the casedetail from Blade using a variable like this:

```<code>{{ $Question->casedetail(2) }}
</code>```

Is returning me the following error:

```<code>"htmlspecialchars() expects parameter 1 to be string, object given (View: /home/vagrant/Code/TestBench/resources/views/testcases/category_questions.blade.php)"
</code>```

If I substitute $caseId for a specific number and remove the variable request from the method then my query works fine:

```<code>return $this->hasOne( 'App\CaseDetail' )->where( 'test_case_id', 2 );
</code>```

Result:

```<code>{"id":1,"test_case_id":2,"question_id":1,"result_type":0,"result":"now what","tester_id":1,"attachment":null,"created_at":"2017-11-30 03:17:42","updated_at":"2017-12-04 06:57:40"}
</code>```

I am trying to retrieve the specific CaseDetail from the database that relates to the question_id and test_case_id. So for each question, give me the related CaseDetail:

```<code>@foreach( $Category->Questions as $Question )

    {{ $Question->casedetail( $TestCase->id ) }}

@endforeach
</code>```

答:
I think everything is correct. In this case, you calling relationship method. Every relationship method returns you object of a collection.

Might be a chance here blade need single property or string to print and method returns collection?

Have you tried like this:
{{ $Question->casedetail(2)->id }}

try to print single property hope it works.

Body:
I am trying to modify a Laravel relationship to return the related case against a question.

My question model has the following relationship entry:

/**
 * A Question has one Case Detail
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasOne
 */
public function casedetail( $caseId ) {

    return $this->hasOne( 'App\CaseDetail' )->where( 'test_case_id', $caseId );

}

However, trying to access the casedetail from Blade using a variable like this:

{{ $Question->casedetail(2) }}

Is returning me the following error:

"htmlspecialchars() expects parameter 1 to be string, object given (View: /home/vagrant/Code/TestBench/resources/views/testcases/category_questions.blade.php)"

If I substitute $caseId for a specific number and remove the variable request from the method then my query works fine:

return $this->hasOne( 'App\CaseDetail' )->where( 'test_case_id', 2 );

Result:

{"id":1,"test_case_id":2,"question_id":1,"result_type":0,"result":"now what","tester_id":1,"attachment":null,"created_at":"2017-11-30 03:17:42","updated_at":"2017-12-04 06:57:40"}

I am trying to retrieve the specific CaseDetail from the database that relates to the question_id and test_case_id. So for each question, give me the related CaseDetail:

@foreach( $Category->Questions as $Question )

    {{ $Question->casedetail( $TestCase->id ) }}

@endforeach


问:
Notification vibrate issue for android 8.0
i create notification channel to show notification in android 8.0 as below

```<code> NotificationChannel uploadChannel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_UPLOAD_ID,"Uploads", NotificationManager.IMPORTANCE_LOW);
 uploadChannel.enableLights(false);
 uploadChannel.setDescription("Uploads Channel");
 notificationManager.createNotificationChannel(uploadChannel);
</code>```

each time i show notification the phone vibrate many times.
i disable vibrate from notification channel as below

```<code>uploadChannel.enableVibration(false);
</code>```

i create notification as below

```<code> NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_UPLOAD_ID);
</code>```

but it is not working phone is vibrating with each notification.

答:
This is a bug on Android 8 notification system. I've tinkered with different combinations of enableVibration with setVibrationPattern(null) but it does not work.

Only solution that stops the vibration for me is this:

```<code>mNotificationChannel.setVibrationPattern(new long[]{ 0 });
mNotificationChannel.enableVibration(true);
</code>```

FYI, even if I set a vibration pattern with 0, but set enableVibration to false, it vibrates.

Body:
i create notification channel to show notification in android 8.0 as below

 NotificationChannel uploadChannel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_UPLOAD_ID,"Uploads", NotificationManager.IMPORTANCE_LOW);
 uploadChannel.enableLights(false);
 uploadChannel.setDescription("Uploads Channel");
 notificationManager.createNotificationChannel(uploadChannel);

each time i show notification the phone vibrate many times.
i disable vibrate from notification channel as below

uploadChannel.enableVibration(false);

i create notification as below

 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_UPLOAD_ID);

but it is not working phone is vibrating with each notification.

Body:
This is a bug on Android 8 notification system. I've tinkered with different combinations of enableVibration with setVibrationPattern(null) but it does not work.

Only solution that stops the vibration for me is this:

mNotificationChannel.setVibrationPattern(new long[]{ 0 });
mNotificationChannel.enableVibration(true);

FYI, even if I set a vibration pattern with 0, but set enableVibration to false, it vibrates.


问:
phalcon MVC model how can delete data?

I am searching for a long time on net, but no luck. Please help or try to give some ideas how to achieve this.

I want to delete some data like:

```<code>$articleIds = '1,2,3,5,8';
$User    = new User();
$success = $User->delete($articleIds);
</code>```

But, that gives an error. What should I do?

Thanks in advance.

答:
Try any of the following ways of deleting multiple records, and pick the one you like the best:

A) Finding then deleting:

```<code>$ids = '1,2,3';
$records = User::find(sprintf("id IN (%s)", $ids)); // or you can avoid using sprintf and simply use concatenating operator like "IN (" . $ids . ")"
$records->delete(); // this should return boolean
</code>```

B) You can also chain the above method calls:

```<code>User::find(sprintf("id IN (%s)", $ids))->delete();
</code>```

C) Or you can iterate each record and then delete it, like shown in the Phalcon documentation: https://docs.phalconphp.com/en/3.2/db-models#delete-records

D) Or finally, you can write a 'raw' SQL statement using Phalcon PHQL:

```<code>$config = [
    'host' => '127.0.0.1',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'test'
];
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
$sql = sprintf("DELETE `users` WHERE `id` IN (%s)", $ids);
$success = $connection->execute($sql);
</code>```

More info here: https://docs.phalconphp.com/en/3.2/db-layer#crud

And remember... be very very careful with accepting record ids from user input (examples: via GET, or from a form/table that allows the user to select records). But I think this is a topic for another question.

Title: phalcon MVC model how can delete data?

Body:
I am searching for a long time on net, but no luck. Please help or try to give some ideas how to achieve this.

I want to delete some data like:

$articleIds = '1,2,3,5,8';
$User    = new User();
$success = $User->delete($articleIds);

But, that gives an error. What should I do?

Thanks in advance.

Body:
Try any of the following ways of deleting multiple records, and pick the one you like the best:

A) Finding then deleting:

$ids = '1,2,3';
$records = User::find(sprintf("id IN (%s)", $ids)); // or you can avoid using sprintf and simply use concatenating operator like "IN (" . $ids . ")"
$records->delete(); // this should return boolean

B) You can also chain the above method calls:

User::find(sprintf("id IN (%s)", $ids))->delete();

C) Or you can iterate each record and then delete it, like shown in the Phalcon documentation: https://docs.phalconphp.com/en/3.2/db-models#delete-records

D) Or finally, you can write a 'raw' SQL statement using Phalcon PHQL:

$config = [
    'host' => '127.0.0.1',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'test'
];
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
$sql = sprintf("DELETE `users` WHERE `id` IN (%s)", $ids);
$success = $connection->execute($sql);

More info here: https://docs.phalconphp.com/en/3.2/db-layer#crud

And remember... be very very careful with accepting record ids from user input (examples: via GET, or from a form/table that allows the user to select records). But I think this is a topic for another question.


答:
return is not a good idea in between a loop in javascript.this overridden due to the same you can use break or continue instead to break the execution in between. There also to get the data as foreach jquery also allowed object map to the same as follows.
and get the value for each as a dynamic string you can work as per the function is given below.

```<code>var number = 5;
var toReturn = function(){
var ar_data = [];
for (var i=0; i <= number; i++){
    ar_data[i] = "somestring" + i;  // Store your dynamic string into a variable
}
return ar_data; // return array
}
var data = toReturn(number);

for(dt in data) // foreach type object mapping and tracing
{
console.log(data[dt]); //print the individual item in array.
}
</code>```

Title: What should I use instead of a "for" loop when appending a number?

Body:
return is not a good idea in between a loop in javascript.this overridden due to the same you can use break or continue instead to break the execution in between. There also to get the data as foreach jquery also allowed object map to the same as follows.
and get the value for each as a dynamic string you can work as per the function is given below.

var number = 5;
var toReturn = function(){
var ar_data = [];
for (var i=0; i <= number; i++){
    ar_data[i] = "somestring" + i;  // Store your dynamic string into a variable
}
return ar_data; // return array
}
var data = toReturn(number);

for(dt in data) // foreach type object mapping and tracing
{
console.log(data[dt]); //print the individual item in array.
}


问:
How to make an assembly code written in Keil Software to an executable file?
I can write an assembly code for x86 processors. But I need to know how to convert it into an executable file.</p>

答:
The last time I looked, Keil made C51 (8051), not i386 (80386+) compilers.

So if that is true, and you have a C51 compiler: no chance. While the 8051 is intel, and somewhat sideways related to x86's earliest pedigree (8080), with 8086, and more importantly with i386 (and later again with x86_64), so much changed that this will probably be fruitless.

The Keil C51 compiler is 8051 8-bit with 16-bit extensions (e.g. Hitachi 80515), and you are probably looking for something i386 or x86_64 (32/64bit)


问:
How to receive AJAX (json) response in a divs with same class name individually?
I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

```<code>$('.trigger_button_inside_divs').click(my_ajax_function);
</code>```

And this is how my ajax looks like:

```<code>function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

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

HTML looks like this:

```<code><div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
</code>```

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done!
Cheers.

PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

```<code>(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

var xhr = new XMLHttpRequest();
var el;

function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })

    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}

function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}

[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})

})()
</code>```

答:
Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:</p>

```<code>$('.trigger_button_inside_divs').click(my_ajax_function);

var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container");

 function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

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

Body:
I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

$('.trigger_button_inside_divs').click(my_ajax_function);

And this is how my ajax looks like:

function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}

HTML looks like this:

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done!
Cheers.

PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

var xhr = new XMLHttpRequest();
var el;

function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })

    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}

function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}

[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})

})()

Body:
Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:

$('.trigger_button_inside_divs').click(my_ajax_function);

var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container");

 function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}


问:
Ember.js : Custom file structure & file naming
I want to use the following file structure and file naming:

```<code>/app
  /components
    /some-component
      component.some-component.template.hbs
      component.some-component.class.js
  /routes
    /some-route
      route.some-route.handler.js
      route.some-route.template.hbs
      route.some-route.controller.js
  /models
   model.some-model.js
</code>```

It's kind of similar to the pods structure but it's not exactly it since the file naming is totally different.

Any hints on how I can achieve this? I tried overriding Resolver methods as it's been suggested here but this is only for when you use pods and you simply want to group all of you route-folders in one parent-folder.

答:
I would suggest NOT adopting your own resolver, but instead encourage waiting for the module unification work to be completed (https://emberjs.com/statusboard)

Straying from the community adopted best-practices here is a good way to run into snags down the road. I spent some time helping a client shift away from their own custom resolver who had gone down this path and wouldn't suggest doing so

Body:
I want to use the following file structure and file naming:

/app
  /components
    /some-component
      component.some-component.template.hbs
      component.some-component.class.js
  /routes
    /some-route
      route.some-route.handler.js
      route.some-route.template.hbs
      route.some-route.controller.js
  /models
   model.some-model.js

It's kind of similar to the pods structure but it's not exactly it since the file naming is totally different.

Any hints on how I can achieve this? I tried overriding Resolver methods as it's been suggested here but this is only for when you use pods and you simply want to group all of you route-folders in one parent-folder.


问:
Unable to get Latitude and Longitude android
I am trying to get Latitude and Longitude using given below code but every time i am getting 0.00 and 0.00 lat and long as result.

```<code>locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000L, 1, listener);
Log.d("Network", "Network");
if (locationManager != null) {
    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location != null) {
        Log.e("Google latitude 111", location.getLatitude() + "");
        Log.e("Google longitude 111", location.getLongitude() + "");
        if (ServiceManager.lat.equals("") || ServiceManager.lng.equals("")) {
            ServiceManager.lat = String.valueOf(location.getLatitude());
            ServiceManager.lng = String.valueOf(location.getLongitude());
            MainActivity.handler.sendEmptyMessage(Response.GOT_LOCATION);
        }
    }
}
</code>```

I want to get actual latitude and longitude. I have taken and allowed all require permissions in device (FINE_LOCATION, COARSE_LOCATION and INTERNET).My target SDK version is 25. Is that any update in Androids Location Manager Policy for latest SDKs?

答:
Go to maps default application and allow user to allow latitude and longitude option.In our application When the GPS signal blinks and when it stops we will get the latitude and longitude. This Worked for me

Also Check

Open Google Maps app and click button on map to get current location.

When you allow Google map permission, then only other apps permission will work.

Now go to your app and try to get current location and it will work.

Try These Steps and Check whether you are getting your Location

Edit 1

Do you check availability with location.hasLocationEnabled().

This will help you to check whether location service is available or not. and turn on GPS. This will solve the problem up to an Extent without opening Google Map

Body:
I am trying to get Latitude and Longitude using given below code but every time i am getting 0.00 and 0.00 lat and long as result.

locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000L, 1, listener);
Log.d("Network", "Network");
if (locationManager != null) {
    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location != null) {
        Log.e("Google latitude 111", location.getLatitude() + "");
        Log.e("Google longitude 111", location.getLongitude() + "");
        if (ServiceManager.lat.equals("") || ServiceManager.lng.equals("")) {
            ServiceManager.lat = String.valueOf(location.getLatitude());
            ServiceManager.lng = String.valueOf(location.getLongitude());
            MainActivity.handler.sendEmptyMessage(Response.GOT_LOCATION);
        }
    }
}

I want to get actual latitude and longitude. I have taken and allowed all require permissions in device (FINE_LOCATION, COARSE_LOCATION and INTERNET).My target SDK version is 25. Is that any update in Androids Location Manager Policy for latest SDKs?