问:
Confused, Why c++ global variable was not declared in this scope
I am new to C++. I am trying to modify a very complex video codec code as part of my final year school project. I have already asked it on another thread but got no help. This is my code:

This is the header file in which I have declared three extern variables:

yuv.h

```<code>#include <vector>
namespace X265_NS
{
extern int frameNumber;
extern int frameSize;
extern std::vector<int>numbers;

class YUVInput : public InputFile, public Thread
{
protected:

// some more variables

public:

// more variables and function declarations

};
}
</code>```

This is the first file that uses these extern variables:

yuv.cpp

```<code>#include "yuv.h"
//more includes
#include <vector>

namespace X265_NS {
    int frameNumber;
    int frameSize;
    std::vector<int>numbers;
}

using namespace X265_NS;

// some stuff and function calls
// here I use my extern variables in a function

frameNumber = readCount.get();
frameSize = ceil((double)height / 32) * ceil((double)width / 32);

//more stuff

bool YUVInput::populateFrameQueue()
{
   if(read<1)
             {
                  ifstream file("/home/abu-bakr/bin/test.txt");
                  int number;
                  while (file >> number)
                           numbers.push_back(number);
             }
}

// more stuff
</code>```

This is the second class where I am using these extern variables:

analysis.cpp

```<code>#include "yuv.h"
#include <vector>
....
using namespace X265_NS;

// some stuff

// its in a function and only place where I am using these variables
int qp_ctu = numbers.at((ctu.m_cuAddr + 1) + (frameSize*(frameNumber - 1)));

// more stuff
</code>```

This is the error I am getting that is making me really confused:

```<code>analysis.cpp
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(170): warning C4244: '=' : conversion from 'int' to 'int8_t', possible loss of data
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'numbers' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2228: left of '.at' must have class/struct/union
1>          type is ''unknown-type''
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameSize' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameNumber' : undeclared identifier

yuv.cpp
2>C:\x265_2.2\x265_2.2\source\input\yuv.cpp(219): warning C4244: '=' : conversion from 'double' to 'int', possible loss of data
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameNumber" (?frameNumber@x265@@3HA) already defined in yuv.cpp.obj
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameSize" (?frameSize@x265@@3HA) already defined in yuv.cpp.obj
2>     Creating library C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.lib and object C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.exp
2>C:\x265_2.2\x265_2.2\build\vc10-x86\Debug\x265.exe : fatal error LNK1169: one or more multiply defined symbols found
</code>```

答:
Check analysis.cpp to see if you DON'T define

```<code>namespace X265_NS {
    int frameNumber;
    int frameSize;
    std::vector<int>numbers;
}
</code>```

again.

or

Maybe you have a wrong initialization like:

```<code>int frameSize = 0;
</code>```

instead of:

```<code>frameSize = 0;
</code>```

Body:
I am new to C++. I am trying to modify a very complex video codec code as part of my final year school project. I have already asked it on another thread but got no help. This is my code:

This is the header file in which I have declared three extern variables:

yuv.h

#include <vector>
namespace X265_NS
{
extern int frameNumber;
extern int frameSize;
extern std::vector<int>numbers;

class YUVInput : public InputFile, public Thread
{
protected:

// some more variables

public:

// more variables and function declarations

};
}

This is the first file that uses these extern variables:

yuv.cpp

#include "yuv.h"
//more includes
#include <vector>

namespace X265_NS {
    int frameNumber;
    int frameSize;
    std::vector<int>numbers;
}

using namespace X265_NS;

// some stuff and function calls
// here I use my extern variables in a function

frameNumber = readCount.get();
frameSize = ceil((double)height / 32) * ceil((double)width / 32);

//more stuff

bool YUVInput::populateFrameQueue()
{
   if(read<1)
             {
                  ifstream file("/home/abu-bakr/bin/test.txt");
                  int number;
                  while (file >> number)
                           numbers.push_back(number);
             }
}

// more stuff

This is the second class where I am using these extern variables:

analysis.cpp

#include "yuv.h"
#include <vector>
....
using namespace X265_NS;

// some stuff

// its in a function and only place where I am using these variables
int qp_ctu = numbers.at((ctu.m_cuAddr + 1) + (frameSize*(frameNumber - 1)));

// more stuff

This is the error I am getting that is making me really confused:

analysis.cpp
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(170): warning C4244: '=' : conversion from 'int' to 'int8_t', possible loss of data
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'numbers' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2228: left of '.at' must have class/struct/union
1>          type is ''unknown-type''
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameSize' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameNumber' : undeclared identifier

yuv.cpp
2>C:\x265_2.2\x265_2.2\source\input\yuv.cpp(219): warning C4244: '=' : conversion from 'double' to 'int', possible loss of data
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameNumber" (?frameNumber@x265@@3HA) already defined in yuv.cpp.obj
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameSize" (?frameSize@x265@@3HA) already defined in yuv.cpp.obj
2>     Creating library C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.lib and object C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.exp
2>C:\x265_2.2\x265_2.2\build\vc10-x86\Debug\x265.exe : fatal error LNK1169: one or more multiply defined symbols found

Body:
Check analysis.cpp to see if you DON'T define

namespace X265_NS {
    int frameNumber;
    int frameSize;
    std::vector<int>numbers;
}

again.

or

Maybe you have a wrong initialization like:

int frameSize = 0;

instead of:

frameSize = 0;


来源: stackexchange

问:
Facebook FBML Questions
I have a client looking to create a Facebook page very similar to http://www.facebook.com/enchantment

Inside the "Enchantment" page, you can see that there is a list of sub-tabs, "Enchantment, Blurbs, Excerpts, Order". I'm looking to create the same style, but I can't seem to figure out how. I've looked through the code and it appears they're using the "FBML Static" application for the main tab, and there's a ton of javascript to show and hide the tabs that I highly doubt was all written by hand.

Does anybody have any experience with this? Thanks in advance.

答:
You will have to create a Facebook application via the My Applications link in the developers page. After you have filled in all the of the fields your app page should be up and running.

Now you need to begin developing the actual app on your website (you will have to specify the link in your application settings). Go through the Developer documentation, as they have quite a good documentation.

So, in order to actually create those tabs, its actually very simple, all you have to do is utilize FBMls clicktoshow and clicktohide attributes. Essentially all you need is the following code:

```<code><a href="#" clicktoshow="nav1" clicktohide="nav2,nav3">Link 1</a>

<a href="#" clicktoshow="nav2" clicktohide="nav1,nav3">Link 2</a>

<a href="#" clicktoshow="nav3" clicktohide="nav1,nav2">Link 3</a>

<div id="nav1">
//content for first tab
</div>

<div id="nav2">
//content for second tab
</div>

<div id="nav3">
//content for third tab
</div>
</code>```

When Facebook 'imports' this (only via FMBL, I'm unsure if this works with iframe) it conveniently does all the work and converts the above links to something like:

```<code>   <a href="#" clicktoshow="nav1" clicktohide="nav2, nav3" class="test"
onclick="(new Image()).src = '/ajax/ct.php?app_id=7146470109&action_type=3&post_form_id=fd583a515fe76b1d3d300e974aba931d&position=16&' + Math.random();FBML.clickToHide("app7146470109_nav2");
FBML.clickToHide("app7146470109_nav3");
FBML.clickToHide("app7146470109_nav4");FBML.clickToHide("app7146470109_nav5");FBML.clickToHide("app7146470109_nav6");
FBML.clickToHide("app7146470109_nav7");FBML.clickToHide("app7146470109_nav8");FBML.clickToShow("app7146470109_nav1");return false;">Test</a>
</code>```

But, you only have to worry about the first part, as Facebook takes care of the second. As you can see it is a fairly straightforward process.

ContentLicense: CC BY-SA 2.5

Title: Facebook FBML Questions

Body:
You will have to create a Facebook application via the My Applications link in the developers page. After you have filled in all the of the fields your app page should be up and running.

Now you need to begin developing the actual app on your website (you will have to specify the link in your application settings). Go through the Developer documentation, as they have quite a good documentation.

So, in order to actually create those tabs, its actually very simple, all you have to do is utilize FBMls clicktoshow and clicktohide attributes. Essentially all you need is the following code:

<a href="#" clicktoshow="nav1" clicktohide="nav2,nav3">Link 1</a>

<a href="#" clicktoshow="nav2" clicktohide="nav1,nav3">Link 2</a>

<a href="#" clicktoshow="nav3" clicktohide="nav1,nav2">Link 3</a>

<div id="nav1">
//content for first tab
</div>

<div id="nav2">
//content for second tab
</div>

<div id="nav3">
//content for third tab
</div>

When Facebook 'imports' this (only via FMBL, I'm unsure if this works with iframe) it conveniently does all the work and converts the above links to something like:

   <a href="#" clicktoshow="nav1" clicktohide="nav2, nav3" class="test"
onclick="(new Image()).src = '/ajax/ct.php?app_id=7146470109&amp;action_type=3&amp;post_form_id=fd583a515fe76b1d3d300e974aba931d&amp;position=16&amp;' + Math.random();FBML.clickToHide(&quot;app7146470109_nav2&quot;);
FBML.clickToHide(&quot;app7146470109_nav3&quot;);
FBML.clickToHide(&quot;app7146470109_nav4&quot;);FBML.clickToHide(&quot;app7146470109_nav5&quot;);FBML.clickToHide(&quot;app7146470109_nav6&quot;);
FBML.clickToHide(&quot;app7146470109_nav7&quot;);FBML.clickToHide(&quot;app7146470109_nav8&quot;);FBML.clickToShow(&quot;app7146470109_nav1&quot;);return false;">Test</a>

But, you only have to worry about the first part, as Facebook takes care of the second. As you can see it is a fairly straightforward process.


问:
Comparing .txt files in Python using askdirectory
I have the below code to run through a directory and select all of the files and compare them to an inserted wordlist file. However I get the following error TypeError: invalid file: ['C:/Users/Nathan/Desktop/chats\\(1,).out'] I cannot figure out how to change the os.path.join to correctly show the file location.

```<code>    self.wordopp = askdirectory(title="Select chat log directory")
    path = self.wordopp
    files = os.listdir(path)
    paths = []
    wordlist = self.wordop
    for file in files:
        paths.append(os.path.join(path, file))
        f = open(wordlist)
        l = set(w.strip().lower() for w in f)
        with open(paths) as f:
            found = False
            file = open("out.txt", "w")
            for line in paths:
                line = line.lower()
                if any(w in line for w in l):
                    found = True
                    file.write(line)
                    print(line)
                    if not found:
                        print(line)
</code>```

答:
Consider this line of code:

```<code>with open(paths) as f:
</code>```

Ask yourself, "what is paths"? It is a list of filenames, not a single file. That's pretty much what the error is telling you: that a list is an invalid file.

Considering that you are looping over a list of filenames, my guess is that your intention is to do:

```<code>with open(file) as f:
</code>```

or maybe

```<code>with open(paths[-1]) as f:
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the below code to run through a directory and select all of the files and compare them to an inserted wordlist file. However I get the following error TypeError: invalid file: ['C:/Users/Nathan/Desktop/chats\\(1,).out'] I cannot figure out how to change the os.path.join to correctly show the file location.

    self.wordopp = askdirectory(title="Select chat log directory")
    path = self.wordopp
    files = os.listdir(path)
    paths = []
    wordlist = self.wordop
    for file in files:
        paths.append(os.path.join(path, file))
        f = open(wordlist)
        l = set(w.strip().lower() for w in f)
        with open(paths) as f:
            found = False
            file = open("out.txt", "w")
            for line in paths:
                line = line.lower()
                if any(w in line for w in l):
                    found = True
                    file.write(line)
                    print(line)
                    if not found:
                        print(line)

Body:
Consider this line of code:

with open(paths) as f:

Ask yourself, "what is paths"? It is a list of filenames, not a single file. That's pretty much what the error is telling you: that a list is an invalid file.

Considering that you are looping over a list of filenames, my guess is that your intention is to do:

with open(file) as f:

or maybe

with open(paths[-1]) as f:


问:
Spring Data Neo4j @GraphId and @Index
Can anyone exmplain the difference betwen @GraphId and @Index annotation from org.neo4j.ogm.annotation ?
For now, after reading the docs it seems that @GraphId is used to create identifier for Neo4j internal logic and users should not rely on that, because it can be reused over time. But what about @Index?

As I understand, the main advantage of graph based databases is that once we know the node/relation from which to start things become easy, since all we need to do is just traverse the graph from that starting node. And indexing helps  to do so, right? So, we can write something like START n = node:index_name(property_name = value) and immitiately start exloring the graph from the indexed node by 'property_name' property, right?

So, consider this entity :

```<code>@ToString
@NodeEntity(label = "Event")
@NoArgsConstructor
public class Event{

    public Event(String eventName, LocalDate dateTime){
        this.name = eventName;
        this.date = dateTime;
    }

    public Event(Long id, String eventName, LocalDate dateTime){
        this(eventName, dateTime);
        this.id = id;
    }

    @Getter
    @GraphId
    private Long id;

    @Getter
    @Index(unique = true, primary = true)
    @Property(name = "name")
    private String name;

    @Getter
    @Property(name = "date")
    @Convert(DateConverter.class)
    private LocalDate date;
}
</code>```

As you can see the String name property is annotated with @Index. How can I write Cypher query to actually start from the node with name = 'something'? What is the index name? Or does Spring Data Neo4j 4.2.0.RELEASE figure it itself when write just MATCH (event:Event {name = 'somehting'} ... ?

```<code>@Repository
public interface EventRepository extends Neo4jRepository<Event, String>{

    Event findOne(String eventName);

}
</code>```

Here the repositry class and as you might see I am using String as the type of the id of the entity the repository manages, so I assume Spring uses name property of Event class to generate a query for Event findOne(String eventName);

答:
Can anyone exmplain the difference betwen @GraphId and @Index annotation from org.neo4j.ogm.annotation ?

I assume that you've checked the doc of Spring Data Neo4j. But one thing I want to add about @GraphId and @Index is that @GraphId is unique among the whole db while @Index can be the same or unique, depending on your decision.

How can I write Cypher query to actually start from the node with name = 'something'? What is the index name? Or does Spring Data Neo4j 4.2.0.RELEASE figure it itself when write just MATCH (event:Event {name = 'somehting'} ... ?

I believe you write the Cypher query in a correct way. Indices (including graph id) are maintained by the database and kept up-to-date. They are stored in a form of certain data structure. For example, B-Tree or Map, which can reduce the time of searching. You can check out your neo4j db for the indices. They are either stored in files maintained by the db (Where does Neo4j store the data?).

As for how Cypher knows the name of an index, since indices are maintained by the db and Cypher queries are also decoded by the db, it would make sense that the db can access to the index according to the Cypher query. This is just my guessing based on my understanding of DB system.

Title: Spring Data Neo4j @GraphId and @Index

Body:
Can anyone exmplain the difference betwen @GraphId and @Index annotation from org.neo4j.ogm.annotation ?
For now, after reading the docs it seems that @GraphId is used to create identifier for Neo4j internal logic and users should not rely on that, because it can be reused over time. But what about @Index?

As I understand, the main advantage of graph based databases is that once we know the node/relation from which to start things become easy, since all we need to do is just traverse the graph from that starting node. And indexing helps  to do so, right? So, we can write something like START n = node:index_name(property_name = value) and immitiately start exloring the graph from the indexed node by 'property_name' property, right?

So, consider this entity :

@ToString
@NodeEntity(label = "Event")
@NoArgsConstructor
public class Event{

    public Event(String eventName, LocalDate dateTime){
        this.name = eventName;
        this.date = dateTime;
    }

    public Event(Long id, String eventName, LocalDate dateTime){
        this(eventName, dateTime);
        this.id = id;
    }

    @Getter
    @GraphId
    private Long id;

    @Getter
    @Index(unique = true, primary = true)
    @Property(name = "name")
    private String name;

    @Getter
    @Property(name = "date")
    @Convert(DateConverter.class)
    private LocalDate date;
}

As you can see the String name property is annotated with @Index. How can I write Cypher query to actually start from the node with name = 'something'? What is the index name? Or does Spring Data Neo4j 4.2.0.RELEASE figure it itself when write just MATCH (event:Event {name = 'somehting'} ... ?

@Repository
public interface EventRepository extends Neo4jRepository<Event, String>{

    Event findOne(String eventName);

}

Here the repositry class and as you might see I am using String as the type of the id of the entity the repository manages, so I assume Spring uses name property of Event class to generate a query for Event findOne(String eventName);


问:
Understanding SAS output data sets
SAS has several forms it uses to create output data sets from within a procedure.  It is not always clear whether or not a particular procedure can generate a data set and, if it seems to be able to, it's not always clear how.

Off the top of my head, here are some examples of how widely the syntax can differ.

Example 1

```<code>proc sort data = sashelp.baseball out = baseball_sorted;
  by
    league
    division
  ;
run;
</code>```

Example 2

```<code>proc means noprint data = baseball_sorted;
  by
    league
    division
  ;
  var nHits;
  output
    out = baseball_avg_hits (drop = _TYPE_ _FREQ_)
    mean = mean_hits
  ;
run;
</code>```

Example 3

```<code>ods exclude all;
ods output
  statistics  = baseball_statistics
  equality    = baseball_ftest
;
proc ttest data = baseball_sorted;
  class league;
  var nHits;
run;
ods exclude none;
</code>```

Example 4

The PROC ANOVA OUTSTAT= option.

It seems almost as if SAS has implemented each of these willy-nilly.  Is the SAS syntax dictating how to create a data set directed by some consistent approach I am not seeing or is it truly capricious and arbitrary?

答:
Agree with Quentin.  You have to remember that there are SAS systems out there running code written in the 80s.  SAS would have a huge headache if they forced every team to rewrite all the procedures and then forced their customers to change all their code.  SAS has been around since the 60s and the organic growth of the syntax is to be expected.

FWIW, having an OUT= statement makes sense on things with no graphical output.  I.E. PROC SORT or PROC TRANSPOSE.

Title: Understanding SAS output data sets

Body:
SAS has several forms it uses to create output data sets from within a procedure.  It is not always clear whether or not a particular procedure can generate a data set and, if it seems to be able to, it's not always clear how.

Off the top of my head, here are some examples of how widely the syntax can differ.

Example 1

proc sort data = sashelp.baseball out = baseball_sorted;
  by
    league
    division
  ;
run;

Example 2

proc means noprint data = baseball_sorted;
  by
    league
    division
  ;
  var nHits;
  output
    out = baseball_avg_hits (drop = _TYPE_ _FREQ_)
    mean = mean_hits
  ;
run;

Example 3

ods exclude all;
ods output
  statistics  = baseball_statistics
  equality    = baseball_ftest
;
proc ttest data = baseball_sorted;
  class league;
  var nHits;
run;
ods exclude none;

Example 4

The PROC ANOVA OUTSTAT= option.

It seems almost as if SAS has implemented each of these willy-nilly.  Is the SAS syntax dictating how to create a data set directed by some consistent approach I am not seeing or is it truly capricious and arbitrary?


问:
Signal Abort(SIGABRT) exception in Xcode
Recently I've been trying to learn how to create apps in my free time. I've been following Apple's Swift documentation along with their tutorials on creating apps. After I finished the "Connect the UI to Code" tutorial, I ran the simulator, only to receive a SIGABRT exception in my "AppDelegate" Class. I looked at the console and it says:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[FoodTracker.ViewController
  nameTextField:]: unrecognized selector sent to instance
  0x7fb572d0a040'

I even replaced my original file with Apple's file just to see if there were any differences (there weren't, with the exception of a few extra comments). Here's my ViewController class file:

```<code>class ViewController: UIViewController, UITextFieldDelegate {

//MARK: Properties

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Handle the text field’s user input through delegate callbacks.
    nameTextField.delegate = self

}

//MARK: UITextFieldDelegate

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {
    mealNameLabel.text = textField.text
}

}
</code>```

答: As I mentioned in my comment, you have inconsistent Storyboard to code bindings. The screenshot below shows you the exclamation points where Xcode complains. Delete and re-add them.

Body:
Recently I've been trying to learn how to create apps in my free time. I've been following Apple's Swift documentation along with their tutorials on creating apps. After I finished the "Connect the UI to Code" tutorial, I ran the simulator, only to receive a SIGABRT exception in my "AppDelegate" Class. I looked at the console and it says:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[FoodTracker.ViewController
  nameTextField:]: unrecognized selector sent to instance
  0x7fb572d0a040'

I even replaced my original file with Apple's file just to see if there were any differences (there weren't, with the exception of a few extra comments). Here's my ViewController class file:

class ViewController: UIViewController, UITextFieldDelegate {

//MARK: Properties

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Handle the text field’s user input through delegate callbacks.
    nameTextField.delegate = self

}

//MARK: UITextFieldDelegate

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {
    mealNameLabel.text = textField.text
}

}


问:
Adding offset to {{@index}} when looping through items in Handlebars
I'm iterating over a list in Handlebars using the built-in each helper.
Within the each block, I'm referencing the current loop index {{@index}} to print the consecutive number of an item:

```<code><script id="list-item-template" type="text/x-handlebars-template">
    {{#each items}}
    <li class="topcoat-list__item">
        <a href="#{{@index}}">Item number {{@index}}</a>
    </li>
    {{/each}}
</script>
</code>```

This gives the following output:

Item number 0

Item number 1

Item number 2

....

The problem is that I want to display an offsetted index which starts with 1 instead of 0.

I tried to perform calculations on the index like {{@index+1}}, but this just leads to an

Uncaught Error: Parse error

答:
I solved this issue for myself by adding a short script tag to the bottom of my handlebars code!

Add a class to wherever you are calling @index and then the below jQuery code works (can also be done using vanilla JS).

```<code><p class="create_index">
     {{@index}}
</p>
<script>
    $(".create_index").text(parseInt($(".create_index").text())+1)
</script>
</code>```

edit 4/28- This has changed to use vanilla JS for better backwards compatibility (i.e. IE7, 8):

```<code><span class="create_index"></span>
<script>
    var divs = document.querySelectorAll('.create_index');
    for (var i = 0; i < divs.length; ++i) {
        divs[i].innerHTML = i + 1;
    }
</script>
</code>```

document.querySelectorAll has great compatibility but could also be document.getElementsByClassName("create_index")

Body:
I'm iterating over a list in Handlebars using the built-in each helper.
Within the each block, I'm referencing the current loop index {{@index}} to print the consecutive number of an item:

This gives the following output:

Item number 0

Item number 1

Item number 2

....

The problem is that I want to display an offsetted index which starts with 1 instead of 0.

I tried to perform calculations on the index like {{@index+1}}, but this just leads to an

Uncaught Error: Parse error

Body:
I solved this issue for myself by adding a short script tag to the bottom of my handlebars code!

Add a class to wherever you are calling @index and then the below jQuery code works (can also be done using vanilla JS).

<p class="create_index">
     {{@index}}
</p>
<script>
    $(".create_index").text(parseInt($(".create_index").text())+1)
</script>

edit 4/28- This has changed to use vanilla JS for better backwards compatibility (i.e. IE7, 8):

<span class="create_index"></span>
<script>
    var divs = document.querySelectorAll('.create_index');
    for (var i = 0; i < divs.length; ++i) {
        divs[i].innerHTML = i + 1;
    }
</script>

document.querySelectorAll has great compatibility but could also be document.getElementsByClassName("create_index")


问:
RxJS- Angular2 - Conditional stream
New to RxJS, using Angular2 & @ngrx/store & /effects.

I'm trying to work out how to make a stream that handles a conditional result from a service... this is to work out if a user is logged in or not when the app first runs by checking if auth credentials are stored in LocalStorage.

This may be the completely wrong way to deal with this so any advice appreciated.

At the moment I have an effect

```<code>  @Effect() check$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_CHECK)
.map(update => this.authService.checkAuth())
// now what?
// returns an observable of false, or a Auth object if LS info found
// needs to return
// this.authActions.authenticateCheckResult(res) if ok and
//  this.authActions.authenticateCheckError() if not ok
</code>```

And the checkAuth method in the authService is like this...

```<code>checkAuth():Observable {
 this._user = <AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY);

 if(this._user && this._user.accessToken) {
   return Observable.of(this._user);
 }
 else {
   return Observable.of(false);
 }
}
</code>```

Update

I have it working doing this...

```<code>  @Effect() check$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_CHECK)
.map(update => this.authService.checkAuth())
.map(result => {
  if(!result) {
    return this.authActions.authenticateCheckError(false);
  } else {
    return this.authActions.authenticateCheckSuccess(result)
  }
});
</code>```

//

```<code>checkAuth():AuthAPI {
this._user = <AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY);

if(this._user && this._user.accessToken) {
  return this._user;
}
else {
  return null;
}
</code>```

}

Is this a valid way of doing this or is there a better way?

答:
You can also chain your calls like </p>

```<code>checkAuth():Observable<AuthAPI> {
    return Rx.Observable.of(<AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY))
                        .filter(user => user)
                        .filter(user.accessToken)
                        .defaultIfEmpty(null)
</code>```

Title: RxJS- Angular2 - Conditional stream

Body:
New to RxJS, using Angular2 & @ngrx/store & /effects.

I'm trying to work out how to make a stream that handles a conditional result from a service... this is to work out if a user is logged in or not when the app first runs by checking if auth credentials are stored in LocalStorage.

This may be the completely wrong way to deal with this so any advice appreciated.

At the moment I have an effect

  @Effect() check$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_CHECK)
.map(update => this.authService.checkAuth())
// now what?
// returns an observable of false, or a Auth object if LS info found
// needs to return
// this.authActions.authenticateCheckResult(res) if ok and
//  this.authActions.authenticateCheckError() if not ok

And the checkAuth method in the authService is like this...

checkAuth():Observable {
 this._user = <AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY);

 if(this._user && this._user.accessToken) {
   return Observable.of(this._user);
 }
 else {
   return Observable.of(false);
 }
}

Update

I have it working doing this...

  @Effect() check$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_CHECK)
.map(update => this.authService.checkAuth())
.map(result => {
  if(!result) {
    return this.authActions.authenticateCheckError(false);
  } else {
    return this.authActions.authenticateCheckSuccess(result)
  }
});

//

checkAuth():AuthAPI {
this._user = <AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY);

if(this._user && this._user.accessToken) {
  return this._user;
}
else {
  return null;
}

}

Is this a valid way of doing this or is there a better way?

Body:
You can also chain your calls like

checkAuth():Observable<AuthAPI> {
    return Rx.Observable.of(<AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY))
                        .filter(user => user)
                        .filter(user.accessToken)
                        .defaultIfEmpty(null)


问:
Passing member function to function pointer
I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?

Thanks.

```<code>classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}
</code>```

答: On the surface, this just looks like a forward declaration issue. Try declaring classA::functionB as you've done, and then defining classA::functionB after the definition of classB.

Body:
I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?

Thanks.

classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}


问:
Tabbed Activity onCreate for each of the tabs
I know there has been a question similar to this, but I have a slightly different problem.

I created the default tabbed activity for android and am using it as is given by Android Studio. I was wondering what the behavior of the onCreateView() function for the Placeholder Fragment is and whether I would be able to change it so that, at the beginning of the activity, it calls the onCreateView() for all three of the Placeholder Fragments, and never calls this function again?

Thanks in advance.

Here is the default tabbed activity for reference:

```<code>    package com.example.myname.myproject;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class SampleActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_sample, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_sample, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }
}
</code>```

答: Sorry, I should have done some more research: mViewPager.setOffscreenPageLimit(3); works

Body:
I know there has been a question similar to this, but I have a slightly different problem.

I created the default tabbed activity for android and am using it as is given by Android Studio. I was wondering what the behavior of the onCreateView() function for the Placeholder Fragment is and whether I would be able to change it so that, at the beginning of the activity, it calls the onCreateView() for all three of the Placeholder Fragments, and never calls this function again?

Thanks in advance.

Here is the default tabbed activity for reference:

    package com.example.myname.myproject;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class SampleActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_sample, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_sample, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }
}


问:
How to I change the size of a storyboard?
I am learning about iOS app development and I started a project but the size of the storyboard is iPhone 7. How can I make it so that its wider and will be available to all phone sizes?

Like this

img

答:
iOS uses size classes and traits. You can create separate layouts for each size class based on the display traits.

When you have the storyboard editor open look at the bottom right in the margins you should se View as: iPhone 7. If you click this it will expand and show you thumbnails of all the devices with one of them highlighted. You can select a different device and make any layout changes and have it apply to that layout only.

See this link for a deeper read: https://makeapppie.com/2016/09/05/an-introduction-to-size-classes-for-xcode-8/


问:
How to create an SVG component dynamically in Angular2?
I am creating a web application which uses SVG.
I have created components consist of SVG element, and they are put into a root svg element.
They have attribute selector, because SVG/XML document tree is strict so I cannot use element selector.
And they have a template starts with svg:g tag:

```<code>@Component({
  selector:'[foo]',
  template: '<svg:g>...</svg:g>',
})
</code>```

In the application, I want to create a component when a user press a button,
and simultaneously start dragging it.
I thought it can be achieved by creating a component dynamically using ComponentResolver:

```<code>  @ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef})
  protected dynamicComponentTarget: ViewContainerRef

  private componentResolver: ComponentResolver

  onMouseDown() {
    this.componentResolver
      .resolveComponent(FooComponent)
      .then((factory) => {
        const dynamicComponent = this.dynamicComponentTarget.createComponent(factory, 0)
        const component: FooComponent = dynamicComponent.instance
        const element = dynamicComponent.location.nativeElement
        // add event listener to start dragging `element`.
      })
  }
</code>```

Component is created when onMouseDown() called, but its DOM element is div, so it is illegal element in svg document and cannot be displayed.

I have tried with selector='svg:g[foo]', then g element is created, but its namespace is not for SVG (http://www.w3.org/2000/svg), but normal HTML namespace (http://www.w3.org/1999/xhtml) and its class is HTMLUnknownElement > g.

I also tried with selector='svg:svg[foo]', then svg:svg element is created and it is displayed. But svg:svg cannot move with transform attribute so this doesn't work well for my application.

How can I dynamically create svg:g element for attribute selector component?

I am using Angular2: 2.0.0-rc4.

答:
You're right about the namespacing issues keeping the g element from rendering as svg. Unfortunately, attaching the node as an svg element is the only way to feasibly get the component to namespace properly.

However, this doesn't mean this won't work. If you add the drag functionality as a directive on the g element in the template, it will be compiled with your component, and you can offset your logic into that directive. The top level svg will be namespaced correctly, and the template will inherit this accordingly.

```<code>import {Component, Input} from '@angular/core';

@Component({
  selector: 'svg:svg[customName]', // prevent this from hijacking other svg
  template: '<svg:g dragDirective>...</svg:g>', // note the directive added here
  style: []
})
export class GComponent {

  constructor() { }

}
</code>```

This may not be ideal, but until https://github.com/angular/angular/issues/10404 is resolved, there's not much of an alternative.

Body:
I am creating a web application which uses SVG.
I have created components consist of SVG element, and they are put into a root svg element.
They have attribute selector, because SVG/XML document tree is strict so I cannot use element selector.
And they have a template starts with svg:g tag:

@Component({
  selector:'[foo]',
  template: '<svg:g>...</svg:g>',
})

In the application, I want to create a component when a user press a button,
and simultaneously start dragging it.
I thought it can be achieved by creating a component dynamically using ComponentResolver:

  @ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef})
  protected dynamicComponentTarget: ViewContainerRef

  private componentResolver: ComponentResolver

  onMouseDown() {
    this.componentResolver
      .resolveComponent(FooComponent)
      .then((factory) => {
        const dynamicComponent = this.dynamicComponentTarget.createComponent(factory, 0)
        const component: FooComponent = dynamicComponent.instance
        const element = dynamicComponent.location.nativeElement
        // add event listener to start dragging `element`.
      })
  }

Component is created when onMouseDown() called, but its DOM element is div, so it is illegal element in svg document and cannot be displayed.

I have tried with selector='svg:g[foo]', then g element is created, but its namespace is not for SVG (http://www.w3.org/2000/svg), but normal HTML namespace (http://www.w3.org/1999/xhtml) and its class is HTMLUnknownElement > g.

I also tried with selector='svg:svg[foo]', then svg:svg element is created and it is displayed. But svg:svg cannot move with transform attribute so this doesn't work well for my application.

How can I dynamically create svg:g element for attribute selector component?

I am using Angular2: 2.0.0-rc4.

Body:
You're right about the namespacing issues keeping the g element from rendering as svg. Unfortunately, attaching the node as an svg element is the only way to feasibly get the component to namespace properly.

However, this doesn't mean this won't work. If you add the drag functionality as a directive on the g element in the template, it will be compiled with your component, and you can offset your logic into that directive. The top level svg will be namespaced correctly, and the template will inherit this accordingly.

import {Component, Input} from '@angular/core';

@Component({
  selector: 'svg:svg[customName]', // prevent this from hijacking other svg
  template: '<svg:g dragDirective>...</svg:g>', // note the directive added here
  style: []
})
export class GComponent {

  constructor() { }

}

This may not be ideal, but until https://github.com/angular/angular/issues/10404 is resolved, there's not much of an alternative.


问:
How to create custom scoped modules in dagger 2.10
I am trying to migrate the company app to dagger 2.10 and the AndroidInjector.inject method, but I think I found a problem. The app uses custom scopes… like the feature Login has 3 activities (each one with it`s own dagger module) and one LoginModule that is responsible  for sharing singletons that only should live in this scope. So in the first Activity I used to execute something like:

```<code>public class LoginActivity extends AppCompatActivity{
public void onCreate(Bundle bla){
LoginActivityComponent activityComponent = ((CustomApplication) getApplicationContext())
                .plus(new LoginModule()) // generates LoginComponent and save the reference in the CustomApplication
                .plus(new LoginActivityModule(this));
        activityComponent.inject(this);
      ...
}
</code>```

In the others activities I just execute ((CustomApplication) getApplicationContext()).getLoginComponent().plus(new ForgetPasswordModule()).inject(this)

How can I archive the same behavior when using AndroidInjector ?

答:
The single-subcomponent cheat

Rather than the normal implementation in your Application:

```<code>public class YourApplication extends Application implements HasActivityInjector {
  @Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;

  @Override
  public AndroidInjector<Activity> activityInjector() {
    return dispatchingActivityInjector;  // Always get it from Multibindings.
  }
}
</code>```

Just move the activity-binding modules to your LoginComponent and delegate to the DispatchingAndroidInjector<Activity> from your LoginComponent instead:

```<code>@Override
public AndroidInjector<Activity> activityInjector() {
  return getOrCreateLoginComponent().getActivityInjector();
}
</code>```

This is the least amount of ongoing maintenance, but it seems pretty backwards, because you're creating your LoginComponent up front. However, if LoginComponent is cheap and is your only subcomponent of this style, then everything works perfectly: LoginComponent's injector can see the multibindings in its parents, so LoginComponent's ActivityInjector will always work even for bindings in the parent.

Because the bindings of non-login activities still reside in the ApplicationComponent, those activities won't be able to use bindings from the parent component. Otherwise, though, this is tantamount to merging your LoginComponent into your ApplicationComponent, which probably isn't an option or else you'd've done it that way.

Delegating AndroidInjector

If your LoginComponent is expensive to create, then as an alternative you could move the getOrCreateLoginComponent() call behind an instanceof check:

```<code>@Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;

@Override
public AndroidInjector<Activity> activityInjector() {
  return new AndroidInjector<Activity>() {
    @Override public void inject(Activity activity) {
      if (Activity instanceof LoginActivity
          || Activity instanceof OtherLoginActivity) {
        getOrCreateLoginComponent().getActivityInjector().inject(activity);
      } else {
        // You can chain other subcomponents here as well.
        dispatchingActivityInjector.inject(activity);
      }
    }
  };
}
</code>```

This means that you would need to keep a separate list (maybe as a field in LoginComponent or LoginModule) of activities that LoginComponent can handle, but if you want to avoid instantiating LoginComponent until you're sure that you're injecting a login-related activity, here's how you'd check it. The above approach also scales well to multiple subcomponents, because you're always calling inject on exactly one DispatchingAndroidInjector<Activity> from exactly one Component.

Hybrid alternative

Because the Map presence check is likely pretty fast, you could also avoid that extra list by checking with the main injector first before throwing it to the login component. Of course, that starts to get ugly if you've got multiple subcomponents of that style.

```<code>@Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;

@Override
public AndroidInjector<Activity> activityInjector() {
  return new AndroidInjector<Activity>() {
    @Override public void inject(Activity activity) {
      if (!dispatchingActivityInjector.maybeInject(activity)) {
        // It's not in the top level. Start checking subcomponents.
        getOrCreateLoginComponent().getActivityInjector().inject(activity);
      }
    }
  };
}
</code>```

Hopefully, between the three, you won't find Android injection here to be "worse than pain from any disease or wound known in the universe".

Body:
I am trying to migrate the company app to dagger 2.10 and the AndroidInjector.inject method, but I think I found a problem. The app uses custom scopes… like the feature Login has 3 activities (each one with it`s own dagger module) and one LoginModule that is responsible  for sharing singletons that only should live in this scope. So in the first Activity I used to execute something like:

public class LoginActivity extends AppCompatActivity{
public void onCreate(Bundle bla){
LoginActivityComponent activityComponent = ((CustomApplication) getApplicationContext())
                .plus(new LoginModule()) // generates LoginComponent and save the reference in the CustomApplication
                .plus(new LoginActivityModule(this));
        activityComponent.inject(this);
      ...
}

In the others activities I just execute ((CustomApplication) getApplicationContext()).getLoginComponent().plus(new ForgetPasswordModule()).inject(this)

How can I archive the same behavior when using AndroidInjector ?

Body:
The single-subcomponent cheat

Rather than the normal implementation in your Application:

public class YourApplication extends Application implements HasActivityInjector {
  @Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;

  @Override
  public AndroidInjector<Activity> activityInjector() {
    return dispatchingActivityInjector;  // Always get it from Multibindings.
  }
}

Just move the activity-binding modules to your LoginComponent and delegate to the DispatchingAndroidInjector<Activity> from your LoginComponent instead:

@Override
public AndroidInjector<Activity> activityInjector() {
  return getOrCreateLoginComponent().getActivityInjector();
}

This is the least amount of ongoing maintenance, but it seems pretty backwards, because you're creating your LoginComponent up front. However, if LoginComponent is cheap and is your only subcomponent of this style, then everything works perfectly: LoginComponent's injector can see the multibindings in its parents, so LoginComponent's ActivityInjector will always work even for bindings in the parent.

Because the bindings of non-login activities still reside in the ApplicationComponent, those activities won't be able to use bindings from the parent component. Otherwise, though, this is tantamount to merging your LoginComponent into your ApplicationComponent, which probably isn't an option or else you'd've done it that way.

Delegating AndroidInjector

If your LoginComponent is expensive to create, then as an alternative you could move the getOrCreateLoginComponent() call behind an instanceof check:

@Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;

@Override
public AndroidInjector<Activity> activityInjector() {
  return new AndroidInjector<Activity>() {
    @Override public void inject(Activity activity) {
      if (Activity instanceof LoginActivity
          || Activity instanceof OtherLoginActivity) {
        getOrCreateLoginComponent().getActivityInjector().inject(activity);
      } else {
        // You can chain other subcomponents here as well.
        dispatchingActivityInjector.inject(activity);
      }
    }
  };
}

This means that you would need to keep a separate list (maybe as a field in LoginComponent or LoginModule) of activities that LoginComponent can handle, but if you want to avoid instantiating LoginComponent until you're sure that you're injecting a login-related activity, here's how you'd check it. The above approach also scales well to multiple subcomponents, because you're always calling inject on exactly one DispatchingAndroidInjector<Activity> from exactly one Component.

Hybrid alternative

Because the Map presence check is likely pretty fast, you could also avoid that extra list by checking with the main injector first before throwing it to the login component. Of course, that starts to get ugly if you've got multiple subcomponents of that style.

@Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;

@Override
public AndroidInjector<Activity> activityInjector() {
  return new AndroidInjector<Activity>() {
    @Override public void inject(Activity activity) {
      if (!dispatchingActivityInjector.maybeInject(activity)) {
        // It's not in the top level. Start checking subcomponents.
        getOrCreateLoginComponent().getActivityInjector().inject(activity);
      }
    }
  };
}

Hopefully, between the three, you won't find Android injection here to be "worse than pain from any disease or wound known in the universe".


问:
bash script grep the etc file for user information
I am trying to write a script in bash to read in arguments (usernames) and then return information about that username by searching the /etc/passwd file. I am not the root on the server that I am scripting this on, but I don't need to be. Here is the code that I have so far, but I dont think I am using the grep command right. </p>

```<code>#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
        UNAME=$1 #set arg to var UNAME
        grep UNAME=$(grep $/etc/passwd)
        if [ $UNAME == /etc/passwd ]; then #if UNAME exists then display info below
                echo "-------------------------------------------"
                echo "Username:       $(grep UNAME/etc/passwd/ $f1) "
                echo "User ID (UID):  $(grep UNAME/etc/passwd/) "
                echo "Group ID (GID): $(grep UNAME/etc/passwd/) "
                echo "User info:      $(grep UNAME/etc/passwd/) "
                echo "Home directory: $(grep UNAME/etc/passwd/) "
                echo "Command shell:  $(grep UNAME/etc/passwd/) "
                echo "-------------------------------------------"
        else #if UNAME is nonexistant then display this error message
                echo "-------------------------------------------"
                echo ""$UNAME" does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi
</code>```

答:
The best tool to read databases such as passwd is getent. This will fetch entries from a database supported by Name Service Switch Libraries. If you really need to limit reading the files databases, you can tell getent to use files database with -s files.

Your code is unnecessarily long. Fetching a record and parsing them into multiple variables should be enough.

```<code>#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
    if IFS=: read username ignore uid gid gecos home shell < <(getent -s files passwd $1); then
                echo "-------------------------------------------"
                echo "Username:       $username"
                echo "User ID (UID):  $uid"
                echo "Group ID (GID): $gid"
                echo "User info:      $gecos"
                echo "Home directory: $home"
                echo "Command shell:  $shell"
                echo "-------------------------------------------"
        else #if $1 is nonexistant then display this error message
                echo "-------------------------------------------"
                echo "'$1' does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi
</code>```

Body:
I am trying to write a script in bash to read in arguments (usernames) and then return information about that username by searching the /etc/passwd file. I am not the root on the server that I am scripting this on, but I don't need to be. Here is the code that I have so far, but I dont think I am using the grep command right.

#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
        UNAME=$1 #set arg to var UNAME
        grep UNAME=$(grep $/etc/passwd)
        if [ $UNAME == /etc/passwd ]; then #if UNAME exists then display info below
                echo "-------------------------------------------"
                echo "Username:       $(grep UNAME/etc/passwd/ $f1) "
                echo "User ID (UID):  $(grep UNAME/etc/passwd/) "
                echo "Group ID (GID): $(grep UNAME/etc/passwd/) "
                echo "User info:      $(grep UNAME/etc/passwd/) "
                echo "Home directory: $(grep UNAME/etc/passwd/) "
                echo "Command shell:  $(grep UNAME/etc/passwd/) "
                echo "-------------------------------------------"
        else #if UNAME is nonexistant then display this error message
                echo "-------------------------------------------"
                echo ""$UNAME" does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi

Body:
The best tool to read databases such as passwd is getent. This will fetch entries from a database supported by Name Service Switch Libraries. If you really need to limit reading the files databases, you can tell getent to use files database with -s files.

Your code is unnecessarily long. Fetching a record and parsing them into multiple variables should be enough.

#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
    if IFS=: read username ignore uid gid gecos home shell < <(getent -s files passwd $1); then
                echo "-------------------------------------------"
                echo "Username:       $username"
                echo "User ID (UID):  $uid"
                echo "Group ID (GID): $gid"
                echo "User info:      $gecos"
                echo "Home directory: $home"
                echo "Command shell:  $shell"
                echo "-------------------------------------------"
        else #if $1 is nonexistant then display this error message
                echo "-------------------------------------------"
                echo "'$1' does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi


问:
How to make ACE Editor manually resizable just like html's textarea
I'm using jquery-ace inside twitter-bootstrap modal.

Is there a way to make the ace editor resizable by user without using jquery-ui.

Or if it's not possible, I want to set min-max lines appear, I have found this demo, but it seems that jquery-ace wrongly documented since I could not get access to the ace object to call setOption

```<code>var decorator = $('.my-code-area').data('ace');
var aceInstance = decorator.ace; // this is wrong
// decorator.editor.ace --> this is more correct but it doesn't have setOption()
</code>```

答:
Spent a ton of time trying to figure out a way to resize the Ace Editor window without jitter, using jQuery UI, or any other additional libs (as that is just additional bloat), so I ended up coming up with my own custom solution for it.

Dragging is handled by a 2px tall div, which on mousedown sets opacity to 0 on the editor, and then back to 1 on mouseup.

This essentially results in the wrapper div showing during the dragging, and then hidden afterwards. Profit!

var editor = ace.edit( "smyles_editor" );
var dragging = false;
var wpoffset = 0;

// If using WordPress uncomment line below as we have to
// 32px for admin bar, minus 1px to center in 2px slider bar
// wpoffset = 31;

editor.setTheme("ace/theme/monokai");
// inline must be true to syntax highlight PHP without opening <?php tag
editor.getSession().setMode( { path: "ace/mode/php", inline: true } );

$( '#smyles_dragbar' ).mousedown( function ( e ) {
 e.preventDefault();
 window.dragging = true;

 var smyles_editor = $( '#smyles_editor' );
 var top_offset = smyles_editor.offset().top - wpoffset;

 // Set editor opacity to 0 to make transparent so our wrapper div shows
 smyles_editor.css( 'opacity', 0 );

 // handle mouse movement
 $( document ).mousemove( function ( e ) {

  var actualY = e.pageY - wpoffset;
  // editor height
  var eheight = actualY - top_offset;

  // Set wrapper height
  $( '#smyles_editor_wrap' ).css( 'height', eheight);

  // Set dragbar opacity while dragging (set to 0 to not show)
  $( '#smyles_dragbar' ).css( 'opacity', 0.15 );

 } );

} );

$( document ).mouseup( function ( e ) {

 if ( window.dragging )
 {
  var smyles_editor = $( '#smyles_editor' );

  var actualY = e.pageY - wpoffset;
  var top_offset = smyles_editor.offset().top - wpoffset;
  var eheight = actualY - top_offset;

  $( document ).unbind( 'mousemove' );

  // Set dragbar opacity back to 1
  $( '#smyles_dragbar' ).css( 'opacity', 1 );

  // Set height on actual editor element, and opacity back to 1
  smyles_editor.css( 'height', eheight ).css( 'opacity', 1 );

  // Trigger ace editor resize()
  editor.resize();
  window.dragging = false;
 }

} );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 40px;
}

#smyles_editor {
  height: 300px;
}

#smyles_editor_wrap {
 background-color: #cccccc;
 border-bottom: 1px solid #222222;
}

#smyles_dragbar {
 background-color: #222222;
 width: 100%;
 height: 2px;
 cursor: row-resize;
 opacity: 1;
}</code>```

  Vertically Resizable Ace Editor

function foo($awesome) {

 $x = 'Smyles make resizable window for youuuuu!';

 if( $awesome === TRUE ){
  $x = 'Enjoy!';
 }

 return x;
}

```

http://jsfiddle.net/tripflex/knnv5e7s/

Body:
I'm using jquery-ace inside twitter-bootstrap modal.

Is there a way to make the ace editor resizable by user without using jquery-ui.

Or if it's not possible, I want to set min-max lines appear, I have found this demo, but it seems that jquery-ace wrongly documented since I could not get access to the ace object to call setOption

var decorator = $('.my-code-area').data('ace');
var aceInstance = decorator.ace; // this is wrong
// decorator.editor.ace --> this is more correct but it doesn't have setOption()

Body:
Spent a ton of time trying to figure out a way to resize the Ace Editor window without jitter, using jQuery UI, or any other additional libs (as that is just additional bloat), so I ended up coming up with my own custom solution for it.

Dragging is handled by a 2px tall div, which on mousedown sets opacity to 0 on the editor, and then back to 1 on mouseup.

This essentially results in the wrapper div showing during the dragging, and then hidden afterwards. Profit!

var editor = ace.edit( "smyles_editor" );
var dragging = false;
var wpoffset = 0;

// If using WordPress uncomment line below as we have to
// 32px for admin bar, minus 1px to center in 2px slider bar
// wpoffset = 31;

editor.setTheme("ace/theme/monokai");
// inline must be true to syntax highlight PHP without opening <?php tag
editor.getSession().setMode( { path: "ace/mode/php", inline: true } );

$( '#smyles_dragbar' ).mousedown( function ( e ) {
 e.preventDefault();
 window.dragging = true;

 var smyles_editor = $( '#smyles_editor' );
 var top_offset = smyles_editor.offset().top - wpoffset;

 // Set editor opacity to 0 to make transparent so our wrapper div shows
 smyles_editor.css( 'opacity', 0 );

 // handle mouse movement
 $( document ).mousemove( function ( e ) {

  var actualY = e.pageY - wpoffset;
  // editor height
  var eheight = actualY - top_offset;

  // Set wrapper height
  $( '#smyles_editor_wrap' ).css( 'height', eheight);

  // Set dragbar opacity while dragging (set to 0 to not show)
  $( '#smyles_dragbar' ).css( 'opacity', 0.15 );

 } );

} );

$( document ).mouseup( function ( e ) {

 if ( window.dragging )
 {
  var smyles_editor = $( '#smyles_editor' );

  var actualY = e.pageY - wpoffset;
  var top_offset = smyles_editor.offset().top - wpoffset;
  var eheight = actualY - top_offset;

  $( document ).unbind( 'mousemove' );

  // Set dragbar opacity back to 1
  $( '#smyles_dragbar' ).css( 'opacity', 1 );

  // Set height on actual editor element, and opacity back to 1
  smyles_editor.css( 'height', eheight ).css( 'opacity', 1 );

  // Trigger ace editor resize()
  editor.resize();
  window.dragging = false;
 }

} );

body {
  margin: 40px;
}

#smyles_editor {
  height: 300px;
}

#smyles_editor_wrap {
 background-color: #cccccc;
 border-bottom: 1px solid #222222;
}

#smyles_dragbar {
 background-color: #222222;
 width: 100%;
 height: 2px;
 cursor: row-resize;
 opacity: 1;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
  Vertically Resizable Ace Editor
</h2>
<br/>
<div id="smyles_editor_wrap">
 <div id="smyles_editor">function foo($awesome) {

 $x = 'Smyles make resizable window for youuuuu!';

 if( $awesome === TRUE ){
  $x = 'Enjoy!';
 }

 return x;
}</div>
 <div id="smyles_dragbar"></div>
</div>

http://jsfiddle.net/tripflex/knnv5e7s/


问:
How do I return (k) amount of bits a binary strings in a file?
Essentially, if I were to type in 4 for n and 4 for k, it should return 4 lines of a 4 bit binary string in a file.

Instead, it returns four lines of binary, but in ascending order of bits. (So first line has one bit, second line has two, third line has three, and so on.)

Here is my code:

```<code>import random
def makeStrings():
    fileName = str(input("file:"))
    outputFile = open(fileName, "w")
    userInput = str(input("k:"))
    anotherinput = str(input("n:"))
    counter = 0
    while (counter < int(anotherinput)):
        stringy = ""
        for i in range(int(userInput)):
            RandoNumber=int(random.random()*2)
            stringy=stringy+str(RandoNumber)
            outputFile.write(str(stringy) + "\n")
            counter = counter +1
    outputFile.close()
</code>```

Thanks for your help!

答:
You mishandled your loop indices.  Your inner loop writes every addition to the string.  Your outer loop runs in parallel with the inner loop; counter is incremented every time through the inner loop.  Try this instead.  I simplified a few lines for testing.

```<code>userInput = 4
anotherinput = 4
for counter in range(int(anotherinput)):
    stringy = ""
    for i in range(int(userInput)):
        RandoNumber=int(random.random()*2)
        stringy=stringy+str(RandoNumber)
    print(str(stringy) + "\n")
# outputFile.close()
</code>```

Body:
Essentially, if I were to type in 4 for n and 4 for k, it should return 4 lines of a 4 bit binary string in a file.

Instead, it returns four lines of binary, but in ascending order of bits. (So first line has one bit, second line has two, third line has three, and so on.)

Here is my code:

import random
def makeStrings():
    fileName = str(input("file:"))
    outputFile = open(fileName, "w")
    userInput = str(input("k:"))
    anotherinput = str(input("n:"))
    counter = 0
    while (counter < int(anotherinput)):
        stringy = ""
        for i in range(int(userInput)):
            RandoNumber=int(random.random()*2)
            stringy=stringy+str(RandoNumber)
            outputFile.write(str(stringy) + "\n")
            counter = counter +1
    outputFile.close()

Thanks for your help!

Body:
You mishandled your loop indices.  Your inner loop writes every addition to the string.  Your outer loop runs in parallel with the inner loop; counter is incremented every time through the inner loop.  Try this instead.  I simplified a few lines for testing.

userInput = 4
anotherinput = 4
for counter in range(int(anotherinput)):
    stringy = ""
    for i in range(int(userInput)):
        RandoNumber=int(random.random()*2)
        stringy=stringy+str(RandoNumber)
    print(str(stringy) + "\n")
# outputFile.close()


问:
instanciated local variable shows as null in debugging inspector
I'm encountering a strange issue when debugging some async code in visual studio:

As you can see I have a for loop that iterates over an IEnumerable with 9 instantiated objects in it (terrible naming I know, Not my DB...)
i is 0 in this case, so elementAt should put the first item in the betalingvariable.
This happens correctly, and this code executes flawlessly, but in the debugger it shows as null:

When I continue debugging, everything is normal, the betalingvariable is used in multiple lines of code and is saved to the DB correctly, so it's only my debug inspector that shows the object as null. This is quite irritating when you are debugging however, as you can't see anything..
I suspect this has to do something with async await. There are multiple DB awaits before this loop. And the save of the betalingobject in the loop is also an await method. When I try to reproduce this behavior in a test project however, everything works fine..

I know you can have problems accessing properties from other threats in async methods, and I'm calling this code from a VM, but then why can I inspect the list? I'm suspecting this to be a bug, and if it isn't it is certainly a strange 'feature' being able to follow the lines of code but not being able to inspect some properties..

I tested this in VIsual Studio 2012 and 2013, same behavior in both.

答:
I see this on both VS 2015 Update 3 and VS 2017.

As a work-around, I found that using the mouse hover/click to 'Run execution to here' preserved the instantiated value, where the keyboard accelerator ('Ctrl+Shift+F10') would null out the instantiated value.


问:
Does Scott Meyers's advice to prefer non-member non-friend methods apply to object construction?
Let's say I have a class:

```<code>class C{
  int x_;
  int y_;
public:
  C(int x, int y): x_(x), y_(y){}
};
</code>```

Then I want to add construction from a string, which would just parse x and y. Before reading Meyers's book I would usually make it another constructor in class C. However, it's also possible to make it non-member non-friend:

```<code>C CFromString(const std::string& s){
  int x, y;
  //...parse them somehow, throw exception if needed...
  return C(x,y);
}
</code>```

To me this is standard situation for many "value classes", when there is a "main" constructor which sets private members to provided values (probably checking there correctness). Other constructors for such classes are often just calculate these values from some other arguments.

Are there any drawbacks in making such constructors non-member non-friends like in my example?

Upd. I understand the Meyers's advice, and what are the advantages of NMNF functions. There is just no examples of NMNF object construction in his book, so I want to ensure that his advice applies to construction as well.

答:
One drawback is a bit of inconsistency, which is an esthetic concern.

You're calling a CFromString constructor function rather than invoking a constructor called C. The relationship between them is arbitrary, just through the C prefix in the name.

If you make it a static member function, then you can call it C::FromString so that it belongs to the class.

If this is done all over the place in a large project, some sort of convention would help. Like say, whenever we have a class C, and a non-member constructor function for making C-s, let's always call it CCons, and then always use overloading for different types. Thus, if we have a Widget class, we then call our overloaded family WidgetCons:

```<code>Widget WidgetCons(const std::string &s) { /* make it from string */ }
Widget WidgetCons(int i) { /* make it from int */ }
</code>```

and so on. If this is consistent in our 250,000 line codebase, whenever someone sees any FooCons or BarCons, they know exactly what it is.

Body:
Let's say I have a class:

class C{
  int x_;
  int y_;
public:
  C(int x, int y): x_(x), y_(y){}
};

Then I want to add construction from a string, which would just parse x and y. Before reading Meyers's book I would usually make it another constructor in class C. However, it's also possible to make it non-member non-friend:

C CFromString(const std::string& s){
  int x, y;
  //...parse them somehow, throw exception if needed...
  return C(x,y);
}

To me this is standard situation for many "value classes", when there is a "main" constructor which sets private members to provided values (probably checking there correctness). Other constructors for such classes are often just calculate these values from some other arguments.

Are there any drawbacks in making such constructors non-member non-friends like in my example?

Upd. I understand the Meyers's advice, and what are the advantages of NMNF functions. There is just no examples of NMNF object construction in his book, so I want to ensure that his advice applies to construction as well.

Body:
One drawback is a bit of inconsistency, which is an esthetic concern.

You're calling a CFromString constructor function rather than invoking a constructor called C. The relationship between them is arbitrary, just through the C prefix in the name.

If you make it a static member function, then you can call it C::FromString so that it belongs to the class.

If this is done all over the place in a large project, some sort of convention would help. Like say, whenever we have a class C, and a non-member constructor function for making C-s, let's always call it CCons, and then always use overloading for different types. Thus, if we have a Widget class, we then call our overloaded family WidgetCons:

Widget WidgetCons(const std::string &s) { /* make it from string */ }
Widget WidgetCons(int i) { /* make it from int */ }

and so on. If this is consistent in our 250,000 line codebase, whenever someone sees any FooCons or BarCons, they know exactly what it is.


问:
Why is isdigit() not working?
Code:

#include <iostream>
#include <string>
using namespace std;
string s1,s2,s3,s4,s5;
int ex(string s){
    int i;
    if(isdigit(s)){
        i = atoi(s.c_str);
    }
    else
        return -1;
    return i;
}

int main(){
    int t;cin>>t;int v1,v2,v3;
    while(t--){
        cin>>s1>>s2>>s3>>s4>>s5;
        v1=ex(s1);
        v2=ex(s2);
        v3=ex(s3);
        if(v1<0) v1=v3-v2;
        if(v2<0) v2=v3-v1;
        if(v3<0) v3=v1+v2;
        cout<<v1<<" + "<<v2<<" = "<<v3;
        }
    }
    return 0;
}
```

<p><strong>Error:</strong></p>

<pre class="lang-none prettyprint-override"><code>error: no matching function for call to 'isdigit(std::string&)'
     if(isdigit(s)){
</code>```

I tried searching all the previous posts regarding this but still could not figure out why isdigit(s) function is not working.
And the question is there will be input of the form
47 + machula = 53, where machula is some word
and output should be 47 + 6 = 53.

答:
isdigit is meant to check whether a single character is a digit or not, not a string. That's why the call isdigit(s) fails to compile.

You could use std::stoi. However, keep in mind that it will throw an exception if no conversion could be performed by the function.

```<code>try
{
   i = std::stoi(s);
}
catch ( ... )
{
   // Deal with the exception
}
</code>```

You could also check whether the first character of the string is a digit before attempting to use std::stoi.

```<code>if ( !(s.empty()) && isdigit(s[0]) )
{
   i = std::stoi(s);
}
</code>```

NB

From the comment by @RemyLebeau:

The above check because that does not guarantee that all characters in the string are digits. std::stoi() parses the entire string and then reports the index of the first non-digit character, even if that is the null terminator. It also skips leading whitespace, so checking the first character may cause a false result where std::stoi() would have normally succeeded.

Title: Why is isdigit() not working?

Body:
Code:

#include <iostream>
#include <string>
using namespace std;
string s1,s2,s3,s4,s5;
int ex(string s){
    int i;
    if(isdigit(s)){
        i = atoi(s.c_str);
    }
    else
        return -1;
    return i;
}

int main(){
    int t;cin>>t;int v1,v2,v3;
    while(t--){
        cin>>s1>>s2>>s3>>s4>>s5;
        v1=ex(s1);
        v2=ex(s2);
        v3=ex(s3);
        if(v1<0) v1=v3-v2;
        if(v2<0) v2=v3-v1;
        if(v3<0) v3=v1+v2;
        cout<<v1<<" + "<<v2<<" = "<<v3;
        }
    }
    return 0;
}

Error:

error: no matching function for call to 'isdigit(std::string&)'
     if(isdigit(s)){

I tried searching all the previous posts regarding this but still could not figure out why isdigit(s) function is not working.
And the question is there will be input of the form
47 + machula = 53, where machula is some word
and output should be 47 + 6 = 53.

Body:
isdigit is meant to check whether a single character is a digit or not, not a string. That's why the call isdigit(s) fails to compile.

You could use std::stoi. However, keep in mind that it will throw an exception if no conversion could be performed by the function.

try
{
   i = std::stoi(s);
}
catch ( ... )
{
   // Deal with the exception
}

You could also check whether the first character of the string is a digit before attempting to use std::stoi.

if ( !(s.empty()) && isdigit(s[0]) )
{
   i = std::stoi(s);
}

NB

From the comment by @RemyLebeau:

The above check because that does not guarantee that all characters in the string are digits. std::stoi() parses the entire string and then reports the index of the first non-digit character, even if that is the null terminator. It also skips leading whitespace, so checking the first character may cause a false result where std::stoi() would have normally succeeded.


问:
Finding characters within a string in C
I'm writing an algorithm in C with netbeans to find asterisks in a string.

```<code>int main() {
    int M=0, i, j;
    scanf("%i",&M);
    int pos[M];
    char c[M];
    scanf("%s", c);

    i=0;
    j=1;

    while(c[i] != '\0'){
        if(c[i]=='*'){
            pos[j] = i;
            j++;
        }
        i++;
    }

    printf("Asterisks in positions: \n\n");

    for(j=1; j<=i; j++){
        printf("%i", pos[j]);
    }
    return 0;
}
</code>```

But it doesn't work, it prints a lot of numbers even if M is a small number.

答:
The problem seems to be you never take into account the number of characters found. You print the whole vector, using i instead of j to iterate. It's j that holds the number of matches.

Also, try using strchr, from cstring :)

Get the first position, then search again from the next character until null is returned.

Title: Finding characters within a string in C

Body:
I'm writing an algorithm in C with netbeans to find asterisks in a string.

int main() {
    int M=0, i, j;
    scanf("%i",&M);
    int pos[M];
    char c[M];
    scanf("%s", c);

    i=0;
    j=1;

    while(c[i] != '\0'){
        if(c[i]=='*'){
            pos[j] = i;
            j++;
        }
        i++;
    }

    printf("Asterisks in positions: \n\n");

    for(j=1; j<=i; j++){
        printf("%i", pos[j]);
    }
    return 0;
}

But it doesn't work, it prints a lot of numbers even if M is a small number.


问:
Negative lookbehind in regex
(Note: not a duplicate of Why can't you use repetition quantifiers in zero-width look behind assertions; see end of post.)

I'm trying to write a grep -P (Perl) regex that matches B, when it is not preceded by A -- regardless of whether there is intervening whitespace.

So, I tried this negative lookbehind, and tested it in regex101.com:

```<code>(?<!A)\s*B
</code>```

This causes "AB" not to be matched, which is good, but "A B" does result in a match, which is not what I want.

I am not exactly sure why this is. It has something to do with the fact that \s* matches the empty string "", and you can say that there are, as such, infinity matches of \s* between A and B. But why does this affect "A B" but not "AB"?

Is the following regex a proper solution, and if so, why exactly does it fix the problem?

```<code>(?<![A\s])\s*B
</code>```

I posted this before and it was incorrectly marked as a duplicate question. The variable-length thing I'm looking for is part of the match, not part of the negative lookbehind itself -- so this quite different from the other question. Yes, I could put the \s* inside the negative lookbehind, but I haven't done so (and doing so is not supported, as the other question explains). Also, I am particularly interested in why the alternate regex I post above works, since I know it works but I'm not exactly sure why. The other question did not help answer that.

答:
But why does this affect "A B" but not "AB"?

Regexes match at a position, which it is helpful to think of as being between characters. In "A B" there is a position (after the space and before the B) where (?<!A) succeeds (because there isn't an A immediately preceding; there's a space instead), and \s*B succeeds (\s* matches the empty string, and B matches B), so the entire pattern succeeds.

In "AB" there is no such position. The only place where \s*B can match (immediately before the B), is also immediately after the A, so (?<!A) cannot succeed. There are no positions that satisfy both, so the pattern as a whole can't succeed.

Is the following regex a proper solution, and if so, why exactly does it fix the problem?

(?<![A\s])\s*B

This works because (?<![A\s]) will not succeed immediately after an A or after a space. So now the lookbehind forbids any match position that has spaces before it. If there are any spaces before the B, they have to be consumed by the \s* portion of the pattern, and the match position must be before them. If that position also doesn't have an A before it, the lookbehind can succeed and the pattern as a whole can match.

This is a trick that's made possible by the fact that \s is a fixed-width pattern that matches at every position inside of a non-empty \s* match. It can't be extended to the general case of any pattern between the (non-)A and the B.

Title: Negative lookbehind in regex

Body:
(Note: not a duplicate of Why can't you use repetition quantifiers in zero-width look behind assertions; see end of post.)

I'm trying to write a grep -P (Perl) regex that matches B, when it is not preceded by A -- regardless of whether there is intervening whitespace.

So, I tried this negative lookbehind, and tested it in regex101.com:

(?<!A)\s*B

This causes "AB" not to be matched, which is good, but "A B" does result in a match, which is not what I want.

I am not exactly sure why this is. It has something to do with the fact that \s* matches the empty string "", and you can say that there are, as such, infinity matches of \s* between A and B. But why does this affect "A B" but not "AB"?

Is the following regex a proper solution, and if so, why exactly does it fix the problem?

(?<![A\s])\s*B

I posted this before and it was incorrectly marked as a duplicate question. The variable-length thing I'm looking for is part of the match, not part of the negative lookbehind itself -- so this quite different from the other question. Yes, I could put the \s* inside the negative lookbehind, but I haven't done so (and doing so is not supported, as the other question explains). Also, I am particularly interested in why the alternate regex I post above works, since I know it works but I'm not exactly sure why. The other question did not help answer that.


问:
the authType parameter in CredentialCache.Add Method
what is the authType in CredentialCache.Add Method ?
http://msdn.microsoft.com/en-us/library/czdw7s9e.aspx
I do not understand what should I pass to it based on the uRi that I am passing to this Add method.  and my uRi is actually an asmx page address</p>

答:
I looked at the other Overload of the CredentialCache.Add() Method:

```<code>CredentialCache.Add(String host, Int32 port, String authenticationType, NetworkCredential credential)
</code>```

The definition may be found here:
https://msdn.microsoft.com/en-us/library/59x2s2s6(v=vs.110).aspx

Here they call the string "authenticationType" (instead of "authType") and states:

The supported values for authType are "NTLM", "Digest", "Kerberos",
  and "Negotiate".

I find this confusing because "authType " and "authenticationType" appear to be used interchangeably.

It worked for my URL when I used "NTLM" and "Negotiate" for "authType" in the Method Overload you reference in your Question:

```<code>CredentialCache.Add(Uri uriPrefix, String authType, NetworkCredential cred)
</code>```

Body:
I looked at the other Overload of the CredentialCache.Add() Method:

CredentialCache.Add(String host, Int32 port, String authenticationType, NetworkCredential credential)

The definition may be found here:
https://msdn.microsoft.com/en-us/library/59x2s2s6(v=vs.110).aspx

Here they call the string "authenticationType" (instead of "authType") and states:

The supported values for authType are "NTLM", "Digest", "Kerberos",
  and "Negotiate".

I find this confusing because "authType " and "authenticationType" appear to be used interchangeably.

It worked for my URL when I used "NTLM" and "Negotiate" for "authType" in the Method Overload you reference in your Question:

CredentialCache.Add(Uri uriPrefix, String authType, NetworkCredential cred)