问:
Xcode 8 attribute "hidden" does not hide view in Interface Builder
seems like Apple change how Interface Builder behaves in Xcode 8? Because when I check hidden in Attributes Inspector on a view in Interface Builder, that view is still visible.

This makes it very tedious to work with views where some views needs to be the view with the highest "z value", the front most view that is.

Is there some other way to show the green view in this example, than to change the order of them to the right (i.e. change their "z value")

In the image below hidden is checked, but I still don't see the green view below. You can download this trivial project at github

When the project is run, the green view is indeed shown, but the issues is that it is annoying when working in Interface Builder.

Am I missing something?

答:
How about unchecking the installed checkbox of the red view?
This has also the flaw that you have to remember to reinstall it, but you don't have to change the z-order of your views.


来源: stackexchange

问:
XGBoostLibraryNotFound: Cannot find XGBoost Library in the candidate path, did you install compilers and run build.sh in root path?
I am facing this problem while moving the python-package directory of XGBoost.

```<code>Traceback (most recent call last): File "setup.py", line 19, in LIB_PATH = libpath'find_lib_path' File "xgboost/libpath.py", line 46, in find_lib_path 'List of candidates:\n' + ('\n'.join(dll_path))) builtin.XGBoostLibraryNotFound: Cannot find XGBoost Library in the candidate path, did you install compilers and run build.sh in root path?
</code>```

Could anyone explain to me how to fix it?
thanks in advance.

答:
You get that message when trying to install the xgboost Python package without the xgboost binaries present. The proper way to install the xgboost Python package from source is the following (assuming you have a compiler such as gcc installed):

```<code>git clone --recursive https://github.com/dmlc/xgboost.git
cd xgboost
./build.sh
cd python-package
python setup.py install
</code>```

I prefer to do it inside a virtual environment. Note that the option --recursive when cloning the repo is essential since it will also clone folders from different repos such as dmlc-core which are necessary for building xgboost.

ContentLicense: CC BY-SA 3.0

Body:
I am facing this problem while moving the python-package directory of XGBoost.

Traceback (most recent call last): File "setup.py", line 19, in LIB_PATH = libpath'find_lib_path' File "xgboost/libpath.py", line 46, in find_lib_path 'List of candidates:\n' + ('\n'.join(dll_path))) builtin.XGBoostLibraryNotFound: Cannot find XGBoost Library in the candidate path, did you install compilers and run build.sh in root path?

Could anyone explain to me how to fix it?
thanks in advance.

Body:
You get that message when trying to install the xgboost Python package without the xgboost binaries present. The proper way to install the xgboost Python package from source is the following (assuming you have a compiler such as gcc installed):

git clone --recursive https://github.com/dmlc/xgboost.git
cd xgboost
./build.sh
cd python-package
python setup.py install

I prefer to do it inside a virtual environment. Note that the option --recursive when cloning the repo is essential since it will also clone folders from different repos such as dmlc-core which are necessary for building xgboost.


问:
PyQt4.QtCore doesn't contain many of its classes and attributes
I have built PyQt4 from source and everything went smoothly until I tried to use some of the classes and attributes located in QtCore. For some reason QtCore is missing a lot of functionality and data that should be there. For example from PyQt4.QtCore import QT_VERSION_STR is an import error. There were no errors or warnings given when building the packages and I have also tried with the PyQt packages from yum but I have the same problem.

Has anyone else encountered this problem before?

Thanks.

答:
If it's really an ImportError, that suggests that it's failing to import the library altogether. Check that it's definitely somewhere that's in your sys.path, and that from PyQt4 import QtCore works.

If the library exists, and QT_VERSION_STR doesn't exist, it will give you a NameError rather than an ImportError.

ContentLicense: CC BY-SA 2.5


问:
Integrating special function and plotting
I am trying to plot an integration of a special (eg. Bessel) function and my minimal code is the following.

```<code>#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
import scipy.special as sp
from scipy.special import jn

#x = np.arange(0.0, 10.0, 0.1)
U = np.linspace(0,10,1000)

#Delta = U**2
#Delta = U-4+8*integrate.quad(lambda x: sp.jv(1,x)/(x*(1.0+np.exp(U*x*0.5))), 0, 100)
Delta = U-4+8*integrate.quad(lambda x: jn(1,x)/(x*(1.0+np.exp(U*x*0.5))), 0.1, 1000)

plt.plot(U,Delta)

plt.xlabel('U')
plt.ylabel('$\Delta$')
plt.show()

</code>```

However, this gives me several an error messages saying quadpack.error: Supplied function does not return a valid float whereas the function gets easily plotted in Mathematica. Do Python's Bessel's functions have limitations?

I have used this documentation for my plotting.

答:
It is difficult to provide an answer that solves the problem before understanding what exactly you are trying to do. However, let me list a number of issues and provide an example that may not achieve what you are trying to do but at least it will provide a path forward.

Because your lambda function multiplies x by an array U, it returns an array instead of a number. A function that needs to be integrated should return a single number. You could fix this, for example, by replacing U by u:

```<code>f = lambda x, u: jn(1,x)/(x*(1.0+np.exp(u*x*0.5)))
</code>```

Make Delta a function of u AND make quad pass additional argument u to f (defined in the previous point) AND extract only the value of the integral from the returned tuple from quad (quad returns a tuple of several values: the integral, the error, etc.):

```<code> Delta = lambda u: -4+8*integrate.quad(f, 0.1, 1000, args=(u,))[0]
</code>```

Compute Delta for each u:

```<code> deltas = np.array(map(Delta, U))
</code>```

plot the data:

```<code> plt.plot(U, deltas)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to plot an integration of a special (eg. Bessel) function and my minimal code is the following.

#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
import scipy.special as sp
from scipy.special import jn

#x = np.arange(0.0, 10.0, 0.1)
U = np.linspace(0,10,1000)

#Delta = U**2
#Delta = U-4+8*integrate.quad(lambda x: sp.jv(1,x)/(x*(1.0+np.exp(U*x*0.5))), 0, 100)
Delta = U-4+8*integrate.quad(lambda x: jn(1,x)/(x*(1.0+np.exp(U*x*0.5))), 0.1, 1000)

plt.plot(U,Delta)

plt.xlabel('U')
plt.ylabel('$\Delta$')
plt.show()

However, this gives me several an error messages saying quadpack.error: Supplied function does not return a valid float whereas the function gets easily plotted in Mathematica. Do Python's Bessel's functions have limitations?

I have used this documentation for my plotting.

Body:
It is difficult to provide an answer that solves the problem before understanding what exactly you are trying to do. However, let me list a number of issues and provide an example that may not achieve what you are trying to do but at least it will provide a path forward.

Because your lambda function multiplies x by an array U, it returns an array instead of a number. A function that needs to be integrated should return a single number. You could fix this, for example, by replacing U by u:

f = lambda x, u: jn(1,x)/(x*(1.0+np.exp(u*x*0.5)))

Make Delta a function of u AND make quad pass additional argument u to f (defined in the previous point) AND extract only the value of the integral from the returned tuple from quad (quad returns a tuple of several values: the integral, the error, etc.):

 Delta = lambda u: -4+8*integrate.quad(f, 0.1, 1000, args=(u,))[0]

Compute Delta for each u:

 deltas = np.array(map(Delta, U))

plot the data:

 plt.plot(U, deltas)


问:
Area Under Curve - 1D Array (Java)
I have a quick question, that in most languages (such as python) would be straightforward.

I am looking to obtain the integral (area of curve) from an 1D-array of fixed points. Java apparently has many numerical integration libraries, all of which seem to require a function (f {double(x)})  as input.

However I can not seem to find any which accommodate arrays (double []) such as [1,4,10,11]. I would be integrating over the entirety of the array (x values 1-n, where n represents the size of the array)

Any help is greatly appreciated

答:
By using trapezoidal rule you can simply call below method to get area under a graph(approx.)</p>

```<code>public static double trapz(double ar[],double xDist){
        if (ar.length==1 || ar.length==0)
            return 0;
        double integral=0;
        double prev=ar[0];
        for (int i=1;i<ar.length;i++)
        {
            integral+=xDist*(prev+ar[i])/2.0;
            prev=ar[i];
        }
        return integral;
    }
</code>```

Title: Area Under Curve - 1D Array (Java)

Body:
By using trapezoidal rule you can simply call below method to get area under a graph(approx.)

public static double trapz(double ar[],double xDist){
        if (ar.length==1 || ar.length==0)
            return 0;
        double integral=0;
        double prev=ar[0];
        for (int i=1;i<ar.length;i++)
        {
            integral+=xDist*(prev+ar[i])/2.0;
            prev=ar[i];
        }
        return integral;
    }


问:
How to get a word from an EditText?
I want the user to input a String word by phrase,

"animal" is a null String and I want to get it when the user enters the words after it or before it, I want to get that single word at its current position.

i.e.:

when I enter in my EditText "cat is an animal" the word "cat" will be saved in the list of animals, or "dog is an animal" and the word "dog" is saved, then the TextView says 'change to "ok"'.

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

ArrayList<String> animal_names = new ArrayList<>();
String animal = null;
TextView say;
EditText enter;

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

    say = (TextView) findViewById(R.id.textView);
    enter = (EditText) findViewById(R.id.editText);

    try {
        InputStream input = getAssets().open("animals names.txt");
        InputStreamReader rd = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(rd);
        String line;
        while ((line = br.readLine()) != null) {
            animal_names.add(line);
        }

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

}

public void click(View view) {
    String s = enter.getText().toString().trim();
    if (s.equals(animal+" is an animal")){
        say.setText("ok");
        animal_names.add(animal);
    }else if (s.equals("is " + animal + "an animal" )){
        if (animal_names.contains(animal)){
            say.setText("yes");
        }else {
            say.setText("no");
        }
    }
}
</code>```

答:
Currently your code checks for the strings null is an animal and is nullan animal (notice your spacing typo?)

So, hard to say if you really need a TextWatcher, but probably a regex instead. For example, a simple regex could be

```<code>"Is ([A-Za-z ]+) an animal?"
</code>```

And

```<code>"([A-Za-z ]+) is an animal"
</code>```

Then, you would use if (s.matches(regex)), and see how to get your animal

How to extract a substring using regex

You can also use a combination of substring and indexOf to extract the animal name

Title: How to get a word from an EditText?

Body:
I want the user to input a String word by phrase,

"animal" is a null String and I want to get it when the user enters the words after it or before it, I want to get that single word at its current position.

i.e.:

when I enter in my EditText "cat is an animal" the word "cat" will be saved in the list of animals, or "dog is an animal" and the word "dog" is saved, then the TextView says 'change to "ok"'.

public class MainActivity extends AppCompatActivity {

ArrayList<String> animal_names = new ArrayList<>();
String animal = null;
TextView say;
EditText enter;

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

    say = (TextView) findViewById(R.id.textView);
    enter = (EditText) findViewById(R.id.editText);

    try {
        InputStream input = getAssets().open("animals names.txt");
        InputStreamReader rd = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(rd);
        String line;
        while ((line = br.readLine()) != null) {
            animal_names.add(line);
        }

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

}

public void click(View view) {
    String s = enter.getText().toString().trim();
    if (s.equals(animal+" is an animal")){
        say.setText("ok");
        animal_names.add(animal);
    }else if (s.equals("is " + animal + "an animal" )){
        if (animal_names.contains(animal)){
            say.setText("yes");
        }else {
            say.setText("no");
        }
    }
}

Body:
Currently your code checks for the strings null is an animal and is nullan animal (notice your spacing typo?)

So, hard to say if you really need a TextWatcher, but probably a regex instead. For example, a simple regex could be

"Is ([A-Za-z ]+) an animal?"

And

"([A-Za-z ]+) is an animal"

Then, you would use if (s.matches(regex)), and see how to get your animal

How to extract a substring using regex

You can also use a combination of substring and indexOf to extract the animal name


问:
Send iMessage to group chat
How can you send a iMessage to a group chat? I have searched everywhere and I can't find anything. I want to send it to a group chat named something, possibly If I get a list of buddies in the chat I can send it to everyone at once? A problem may be that I'm also in the chat, so that might be a problem.</p>

答:
To send to an existing group chat, you will need to obtain the chat's internal guid. There are 2 methods of doing this.

Extract it from the messages.app internal database, located on disk at ~/Library/Messages/chat.db. It is the guid column under the chat table. If you have the group chat named it will be easy to find by display_name.

You can use an AppleScript handler for Messages with the on chat room message received handler to capture the ID when someone posts in that chat.

Once you have the guid (should in a format similar to iMessage;+;chat831551415676550949), you can use AppleScript to send the message.

```<code>tell application "Messages"
  set myid to "iMessage;+;chat831551415676550949"
  set mymessage to "Hello World"
  set theBuddy to a reference to text chat id myid
  send mymessage to theBuddy
end tell
</code>```

To send an image, replace the mymessage text with:

```<code>set ImageAttachment to POSIX file "File path here" as alias
</code>```

Title: Send iMessage to group chat

Body:
To send to an existing group chat, you will need to obtain the chat's internal guid. There are 2 methods of doing this.

Extract it from the messages.app internal database, located on disk at ~/Library/Messages/chat.db. It is the guid column under the chat table. If you have the group chat named it will be easy to find by display_name.

You can use an AppleScript handler for Messages with the on chat room message received handler to capture the ID when someone posts in that chat.

Once you have the guid (should in a format similar to iMessage;+;chat831551415676550949), you can use AppleScript to send the message.

tell application "Messages"
  set myid to "iMessage;+;chat831551415676550949"
  set mymessage to "Hello World"
  set theBuddy to a reference to text chat id myid
  send mymessage to theBuddy
end tell

To send an image, replace the mymessage text with:

set ImageAttachment to POSIX file "File path here" as alias


问:
Changing the color of individual characters in a glyph
As I understand it, a string contains glyphs and a glyph might consist of individual characters. For me this is a problem, as I would like to change the color of some diacritics in a string.

Let's say we have the following string:

วาีม

For this string I would like to make the consonants a different color as it's diacritic. I.e.: I want a different color for วาม and ี.

From my tests it seems that I am only able to color individual glyphs. It seems I can not change the color at a character (diacritic) level. Some example code:

```<code>let text = NSMutableAttributedString(string: "วาีม")
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(0, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(1, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSMakeRange(2, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(3, 1))
label.attributedText = text
</code>```

The above would render as follows:

As can be seen the diacritic is not rendered with a green color.

Does anyone know if there is some way to achieve the result I want?

答:
I doubt you'll find a good way to do this. The glyph for าี in the font is a completely different thing than the glyph for า. For example, in the Thonburi font on my Mac, the former is glyph 1507 and the latter is glyph 78. Each glyph entry in the font is a completely separate little description of how to draw the glyph. For the combined glyph, the diacritic is not a separate thing. The system has no way to know when it's drawing the base character and when it's drawing the diacritic. It's just drawing one thing. So, it can't apply different colors.

I'm completely unfamiliar with Thai, so I'm just speculating for this next part, although it's certainly true for some languages: I suspect there are glyphs for combining sequences which are radically different from what you'd get by just overlaying the component parts on top of each other. So, even in principle, it's not clear that there's a visually separable diacritic shape vs. the base character.

Body:
As I understand it, a string contains glyphs and a glyph might consist of individual characters. For me this is a problem, as I would like to change the color of some diacritics in a string.

Let's say we have the following string:

วาีม

For this string I would like to make the consonants a different color as it's diacritic. I.e.: I want a different color for วาม and ี.

From my tests it seems that I am only able to color individual glyphs. It seems I can not change the color at a character (diacritic) level. Some example code:

let text = NSMutableAttributedString(string: "วาีม")
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(0, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(1, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSMakeRange(2, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(3, 1))
label.attributedText = text

The above would render as follows:

As can be seen the diacritic is not rendered with a green color.

Does anyone know if there is some way to achieve the result I want?


问:
Setup that selects automation server (written in .NET) in excel
We have some excel formulas written in .NET and exposed to Excel via COM. The user who wants use our formulas have to:

run some bat file that registers dll's into COM (using RegAsm)

then in Excel (2010) select File|Options|Add-ins|Excel Add-ins|Automation|Select our server|GO|GO

We want to avoid the (2.) using some automatic setup. Does anybody have any idea how it can be accomplished?

Thanks in advance.

答:
You have not had an answer in some time. I do not know that this will work, but it may be worth trying:

```<code>Sub Add_an_Addin()

Dim oAddin As AddIn
Dim oTempBk As Workbook

Set oTempBk = Workbooks.Add

Set oAddin = AddIns.Add("E:\CostBenefit1.0.xla", True)
oAddin.Installed = True

oTempBk.Close

End Sub
</code>```

FROM: http://vbadud.blogspot.com/2007/06/excel-vba-install-excel-add-in-xla-or.html

Body:
You have not had an answer in some time. I do not know that this will work, but it may be worth trying:

Sub Add_an_Addin()

Dim oAddin As AddIn
Dim oTempBk As Workbook

Set oTempBk = Workbooks.Add

Set oAddin = AddIns.Add("E:\CostBenefit1.0.xla", True)
oAddin.Installed = True

oTempBk.Close

End Sub

FROM: http://vbadud.blogspot.com/2007/06/excel-vba-install-excel-add-in-xla-or.html


问:
ng-repeat not listing different json values, instead it just displays the entire json file content in single list item
ng-repeat is not listing different json values, instead it just displays the entire json file content in single list item

codepen

html:

```<code>      <div ng-app="myApp">

    <div ng-controller="myCtrl" class="container">

        <h2>Basic List</h2>

        <ul class="list-group">
            <li class="list-group-item" ng-reapeat="student">
                {{student}}
            </li>

        </ul>

    </div>

</div>
</code>```

All the json file content is in here. I just need the specific data to display on each list item.
For Example,

Student One

Student Two

Student Three

Student Four

Student Five

 See image for issue

JS

```<code><script>

var app = angular.module('myApp', []);
//$.ajax({url: app, crossDomain:true, dataType: 'json', type: 'GET'})
app.controller('myCtrl', function($scope, $http){
  $http.get("student.json")
 // $http.get("stud.json")
  .then(function(response) {
      $scope.student = response.data;
  });

});

</script>
</code>```

json

```<code>[

{
    "name" : "Student One"
},

{
    "name" : "Student Two"
},

{
    "name" : "Student Three"
},

{
    "name" : "Student Four"
},

{
    "name" : "Student Five"
}
</code>```

]

答:
I figured it out!

I fixed the syntax of the parameter in ng-repeat attribute.

So instead of the previous :

```<code><ul class="list-group">
            <li class="list-group-item" ng-reapeat="student">
                {{student}}
            </li>
</code>```

Before

it should be like this :

```<code> <ul class="list-group" >
  <li class="list-group-item" ng-repeat="student in student" >
    {{student.name}}
</li>
</code>```

Result:
After

Body:
ng-repeat is not listing different json values, instead it just displays the entire json file content in single list item

codepen

html:

Basic List

                {{student}}

All the json file content is in here. I just need the specific data to display on each list item.
For Example,

Student One

Student Two

Student Three

Student Four

Student Five

 See image for issue

JS

json

[

{
    "name" : "Student One"
},

{
    "name" : "Student Two"
},

{
    "name" : "Student Three"
},

{
    "name" : "Student Four"
},

{
    "name" : "Student Five"
}

]

Body:
I figured it out!

I fixed the syntax of the parameter in ng-repeat attribute.

So instead of the previous :

<ul class="list-group">
            <li class="list-group-item" ng-reapeat="student">
                {{student}}
            </li>

Before

it should be like this :

 <ul class="list-group" >
  <li class="list-group-item" ng-repeat="student in student" >
    {{student.name}}
</li>

Result:
After


问:
Class member initialization C++
I want to initialize transform variable when creating theGameObject, but something is going wrong. Compiler says:

```<code>C3646   'transform' : unknown override specifier    (line 4)
C4430   missing type specifier - int assumed. Note: C++ does not support default-int    (line 4)
C3861   'Transform': identifier not found    (line 5)
C2614   'GameObject' : illegal member initialization: 'transform' is not a base or member    (line 5)

    1.    class GameObject
    2.    {
    3.    public:
    4.        Transform transform;
    5.        GameObject() : transform(Transform()) {}
    6.    };
    7.
    8.    class Transform
    9.    {
   10.    public:
   11.        Vector3 position;
   12.        Vector3 rotation;
   13.        Vector3 dimension;
   14.
   15.        Transform()
   16.        {
   17.            position = Vector3();
   18.            rotation = Vector3();
   19.            dimension = Vector3();
   20.        }
   21.    }
</code>```

In main.cpp I call:

```<code>GameObject theGameObject = GameObject();
</code>```

What I've done wrong?

答:
In your GameObject class you have a Transform object Transform transform; but the compiler hasn't seen the Transform class yet and thus it doesn't know it's size or what it even is. You should define Transform and then GameObject instead of GameObject and then Transform. You probably want to seperate these classes in individual header files too.

Side note:
You can just do GameObject theGameObject; too.

Title: Class member initialization C++

Body:
I want to initialize transform variable when creating theGameObject, but something is going wrong. Compiler says:

C3646   'transform' : unknown override specifier    (line 4)
C4430   missing type specifier - int assumed. Note: C++ does not support default-int    (line 4)
C3861   'Transform': identifier not found    (line 5)
C2614   'GameObject' : illegal member initialization: 'transform' is not a base or member    (line 5)

    1.    class GameObject
    2.    {
    3.    public:
    4.        Transform transform;
    5.        GameObject() : transform(Transform()) {}
    6.    };
    7.
    8.    class Transform
    9.    {
   10.    public:
   11.        Vector3 position;
   12.        Vector3 rotation;
   13.        Vector3 dimension;
   14.
   15.        Transform()
   16.        {
   17.            position = Vector3();
   18.            rotation = Vector3();
   19.            dimension = Vector3();
   20.        }
   21.    }

In main.cpp I call:

GameObject theGameObject = GameObject();

What I've done wrong?


问:
Rails 3: Social Stream Gem. Where is the code?
I've installed social_stream according to the README ( https://github.com/ging/social_stream ) and it works fine, however, I'd like to have the code in my app/ directory and the code isn't there.

The same question arises for Devise and other gems. When I install it, I'd like to have access to the controllers, models, views, etc but it seems nothing is in the app/.

What do I have to do in order to put the code there and being able to change it as I'd like? Or, access it in other folder.

Thank you

答:
Here is the url that explain how to change the views
https://github.com/ging/social_stream/wiki/How-to-change-controllers%2C-models-and-views</p>


问:
How can i display only the first image from this JSON array?
OK, I'm trying to integrate an API that lists adoptable pets into a wordpress website. I've done lots of googling and read through tutorials, and so far have managed to put together a super basic plugin that seems to do what I'm trying to accomplish. Currently I'm trying to pull in an image, but just the first image. Each animal may have 5 images associated with it, but I only want to pull in the first (default). Currently my code brings them all. Now I realize the problem is that I'm using "foreach()". But, this is new to me and my googling is not going well, and any other way I've tried to do it is just not getting me ANY pictures. Any advice is appreciated....and if I'm doing anything else wrong, feel free to let me know :) I also need to figure out how to paginate it, but I'm thinking that's a separate question! Thanks!

<?php
add_shortcode('pets', 'petsshortcode');
function petsshortcode() {
$request = wp_remote_get( 'https://petstablished.com/api/v2/public/pets?public_key=UlEK4EWvDAoOjXeQXSCQZAyBywWfqfOg&search[status]=available,foster&pagination[limit]=20&pagination[page]=1' );

if( is_wp_error( $request ) ) {
 return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );

$data = json_decode( $body );

if( ! empty( $data ) ) {

 foreach( $data->collection as $collection ) {
  echo '

'. $collection->name; echo '
';
  echo '
'.'' . $collection->sex; echo '' . '' . $collection->breed; echo '' . $collection->age; echo '
';
  echo '

' . $collection->description; echo '

';
 foreach( $collection->images as $images ) {
  echo '
image->url; echo '" width="200">
';}
  echo '

';
 }
}
}```

答:
You don't need nested foreach loops in this case, simply use just one foreach loop like this:

```<code>// your code
foreach( $data->collection as $collection ) {
    echo '<div id="pet-block"><ul class="pet-profile"><li class="pet-name">'. $collection->name;    echo '</li>';
    echo '<li class="pet-meta">'.'<span class="sex">' . $collection->sex; echo '</span>' . '<span class="breed">' . $collection->breed; echo '</span><span class="age">' . $collection->age; echo '</span></li>';
    echo '<li><p>' . $collection->description; echo '</li></p>';
    echo '<div class="pet-photo"><img src="' . $collection->images[0]->image->url; echo '" width="200"></div>';
    echo '</ul></div>';
}
// your code
</code>```

Body:
You don't need nested foreach loops in this case, simply use just one foreach loop like this:

// your code
foreach( $data->collection as $collection ) {
    echo '<div id="pet-block"><ul class="pet-profile"><li class="pet-name">'. $collection->name;    echo '</li>';
    echo '<li class="pet-meta">'.'<span class="sex">' . $collection->sex; echo '</span>' . '<span class="breed">' . $collection->breed; echo '</span><span class="age">' . $collection->age; echo '</span></li>';
    echo '<li><p>' . $collection->description; echo '</li></p>';
    echo '<div class="pet-photo"><img src="' . $collection->images[0]->image->url; echo '" width="200"></div>';
    echo '</ul></div>';
}
// your code


问:
Resources$NotFoundException when calling Robolectric.buildActivity()
I am using Robolectric 3.0 RC3 for unit testing in Android Studio. And I am getting a ResourceNotFoundException every time I run the test. Please help me resolve the issue.

build.gradle

```<code>dependencies {
    testCompile 'junit:junit:4.12'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    testCompile 'org.mockito:mockito-core:1.9.5'
    testCompile 'org.robolectric:robolectric:3.0-rc3'
    compile 'com.ibm.icu:icu4j:53.1'
}
</code>```

Test Class

```<code>@Before
public void setUp() throws Exception {
    activity = Robolectric.buildActivity(MainActivity.class).create().get();
}
@Test
public void pressingTheButtonShouldStartTheListActivity() throws Exception {
   //Something to test
}
</code>```

So, whenever Robolectric.buildActivity() I get the Resources$NotFoundException. Resource #0x7f040016 points to R.layout.activity_main(xml). Following id the stack trace-

```<code>android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f040016
at org.robolectric.shadows.ShadowResources.checkResName(ShadowResources.java:343)
at org.robolectric.shadows.ShadowResources.resolveResName(ShadowResources.java:338)
at org.robolectric.shadows.ShadowResources.loadXmlResourceParser(ShadowResources.java:429)
at android.content.res.Resources.loadXmlResourceParser(Resources.java)
at android.content.res.Resources.getLayout(Resources.java:852)
at android.view.LayoutInflater.inflate(LayoutInflater.java:394)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
at android.app.Activity.setContentView(Activity.java:1867)
at com.aricent.anas.unittesting2.MainActivity.onCreate(MainActivity.java:15) //****HERE****
at android.app.Activity.performCreate(Activity.java:5008)
at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:195)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:122)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:305)
at org.robolectric.shadows.CoreShadowsAdapter$2.runPaused(CoreShadowsAdapter.java:45)
at org.robolectric.util.ActivityController.create(ActivityController.java:118)
at org.robolectric.util.ActivityController.create(ActivityController.java:129)
at com.aricent.anas.unittesting2.MainActivityTest.setUp(MainActivityTest.java:32) //****HERE****
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:245)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:185)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:149)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code -1
</code>```

MainActivity.java:15 is setContentView(R.layout.activity_main);

MainActivityTest.java:32 is activity = Robolectric.buildActivity(MainActivity.class).create().get();

答:
This is realy help for me with Robolectric!
Open Gradle, Double click on ProjectName > :app > Tasks > verification > testDebugUnitTest.
More details  here

Body:
I am using Robolectric 3.0 RC3 for unit testing in Android Studio. And I am getting a ResourceNotFoundException every time I run the test. Please help me resolve the issue.

build.gradle

dependencies {
    testCompile 'junit:junit:4.12'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    testCompile 'org.mockito:mockito-core:1.9.5'
    testCompile 'org.robolectric:robolectric:3.0-rc3'
    compile 'com.ibm.icu:icu4j:53.1'
}

Test Class

@Before
public void setUp() throws Exception {
    activity = Robolectric.buildActivity(MainActivity.class).create().get();
}
@Test
public void pressingTheButtonShouldStartTheListActivity() throws Exception {
   //Something to test
}

So, whenever Robolectric.buildActivity() I get the Resources$NotFoundException. Resource #0x7f040016 points to R.layout.activity_main(xml). Following id the stack trace-

android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f040016
at org.robolectric.shadows.ShadowResources.checkResName(ShadowResources.java:343)
at org.robolectric.shadows.ShadowResources.resolveResName(ShadowResources.java:338)
at org.robolectric.shadows.ShadowResources.loadXmlResourceParser(ShadowResources.java:429)
at android.content.res.Resources.loadXmlResourceParser(Resources.java)
at android.content.res.Resources.getLayout(Resources.java:852)
at android.view.LayoutInflater.inflate(LayoutInflater.java:394)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
at android.app.Activity.setContentView(Activity.java:1867)
at com.aricent.anas.unittesting2.MainActivity.onCreate(MainActivity.java:15) //****HERE****
at android.app.Activity.performCreate(Activity.java:5008)
at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:195)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:122)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:305)
at org.robolectric.shadows.CoreShadowsAdapter$2.runPaused(CoreShadowsAdapter.java:45)
at org.robolectric.util.ActivityController.create(ActivityController.java:118)
at org.robolectric.util.ActivityController.create(ActivityController.java:129)
at com.aricent.anas.unittesting2.MainActivityTest.setUp(MainActivityTest.java:32) //****HERE****
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:245)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:185)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:149)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code -1

MainActivity.java:15 is setContentView(R.layout.activity_main);

MainActivityTest.java:32 is activity = Robolectric.buildActivity(MainActivity.class).create().get();


问:
Render error in Android Studio 3.0 Layout Editor
I just started learning Kotlin for android development and started an empty project and added an activity. I have added the required gradle dependencies as said in Kotlin docs. By default the xml file of MainActivity contains only a TextView. But when I try to preview the xml in Layout Editor it shows a "Render Error"

```<code>Render problem

Failed to load AppCompat ActionBar with unknown error.
</code>```

Also I'm getting this

```<code>The following classes could not be instantiated:
- android.support.v7.widget.AppCompatImageView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContainer (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.Toolbar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.AppCompatTextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.app.WindowDecorActionBar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarOverlayLayout (Open Class, Show Exception, Clear Cache)

Exception Details java.lang.ClassNotFoundException: android.support.v4.view.TintableBackgroundView
</code>```

I have tried rebuilding the project and refreshing layout manually. But nothing seems to work.

So what do I do? I'm using Android Studio 3.0 Canary 2 with Kotlin

EDITED:

I have made some progress. I have found that none of my AppCompat Themes are working.

答:
I'm facing same issue when i tried autofill. but
This will working for me. Make sure you add these dependencies:

```<code>compile "com.android.support:support-core-utils:26.0.0-beta2"
compile "com.android.support:support-v4:26.0.0-beta2"
compile "com.android.support:support-v13:26.0.0-beta2"
compile "com.android.support:appcompat-v7:26.0.0-beta2"
compile 'com.android.support:design:26.0.0-beta2'
</code>```

and

```<code>classpath 'com.android.tools.build:gradle:2.3.3'
</code>```

Body:
I just started learning Kotlin for android development and started an empty project and added an activity. I have added the required gradle dependencies as said in Kotlin docs. By default the xml file of MainActivity contains only a TextView. But when I try to preview the xml in Layout Editor it shows a "Render Error"

Render problem

Failed to load AppCompat ActionBar with unknown error.

Also I'm getting this

The following classes could not be instantiated:
- android.support.v7.widget.AppCompatImageView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContainer (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.Toolbar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.AppCompatTextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.app.WindowDecorActionBar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarOverlayLayout (Open Class, Show Exception, Clear Cache)

Exception Details java.lang.ClassNotFoundException: android.support.v4.view.TintableBackgroundView

I have tried rebuilding the project and refreshing layout manually. But nothing seems to work.

So what do I do? I'm using Android Studio 3.0 Canary 2 with Kotlin

EDITED:

I have made some progress. I have found that none of my AppCompat Themes are working.

Body:
I'm facing same issue when i tried autofill. but
This will working for me. Make sure you add these dependencies:

compile "com.android.support:support-core-utils:26.0.0-beta2"
compile "com.android.support:support-v4:26.0.0-beta2"
compile "com.android.support:support-v13:26.0.0-beta2"
compile "com.android.support:appcompat-v7:26.0.0-beta2"
compile 'com.android.support:design:26.0.0-beta2'

and

classpath 'com.android.tools.build:gradle:2.3.3'


问:
How to get total numbers of digits used in an integer in c language?
We all know that we can get numbers of characters in an string using strlen() function, but if I want to get a number of the digits used in an integer, how can I do it?

Like if there is 1000 stored in a variable a and that variable is an integer type, I want to get length of the number and that is 4.

答:
If you know the number is positive, or you want the minus sign to be included in the count:

```<code>snprintf(NULL, 0, "%d", a);
</code>```

If you want the number of digits in the absolute value of the number:

```<code>snprintf(NULL, 0, "+%d", a) - 1;
</code>```

The key to both these solutions is that snprintf returns the number of bytes it would have written had the buffer been large enough to write into. Since we're not giving it a buffer, it needs to return the number of bytes which it would have written, which is the size of the formatted number.

This may not be the fastest solution, but it does not suffer from inaccuracies in log10 (if you use log10, remember to round rather than truncate to an integer, and beware of large integers which cannot be accurately converted to a double because they would require more than 53 mantissa bits), and it doesn't require writing out a loop.

Body:
If you know the number is positive, or you want the minus sign to be included in the count:

snprintf(NULL, 0, "%d", a);

If you want the number of digits in the absolute value of the number:

snprintf(NULL, 0, "+%d", a) - 1;

The key to both these solutions is that snprintf returns the number of bytes it would have written had the buffer been large enough to write into. Since we're not giving it a buffer, it needs to return the number of bytes which it would have written, which is the size of the formatted number.

This may not be the fastest solution, but it does not suffer from inaccuracies in log10 (if you use log10, remember to round rather than truncate to an integer, and beware of large integers which cannot be accurately converted to a double because they would require more than 53 mantissa bits), and it doesn't require writing out a loop.


问:
Watir not working as expected - Selenium::WebDriver::Error::UnknownError
I installed Watir and trying a simple example given in that website.

```<code>require 'watir'
browser = Watir::Browser.new :chrome
browser.goto 'https://www.google.com'
browser.text_field(title: 'Search').set 'Hello World!'
browser.button(type: 'submit').click
browser.quit
</code>```

When I run the Ruby program I get an error as follows.

C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib/selenium/web driver/remote/response.rb:69:in 'assert_ok': unknown error: Runtime.executionCon textCreated has invalid 'context': {"auxData":{"frameId":"1352.1","isDefault":tr ue},"id":1,"name":"","origin":"://"} (Selenium::WebDriver::Error::UnknownError) (Session info: chrome=59.0.3071.115) (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86_64) from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/response.rb:32:in 'initialize' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/common.rb:83:in 'new' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/common.rb:83:in 'create_response' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/default.rb:107:in 'request' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/common.rb:61:in 'call' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/bridge.rb:170:in 'execute' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/oss/bridge.rb:579:in 'execute' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/oss/bridge.rb:52:in 'get' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/common/navigation.rb:32:in 'to' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/watir-6.3.0/lib/watir/browse r.rb:78:in 'goto'from example.rb:3:in ''

I am running on windows 7.

答: You are running chromedriver=2.9.248315 against chrome v59.  Upgrade to chromedriver 2.30, which supports chrome v58-60.

Body:
I installed Watir and trying a simple example given in that website.

require 'watir'
browser = Watir::Browser.new :chrome
browser.goto 'https://www.google.com'
browser.text_field(title: 'Search').set 'Hello World!'
browser.button(type: 'submit').click
browser.quit

When I run the Ruby program I get an error as follows.

C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib/selenium/web driver/remote/response.rb:69:in 'assert_ok': unknown error: Runtime.executionCon textCreated has invalid 'context': {"auxData":{"frameId":"1352.1","isDefault":tr ue},"id":1,"name":"","origin":"://"} (Selenium::WebDriver::Error::UnknownError) (Session info: chrome=59.0.3071.115) (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86_64) from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/response.rb:32:in 'initialize' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/common.rb:83:in 'new' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/common.rb:83:in 'create_response' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/default.rb:107:in 'request' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/http/common.rb:61:in 'call' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/bridge.rb:170:in 'execute' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/oss/bridge.rb:579:in 'execute' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/remote/oss/bridge.rb:52:in 'get' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.3/lib /selenium/webdriver/common/navigation.rb:32:in 'to' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/watir-6.3.0/lib/watir/browse r.rb:78:in 'goto'from example.rb:3:in ''

I am running on windows 7.


问:
How to get AdTags for Google IMA SDK android
I have created a mobile application, I want to show Google IMA ads in my app with my Exoplayer. We have created a sample application to show IMA ads in Exoplayer using sample tags provided by this url : https://developers.google.com/interactive-media-ads/docs/sdks/android/tags. I want to get video ads from Google. So i have created an account in DoubleClick for Publishers. How can i generate adtags to get preroll,midroll,postroll ads in my Exoplayer.</p>

答: To get preroll, midroll, and postroll ads you might want to look into Ad Rules offered by DoubleClick. You will be able to generate tags once you have specified tracking URLs, and uploaded your mediafiles to the DFP UI.</p>


问:
For each char in string gives wrong result
There's a string that is in UTF-8 encoding, I can read it from a file and write it into another file just fine. But when I try to load each of the characters in that string one by one the result isn't coherent. I'm most likely doing this in a very wrong way, but what is the correct way to do this?

The content in source.txt is

```<code>afternoon_gb_1          ɑftənun
</code>```

The code i wrote is

```<code>while (source >> word >> word_ipa) {
for (char& c : word_ipa)
 myfile <<word<<" is " << c<< endl;}
</code>```

The content in the txt file myfile gets written as

```<code>afternoon_gb_1 is �
afternoon_gb_1 is �
afternoon_gb_1 is f
afternoon_gb_1 is t
afternoon_gb_1 is �
afternoon_gb_1 is �
afternoon_gb_1 is n
afternoon_gb_1 is u
afternoon_gb_1 is n
</code>```

答:
In UTF-8 each code-point (=logical character) is represented by multiple code units (=char); ɑftənun, in particular, is:

```<code>ch| c.p. | c.u.
--+------+-------
ɑ | 0251 | c9 91
f | 0066 | 66
t | 0074 | 74
ə | 0259 | c9 99
n | 006e | 6e
u | 0075 | 75
n | 006e | 6e
</code>```

(ch=character; c.p.: code point number; c.p. code unit representation in UTF-8; c.u. and c.p. are expressed in hexadecimal)

The exact details of how the code points are mapped to the code units is explained in many places; the very basics are that:

code points less than 0x7f are mapped straight to a single code unit; for these, the high bit is never set;

code points from 0x80 onwards are mapped to multiple code units; all the code units in a multi-code-unit sequence have the high bit set;

if the high bit is set, the top bits have a particular meaning; in the first byte of a multibyte sequence they tell how many continuation bytes are to be expected, in the others they are unambiguously marked as continuation bytes.

If you print out each code unit on its own you are breaking the UTF-8 encoding for the code points that require more than one code unit to be expressed. Your terminal application in the first row sees

```<code>c9 0a
</code>```

(the first code unit followed by a newline), and immediately detects that this is a broken UTF-8 sequence, as c9 has the high bit set but the next c.u. doesn't have it; hence the � character. The same holds for the second character, as well as for the c.u. parts of the sequence representing ə.

Now, if you want to print out full code-points (not code-units), std::string won't be of any help - std::string knows nothing about this stuff, it is essentially a glorified std::vector<char>, completely oblivious of encoding issues; all it does is to store/index code units, not code points.

There are however third party libraries to help work with this; utf8-cpp is a small but complete one; in your case, the utf8::next function would be particularly helpful:

```<code>while (source >> word >> word_ipa) {
    auto cur = word_ipa.begin();
    auto end = word_ipa.end();
    auto next = cur;
    for(;cur!=end; cur=next) {
        utf8::next(next, end);
        myfile << word << "is ";
        for(; cur!=next; ++cur) myfile<<*cur;
        myfile << "\n";
    }
}
</code>```

utf8::next here just increments the given iterator to make it point to the code point that starts the next code unit; this code makes sure that we print together all the code units that make up a single code point.

Notice that we can reproduce its barebones behavior quite simply, it's just a matter of reading the UTF-8 specs (see the first table in the link to Wikipedia above):

```<code>template<typename ItT>
void safe_advance(ItT &it, size_t n, ItT end) {
    size_t d = std::distance(it, end);
    if(n>d) throw std::logic_error("Truncated UTF-8 sequence");
    std::advance(it, n);
}

template<typename ItT>
void my_next(ItT &it, ItT end) {
    uint8_t b = *it;
    if(b>>7 == 0) safe_advance(it, 1, end);
    else if(b>>5 == 6) safe_advance(it, 2, end);
    else if(b>>4 == 14) safe_advance(it, 3, end);
    else if(b>>3 == 30) safe_advance(it, 4, end);
    else throw std::logic_error("Invalid UTF-8 sequence");
}
</code>```

Here we are exploiting the fact that the first byte of a sequence declares how many extra code points are going to come to complete the code unit.

(notice that this expects valid UTF-8 and does not do any attempt to resynchronize a broken UTF-8 sequence; the library version probably fares way better in this regard)

OTOH, it's also possible to inline just what's necessary to keep the same code unit together:

```<code>while (source >> word >> word_ipa) {
    auto cur = word_ipa.begin();
    auto end = word_ipa.end();
    for(;cur!=end;) {
        myfile << word << "is "<<*cur;
        if(uint8_t(*cur++)>>7 != 0) {
            for(; cur!=end && (uint8_t(*cur)>>6)==2; ++cur) myfile<<*cur;
        }
        myfile << "\n";
    }
}
</code>```

Here instead we are disregarding completely the "declared count" in the first c.u., we just check if the high bit is set; in this case, we go on printing as long as we get c.u. with the top two bytes set to 10 (in binary, AKA 2 in decimal) - since the "continuation c.u." of a multi-c.u. UTF-8 sequence all follow this pattern.

Body:
There's a string that is in UTF-8 encoding, I can read it from a file and write it into another file just fine. But when I try to load each of the characters in that string one by one the result isn't coherent. I'm most likely doing this in a very wrong way, but what is the correct way to do this?

The content in source.txt is

afternoon_gb_1          ɑftənun

The code i wrote is

while (source >> word >> word_ipa) {
for (char& c : word_ipa)
 myfile <<word<<" is " << c<< endl;}

The content in the txt file myfile gets written as

afternoon_gb_1 is �
afternoon_gb_1 is �
afternoon_gb_1 is f
afternoon_gb_1 is t
afternoon_gb_1 is �
afternoon_gb_1 is �
afternoon_gb_1 is n
afternoon_gb_1 is u
afternoon_gb_1 is n

Body:
In UTF-8 each code-point (=logical character) is represented by multiple code units (=char); ɑftənun, in particular, is:

ch| c.p. | c.u.
--+------+-------
ɑ | 0251 | c9 91
f | 0066 | 66
t | 0074 | 74
ə | 0259 | c9 99
n | 006e | 6e
u | 0075 | 75
n | 006e | 6e

(ch=character; c.p.: code point number; c.p. code unit representation in UTF-8; c.u. and c.p. are expressed in hexadecimal)

The exact details of how the code points are mapped to the code units is explained in many places; the very basics are that:

code points less than 0x7f are mapped straight to a single code unit; for these, the high bit is never set;

code points from 0x80 onwards are mapped to multiple code units; all the code units in a multi-code-unit sequence have the high bit set;

if the high bit is set, the top bits have a particular meaning; in the first byte of a multibyte sequence they tell how many continuation bytes are to be expected, in the others they are unambiguously marked as continuation bytes.

If you print out each code unit on its own you are breaking the UTF-8 encoding for the code points that require more than one code unit to be expressed. Your terminal application in the first row sees

c9 0a

(the first code unit followed by a newline), and immediately detects that this is a broken UTF-8 sequence, as c9 has the high bit set but the next c.u. doesn't have it; hence the � character. The same holds for the second character, as well as for the c.u. parts of the sequence representing ə.

Now, if you want to print out full code-points (not code-units), std::string won't be of any help - std::string knows nothing about this stuff, it is essentially a glorified std::vector<char>, completely oblivious of encoding issues; all it does is to store/index code units, not code points.

There are however third party libraries to help work with this; utf8-cpp is a small but complete one; in your case, the utf8::next function would be particularly helpful:

while (source >> word >> word_ipa) {
    auto cur = word_ipa.begin();
    auto end = word_ipa.end();
    auto next = cur;
    for(;cur!=end; cur=next) {
        utf8::next(next, end);
        myfile << word << "is ";
        for(; cur!=next; ++cur) myfile<<*cur;
        myfile << "\n";
    }
}

utf8::next here just increments the given iterator to make it point to the code point that starts the next code unit; this code makes sure that we print together all the code units that make up a single code point.

Notice that we can reproduce its barebones behavior quite simply, it's just a matter of reading the UTF-8 specs (see the first table in the link to Wikipedia above):

template<typename ItT>
void safe_advance(ItT &it, size_t n, ItT end) {
    size_t d = std::distance(it, end);
    if(n>d) throw std::logic_error("Truncated UTF-8 sequence");
    std::advance(it, n);
}

template<typename ItT>
void my_next(ItT &it, ItT end) {
    uint8_t b = *it;
    if(b>>7 == 0) safe_advance(it, 1, end);
    else if(b>>5 == 6) safe_advance(it, 2, end);
    else if(b>>4 == 14) safe_advance(it, 3, end);
    else if(b>>3 == 30) safe_advance(it, 4, end);
    else throw std::logic_error("Invalid UTF-8 sequence");
}

Here we are exploiting the fact that the first byte of a sequence declares how many extra code points are going to come to complete the code unit.

(notice that this expects valid UTF-8 and does not do any attempt to resynchronize a broken UTF-8 sequence; the library version probably fares way better in this regard)

OTOH, it's also possible to inline just what's necessary to keep the same code unit together:

while (source >> word >> word_ipa) {
    auto cur = word_ipa.begin();
    auto end = word_ipa.end();
    for(;cur!=end;) {
        myfile << word << "is "<<*cur;
        if(uint8_t(*cur++)>>7 != 0) {
            for(; cur!=end && (uint8_t(*cur)>>6)==2; ++cur) myfile<<*cur;
        }
        myfile << "\n";
    }
}

Here instead we are disregarding completely the "declared count" in the first c.u., we just check if the high bit is set; in this case, we go on printing as long as we get c.u. with the top two bytes set to 10 (in binary, AKA 2 in decimal) - since the "continuation c.u." of a multi-c.u. UTF-8 sequence all follow this pattern.


问:
Android create object of one of the similar classes
I have two classes that do the same things but by the different ways. I need to create an object of one of these classes depending on config settings. Here is a brief example of what do I want to do.

```<code>public class A {
    public string getLetter() {
        return "A";
    }
}
public class B {
    public string getLetter() {
        return "B";
    }
}

public class MainActivity {
    private myObject; // How to declare it in my case?
    private int config = 0;

    public void onCreate(Bundle savedInstanceState) {
        if (config == 0) {
            myObject = new A();
        } else {
            myObject = new B();
        }
        String letter = myObject.getLetter();
    }
}
</code>```

Actually everything is much more complex. Each of classes A and B asynchronously listens to the different sources of data, converts it to the format that can be used in further processing and passes it to MainActivity. Depending on configuration only one source of data must be selected. How can I do this? Variant with

```<code>letter = A.getLetter();
</code>```

will not work.

答:
Use interface or abstract class and implement or extend it in class A and B, e.g.

```<code>public interface Letter {
    String getLetter();
}
public class A implements Letter {
    public String getLetter() {
        return "A";
    }
}
public class B implements Letter {
    public String getLetter() {
        return "B";
    }
}

// Then you can declare and use it as interface
private Letter myObject;

// init logic
...
String letter = myObject.getLetter();
</code>```

Body:
I have two classes that do the same things but by the different ways. I need to create an object of one of these classes depending on config settings. Here is a brief example of what do I want to do.

public class A {
    public string getLetter() {
        return "A";
    }
}
public class B {
    public string getLetter() {
        return "B";
    }
}

public class MainActivity {
    private myObject; // How to declare it in my case?
    private int config = 0;

    public void onCreate(Bundle savedInstanceState) {
        if (config == 0) {
            myObject = new A();
        } else {
            myObject = new B();
        }
        String letter = myObject.getLetter();
    }
}

Actually everything is much more complex. Each of classes A and B asynchronously listens to the different sources of data, converts it to the format that can be used in further processing and passes it to MainActivity. Depending on configuration only one source of data must be selected. How can I do this? Variant with

letter = A.getLetter();

will not work.

Body:
Use interface or abstract class and implement or extend it in class A and B, e.g.

public interface Letter {
    String getLetter();
}
public class A implements Letter {
    public String getLetter() {
        return "A";
    }
}
public class B implements Letter {
    public String getLetter() {
        return "B";
    }
}

// Then you can declare and use it as interface
private Letter myObject;

// init logic
...
String letter = myObject.getLetter();


问:
C# ASP.NET How to modify CSS class via code-behind
So just like the title, how to modify the CSS class via code-behind?
For example the following code

```<code>                    <li class="active"><a href="pages-messages.html"><span class="fa fa-comments"></span> Messages</a></li>
                    <li><a href="pages-calendar.html"><span class="fa fa-calendar"></span> Calendar</a></li>
                    <li><a href="pages-tasks.html"><span class="fa fa-edit"></span> Tasks</a></li>
                    <li><a href="pages-content-table.html"><span class="fa fa-columns"></span> Content Table</a></li>
                    <li><a href="pages-faq.html"><span class="fa fa-question-circle"></span> FAQ</a></li>
                    <li><a href="pages-search.html"><span class="fa fa-search"></span> Search</a></li>
</code>```

The code above is navigation for my HTML page and the first line has li class="active", how to change it into just li and the second row which is pages-calender change it into li class="active" ?

Thanks

答:
If you are using WebForms, then add runat="server" attributes and set unique id attribute for each li tag you need to modify in code-behind.
Addition of this tags is needed  to enable programmatic access from code-behind to the HTML element.

For example:

```<code><li runat="server" id="PagesMessages" class="active"><a href="pages-messages.html"><span class="fa fa-comments"></span> Messages</a></li>
<li runat="server" id="PagesCalender"><a href="pages-calendar.html"><span class="fa fa-calendar"></span> Calendar</a></li>
</code>```

Then in code-behind:

```<code>PagesMessages.Attributes["class"] = string.Empty;
PagesCalender.Attributes["class"] = "active";
</code>```

Body:
So just like the title, how to modify the CSS class via code-behind?
For example the following code

 Messages

 Calendar

 Tasks

 Content Table

 FAQ

 Search

The code above is navigation for my HTML page and the first line has li class="active", how to change it into just li and the second row which is pages-calender change it into li class="active" ?

Thanks

Body:
If you are using WebForms, then add runat="server" attributes and set unique id attribute for each li tag you need to modify in code-behind.
Addition of this tags is needed  to enable programmatic access from code-behind to the HTML element.

For example:

<li runat="server" id="PagesMessages" class="active"><a href="pages-messages.html"><span class="fa fa-comments"></span> Messages</a></li>
<li runat="server" id="PagesCalender"><a href="pages-calendar.html"><span class="fa fa-calendar"></span> Calendar</a></li>

Then in code-behind:

PagesMessages.Attributes["class"] = string.Empty;
PagesCalender.Attributes["class"] = "active";


问:
pygame mouse registering multiple clicks
I have two lists and a function. The function appends items from one list to the other every time the mouse is clicked. However, the mouse sometimes appends more than one item from the list. After doing a little digging around I found that this was because the mouse is held down for too long. How do I make it so regardless of how long the mouse is held down, it only appends one item? Here is a code sample:

```<code>list_A = [1,2,3,4,5,6]
list_B = []

def appender():
    if mouse.get_pressed()[0] = 1
        list_B.append(list_A[len(list_A)-1])
        list_A.remove(list_A[len(list_A)-1])
</code>```

I call the appended function inside of a game loop with all the right setups. However, it appends multiple items when the mouse is held down, any suggestions?

答:
I suggest an alternative way to detect mouse click. loop through events in pygame and see if any of them are MOUSEBUTTONDOWN:

```<code>list_A = [1,2,3,4,5,6]
list_B = []
def appender():
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            list_B.append(list_A[len(list_A)-1])
            list_A.remove(list_A[len(list_A)-1])
</code>```

Body:
I have two lists and a function. The function appends items from one list to the other every time the mouse is clicked. However, the mouse sometimes appends more than one item from the list. After doing a little digging around I found that this was because the mouse is held down for too long. How do I make it so regardless of how long the mouse is held down, it only appends one item? Here is a code sample:

list_A = [1,2,3,4,5,6]
list_B = []

def appender():
    if mouse.get_pressed()[0] = 1
        list_B.append(list_A[len(list_A)-1])
        list_A.remove(list_A[len(list_A)-1])

I call the appended function inside of a game loop with all the right setups. However, it appends multiple items when the mouse is held down, any suggestions?

Body:
I suggest an alternative way to detect mouse click. loop through events in pygame and see if any of them are MOUSEBUTTONDOWN:

list_A = [1,2,3,4,5,6]
list_B = []
def appender():
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            list_B.append(list_A[len(list_A)-1])
            list_A.remove(list_A[len(list_A)-1])


问:
Gremlin .match()
I have a query in Gremlin, using Datastax studio that looks like this: </p>

```<code>g.V().has('vertexLabel', 'vertexProperty1', '12345').match(
    __.as('d').in('edgeLabel1').values('property2').as('NAME1'),
    __.as('d').in('edgeLabel2').values('property3').as('NAME2'),
    __.as('d').in('edgeLabel1').out('edgeLabel3').values('property4').as('NAME3')
    ).select('NAME1', 'NAME2', 'NAME3')
</code>```

<p>This works just fine if all entities exists, but if one of them is not on the graph, no results are found, even though I know there are. How can I make an .or query that will find the values if they exist. Say, if property4 was not found at the end of edgeLabel3, how can my query still give me the other two results (property2 and property3)? I've tried doing .or queries, but I haven't had any luck.  </p>

答:
Have you tried using a union step in Gremlin?  It should look something like this:</p>

```<code>g.V('book:882178048:25').has('vertexLabel', 'vertexProperty1', '12345')
.union(
    as('d').in('edgeLabel1').values('property2').store('NAME1'),
    as('d').in('edgeLabel2').values('property3').store('NAME2'),
    as('d').in('edgeLabel1').out('edgeLabel3').values('property4').store('NAME3')
).cap('NAME1', 'NAME2', 'NAME3')
</code>```

Title: Gremlin .match()

Body:
I have a query in Gremlin, using Datastax studio that looks like this:

g.V().has('vertexLabel', 'vertexProperty1', '12345').match(
    __.as('d').in('edgeLabel1').values('property2').as('NAME1'),
    __.as('d').in('edgeLabel2').values('property3').as('NAME2'),
    __.as('d').in('edgeLabel1').out('edgeLabel3').values('property4').as('NAME3')
    ).select('NAME1', 'NAME2', 'NAME3')

This works just fine if all entities exists, but if one of them is not on the graph, no results are found, even though I know there are. How can I make an .or query that will find the values if they exist. Say, if property4 was not found at the end of edgeLabel3, how can my query still give me the other two results (property2 and property3)? I've tried doing .or queries, but I haven't had any luck.

Body:
Have you tried using a union step in Gremlin?  It should look something like this:

g.V('book:882178048:25').has('vertexLabel', 'vertexProperty1', '12345')
.union(
    as('d').in('edgeLabel1').values('property2').store('NAME1'),
    as('d').in('edgeLabel2').values('property3').store('NAME2'),
    as('d').in('edgeLabel1').out('edgeLabel3').values('property4').store('NAME3')
).cap('NAME1', 'NAME2', 'NAME3')


问:
javaFX circle in a layout not visible
I made a circle and added as a child to a group. then I added the group as a child to a layout(Region). I added Region to the scene. I made both with different colours but I cannot see the circle

Analog_clock.java

```<code>package analog_clock;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Analog_clock extends Application {

    @Override
    public void start(Stage primaryStage) {

        Circle circle = new Circle();
        circle.setCenterX(100.0f);
        circle.setCenterY(100.0f);
        circle.setRadius(50.0f);
        circle.setFill(Color.ALICEBLUE);

        Group g = new Group();
        g.getChildren().add(circle);

        Background_region_ bg = new Background_region_();
        bg.getChildrenUnmodifiable().add(g);

        Scene scene = new Scene(bg, 300, 250);
        scene.getStylesheets().add(this.getClass().getResource("style.css").toExternalForm());

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

Background_Region_.java

```<code>package analog_clock;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Background_region_ extends Region
{
    //CONSTRUCTOR
    public Background_region_()
    {
        setStyle("-fx-background-color: #ACACE6");
    }

}
</code>```

style.css

```<code>.circle{-fx-stroke: #cdd0d7;}
</code>```

答:
Use Pane instead of Region. Region is a special parent class for control's developers.

Next line throws exception in your code:

```<code>bg.getChildrenUnmodifiable().add(g);
</code>```

Note word "Unmodifiable". It means your are not supposed and can't modify this list.

Title: javaFX circle in a layout not visible

Body:
I made a circle and added as a child to a group. then I added the group as a child to a layout(Region). I added Region to the scene. I made both with different colours but I cannot see the circle

Analog_clock.java

package analog_clock;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Analog_clock extends Application {

    @Override
    public void start(Stage primaryStage) {

        Circle circle = new Circle();
        circle.setCenterX(100.0f);
        circle.setCenterY(100.0f);
        circle.setRadius(50.0f);
        circle.setFill(Color.ALICEBLUE);

        Group g = new Group();
        g.getChildren().add(circle);

        Background_region_ bg = new Background_region_();
        bg.getChildrenUnmodifiable().add(g);

        Scene scene = new Scene(bg, 300, 250);
        scene.getStylesheets().add(this.getClass().getResource("style.css").toExternalForm());

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Background_Region_.java

package analog_clock;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Background_region_ extends Region
{
    //CONSTRUCTOR
    public Background_region_()
    {
        setStyle("-fx-background-color: #ACACE6");
    }

}

style.css

.circle{-fx-stroke: #cdd0d7;}

Body:
Use Pane instead of Region. Region is a special parent class for control's developers.

Next line throws exception in your code:

bg.getChildrenUnmodifiable().add(g);

Note word "Unmodifiable". It means your are not supposed and can't modify this list.


问:
Is that possible that two different product of same vendor show different pair of devicename, vid, pid?
Currently i am thinking for a functionality for devices which has to rely on identification of unique devices. Currently i am thinking to keep device name also in that list as a measure to identify uniqueness of device.

My question is : Will ever be a case ever that a manufacturer has two product having same vid, different pid but same name ?

答:
If you're trying to uniquely identify specific devices, use the VID, PID, and serial number if available. This will allow you to sometimes tell two instances of the same device apart, like two flash drives or USB serial adapters.

I wouldn't use the device name -- if the VID and PID of two devices are the same, the devices will almost always have the same name, so using it is unlikely to make much of a difference.

Will ever be a case ever that a manufacturer has two product having same vid, different pid but same name ?

This is a slightly different question. Yes, this will happen sometimes, typically in situations where a product name is somewhat generic. (For instance, a manufacturer of flash drives will probably have many different devices all with their VID and the name "USB Flash Drive", but different PIDs.)


答:
The problem is the Region Class only has an Unmodifiable List of children via its public API, that means, the only way to add children to it is to subclass it (e.g Pane). So use Pane or another subclass, something like this for example:

```<code>Pane bg = new Pane();
bg.setBackground(new Background(new BackgroundFill(Color.web("#ACACE6"), null,null)));
bg.getChildren().add(g);
</code>```

Title: javaFX circle in a layout not visible

Body:
The problem is the Region Class only has an Unmodifiable List of children via its public API, that means, the only way to add children to it is to subclass it (e.g Pane). So use Pane or another subclass, something like this for example:

Pane bg = new Pane();
bg.setBackground(new Background(new BackgroundFill(Color.web("#ACACE6"), null,null)));
bg.getChildren().add(g);


问:
Use Same Variable In Multiple View Controllers
I have two colour variables:

```<code>var blue = UIColor(red:0.08, green:0.49, blue:0.49, alpha:1.0)
var red = UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)
</code>```

I have declared these variables in my EntryViewController, however, I also need to use them in my other ViewControllers. I was wondering if it were possible to use the same variables in multiple ViewControllers? I already know about passing data with segues, but I was wondering if there were a way to maybe declare the colours in their own class and subclass my ViewControllers with this class. Thank you.

答:
One approach here is to create an extension on UIColor. You can then make them global to your module.

```<code>extension UIColor {
    static var myRed: UIColor {
        return UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)
    }
    static var myBlue: UIColor {
        return UIColor(red: 0.08, green: 0.49, blue: 0.49, alpha:1.0)
    }
}
</code>```

Body:
I have two colour variables:

var blue = UIColor(red:0.08, green:0.49, blue:0.49, alpha:1.0)
var red = UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)

I have declared these variables in my EntryViewController, however, I also need to use them in my other ViewControllers. I was wondering if it were possible to use the same variables in multiple ViewControllers? I already know about passing data with segues, but I was wondering if there were a way to maybe declare the colours in their own class and subclass my ViewControllers with this class. Thank you.

Body:
One approach here is to create an extension on UIColor. You can then make them global to your module.

extension UIColor {
    static var myRed: UIColor {
        return UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)
    }
    static var myBlue: UIColor {
        return UIColor(red: 0.08, green: 0.49, blue: 0.49, alpha:1.0)
    }
}


问:
Mapping SQL query results to JSON in PHP
I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.

```<code>$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
        INNER JOIN matchup_option
        ON matchup_option.matchupID= matchup.matchupID;';

$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
    $data[] = array (
        'id' => $attachment['matchupID'],
        'options' => array(
            array (
                "name" => $attachment['player_name'],
                "playerid" => $attachment['player_id']
            )
        )
    );
    //VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);
</code>```

Gives me this output:

```<code>{
"matchup":[
  {
     "id":"111222",
     "options":[
        {
           "name":"111",
           "playerid":"111"
        }
     ]
  },
  {
     "id":"111222",
     "options":[
        {
           "name":"222",
           "playerid":"222"
        }
     ]
  }
]
}
</code>```

And here's what I'm trying to get to:

```<code>{
"matchup":[
  {
     "id":"111222",
     "options":[
        {
           "name":"111",
           "playerid":"111"
        },
        {
           "name":"222",
           "playerid":"222"
        }
     ]
  }
]
}
</code>```

I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!

答:
You need to store $attachment['matchupID'] as an array key of $data:

```<code>$data = array();
while ($attachment = $db->fetch_array($attachments)){
    if (!isset($data[$attachment['matchupID']])) {
        $data[$attachment['matchupID']] = array (
            'id' => $attachment['matchupID'],
            'options' => array()
        );
    }
    $data[$attachment['matchupID']]['options'][] = array (
        "name" => $attachment['player_name'],
        "playerid" => $attachment['player_id']
    );
}

// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);
</code>```

Body:
I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.

$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
        INNER JOIN matchup_option
        ON matchup_option.matchupID= matchup.matchupID;';

$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
    $data[] = array (
        'id' => $attachment['matchupID'],
        'options' => array(
            array (
                "name" => $attachment['player_name'],
                "playerid" => $attachment['player_id']
            )
        )
    );
    //VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);

Gives me this output:

{
"matchup":[
  {
     "id":"111222",
     "options":[
        {
           "name":"111",
           "playerid":"111"
        }
     ]
  },
  {
     "id":"111222",
     "options":[
        {
           "name":"222",
           "playerid":"222"
        }
     ]
  }
]
}

And here's what I'm trying to get to:

{
"matchup":[
  {
     "id":"111222",
     "options":[
        {
           "name":"111",
           "playerid":"111"
        },
        {
           "name":"222",
           "playerid":"222"
        }
     ]
  }
]
}

I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!

Body:
You need to store $attachment['matchupID'] as an array key of $data:

$data = array();
while ($attachment = $db->fetch_array($attachments)){
    if (!isset($data[$attachment['matchupID']])) {
        $data[$attachment['matchupID']] = array (
            'id' => $attachment['matchupID'],
            'options' => array()
        );
    }
    $data[$attachment['matchupID']]['options'][] = array (
        "name" => $attachment['player_name'],
        "playerid" => $attachment['player_id']
    );
}

// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);


问:
No Option To Get Angular Smart Table State With Visible Columns
I'm just wondering if they have provided a options to make table columns show and hide as user preference and save it in table state and load it back when page refreshes.

```<code>ctrl.tableState()
</code>```

upper code only brings the pagination,sorting and search objects as in current table state. How can i implement showing and hide table columns like in jquery Datatable and load it back from the table state object?

答: Decided to use Jquery Data Table instead with AngularJS ng-repeat</p>

Body:
I'm just wondering if they have provided a options to make table columns show and hide as user preference and save it in table state and load it back when page refreshes.

ctrl.tableState()

upper code only brings the pagination,sorting and search objects as in current table state. How can i implement showing and hide table columns like in jquery Datatable and load it back from the table state object?


问:
Create Windows 10 app shortcut on desktop vbsscript
I try to create a VBS installer that creates a shortcut of a Windows 10 APP on the desktop. However after hours of trying I can't seem to make it work.

This is my current script.

```<code>With CreateObject("WScript.Shell")
    With .CreateShortcut(.SpecialFolders("Desktop") & "\Todoist To-Do List and Task Manager.lnk")
         .TargetPath = "shell:AppsFolder" & "\Todoist To-Do List and Task Manager"
         .Description = "Todoist To-Do List and Task Manager"
         .Save
    End  With
End  With
</code>```

The name of the program I want to create a shortcut for is "Todoist To-Do List and Task Manager"

I think the main problem is the Target Path. But I can't seem to find out how to point to a file inside a special folder. The special folder CLSID = {4234d49b-0245-4df3-b780-3893943456e1}. How do I point to a file in that folder?

Thanks a lot in advance,

Greetings,

Rick,

答:
Took me some time but I finally found a way :).</p>

```<code>'Add AppUserModelid to AutoHotKey filesys
'Change file extension
strFile = scriptdir & "\Todoist_global_shortcuts.ahk"
WScript.Echo strFile
strRename = scriptdir & "\Todoist_global_shortcuts.txt"

If filesys.FileExists(strFile) Then
   filesys.MoveFile strFile, strRename
End If

'Create shortcut
With CreateObject("WScript.Shell")
    With .CreateShortcut(.SpecialFolders("Desktop") & "\Todoist To-Do List and Task Manager.lnk")
         .TargetPath = "shell:AppsFolder\" & pathStr
         .Description = "Todoist To-Do List and Task Manager"
         .Save
    End  With
End  With
</code>```

Body:
I try to create a VBS installer that creates a shortcut of a Windows 10 APP on the desktop. However after hours of trying I can't seem to make it work.

This is my current script.

With CreateObject("WScript.Shell")
    With .CreateShortcut(.SpecialFolders("Desktop") & "\Todoist To-Do List and Task Manager.lnk")
         .TargetPath = "shell:AppsFolder" & "\Todoist To-Do List and Task Manager"
         .Description = "Todoist To-Do List and Task Manager"
         .Save
    End  With
End  With

The name of the program I want to create a shortcut for is "Todoist To-Do List and Task Manager"

I think the main problem is the Target Path. But I can't seem to find out how to point to a file inside a special folder. The special folder CLSID = {4234d49b-0245-4df3-b780-3893943456e1}. How do I point to a file in that folder?

Thanks a lot in advance,

Greetings,

Rick,

Body:
Took me some time but I finally found a way :).

'Add AppUserModelid to AutoHotKey filesys
'Change file extension
strFile = scriptdir & "\Todoist_global_shortcuts.ahk"
WScript.Echo strFile
strRename = scriptdir & "\Todoist_global_shortcuts.txt"

If filesys.FileExists(strFile) Then
   filesys.MoveFile strFile, strRename
End If

'Create shortcut
With CreateObject("WScript.Shell")
    With .CreateShortcut(.SpecialFolders("Desktop") & "\Todoist To-Do List and Task Manager.lnk")
         .TargetPath = "shell:AppsFolder\" & pathStr
         .Description = "Todoist To-Do List and Task Manager"
         .Save
    End  With
End  With


问:
NPM module curlrequest producing Possible EventEmitter memory leak detected
I have been searching around trying to resolve the following issue:

I am doing a curlrequest using the npm module 'curlrequest'

I am looping thru an array of id numbers and each id is then used to make a outgoing POST request to a remote server using this module 'curlrequest'

I am getting the following error:

```<code>        curl.stdout.on('data', function (data) {
               ^
TypeError: Cannot read property 'on' of undefined
</code>```

With the following warnings:

```<code>(node:21363) Warning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 unpipe listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit
</code>```

Any ideas?

答: My specific solution did not really solve this exact issue , but i decided to just stop using this module and switched over to standard request library.</p>

Body:
I have been searching around trying to resolve the following issue:

I am doing a curlrequest using the npm module 'curlrequest'

I am looping thru an array of id numbers and each id is then used to make a outgoing POST request to a remote server using this module 'curlrequest'

I am getting the following error:

        curl.stdout.on('data', function (data) {
               ^
TypeError: Cannot read property 'on' of undefined

With the following warnings:

(node:21363) Warning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 unpipe listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
(node:21363) Warning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit

Any ideas?


问:
How to echo javascript code which contains php tags inside?
I usually echo script alert by simply

echo '';

but how to echo the script when the script contains php tags? (see my example code)

Because of my php obfuscator script, I have to use only one <?php ?> tag. so in this case I need to echo the javascript without having <?php tags. What are the possible solutions in this case?

```<code>    <?php
...some php code...
<script type="text/javascript">
    jQuery(document).ready(function($){
        $i = 0;
        $('.wrapper_vertical_menu .megamenu_menu').append('<div class="more-wrap"><span class="more"><?php echo $this->__("More"); ?></span></div>');
        $('.wrapper_vertical_menu .megamenu_menu > li.megamenu_lv1').each(function(){
            $i ++;
            if($i>13){
                $(this).css('display', 'none');
            }
        });
        ... more js code ...
</code>```

答:
JavaScript doesn't "contain PHP tags".  All your PHP code needs to do is build the resulting output string (which happens to be JavaScript code, but that doesn't matter to PHP) and echo it.

So where you have something like this:

```<code>echo "some javascript code <?php echo some_php_value; ?> more javascript code";
</code>```

What you really want, quite simply, is this:

```<code>echo "some javascript code " . some_php_value . " more javascript code";
</code>```

Don't try to nest <?php ?> tags within each other.  Just concatenate the actual output you want and echo that output.

Body:
I usually echo script alert by simply

echo '';

but how to echo the script when the script contains php tags? (see my example code)

Because of my php obfuscator script, I have to use only one <?php ?> tag. so in this case I need to echo the javascript without having <?php tags. What are the possible solutions in this case?

    <?php
...some php code...

Body:
JavaScript doesn't "contain PHP tags".  All your PHP code needs to do is build the resulting output string (which happens to be JavaScript code, but that doesn't matter to PHP) and echo it.

So where you have something like this:

echo "some javascript code <?php echo some_php_value; ?> more javascript code";

What you really want, quite simply, is this:

echo "some javascript code " . some_php_value . " more javascript code";

Don't try to nest <?php ?> tags within each other.  Just concatenate the actual output you want and echo that output.


问:
Run command line in python and save the details
i am trying to run some command line in python script, like:

```<code>ping 8.8.8.8
</code>```

and when i write this code:

```<code>import os
os.system('ping 8.8.8.8')
</code>```

it printing me the details of the command.
but i want it for be background command,
what mean i dont want to user will see all the details.
i want to save it to varilble, and after that edit and print as my wish.
how can i do that?
i try to store what the function return, as:

```<code>answer = os.system('ping 8.8.8.8')
</code>```

but the function return 0. help someone?

答:
Simply create a bat file with ping 8.8.8.8 written in it.
Then you can use the subprocess command to invoke it from within the python script.</p>

```<code>import subprocess
subprocess.Popen('ping.bat')
</code>```

Body:
i am trying to run some command line in python script, like:

ping 8.8.8.8

and when i write this code:

import os
os.system('ping 8.8.8.8')

it printing me the details of the command.
but i want it for be background command,
what mean i dont want to user will see all the details.
i want to save it to varilble, and after that edit and print as my wish.
how can i do that?
i try to store what the function return, as:

answer = os.system('ping 8.8.8.8')

but the function return 0. help someone?

Body:
Simply create a bat file with ping 8.8.8.8 written in it.
Then you can use the subprocess command to invoke it from within the python script.

import subprocess
subprocess.Popen('ping.bat')


问:
How to add a class on React component mount?
My React app has a base div like so:

```<code><body>
    <div id="root">
        ....
    </div>
</body>
</code>```

In my Welcome container, I would like to add a class to the div w id="root and then on Welcome container unmount, remove the class.

```<code>class Welcome extends React.Component {

  componentDidMount() {
    console.log('componentDidMount');
    console.log($('#root'));
  }
  ....
</code>```

With jQuery I could do something like

```<code>$('#root').addClass('myClass')
....
$('#root').removeClass('myClass')
</code>```

What is the equivalent in React for adding and removing a class on a div after finding it by its ID?

答:
This makes no sense. You shouldn't be adding classes to root from React components. The root div should just exist to inject React in to using ReactDOM.

Instead of modifying the html root, create a react class called App or something and render a
 that wraps all of your components. You can then use React state or props to modify the className.

```<code>class App extends React.Component {
    constructor() {
        super();

        this.state = {
            appClass: 'myClass'
        };
    }

    componentDidMount() {
        this.setState({ appClass: 'newClass' });
    }

    render() {
        return (
            <div className={this.state.appClass}>
                // Render children here
            </div>
        );
    }
}
</code>```

If you want to modify the appClass from a child component such as Welcome which is further down in your application then you will need to use a state management like Redux or Flux to modify the className from a child component otherwise it will get messy fast.

EDIT: removed semicolon from this.state object

Body:
My React app has a base div like so:

        ....

In my Welcome container, I would like to add a class to the div w id="root and then on Welcome container unmount, remove the class.

class Welcome extends React.Component {

  componentDidMount() {
    console.log('componentDidMount');
    console.log($('#root'));
  }
  ....

With jQuery I could do something like

$('#root').addClass('myClass')
....
$('#root').removeClass('myClass')

What is the equivalent in React for adding and removing a class on a div after finding it by its ID?

Body:
This makes no sense. You shouldn't be adding classes to root from React components. The root div should just exist to inject React in to using ReactDOM.

Instead of modifying the html root, create a react class called App or something and render a <div className="app" /> that wraps all of your components. You can then use React state or props to modify the className.

class App extends React.Component {
    constructor() {
        super();

        this.state = {
            appClass: 'myClass'
        };
    }

    componentDidMount() {
        this.setState({ appClass: 'newClass' });
    }

    render() {
        return (
            <div className={this.state.appClass}>
                // Render children here
            </div>
        );
    }
}

If you want to modify the appClass from a child component such as Welcome which is further down in your application then you will need to use a state management like Redux or Flux to modify the className from a child component otherwise it will get messy fast.

EDIT: removed semicolon from this.state object