问:
Intent object showing error Android
I am working with android activities , and trying to launch an activity when a button is clicked on the previous activity, the problem start in intent object, because the first parameter i.e; context parameter of intent constructor doesn't work with "this, MainActivity.this, getApplicationContext(),getBaseContext" i tried all of the parameters in the first parameter of the intent constructor object. Below is my code.

```<code>package com.example.nadeemahmad.guitest;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

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

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });

    }

}
</code>```

Image

答:
Add this line after set content view :</p>

```<code>prof_sub_btn = (Button)findViewById(R.id.prof_sub_btn);
</code>```

Title: Intent object showing error Android

Body:
I am working with android activities , and trying to launch an activity when a button is clicked on the previous activity, the problem start in intent object, because the first parameter i.e; context parameter of intent constructor doesn't work with "this, MainActivity.this, getApplicationContext(),getBaseContext" i tried all of the parameters in the first parameter of the intent constructor object. Below is my code.

package com.example.nadeemahmad.guitest;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

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

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });

    }

}

Image

Body:
Add this line after set content view :

prof_sub_btn = (Button)findViewById(R.id.prof_sub_btn);


来源: stackexchange

问:
UIAlertController handle dismiss upon click outside (IPad)
Previous to iOS8 we used the UIActionSheet for showing alert and now we need to use the UIAlertController.

When we used the UIActionSheet we could easily handle situations where the user clicked outside the pop up (which means he want to cancel the operation) by comparing the clickedButtonAtIndex to the cancelButtonIndex  - if the user indeed pressed outside the popup we got the cancel button index in this function.

How can we handle these situations with the new UIAlertController? I tried to use the "completion" block but it doesn't have any context. Is there an easy way to handle this? (other than "saving" the actions states in some general variable).

答:
UITapGestureRecognizer didn't work for me so I've used this way:</p>

```<code>func addDismissControl(_ toView: UIView) {
    let dismissControl = UIControl()
    dismissControl.addTarget(self, action: #selector(self.dismissAlertController), for: .touchDown)
    dismissControl.frame = toView.superview?.frame ?? CGRect.zero
    toView.superview?.insertSubview(dismissControl, belowSubview: toView)
}

func dismissAlertController() {
    self.dismiss(animated: true, completion: nil)
}

func presentAlertController(title: String?, message: String?, preferredStyle: UIAlertControllerStyle,  handler: ((UIAlertAction) -> Swift.Void)? = nil, completion: (() -> Swift.Void)? = nil) {

    let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
    alertController.addAction(UIAlertAction(title: "OK", style: .default) { (alertAction) -> Void in
        handler?(alertAction)
    })

    self.present(alertController, animated: true, completion: {
        self.addDismissControl(alertController.view)
        completion?()
    })
}

func someWhereInYourViewController() {
    // ...
    presentAlertController(title: "SomeTitle", message: "SomeMessage", preferredStyle: .actionSheet, handler: { (alertAction) -> Void in
        //do some action
    }, completion: {
        //do something after presentation
    })
    // ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
UITapGestureRecognizer didn't work for me so I've used this way:

func addDismissControl(_ toView: UIView) {
    let dismissControl = UIControl()
    dismissControl.addTarget(self, action: #selector(self.dismissAlertController), for: .touchDown)
    dismissControl.frame = toView.superview?.frame ?? CGRect.zero
    toView.superview?.insertSubview(dismissControl, belowSubview: toView)
}

func dismissAlertController() {
    self.dismiss(animated: true, completion: nil)
}

func presentAlertController(title: String?, message: String?, preferredStyle: UIAlertControllerStyle,  handler: ((UIAlertAction) -> Swift.Void)? = nil, completion: (() -> Swift.Void)? = nil) {

    let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
    alertController.addAction(UIAlertAction(title: "OK", style: .default) { (alertAction) -> Void in
        handler?(alertAction)
    })

    self.present(alertController, animated: true, completion: {
        self.addDismissControl(alertController.view)
        completion?()
    })
}

func someWhereInYourViewController() {
    // ...
    presentAlertController(title: "SomeTitle", message: "SomeMessage", preferredStyle: .actionSheet, handler: { (alertAction) -> Void in
        //do some action
    }, completion: {
        //do something after presentation
    })
    // ...
}


问:
Javascript: How can I use object properties in functions using the parameter?
I am a beginner to Javascript and I am trying to make a text-based game for practice. I have made objects for enemies like so:

```<code>export const spider = {
strength: 1,
health: 4,
gold: 1
};
</code>```

I am now trying to make a function which can search for their stats when their name is entered in the field. It looks like this:

```<code>export const findStats = (target) => {
return target.health;
}
</code>```

However, when I do this and test it I get 'undefined.' However, if I replace 'target.health' with 'spider.health' it works properly.

The error occurs when I try doing findStats("spider") which gives me the 'undefined results.'

Any help would be appreciated. Note: I did look around this site but found the threads too complex or not quite what I was looking for. I am a beginner so simple terms would be greatly appreciated!
Thanks for all your comments!

My issue is unlike to the one on the right as when I try it with my code is still returns 'undefined.' Here is the code that I have just tried using the other thread. Keep in mind I am a beginner so I am probably doing it very wrong but if you could help further I would be very happy.

```<code>export const findLocalStats = (target) => {
  var bar = 'strength';
  console.log(target[bar]);
}
</code>```

Here are is my test command:

```<code>expect(findLocalStats("spider")).toEqual(1);
</code>```

Furthermore, when I tried the code written in JSFiddle in my editor, it still gave the same error in the terminal which is 'undefined.'

```<code>export function findStats(target) {
return target.strength;
}
</code>```

And the test command:

```<code>expect(findStats("spider")).toEqual(1);
</code>```

And the exact error message:

findStats() gives the stats of the target wanted.

```<code>expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  undefined

Difference:

  Comparing two different types of values. Expected number but received undefined.
</code>```

Sorry if this is very tedious.
Note 2: I posted this question before but I have changed it to attempt to explain my issue better as I still do not understand the answers I was given and the links to duplicate questions - which I have tried to replicate. Furthermore, the duplicate that I was given was different. It used the object as the keyword, however I want to use it as a feed-in to a parameter so that it is versatile for more than one enemies if that makes sense. Thank you!

答:
When you are calling findStats like this : findStats("spider") you are sending a string to the function as an argument. That's why when it tries to get the property health it says undefined.

You need to give the function an instance of your spider object. To create an instance you can use the Object.create() method like var killMe = Object.create(spider). This will create a new object based on the one you declared before. Then you can call your function like this : findStats(killMe)

You can find an exemple here : https://jsfiddle.net/10ex1xqt/

Body:
I am a beginner to Javascript and I am trying to make a text-based game for practice. I have made objects for enemies like so:

export const spider = {
strength: 1,
health: 4,
gold: 1
};

I am now trying to make a function which can search for their stats when their name is entered in the field. It looks like this:

export const findStats = (target) => {
return target.health;
}

However, when I do this and test it I get 'undefined.' However, if I replace 'target.health' with 'spider.health' it works properly.

The error occurs when I try doing findStats("spider") which gives me the 'undefined results.'

Any help would be appreciated. Note: I did look around this site but found the threads too complex or not quite what I was looking for. I am a beginner so simple terms would be greatly appreciated!
Thanks for all your comments!

My issue is unlike to the one on the right as when I try it with my code is still returns 'undefined.' Here is the code that I have just tried using the other thread. Keep in mind I am a beginner so I am probably doing it very wrong but if you could help further I would be very happy.

export const findLocalStats = (target) => {
  var bar = 'strength';
  console.log(target[bar]);
}

Here are is my test command:

expect(findLocalStats("spider")).toEqual(1);

Furthermore, when I tried the code written in JSFiddle in my editor, it still gave the same error in the terminal which is 'undefined.'

export function findStats(target) {
return target.strength;
}

And the test command:

expect(findStats("spider")).toEqual(1);

And the exact error message:

findStats() gives the stats of the target wanted.

expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  undefined

Difference:

  Comparing two different types of values. Expected number but received undefined.

Sorry if this is very tedious.
Note 2: I posted this question before but I have changed it to attempt to explain my issue better as I still do not understand the answers I was given and the links to duplicate questions - which I have tried to replicate. Furthermore, the duplicate that I was given was different. It used the object as the keyword, however I want to use it as a feed-in to a parameter so that it is versatile for more than one enemies if that makes sense. Thank you!


问:
Is it possible to place plugin files inside a Wordpress theme?
I'm building a Wordpress theme, and I would like it to work without having to separately download the plugins it uses (e.g. internalization, contact form and lightbox).

Is it possible to place plugin files inside a Wordpress theme (or is there another way of solving this)?

e.g: wp-content/themes/my-wordpress-theme/plugins

答:
When a theme comes packaged with its own plugins, the end user is instructed to install it in /wpcontent as opposed to the normal /wp-content/themes directory so that plugins and theme files are installed in their appropriate places. You want that separation between form and function.

The theme should include hooks to those plugins, and then the administrator has to activate them after installation.

Packaging your theme like this is effectively what you are trying to do; we are just broadening the definition of a theme a bit to include its plugin directory.

If you are determined to have the plugin directory be a subdirectory of the theme, I'm not sure if or how that's doable, but it is bad practice because it doesn't maintain the separation between form and function.

ContentLicense: CC BY-SA 2.5


问:
C# - boolean and if statement
I'm currently writing code analysing images with the Google API Vision on Visual Studios.
But I have a problem that occures during my loop.
The analysis returns a list of annotation ( car, vehicle, land vehicle, etc.. ) and I wanted to filter it, with an "if", so i wrote this :

```<code>var image = Google.Cloud.Vision.V1.Image.FromFile("C:\\temp\\sequence\\1.jpg");
var client = ImageAnnotatorClient.Create();
var response = client.DetectLabels(image);
CropHintsAnnotation confidence = client.DetectCropHints(image);
bool empty = false;

foreach (var annotation in response)
{
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle"))
    {
        empty = false;
    }
    else
    {
        empty = true;
    }

}
textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
</code>```

So, if I wrote this well, it should say " Empty ? false ", because the analysis returns "vehicle" once.
I tried also to replace the :

```<code>annotation.Description.Equals("vehicle")
</code>```

by

```<code>annotation.Description.Contains("vehicle") == true
</code>```

but no way, it still says " Empty ? true ", as it should not.

Any ideas ?

Thanks in advance for reading this, and for the help !

答:
Have your considered the case of the returned string? Try to ignore the case:

```<code>annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)
</code>```

Just a side note: The Equals function returns a Boolean, so you can remove the entire if statement and simplify your code to:

```<code>empty = !annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)
</code>```

Title: C# - boolean and if statement

Body:
I'm currently writing code analysing images with the Google API Vision on Visual Studios.
But I have a problem that occures during my loop.
The analysis returns a list of annotation ( car, vehicle, land vehicle, etc.. ) and I wanted to filter it, with an "if", so i wrote this :

var image = Google.Cloud.Vision.V1.Image.FromFile("C:\\temp\\sequence\\1.jpg");
var client = ImageAnnotatorClient.Create();
var response = client.DetectLabels(image);
CropHintsAnnotation confidence = client.DetectCropHints(image);
bool empty = false;

foreach (var annotation in response)
{
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle"))
    {
        empty = false;
    }
    else
    {
        empty = true;
    }

}
textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";

So, if I wrote this well, it should say " Empty ? false ", because the analysis returns "vehicle" once.
I tried also to replace the :

annotation.Description.Equals("vehicle")

by

annotation.Description.Contains("vehicle") == true

but no way, it still says " Empty ? true ", as it should not.

Any ideas ?

Thanks in advance for reading this, and for the help !

Body:
Have your considered the case of the returned string? Try to ignore the case:

annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)

Just a side note: The Equals function returns a Boolean, so you can remove the entire if statement and simplify your code to:

empty = !annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)


问:
Round corners of table
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

```

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners

答: You should use border-collapse: separate; for the CSS of Table.

Title: Round corners of table

Body:
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners


问:
System.Data.SqlClient.SqlException: Incorrect syntax near '*'
I'm trying to create session, using the following code:</p>

```<code>SqlConnection conn = new SqlConnection("Data Source=THIRD-I;Initial Catalog=sessionlogin;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select (*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
    Session["user"] = UserName.Text;
    Response.Redirect("welcome.aspx");
}
</code>```

答:
To fix an error:

Remove brackets from Select (*) or if you looking for total number add count

Must be select * or select count(*)

But your full code required big refactoring.

Disposing objects

Parameterize query

Assuming you take user input you should filter input

Body:
I'm trying to create session, using the following code:

SqlConnection conn = new SqlConnection("Data Source=THIRD-I;Initial Catalog=sessionlogin;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select (*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
    Session["user"] = UserName.Text;
    Response.Redirect("welcome.aspx");
}


问:
"PermissionError" thrown when typing "exit()" to leave the Python interpreter
When I enter the python interpreter as a regular user with python. I see this:

```<code>Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
</code>```

I can immediately type exit() and this happens:

```<code>>>> exit()
Error in atexit._run_exitfuncs:
PermissionError: [Errno 13] Permission denied
</code>```

I think it may be related to the fact that running sudo python3 gives:

```<code>Python 3.5.2 (default, Jul  5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

This looks to be a different python 3.5 install.

If this is the issue I would like to have my anaconda python install run when I type sudo python3. How do I do this?

答: Changing the owner of ~/.python_history from root to my_user_account solved the problem.

Body:
When I enter the python interpreter as a regular user with python. I see this:

Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.

I can immediately type exit() and this happens:

>>> exit()
Error in atexit._run_exitfuncs:
PermissionError: [Errno 13] Permission denied

I think it may be related to the fact that running sudo python3 gives:

Python 3.5.2 (default, Jul  5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

This looks to be a different python 3.5 install.

If this is the issue I would like to have my anaconda python install run when I type sudo python3. How do I do this?


问:
HDFS calculate size of subfolders
Please advice on how can I calculate the size of subfolders in HDFS and sort them by size?

hdfs dfs -ls -h /mds/snapshots/user/data | du -sh * | sort -rh | head -10

Seems it should work - but as I understand hdfs doesn't work with additional commands after |

答:
You can use:</p>

```<code>hdfs dfs -du -s /path/* | sort -r -k 1 -g | awk '{ suffix="KMGT"; for(i=0;
$1>1024 && i < length(suffix); i++) $1/=1024; print int($1) substr(suffix, i,
1), $3; }'
</code>```

Title: HDFS calculate size of subfolders

Body:
You can use:

hdfs dfs -du -s /path/* | sort -r -k 1 -g | awk '{ suffix="KMGT"; for(i=0;
$1>1024 && i < length(suffix); i++) $1/=1024; print int($1) substr(suffix, i,
1), $3; }'


问:
OAuth 2, cant send the mail exception
I'm trying to send a mail with oauth 2 token, I already have it but when I'm going to send the mail it simply doesn't work.

I'm getting the following:

```<code> {"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}
</code>```

This is the line that is not working:

```<code> SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, user, oauthToken, true);
</code>```

答:
I was calling the token like this:

```<code>String authURL = "https://accounts.google.com/o/oauth2/v2/auth?scope=email&"
</code>```

I changed the "email" for this:

```<code>String authURL = "https://accounts.google.com/o/oauth2/v2/auth?scope=https://mail.google.com/%20profile&"
</code>```

I hope this help someone

Title: OAuth 2, cant send the mail exception

Body:
I'm trying to send a mail with oauth 2 token, I already have it but when I'm going to send the mail it simply doesn't work.

I'm getting the following:

 {"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}

This is the line that is not working:

 SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, user, oauthToken, true);

Body:
I was calling the token like this:

String authURL = "https://accounts.google.com/o/oauth2/v2/auth?scope=email&"

I changed the "email" for this:

String authURL = "https://accounts.google.com/o/oauth2/v2/auth?scope=https://mail.google.com/%20profile&"

I hope this help someone


问:
DriveApp.getFolderById Permissions
I'm trying to "upgrade" an old script from DocsList to DriveApp and having a problem with a getFolderById call. The script had worked previously using DocsList.getFolder. I have a (previously-created) folder named "Email Archive" that I'm trying to access in script. Through using Logs and Execution Transcript, I've verified that I'm correctly passing the string "Email Archive" in the baseFolder parameter to the following statement:

var baseFolderObject = DriveApp.getFolderById(baseFolder);

When that statement is executed, I get the following error:

Execution failed: No item with the given ID could be found, or you do
  not have permission to access it.

The "Email Archive" folder was created previously by the same script with a script call to docsList.CreateFolder, and no permissions were specified.

Do I need to do something to change the folder permissions to allow my script to access it now that I'm using DriveApp instead of DocsList? Do I need to create a new folder using DriveApp and specify permissions, and if so what permissions do I set to allow my script to access the folder and create subfolders and files without allowing it to be visible to the entire Internet?

Thanks in advance for any help,

~ Jim Fennell

答: var myFolder = DriveApp.getFoldersByName("Email Archive").next();</p>

Title: DriveApp.getFolderById Permissions


问:
How to initialize a a struct of structs inside a header file in C?
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system.  In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize.  I am getting warnings when I compile with the way the legacy code was written.  Any tips on how I can get this to work with staying inside the same header file?

The following is a simplified example I made of what they are doing.

```<code>struct A
{

    struct B  temp1;
    struct C  temp2;
};

struct B
{

    int temp3;
    int temp4;
    int temp5;
};

struct C
{

    int temp6;
    int temp7;
    int temp8;
};

//These are the variables in how they are related to the initialization below

//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};

struct A test_one = {{1,2,3},{4,5,6}};
</code>```

答:
Declare struct B and C before A, i.e. :</p>

```<code>struct B { int temp3; int temp4; int temp5; };
struct C { int temp6; int temp7; int temp8; };
struct A { struct B temp1; struct C temp2; };
</code>```

Body:
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system.  In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize.  I am getting warnings when I compile with the way the legacy code was written.  Any tips on how I can get this to work with staying inside the same header file?

The following is a simplified example I made of what they are doing.

struct A
{

    struct B  temp1;
    struct C  temp2;
};

struct B
{

    int temp3;
    int temp4;
    int temp5;
};

struct C
{

    int temp6;
    int temp7;
    int temp8;
};

//These are the variables in how they are related to the initialization below

//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};

struct A test_one = {{1,2,3},{4,5,6}};

Body:
Declare struct B and C before A, i.e. :

struct B { int temp3; int temp4; int temp5; };
struct C { int temp6; int temp7; int temp8; };
struct A { struct B temp1; struct C temp2; };


问:
MongoDB Count Distinct Speed
I'm using the following code in PyMongo:

```<code>db.collection.group(["myField"], {}, {"count":0},"function(o, p){p.count++}" )
</code>```

Which correctly returns the numbers I need but the search takes 30 seconds to complete. Would indexing speed this up? I find it hard to know whether fields should or shouldn't be indexed because I read an article which said don't index too much or everything will slow down so I've indexed nothing..

答:
Count existing keys

See: https://docs.mongodb.com/manual/reference/method/db.collection.count/

db.collection.count({"myField": {"$exists": True} })

Count by grouping key

See: https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum

db.collection.aggregate([{"$group": {"_id": "myField", "count": {"$sum":1} }])

Title: MongoDB Count Distinct Speed

Body:
I'm using the following code in PyMongo:

db.collection.group(["myField"], {}, {"count":0},"function(o, p){p.count++}" )

Which correctly returns the numbers I need but the search takes 30 seconds to complete. Would indexing speed this up? I find it hard to know whether fields should or shouldn't be indexed because I read an article which said don't index too much or everything will slow down so I've indexed nothing..


问:
Change the font family of
?
I tried to change the family font of my mainmenu in website : http://www.train-luxe-afrique.com/

It doesn't work. Do you have any idea ?

答:
I think your problem relates to specificity so in your style.css, just add the lines.

```<code>li.menu-item a{
    font-family: "whatever" !important;
}
</code>```

The !important will override all other styles.

You should also try refactoring your code to make it less cluttered that way you won't have to use hacks like that.

Title: Change the font family of <div class="mainmenu">?

Body:
I think your problem relates to specificity so in your style.css, just add the lines.

li.menu-item a{
    font-family: "whatever" !important;
}

The !important will override all other styles.

You should also try refactoring your code to make it less cluttered that way you won't have to use hacks like that.


问:
issue working with HARDWARE acceleration / gstreamer on odroid XU4
i try to have a v4l source from my c920 logitech camera with gstreamer . I have an odroid XU4 with ubuntu 14.04 version 4.9 . I 'm trying to use the hardware acceleration to avoid using a lot of CPU .
I installed gstreamer from source since version > 1.2 is not available directly for ubuntu 14.04
I did it like this :

```<code>
git clone -b 1.10 https://github.com/GStreamer/gstreamer.git
cd gstreamer
./autogen.sh
make -j
sudo make install
sudo ldconfig
</code>```

I followed this tutorial :
https://forum.odroid.com/viewtopic.php?f=146&t=24366

I did the build from source for each dependencies needed by the tutorial in this order:
- gst-plugins-base
- gst-libav
- gst-plugins-bad

after that I get gst-plugins-good from https://github.com/mihailescu2m/gst-plugins-good and compile/install it
But I try to make I get this error :

```<code>gstv4l2videodec.c:48:3: error: conflicting types for 'GstV4l2VideoCData'
 } GstV4l2VideoCData;</code>```

I don't understand where that come from and did not find any solution on the web. I don't want to break anything so I don't want to install wrong versions of libraries . Any idea of the source of the bug ?

Thanks for your help , i'm quite a noobie with odroid so sorry if the answer is obvious.

答:
I fixed the error by applying this patch to the files concerned :  https://github.com/fnoop/gst-plugins-good/commit/3825320c95740d57501638563cdf2546dc016846
but now I get an error when I 'm trying to run

```<code>dpkg-buildpackage -us -uc -b -j4
</code>```

I get :

```<code>
dpkg-checkbuilddeps: Unmet build dependencies: libgstreamer1.0-dev (>= 1.8.0) libgstreamer-plugins-base1.0-dev (>= 1.8.1) gstreamer1.0-plugins-base (>= 1.8.0) libsoup2.4-dev (>= 2.48) gstreamer1.0-doc gstreamer1.0-plugins-base-doc
</code>```

I don't know how to install the correct versions of libgstreamer-plugins-base1.0-dev and libgstreamer1.0-dev for Ubuntu 14.04.

Does anyone know how to get to this ?

Body:
i try to have a v4l source from my c920 logitech camera with gstreamer . I have an odroid XU4 with ubuntu 14.04 version 4.9 . I 'm trying to use the hardware acceleration to avoid using a lot of CPU .
I installed gstreamer from source since version > 1.2 is not available directly for ubuntu 14.04
I did it like this :

git clone -b 1.10 https://github.com/GStreamer/gstreamer.git
cd gstreamer
./autogen.sh
make -j
sudo make install
sudo ldconfig

I followed this tutorial :
https://forum.odroid.com/viewtopic.php?f=146&t=24366

I did the build from source for each dependencies needed by the tutorial in this order:
- gst-plugins-base
- gst-libav
- gst-plugins-bad

after that I get gst-plugins-good from https://github.com/mihailescu2m/gst-plugins-good and compile/install it
But I try to make I get this error :

gstv4l2videodec.c:48:3: error: conflicting types for 'GstV4l2VideoCData'
 } GstV4l2VideoCData;

I don't understand where that come from and did not find any solution on the web. I don't want to break anything so I don't want to install wrong versions of libraries . Any idea of the source of the bug ?

Thanks for your help , i'm quite a noobie with odroid so sorry if the answer is obvious.

Body:
I fixed the error by applying this patch to the files concerned :  https://github.com/fnoop/gst-plugins-good/commit/3825320c95740d57501638563cdf2546dc016846
but now I get an error when I 'm trying to run

dpkg-buildpackage -us -uc -b -j4

I get :

dpkg-checkbuilddeps: Unmet build dependencies: libgstreamer1.0-dev (>= 1.8.0) libgstreamer-plugins-base1.0-dev (>= 1.8.1) gstreamer1.0-plugins-base (>= 1.8.0) libsoup2.4-dev (>= 2.48) gstreamer1.0-doc gstreamer1.0-plugins-base-doc

I don't know how to install the correct versions of libgstreamer-plugins-base1.0-dev and libgstreamer1.0-dev for Ubuntu 14.04.

Does anyone know how to get to this ?


问:
What are the pros and cons of raising an error class vs. an instance of the class
The following appears to have the same effect:

```<code>>>> raise NotImplementedError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError

>>> raise NotImplementedError()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError
</code>```

Is there a difference, and if so, what are the pros and cons of each?

答:
There is no difference:

```<code>>>> try:
...     raise NotImplementedError
... except Exception as e:
...     pass
...
>>> e
NotImplementedError()
>>> type(e)
<type 'exceptions.NotImplementedError'>
>>> type(NotImplementedError)
<type 'type'>
>>> type(NotImplementedError())
<type 'exceptions.NotImplementedError'>
>>>
</code>```

See section 8.4 of the docs: https://docs.python.org/3/tutorial/errors.html#raising-exceptions

Body:
The following appears to have the same effect:

>>> raise NotImplementedError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError

>>> raise NotImplementedError()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError

Is there a difference, and if so, what are the pros and cons of each?

Body:
There is no difference:

>>> try:
...     raise NotImplementedError
... except Exception as e:
...     pass
...
>>> e
NotImplementedError()
>>> type(e)
<type 'exceptions.NotImplementedError'>
>>> type(NotImplementedError)
<type 'type'>
>>> type(NotImplementedError())
<type 'exceptions.NotImplementedError'>
>>>

See section 8.4 of the docs: https://docs.python.org/3/tutorial/errors.html#raising-exceptions


问:
C# 6.0 null-coalescing not working correctly for me
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?</p>

```<code>  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";
</code>```

答:
You are checking for null on the result that is being returned after calling the ToString() method on the Value property of stop.pallets_qty_total while there is chance that stop.pallets_qty_total is null and it is also possible that the stop itself is null which will also cause your code to go in failure.

You need try something like following using Null-Propogation operator:

```<code>string qty = (stop?.pallets_qty_total?.ToString()) ?? "0";
</code>```

Body:
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?

  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";

Body:
You are checking for null on the result that is being returned after calling the ToString() method on the Value property of stop.pallets_qty_total while there is chance that stop.pallets_qty_total is null and it is also possible that the stop itself is null which will also cause your code to go in failure.

You need try something like following using Null-Propogation operator:

string qty = (stop?.pallets_qty_total?.ToString()) ?? "0";


问:
How to transform a SQL record set in BLOB?
I am using an ORACLE database and I need to get the BLOB (or another LOB format) of a huge recordset (few thousands of rows), which I retrieve from a query.
I need to populate the output format as a LOB to then provide it, as input to the DBMS_CRYPTO.Hash function, which generate the hash key I need.

Is it possible to populate the LOB directly with the data of the query parsed to a JSON type? Or do you advise me to use other format to populate the (B)LOB format in an efficient way?

Thanks

答:
The immediate answer is you can serialize to your huge recordset to XML

```<code>SELECT DBMS_XMLGEN.getxmltype ('select * from EMPLOYEE') FROM DUAL
</code>```

Output:

SELECT DBMS_XMLGEN.getxmltype ('select * from EMPLOYEE') FROM DUAL

Output:

```<code><ROWSET>
  <ROW>
    <EMP_ID>1</EMP_ID>
    <EMP_NAME>Employee 1</EMP_NAME>
    <EMP_DEPT_ID>1</EMP_DEPT_ID>
    <EMP_LOC>1</EMP_LOC>
    <EMP_SAL>2000</EMP_SAL>
  </ROW>
  <ROW>
    <EMP_ID>2</EMP_ID>
    <EMP_NAME>Employee 2</EMP_NAME>
    <EMP_DEPT_ID>2</EMP_DEPT_ID>
    <EMP_LOC>2</EMP_LOC>
    <EMP_SAL>1000</EMP_SAL>
  </ROW>
</ROWSET>
</code>```

After that you can use to_clob or_to_blob function

```<code>SELECT TO_CLOB (DBMS_XMLGEN.getxmltype ('select * from EMPLOYEE'))  FROM DUAL
</code>```

output :(HUGECLOB)

Body:
The immediate answer is you can serialize to your huge recordset to XML

SELECT DBMS_XMLGEN.getxmltype ('select * from EMPLOYEE') FROM DUAL

Output:

SELECT DBMS_XMLGEN.getxmltype ('select * from EMPLOYEE') FROM DUAL

Output:

<ROWSET>
  <ROW>
    <EMP_ID>1</EMP_ID>
    <EMP_NAME>Employee 1</EMP_NAME>
    <EMP_DEPT_ID>1</EMP_DEPT_ID>
    <EMP_LOC>1</EMP_LOC>
    <EMP_SAL>2000</EMP_SAL>
  </ROW>
  <ROW>
    <EMP_ID>2</EMP_ID>
    <EMP_NAME>Employee 2</EMP_NAME>
    <EMP_DEPT_ID>2</EMP_DEPT_ID>
    <EMP_LOC>2</EMP_LOC>
    <EMP_SAL>1000</EMP_SAL>
  </ROW>
</ROWSET>

After that you can use to_clob or_to_blob function

SELECT TO_CLOB (DBMS_XMLGEN.getxmltype ('select * from EMPLOYEE'))  FROM DUAL

output :(HUGECLOB)


问:
Ionic platform.ready() method is needed
I have a basic question about platform.ready().then(() => {}) method.Do we need to use this method each and every time when we use a native plugin? Like Status bar or LocalStorage or etc?

Is that not enough if we use above method only inside the app.component.ts file hence it is the root component? After this root component hope platform is ready for all the other subsequent components no? Then why do we need to use ready method each and every other child components too? Because I have seen so many articles and videos where it uses if there is any native plugin.Hope this is not needed no?

On this official doc where you can see that it uses inside the child component too no? Your thoughts? platform.ready().then(() => {})

答:
platform.ready() is a promise that resolves once your device/native plugins are ready.

Let's look at the ionic sidemenu starter template https://github.com/ionic-team/ionic2-starter-sidemenu/blob/master/src/app/app.component.ts.

As you can see in the app.component.ts on line 15 the rootPage gets set and will get loaded as soon as possible. In the constructor this.initializeApp(); calls

```<code>this.platform.ready().then(() => {
  // Okay, so the platform is ready and our plugins are available.
  // Here you can do any higher level native things you might need.
  this.statusBar.styleDefault();
  this.splashScreen.hide();
});
</code>```

As with every promise in javascript, you can't tell when it resolves. And as you can see in the code, the ionic-app does not "wait" for the platform to be ready. Only the statusBar.styleDefault() and splashScreen.hide() calls wait for that promise.

Let's say it takes a very long time for the promise to be resolved, for example 5 seconds.

If you have any ionic-native code in your HomePage, any providers that you use inside app.component.ts or any other page (because the user could already navigate around the app during that time), the ionic-native call will fail because the platform is not ready yet.

As an example:

```<code> constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private: qrScanner: QrScanner) {
      this.initializeApp();

      this.qrScanner.scan(); // Let's assume this is a provider we made to start a QR scanner. It will try to load the scanner immediately, regardless of the state of the platform.ready() promise. So if the platform is not ready, it will crash.

      // used for an example of ngFor and navigation
      this.pages = [
        { title: 'Home', component: HomePage },
        { title: 'List', component: ListPage }
      ];

  }
</code>```

This means that in theory, you should always use this.platform.ready() when using native plugins to make sure the platform is available. In practice it really depends on the specific case because often the platform is ready very fast and you won't notice any difference if you don't use it. But if you want to be sure, you should use it everywhere.

Title: Ionic platform.ready() method is needed

Body:
platform.ready() is a promise that resolves once your device/native plugins are ready.

Let's look at the ionic sidemenu starter template https://github.com/ionic-team/ionic2-starter-sidemenu/blob/master/src/app/app.component.ts.

As you can see in the app.component.ts on line 15 the rootPage gets set and will get loaded as soon as possible. In the constructor this.initializeApp(); calls

this.platform.ready().then(() => {
  // Okay, so the platform is ready and our plugins are available.
  // Here you can do any higher level native things you might need.
  this.statusBar.styleDefault();
  this.splashScreen.hide();
});

As with every promise in javascript, you can't tell when it resolves. And as you can see in the code, the ionic-app does not "wait" for the platform to be ready. Only the statusBar.styleDefault() and splashScreen.hide() calls wait for that promise.

Let's say it takes a very long time for the promise to be resolved, for example 5 seconds.

If you have any ionic-native code in your HomePage, any providers that you use inside app.component.ts or any other page (because the user could already navigate around the app during that time), the ionic-native call will fail because the platform is not ready yet.

As an example:

 constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private: qrScanner: QrScanner) {
      this.initializeApp();

      this.qrScanner.scan(); // Let's assume this is a provider we made to start a QR scanner. It will try to load the scanner immediately, regardless of the state of the platform.ready() promise. So if the platform is not ready, it will crash.

      // used for an example of ngFor and navigation
      this.pages = [
        { title: 'Home', component: HomePage },
        { title: 'List', component: ListPage }
      ];

  }

This means that in theory, you should always use this.platform.ready() when using native plugins to make sure the platform is available. In practice it really depends on the specific case because often the platform is ready very fast and you won't notice any difference if you don't use it. But if you want to be sure, you should use it everywhere.

ContentLicense: CC BY-SA 4.0


问:
Can't set breakpoint in eclipse
I'm using eclipse (and also the groovy-eclipse plugin), and sometimes I can't set breakpoints on lines.  I'll double click the gutter, and the breakpoint will flash on then off, and it will set the breakpoint somewhere else, lower in the code.

I'll be able to set breakpoints fine for certain parts of the code, but some sections of the code will exhibit the above described behavior.

When this happens I have to restart eclipse, or cut the code i want to set the breakpoint on, and paste it lower in the file.

Anyone else experience this, or have an idea what causes it?

答:
Well, there are few types of breakpoints available in Eclipse:

Line Breakpoint -> Lines those will be executing. You will always get a breakpoint.

Method Breakpoint -> for methods

WatchPoint -> for member declarations.

BreakPoint -> for class level breakpoint

When u double click for breakpoint at a line containing bracket "{" or "}", the LineBreakPoint is set to the next executable line automatically.

Title: Can't set breakpoint in eclipse


答:
There is essentially no difference if the exception class requires no arguments for initialization:

If an exception class is passed, it will be implicitly instantiated by
  calling its constructor with no arguments.

[Emphasis mine]

Otherwise, you'll get another exception complaining about the initialization of the instance:

```<code>class MyException(Exception):
   def __init__(self, arg):
      pass

raise MyException
</code>```

```<code>Traceback (most recent call last):
  File "python", line 6, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)
</code>```

Apparently, you can do more by passing custom arguments to custom exception classes, or passing a custom message to a builtin exception class:

```<code>>>> raise ValueError('number must be 42')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: number must be 42
</code>```

The above is much more informative (quite desirable from a users' perspective) than a barren ValueError.

Title: What are the pros and cons of raising an error class vs. an instance of the class

Body:
There is essentially no difference if the exception class requires no arguments for initialization:

If an exception class is passed, it will be implicitly instantiated by
  calling its constructor with no arguments.

[Emphasis mine]

Otherwise, you'll get another exception complaining about the initialization of the instance:

class MyException(Exception):
   def __init__(self, arg):
      pass

raise MyException

Traceback (most recent call last):
  File "python", line 6, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)

Apparently, you can do more by passing custom arguments to custom exception classes, or passing a custom message to a builtin exception class:

>>> raise ValueError('number must be 42')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: number must be 42

The above is much more informative (quite desirable from a users' perspective) than a barren ValueError.


问:
Convert from ListView Adapter to RecyclerView Adapter for Fragments
My project is based on Fragments and I am trying to implement HypeLabs Mesh Network Chat as extra functionality. How do I convert the Activities in the Hype Labs Github Project shown in the attached URL into Fragments such as ChatFragment and ContactsFragment.

The original ContactsViewAdapter is as follows:

```<code>public class DirectContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected final Activity mActivity;
private Map<String, Store> stores;

public DirectContactsAdapter(@NonNull Activity mActivity, Map<String, Store> stores) {
    this.mActivity = mActivity;
    this.stores = stores;
}

protected Map<String, Store> getStores() {
    return stores;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView;
    itemView = LayoutInflater.from(mActivity).inflate(R.layout.row_direct_contacts, parent, false);
    return new DirectContactsViewHolder(itemView);

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    if(holder instanceof DirectContactsViewHolder) {
        final DirectContactsViewHolder directContactsHolder = (DirectContactsViewHolder) holder;
        final Store contactsStore = this.stores.get(position);
        try {
            directContactsHolder.displayName.setText(contactsStore.getInstance().getRealmStringIdentifier());
            directContactsHolder.contentIndicator.setVisibility(contactsStore.hasNewMessages
                    () ? View.VISIBLE : View.INVISIBLE);

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                            Intent intent = new Intent(DirectContactsFragment.this, DirectChatsFragment
                                    .class);

                            TextView displayName = (TextView) view.findViewById(R.id.display_name);
                            CharSequence charSequence = displayName.getText();

                            setDisplayName(charSequence.toString());

                            Store store = chatApplication.getStores().get(getDisplayName());
                            store.setDelegate(contactActivity);

                            intent.putExtra(ChatActivity.INTENT_EXTRA_STORE, store.getInstance().getStringIdentifier());

                            startActivity(intent);
                        }
            });
        } catch (Exception e) {
            AppHelper.LogCat("Contacts adapters Exception " + e.getMessage());
        }
    }

}

@Override
public int getItemCount() {
    return stores.size();
}

public Store getItem(int position) {
    return stores.get(position);
}

public class DirectContactsViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.avatar)
    ImageView userImage;
    @BindView(R.id.display_name)
    TextView displayName;
    @BindView(R.id.new_content)
    ImageView contentIndicator;

    DirectContactsViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

}}
</code>```

I am quite new to Fragments and the examples Android Studio generates confuse me further.

Any help is highly appreciated.

答:
@Victor do u want to pass some data from ur adapter to the Fragment instead of Activity? if so, u should use Callback pattern. For doing that u can create an enclosing interface class as follows:

```<code>    public class DirectContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private IItemClickListener mListener;
    public void setListener(IItemClickListener listener) {mListener=listener;}

    ...
    public DirectContactsAdapter(@NonNull Activity mActivity, Map<String, Store> stores) { // this is the bad practice to pass Activity object, better pass Context
        this.mActivity = mActivity;
        this.stores = stores;
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if(holder instanceof DirectContactsViewHolder) {
            final DirectContactsViewHolder directContactsHolder = (DirectContactsViewHolder) holder;
            final Store contactsStore = stores.get(position);
            try {
                directContactsHolder.displayName.setText(contactsStore.getInstance().getRealmStringIdentifier());
                directContactsHolder.contentIndicator.setVisibility(contactsStore.hasNewMessages
                        () ? View.VISIBLE : View.INVISIBLE);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                                TextView displayName = (TextView) view.findViewById(R.id.display_name); // this is redundant cause u use butterknife and ur ViewHolder already have reference to its TextView
                                CharSequence charSequence = displayName.getText(); // u should use DirectContactsViewHolder.displayName.getText() instead

                                setDisplayName(charSequence.toString());

                                Store store = chatApplication.getStores().get(getDisplayName());
                                store.setDelegate(contactActivity);

                                if(mListener != null)
                                   mListener.onItemClicked(store.getInstance().getStringIdentifier());
                            }
                });
            } catch (Exception e) {
                AppHelper.LogCat("Contacts adapters Exception " + e.getMessage());
            }
        }

    }

    public interface IItemClickListener {
        void onItemClicked(String identifier);
    }
</code>```

after doing that u should implement this interface in Fragment:

```<code>class YourFragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    DirectContactsAdapter adapter = new DirectContactsAdapter(...);
    adapter.setListener(new DirectContactsAdapter.IItemClickListener() {
        @Override
        void onItemClicked(String identifier) {
            //do what u want with identifier
    });
}
</code>```

Body:
My project is based on Fragments and I am trying to implement HypeLabs Mesh Network Chat as extra functionality. How do I convert the Activities in the Hype Labs Github Project shown in the attached URL into Fragments such as ChatFragment and ContactsFragment.

The original ContactsViewAdapter is as follows:

public class DirectContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected final Activity mActivity;
private Map<String, Store> stores;

public DirectContactsAdapter(@NonNull Activity mActivity, Map<String, Store> stores) {
    this.mActivity = mActivity;
    this.stores = stores;
}

protected Map<String, Store> getStores() {
    return stores;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView;
    itemView = LayoutInflater.from(mActivity).inflate(R.layout.row_direct_contacts, parent, false);
    return new DirectContactsViewHolder(itemView);

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    if(holder instanceof DirectContactsViewHolder) {
        final DirectContactsViewHolder directContactsHolder = (DirectContactsViewHolder) holder;
        final Store contactsStore = this.stores.get(position);
        try {
            directContactsHolder.displayName.setText(contactsStore.getInstance().getRealmStringIdentifier());
            directContactsHolder.contentIndicator.setVisibility(contactsStore.hasNewMessages
                    () ? View.VISIBLE : View.INVISIBLE);

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                            Intent intent = new Intent(DirectContactsFragment.this, DirectChatsFragment
                                    .class);

                            TextView displayName = (TextView) view.findViewById(R.id.display_name);
                            CharSequence charSequence = displayName.getText();

                            setDisplayName(charSequence.toString());

                            Store store = chatApplication.getStores().get(getDisplayName());
                            store.setDelegate(contactActivity);

                            intent.putExtra(ChatActivity.INTENT_EXTRA_STORE, store.getInstance().getStringIdentifier());

                            startActivity(intent);
                        }
            });
        } catch (Exception e) {
            AppHelper.LogCat("Contacts adapters Exception " + e.getMessage());
        }
    }

}

@Override
public int getItemCount() {
    return stores.size();
}

public Store getItem(int position) {
    return stores.get(position);
}

public class DirectContactsViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.avatar)
    ImageView userImage;
    @BindView(R.id.display_name)
    TextView displayName;
    @BindView(R.id.new_content)
    ImageView contentIndicator;

    DirectContactsViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

}}

I am quite new to Fragments and the examples Android Studio generates confuse me further.

Any help is highly appreciated.

Body:
@Victor do u want to pass some data from ur adapter to the Fragment instead of Activity? if so, u should use Callback pattern. For doing that u can create an enclosing interface class as follows:

    public class DirectContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private IItemClickListener mListener;
    public void setListener(IItemClickListener listener) {mListener=listener;}

    ...
    public DirectContactsAdapter(@NonNull Activity mActivity, Map<String, Store> stores) { // this is the bad practice to pass Activity object, better pass Context
        this.mActivity = mActivity;
        this.stores = stores;
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if(holder instanceof DirectContactsViewHolder) {
            final DirectContactsViewHolder directContactsHolder = (DirectContactsViewHolder) holder;
            final Store contactsStore = stores.get(position);
            try {
                directContactsHolder.displayName.setText(contactsStore.getInstance().getRealmStringIdentifier());
                directContactsHolder.contentIndicator.setVisibility(contactsStore.hasNewMessages
                        () ? View.VISIBLE : View.INVISIBLE);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                                TextView displayName = (TextView) view.findViewById(R.id.display_name); // this is redundant cause u use butterknife and ur ViewHolder already have reference to its TextView
                                CharSequence charSequence = displayName.getText(); // u should use DirectContactsViewHolder.displayName.getText() instead

                                setDisplayName(charSequence.toString());

                                Store store = chatApplication.getStores().get(getDisplayName());
                                store.setDelegate(contactActivity);

                                if(mListener != null)
                                   mListener.onItemClicked(store.getInstance().getStringIdentifier());
                            }
                });
            } catch (Exception e) {
                AppHelper.LogCat("Contacts adapters Exception " + e.getMessage());
            }
        }

    }

    public interface IItemClickListener {
        void onItemClicked(String identifier);
    }

after doing that u should implement this interface in Fragment:

class YourFragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    DirectContactsAdapter adapter = new DirectContactsAdapter(...);
    adapter.setListener(new DirectContactsAdapter.IItemClickListener() {
        @Override
        void onItemClicked(String identifier) {
            //do what u want with identifier
    });
}


问:
Regex to extract specific field with other constraints
I have to create a Regex which extract specific field from large log file. I have created one but its not perfect as different type of occurane present in logs.

I have attached screenshot. There are 2 different type of log entry and I want to extract real="value".

The problem is, multiple "real=value" present in extracted line and I want to get only first occurance. +

My Regex:

```<code>CMS-concurrent-abortable-preclean:\s.*real=(?P<cms_abortable_preclean>\d+\.\d+)\s
</code>```

Screen Shot: Sample data and Regex command

Sample Data:

2017-05-16T13:21:47.420+0200: 5.114: [GC (Allocation Failure)
  2017-05-16T13:21:47.420+0200: 5.114:
  [ParNew2017-05-16T13:21:47.461+0200: 5.155:
  [CMS-concurrent-abortable-preclean: 0.120/0.735 secs] [Times:
  user=1.17 sys=0.12, real=0.73 secs] : 886080K->110720K(996800K),
  0.3158400 secs] 886080K->161751K(6180736K), 0.3168208 secs] [Times: user=0.33 sys=0.10, real=0.32 secs]

1.583: [CMS-concurrent-abortable-preclean: 0.052/0.171 secs] [Times: user=0.20 sys=0.01, real=0.17 secs]  CMS: abort preclean due to time
  8077.162: [CMS-concurrent-abortable-preclean: 4.850/5.566 secs] [Times: user=5.92 sys=0.02, real=5.57 secs]

I want to extract fields in bold.

答:
One approach:

```<code>(CMS-concurrent-abortable-preclean:).*?(?=.*:)(?<=real=)(\d+\.\d+)
</code>```

Demo

The first group match: CMS-concurrent-abortable-preclean:

And the second is: (\d+\.\d+)

Fast test:

```<code>perl -lne 'print "$1 and $2" while/(CMS-concurrent-abortable-preclean:).*?(?=.*:)(?<=real=)(\d+\.\d+)/g;' file
</code>```

the output:

```<code>CMS-concurrent-abortable-preclean: and 0.73
CMS-concurrent-abortable-preclean: and 0.17
</code>```

Body:
I have to create a Regex which extract specific field from large log file. I have created one but its not perfect as different type of occurane present in logs.

I have attached screenshot. There are 2 different type of log entry and I want to extract real="value".

The problem is, multiple "real=value" present in extracted line and I want to get only first occurance. +

My Regex:

CMS-concurrent-abortable-preclean:\s.*real=(?P<cms_abortable_preclean>\d+\.\d+)\s

Screen Shot: Sample data and Regex command

Sample Data:

2017-05-16T13:21:47.420+0200: 5.114: [GC (Allocation Failure)
  2017-05-16T13:21:47.420+0200: 5.114:
  [ParNew2017-05-16T13:21:47.461+0200: 5.155:
  [CMS-concurrent-abortable-preclean: 0.120/0.735 secs] [Times:
  user=1.17 sys=0.12, real=0.73 secs] : 886080K->110720K(996800K),
  0.3158400 secs] 886080K->161751K(6180736K), 0.3168208 secs] [Times: user=0.33 sys=0.10, real=0.32 secs]

1.583: [CMS-concurrent-abortable-preclean: 0.052/0.171 secs] [Times: user=0.20 sys=0.01, real=0.17 secs]  CMS: abort preclean due to time
  8077.162: [CMS-concurrent-abortable-preclean: 4.850/5.566 secs] [Times: user=5.92 sys=0.02, real=5.57 secs]

I want to extract fields in bold.

Body:
One approach:

(CMS-concurrent-abortable-preclean:).*?(?=.*:)(?<=real=)(\d+\.\d+)

Demo

The first group match: CMS-concurrent-abortable-preclean:

And the second is: (\d+\.\d+)

Fast test:

perl -lne 'print "$1 and $2" while/(CMS-concurrent-abortable-preclean:).*?(?=.*:)(?<=real=)(\d+\.\d+)/g;' file

the output:

CMS-concurrent-abortable-preclean: and 0.73
CMS-concurrent-abortable-preclean: and 0.17


问:
How to easily consume a web service from PHP
Is there available any tool for PHP which can be used to generate code for consuming a web service based on its WSDL? Something comparable to clicking "Add Web Reference" in Visual Studio or the Eclipse plugin which does the same thing for Java.</p>

答:
Well, those features are specific to a tool that you are using for development in those languages.

You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.

For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

LastEditorDisplayName: Chris Fournier


问:
What essential design artifacts do you produce?
In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice?

The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI-based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices?

答:
Working code...and whiteboard drawings.

:P

OwnerDisplayName: JasonBunting


问:
Nested hyperlinked areas without nested link elements in HTML source
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

```
|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|
```

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

```<code><a href="xxx" style="display: block">
  Some text
  <a href="yyy">link</a>
</a>
</code>```

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

```<code><a href="xxx" ...>Some text</a>
<a href="yyy" ...>Link</a>
<a href="xxx" ...>& nbsp;</a>
...
</code>```

答:
Perhaps this would work?</p>

```<code>div.parentBox {
  position:relative;
  height:100px;
}
  a.someLink {
    position:absolute;
    top:0;
    left:0;
    height:100px;
  }

// Now just position the two spans

<div class="parentBox">
  <span class="someText">Some Text</span>
  <a href="#" class="someLink">
    <span class="linkText">Link Text</span>
  </a>
</div>
</code>```

OwnerDisplayName: Jakub Narębski

Body:
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

  Some text
  link

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

Some text
Link
& nbsp;
...

LastEditorDisplayName: Jakub Narębski

Body:
Perhaps this would work?

div.parentBox {
  position:relative;
  height:100px;
}
  a.someLink {
    position:absolute;
    top:0;
    left:0;
    height:100px;
  }

// Now just position the two spans

<div class="parentBox">
  <span class="someText">Some Text</span>
  <a href="#" class="someLink">
    <span class="linkText">Link Text</span>
  </a>
</div>

OwnerDisplayName: Jonathan Sampson

LastEditorDisplayName: Jonathan Sampson


答:
You shouldn't instantiate any structures in header files. If you do a different instance will be created in each C file you include the header in which is usually not the desired effect.

In a C file to do this you would have to do the following.

```<code>void foo(){
struct A parent;
struct B child_b;
struct C child_c;

child_b.temp3 = 3;
child_b.temp4 = 4;
child_b.temp5 = 5;

child_c.temp6 = 6;
child_c.temp7 = 7;
child_c.temp8 = 8;

parent.temp1 = child_b;
parent.temp2 = child_c;
}
</code>```

I would strong consider making helper functions similar to this

```<code>void initB(struct B* s, int x, int y, int z){
    s->temp3 = x;
    s->temp4 = y;
    s->temp5 = z;
}
</code>```

If you would like the keep the array initialization syntax then consider using a union.

Title: How to initialize a a struct of structs inside a header file in C?

Body:
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system.  In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize.  I am getting warnings when I compile with the way the legacy code was written.  Any tips on how I can get this to work with staying inside the same header file?

The following is a simplified example I made of what they are doing.

struct A
{

    struct B  temp1;
    struct C  temp2;
};

struct B
{

    int temp3;
    int temp4;
    int temp5;
};

struct C
{

    int temp6;
    int temp7;
    int temp8;
};

//These are the variables in how they are related to the initialization below

//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};

struct A test_one = {{1,2,3},{4,5,6}};

Body:
You shouldn't instantiate any structures in header files. If you do a different instance will be created in each C file you include the header in which is usually not the desired effect.

In a C file to do this you would have to do the following.

void foo(){
struct A parent;
struct B child_b;
struct C child_c;

child_b.temp3 = 3;
child_b.temp4 = 4;
child_b.temp5 = 5;

child_c.temp6 = 6;
child_c.temp7 = 7;
child_c.temp8 = 8;

parent.temp1 = child_b;
parent.temp2 = child_c;
}

I would strong consider making helper functions similar to this

void initB(struct B* s, int x, int y, int z){
    s->temp3 = x;
    s->temp4 = y;
    s->temp5 = z;
}

If you would like the keep the array initialization syntax then consider using a union.


问:
IIS WCF Service authentication, javascript client
What is the best (or at least one that works) option to secure a IIS hosted REST WCF service that will be called by javascript clients?

The service that I have is a REST service that receives GETs and POSTs from the clients and it's working fine, through http and https.

I've been trying to implement authentication, and I have a database with my own structure for users and roles and the such (so I want to avoid Windows authentication)
I've been trying different things but I can't get anything to work.

Last thing I've tried is Basic Authentication (Transport) with a ServiceAuthorizationManager and UserName Auth (Message) with a custom validator.

I don't know if I can use the custom validator (inheriting from System.IdentityModel.Selectors.UserNamePasswordValidator) with Basic authentication, or if I can add UserName authentication credentials in the http(s) REST requests (maybe it needs to be a SOAP service?).

Also I would like to use something like a custom RoleProvider to control method access based on user groups /roles .

Thanks.

答:
There are few ways to do this:

**1. Using Client Certificate Authentication.

See these articles:**

Securing WCF Services with Certificates.

Use Certificate Authentication and Message Security in WCF

You can authorise your clients based on the certificate they pass (using thumbprint) and you can categorise them easily.

2. Implement Basic authentication with SQL Membership Provider.

Refer these articles:

WCF Basic Authentication with SQL Membership Provider

Use Username Authentication with the SQL Server Membership Provider

You will have to take a call on what best serves your purpose and what will be easier to maintain in future. Certificate management is a pain most of the times, however it has its own set of advantages. I personally would go with the second option which is using Basic Auth with SQL membership provider.


问:
DXL DOORs Need help applying a filter using a loop
So i just realized that the current filter i have been using only seems to work properly if the first string it finds is incorrect.

```<code>Module m = current
Object o = current
Filter f

load view "Standard view"

//column attribute Object Type
insert(column 3)
attribute(column 3, "Object Type")
width(column 3, 100)

f1 = attribute "Object Type" == "Requirement"
f2 = attribute "Object Type" == "Derived Requirement"
f3 = contains(attribute "Object Text", "(Testing) ", true)

for o in m do
{
f = (f1 || f2) && !(f3)
}
set f
filtering on
refresh current
</code>```

Example: this would be my current table (Not great at making a table)

```<code>ID|        Module Information            |Object Type
__|______________________________________|____________________
1 | (Teting) this is the incorrect format| Requirements
__|______________________________________|____________________
2 | (Testing) this is also correct format| Derived Requirements
  | (Test) this is incorrect format      |
__|______________________________________|____________________
3 | (Testing) this is the correct format | Requirements
  | (Testing) this is the correct format |
__|______________________________________|____________________
4 | (Testing) this is the correct format | Requirements
  | (Teting) this is incorrect format    |
__|______________________________________|____________________
</code>```

So if i were to run my script here it would only show me

```<code>ID|        Module Information            |Object Type
__|______________________________________|____________________
1 | (Teting) this is the incorrect format| Requirements
</code>```

and not what i was hoping it would show me:

```<code>ID|        Module Information            |Object Type
__|______________________________________|____________________
1 | (Teting) this is the incorrect format| Requirements
__|______________________________________|____________________
2 | (Testing) this is also correct format| Derived Requirements
  | (Test) this is incorrect format      |
__|______________________________________|____________________
4 | (Testing) this is the correct format | Requirements
  | (Teting) this is incorrect format    |
__|______________________________________|____________________
</code>```

So how would i go about showing the correct view? I assume it's something to do with looping

"Object Text contains" filter but i am unsure how i could go about doing that.

答:
From what I can tell, your DXL is working perfectly. However, you may want to alter your question slightly.

Firstly, your DXL is checking whether Object Type is "Requirement" or "Derived Requirement", whereas your test data has "Requirements" and "Derived Requirements".

Secondly your code f = (f1 || f2) && !(f3) is checking that the object type is either Requirement or Derived Requirement and also does not contain "(Testing)" anywhere within the object text. Your code does this, and thus will not give you the result you expect, as the last three objects contain the text "(Testing)".

I assume that what you are after is to check that not all of the lines contain "(Testing)", as opposed to none. In which case the code would be something like:

```<code>Module m = current
Object o = current
Regexp REGEX_INVALID = regexp2("\\(Testing\\)")
Regexp REGEX_VALID = regexp2("\\(.*\\)")
Buffer searchText = create
Buffer original = create

//Returns true if Object Text contains any one or more pairs of brackets that do not match (Testing)
bool filterObjectText(string objText)
{
    searchText = objText
    original = objText

    while(REGEX_VALID searchText)
    {
        if (REGEX_INVALID searchText)
        {
            int offset = null
            int subStrLength = null
            findPlainText(tempStringOf(searchText), "(Testing)", offset, subStrLength, true)
            searchText = searchText[offset + subStrLength:]
        }
        else
        {
            return true
        }
    }

    return false
}

filtering off

for o in m do
{
    string objectType = o."Object Type"
    string objectText = o."Object Text"

    if ((objectType == "Requirements" || objectType == "Derived Requirements") && filterObjectText(objectText))
    {
        accept o
    }
    else
    {
        reject o
    }
}

filtering on
refresh current
</code>```

Body:
So i just realized that the current filter i have been using only seems to work properly if the first string it finds is incorrect.

Module m = current
Object o = current
Filter f

load view "Standard view"

//column attribute Object Type
insert(column 3)
attribute(column 3, "Object Type")
width(column 3, 100)

f1 = attribute "Object Type" == "Requirement"
f2 = attribute "Object Type" == "Derived Requirement"
f3 = contains(attribute "Object Text", "(Testing) ", true)

for o in m do
{
f = (f1 || f2) && !(f3)
}
set f
filtering on
refresh current

Example: this would be my current table (Not great at making a table)

ID|        Module Information            |Object Type
__|______________________________________|____________________
1 | (Teting) this is the incorrect format| Requirements
__|______________________________________|____________________
2 | (Testing) this is also correct format| Derived Requirements
  | (Test) this is incorrect format      |
__|______________________________________|____________________
3 | (Testing) this is the correct format | Requirements
  | (Testing) this is the correct format |
__|______________________________________|____________________
4 | (Testing) this is the correct format | Requirements
  | (Teting) this is incorrect format    |
__|______________________________________|____________________

So if i were to run my script here it would only show me

ID|        Module Information            |Object Type
__|______________________________________|____________________
1 | (Teting) this is the incorrect format| Requirements

and not what i was hoping it would show me:

ID|        Module Information            |Object Type
__|______________________________________|____________________
1 | (Teting) this is the incorrect format| Requirements
__|______________________________________|____________________
2 | (Testing) this is also correct format| Derived Requirements
  | (Test) this is incorrect format      |
__|______________________________________|____________________
4 | (Testing) this is the correct format | Requirements
  | (Teting) this is incorrect format    |
__|______________________________________|____________________

So how would i go about showing the correct view? I assume it's something to do with looping

"Object Text contains" filter but i am unsure how i could go about doing that.

Body:
From what I can tell, your DXL is working perfectly. However, you may want to alter your question slightly.

Firstly, your DXL is checking whether Object Type is "Requirement" or "Derived Requirement", whereas your test data has "Requirements" and "Derived Requirements".

Secondly your code f = (f1 || f2) && !(f3) is checking that the object type is either Requirement or Derived Requirement and also does not contain "(Testing)" anywhere within the object text. Your code does this, and thus will not give you the result you expect, as the last three objects contain the text "(Testing)".

I assume that what you are after is to check that not all of the lines contain "(Testing)", as opposed to none. In which case the code would be something like:

Module m = current
Object o = current
Regexp REGEX_INVALID = regexp2("\\(Testing\\)")
Regexp REGEX_VALID = regexp2("\\(.*\\)")
Buffer searchText = create
Buffer original = create

//Returns true if Object Text contains any one or more pairs of brackets that do not match (Testing)
bool filterObjectText(string objText)
{
    searchText = objText
    original = objText

    while(REGEX_VALID searchText)
    {
        if (REGEX_INVALID searchText)
        {
            int offset = null
            int subStrLength = null
            findPlainText(tempStringOf(searchText), "(Testing)", offset, subStrLength, true)
            searchText = searchText[offset + subStrLength:]
        }
        else
        {
            return true
        }
    }

    return false
}

filtering off

for o in m do
{
    string objectType = o."Object Type"
    string objectText = o."Object Text"

    if ((objectType == "Requirements" || objectType == "Derived Requirements") && filterObjectText(objectText))
    {
        accept o
    }
    else
    {
        reject o
    }
}

filtering on
refresh current


答:
It will only check if the Value is null but if object before is null then it well throw exception.</p>

```<code>string qty = stop?.pallets_qty_total?.Value.ToString() ?? "0";
</code>```

Title: C# 6.0 null-coalescing not working correctly for me

Body:
It will only check if the Value is null but if object before is null then it well throw exception.

string qty = stop?.pallets_qty_total?.Value.ToString() ?? "0";


问:
Getting the combination of facevalues that gives the highest score in a dicegame
Working on a dicegame for school and I have trouble figuring out how to do automatic calculation of the result. (we don't have to do it automatically, so I could just let the player choose which dice to use and then just check that the user choices are valid) but now that I have started to think about it I can't stop...

the problem is as follows:

I have six dice, the dice are normal dice with the value of 1-6.

In this example I have already roled the dice and they have the following values:

```<code>[2, 2, 2, 1, 1, 1]
</code>```

But I don't know how to calulate all combinations so that as many dicecombinations as possible whose value combined(addition) are 3 (in this example) are used.

The values should be added together (for example a die with value 1 and another die with the value 2 are together 3) then there are different rounds in the game where the aim is to get different values (which can be a combination(addition) of die-values for example
dicevalues: [2, 2, 2, 2, 2, 2]
could give the user a total of 12 points if 4 is the goal for the current round)

```<code>2 + 2 = 4
2 + 2 = 4
2 + 2 = 4
</code>```

if the goal of the round instead where 6 then the it would be

```<code>2 + 2 + 2 = 6
2 + 2 + 2 = 6
</code>```

instead which would give the player 12 points (6 + 6)

```<code>[1, 3, 6, 6, 6, 6]
</code>```

with the goal of 3 would only use the dice with value 3 and discard the rest since there is no way to add them up to get three.

```<code>2 + 1 = 3
2 + 1 = 3
2 + 1 = 3
</code>```

would give the user 9 points.
but if it where calculated the wrong way and the ones where used up together instead of each 1 getting apierd with a two 1 + 1 + 1 which would only give the player 3 points och the twos couldn't be used.

Another example is:
    [1, 2, 3, 4, 5, 6]
and all combinations that are equal to 6 gives the user points

```<code>[6], [5, 1], [4 ,2]
</code>```

user gets 18 points (3 * 6)

    [1 ,2 ,3], [6]
user gets 12 points (2 * 6) (Here the user gets six points less due to adding upp 1 + 2 + 3 instead of doing like in the example above)

A dice can have a value between 1 and 6.

I haven't really done much more than think about it and I'm pretty sure that I could do it right now, but it would be a solution that would scale really bad if I for example wanted to use 8 dices instead and every time I start programming on it I start to think that have to be a better/easier way of doing it... Anyone have any suggestion on where to start? I tried searching for an answer and I'm sure it's out there but I have problem forumulating a query that gives me relevant result...

答:
With problems that look confusing like this, it is a really good idea to start with some working and examples. We have 6 die, with range [1 to 6]. The possible combinations we could make therefore are:

```<code>target = 2

1 combination: 2
2 combination: 1+1

target = 3

1 combination: 3
2 combination: 2+1
3 combination: 1+1+1

target = 4

1 combination: 4
2 combination: 3+1
               2+2
3 combination: 2+1+1
4 combination: 1+1+1+1

target = 5

1 combination: 5
2 combination: 4+1
               3+2
3 combination: 2+2+1
4 combination: 2+1+1+1
5 combination: 1+1+1+1+1
</code>```

See the pattern? Hint, we go backwards from target to 1 for the first number we can add, and then given this first number, and the size of the combination, there is a limit to how big subsequent numbers can be!

There is a finite list of possible combinations. You can by looking for 1 combination scores, and remove these from the die available. Then move on to look for 2 combination scores, etc.

If you want to read more about this sub-field of mathematics, the term you need to look for is "Combinatorics". Have fun!

Body:
Working on a dicegame for school and I have trouble figuring out how to do automatic calculation of the result. (we don't have to do it automatically, so I could just let the player choose which dice to use and then just check that the user choices are valid) but now that I have started to think about it I can't stop...

the problem is as follows:

I have six dice, the dice are normal dice with the value of 1-6.

In this example I have already roled the dice and they have the following values:

[2, 2, 2, 1, 1, 1]

But I don't know how to calulate all combinations so that as many dicecombinations as possible whose value combined(addition) are 3 (in this example) are used.

The values should be added together (for example a die with value 1 and another die with the value 2 are together 3) then there are different rounds in the game where the aim is to get different values (which can be a combination(addition) of die-values for example
dicevalues: [2, 2, 2, 2, 2, 2]
could give the user a total of 12 points if 4 is the goal for the current round)

2 + 2 = 4
2 + 2 = 4
2 + 2 = 4

if the goal of the round instead where 6 then the it would be

2 + 2 + 2 = 6
2 + 2 + 2 = 6

instead which would give the player 12 points (6 + 6)

[1, 3, 6, 6, 6, 6]

with the goal of 3 would only use the dice with value 3 and discard the rest since there is no way to add them up to get three.

2 + 1 = 3
2 + 1 = 3
2 + 1 = 3

would give the user 9 points.
but if it where calculated the wrong way and the ones where used up together instead of each 1 getting apierd with a two 1 + 1 + 1 which would only give the player 3 points och the twos couldn't be used.

Another example is:
    [1, 2, 3, 4, 5, 6]
and all combinations that are equal to 6 gives the user points

[6], [5, 1], [4 ,2]

user gets 18 points (3 * 6)

    [1 ,2 ,3], [6]
user gets 12 points (2 * 6) (Here the user gets six points less due to adding upp 1 + 2 + 3 instead of doing like in the example above)

A dice can have a value between 1 and 6.

I haven't really done much more than think about it and I'm pretty sure that I could do it right now, but it would be a solution that would scale really bad if I for example wanted to use 8 dices instead and every time I start programming on it I start to think that have to be a better/easier way of doing it... Anyone have any suggestion on where to start? I tried searching for an answer and I'm sure it's out there but I have problem forumulating a query that gives me relevant result...

Body:
With problems that look confusing like this, it is a really good idea to start with some working and examples. We have 6 die, with range [1 to 6]. The possible combinations we could make therefore are:

target = 2

1 combination: 2
2 combination: 1+1

target = 3

1 combination: 3
2 combination: 2+1
3 combination: 1+1+1

target = 4

1 combination: 4
2 combination: 3+1
               2+2
3 combination: 2+1+1
4 combination: 1+1+1+1

target = 5

1 combination: 5
2 combination: 4+1
               3+2
3 combination: 2+2+1
4 combination: 2+1+1+1
5 combination: 1+1+1+1+1

See the pattern? Hint, we go backwards from target to 1 for the first number we can add, and then given this first number, and the size of the combination, there is a limit to how big subsequent numbers can be!

There is a finite list of possible combinations. You can by looking for 1 combination scores, and remove these from the die available. Then move on to look for 2 combination scores, etc.

If you want to read more about this sub-field of mathematics, the term you need to look for is "Combinatorics". Have fun!


问:
SQL: How to get the row count of a certain record
For example, if I store 150 phone numbers in the table phone_numbers. How will I go about retrieving the row number containing 555-555-5555? I checked out many different queries, but seems I have to loop through all the data to find it.</p>

答:
Try:</p>

```<code>SELECT rowid FROM phone_numbers WHERE number ='555-555-5555';
</code>```

Body:
Try:

SELECT rowid FROM phone_numbers WHERE number ='555-555-5555';


问:
how to print __uint128_t number using gcc?
Is there PRIu128 that behaves similar to PRIu64 from <inttypes.h>:

```<code>printf("%" PRIu64 "\n", some_uint64_value);
</code>```

Or converting manually digit by digit:

```<code>int print_uint128(uint128_t n) {
  if (n == 0)  return printf("0\n");

  char str[40] = {0}; // log10(1 << 128) + '\0'
  char *s = str + sizeof(str) - 1; // start at the end
  while (n != 0) {
    if (s == str) return -1; // never happens

    *--s = "0123456789"[n % 10]; // save last digit
    n /= 10;                     // drop it
  }
  return printf("%s\n", s);
}
</code>```

is the only option?

Note that uint128_t is my own typedef for __uint128_t.

答:
Based on sebastian's answer, this is for signed int128 in g++, not thread safe.</p>

```<code>// g++ -Wall fact128.c && a.exe
// 35! overflows 128bits

#include <stdio.h>

char * sprintf_int128( __int128_t n ) {
    static char str[41] = { 0 };        // sign + log10(2**128) + '\0'
    char *s = str + sizeof( str ) - 1;  // start at the end
    bool neg = n < 0;
    if( neg )
        n = -n;
    do {
        *--s = "0123456789"[n % 10];    // save last digit
        n /= 10;                // drop it
    } while ( n );
    if( neg )
        *--s = '-';
    return s;
}

__int128_t factorial( __int128_t i ) {
    return i < 2 ? i : i * factorial( i - 1 );
}

int main(  ) {
    for( int i = 0; i < 35; i++ )
        printf( "fact(%d)=%s\n", i, sprintf_int128( factorial( i ) ) );
    return 0;
}
</code>```

Body:
Is there PRIu128 that behaves similar to PRIu64 from <inttypes.h>:

printf("%" PRIu64 "\n", some_uint64_value);

Or converting manually digit by digit:

int print_uint128(uint128_t n) {
  if (n == 0)  return printf("0\n");

  char str[40] = {0}; // log10(1 << 128) + '\0'
  char *s = str + sizeof(str) - 1; // start at the end
  while (n != 0) {
    if (s == str) return -1; // never happens

    *--s = "0123456789"[n % 10]; // save last digit
    n /= 10;                     // drop it
  }
  return printf("%s\n", s);
}

is the only option?

Note that uint128_t is my own typedef for __uint128_t.

Body:
Based on sebastian's answer, this is for signed int128 in g++, not thread safe.

// g++ -Wall fact128.c && a.exe
// 35! overflows 128bits

#include <stdio.h>

char * sprintf_int128( __int128_t n ) {
    static char str[41] = { 0 };        // sign + log10(2**128) + '\0'
    char *s = str + sizeof( str ) - 1;  // start at the end
    bool neg = n < 0;
    if( neg )
        n = -n;
    do {
        *--s = "0123456789"[n % 10];    // save last digit
        n /= 10;                // drop it
    } while ( n );
    if( neg )
        *--s = '-';
    return s;
}

__int128_t factorial( __int128_t i ) {
    return i < 2 ? i : i * factorial( i - 1 );
}

int main(  ) {
    for( int i = 0; i < 35; i++ )
        printf( "fact(%d)=%s\n", i, sprintf_int128( factorial( i ) ) );
    return 0;
}