问:
memory leak using MBProgressHUD
I am using the MBProgressHUB, with variations on the code found here.

Some things about my code:

The code is in my App Delegate

A number of other classes call it

I'm using it with asynchronous NSURLConnection

I do not declare it: @property (nonatomic, retain) MBProgressHUD *HUD;

I do not: @synthesize HUD;

(and of course I do not release it in my dealloc)

I use it as follows:

```<code>- (void)setSearchingMode:(BOOL)isSearching {
    // when network action, toggle network indicator and activity indicator
    if (isSearching) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];

        //HUD.labelText = @"Connecting";
        [HUD show:YES];
    } else {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

        [HUD hide:YES];
        [HUD removeFromSuperview];
        [HUD release];
    }
}

- (void)setSearchingText:(NSString *)whatToSay {
    HUD.labelText = whatToSay;
}
</code>```

I am fairly sure that the code is causing a memory management problem somewhere. In my crash log, I get:

Exception Type:  EXC_BAD_ACCESS (SIGBUS)

Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000c

0   libobjc.A.dylib   0x000027d8 objc_msgSend + 16

1   My            0x00003120 -[MyAppDelegate setSearchingMode:] (MyAppDelegate.m:363)

2   My            0x00003458 -[MyAppDelegate connectionDidFinishLoading:] (MyAppDelegate.m:341)

3   Foundation        0x00032896 -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading] + 62

4   Foundation        0x00032818 _NSURLConnectionDidFinishLoading + 72

in connectionDidFinishLoading I call:

```<code>[self setSearchingMode:NO];
</code>```

I tried to do it by making property accessors for HUD, but was not able to get around the line "[MBProgressHUD alloc] initWithWindow" - and I don't want to keep on alloc'ing an ivar!

Thanks, if anyone can point me in a better direction here..

答:
If you happen to end up with the sequence of:

```<code>[self setSearchingMode:YES];
[self setSearchingMode:NO];
[self setSearchingMode:NO];
</code>```

That code will crash as described because of the dangling reference to HUD.  When you do [HUD release];, add HUD = nil; after that line.

It isn't a memory leak;  it is an over-release.  Or, more likely, a dangling reference.

(and of course I do not release it in
  my dealloc)

Why not? If you retain it, you better release it!

Title: memory leak using MBProgressHUD

Body:
I am using the MBProgressHUB, with variations on the code found here.

Some things about my code:

The code is in my App Delegate

A number of other classes call it

I'm using it with asynchronous NSURLConnection

I do not declare it: @property (nonatomic, retain) MBProgressHUD *HUD;

I do not: @synthesize HUD;

(and of course I do not release it in my dealloc)

I use it as follows:

- (void)setSearchingMode:(BOOL)isSearching {
    // when network action, toggle network indicator and activity indicator
    if (isSearching) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];

        //HUD.labelText = @"Connecting";
        [HUD show:YES];
    } else {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

        [HUD hide:YES];
        [HUD removeFromSuperview];
        [HUD release];
    }
}

- (void)setSearchingText:(NSString *)whatToSay {
    HUD.labelText = whatToSay;
}

I am fairly sure that the code is causing a memory management problem somewhere. In my crash log, I get:

Exception Type:  EXC_BAD_ACCESS (SIGBUS)

Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000c

0   libobjc.A.dylib   0x000027d8 objc_msgSend + 16

1   My            0x00003120 -[MyAppDelegate setSearchingMode:] (MyAppDelegate.m:363)

2   My            0x00003458 -[MyAppDelegate connectionDidFinishLoading:] (MyAppDelegate.m:341)

3   Foundation        0x00032896 -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading] + 62

4   Foundation        0x00032818 _NSURLConnectionDidFinishLoading + 72

in connectionDidFinishLoading I call:

[self setSearchingMode:NO];

I tried to do it by making property accessors for HUD, but was not able to get around the line "[MBProgressHUD alloc] initWithWindow" - and I don't want to keep on alloc'ing an ivar!

Thanks, if anyone can point me in a better direction here..

Body:
If you happen to end up with the sequence of:

[self setSearchingMode:YES];
[self setSearchingMode:NO];
[self setSearchingMode:NO];

That code will crash as described because of the dangling reference to HUD.  When you do [HUD release];, add HUD = nil; after that line.

It isn't a memory leak;  it is an over-release.  Or, more likely, a dangling reference.

(and of course I do not release it in
  my dealloc)

Why not? If you retain it, you better release it!


来源: stackexchange

问:
What is overlay network and how does DNS resolution work?
I cannot connect to external mongodb server from my docker swarm cluster.

As I understand this is because of cluster uses overlay network driver. Am I right?

If not, how does docker overlay driver works and how can I connect to external mongodb server from cluster?

答:
Q. How does the docker overlay driver work?

I would recommend this good reference for understanding docker swarm network overlay, and more globally, Docker's architecture.

This states that:

Docker uses embedded DNS to provide service discovery for containers running on a single Docker Engine and tasks running in a Docker Swarm. Docker Engine has an internal DNS server that provides name resolution to all of the containers on the host in user-defined bridge, overlay, and MACVLAN networks.

Each Docker container ( or task in Swarm mode) has a DNS resolver that forwards DNS queries to Docker Engine, which acts as a DNS server.

So, in multi-host docker swarm mode, with this example setup :

In this example there is a service of two containers called myservice. A second service (client) exists on the same network. The client executes two curl operations for docker.com and myservice.

These are the resulting actions:

DNS queries are initiated by client for docker.com and myservice.

The container's built-in resolver intercepts the DNS queries on 127.0.0.11:53 and sends them to Docker Engine's DNS server.

myservice resolves to the Virtual IP (VIP) of that service which is internally load balanced to the individual task IP addresses. Container names resolve as well, albeit directly to their IP addresses.

docker.com does not exist as a service name in the mynet network and so the request is forwarded to the configured default DNS server.

Back to your question:

How can I connect to an external mongodb server form cluster?

For your external mongodb (let's say you have a DNS for that mongodb.mydomain.com), you are in the same situation as the client in above architecture, wanting to connect to docker.com, except that you certainly don't wan't to expose that mongodb.mydomain.com to the entire web, so you may have declared it in your internal cluster DNS server.

Then, how to tell docker engine to use this internal DNS server to resolve mongodb.mydomain.com?

You have to indicate in your docker service task that you want to use an internal DNS server, like so:

```<code>docker service create \
--name myservice \
--network my-overlay-network \
--dns=10.0.0.2 \
myservice:latest
</code>```

The important thing here is --dns=10.0.0.2. This will tell the Docker engine to use the DNS server at 10.0.0.2:53 as default if it can not resolve the DNS name in the VIP.

Finally, when you say :

I cannot connect to external mongodb server from my docker swarm cluster. As I understand this is because of cluster uses overlay network driver. Am I right?

I would say no, as there is a built in method in docker engine to forward unknown DNS name coming from overlay network to the DNS server you want.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
Q. How does the docker overlay driver work?

I would recommend this good reference for understanding docker swarm network overlay, and more globally, Docker's architecture.

This states that:

Docker uses embedded DNS to provide service discovery for containers running on a single Docker Engine and tasks running in a Docker Swarm. Docker Engine has an internal DNS server that provides name resolution to all of the containers on the host in user-defined bridge, overlay, and MACVLAN networks.

Each Docker container ( or task in Swarm mode) has a DNS resolver that forwards DNS queries to Docker Engine, which acts as a DNS server.

So, in multi-host docker swarm mode, with this example setup :

In this example there is a service of two containers called myservice. A second service (client) exists on the same network. The client executes two curl operations for docker.com and myservice.

These are the resulting actions:

DNS queries are initiated by client for docker.com and myservice.

The container's built-in resolver intercepts the DNS queries on 127.0.0.11:53 and sends them to Docker Engine's DNS server.

myservice resolves to the Virtual IP (VIP) of that service which is internally load balanced to the individual task IP addresses. Container names resolve as well, albeit directly to their IP addresses.

docker.com does not exist as a service name in the mynet network and so the request is forwarded to the configured default DNS server.

Back to your question:

How can I connect to an external mongodb server form cluster?

For your external mongodb (let's say you have a DNS for that mongodb.mydomain.com), you are in the same situation as the client in above architecture, wanting to connect to docker.com, except that you certainly don't wan't to expose that mongodb.mydomain.com to the entire web, so you may have declared it in your internal cluster DNS server.

Then, how to tell docker engine to use this internal DNS server to resolve mongodb.mydomain.com?

You have to indicate in your docker service task that you want to use an internal DNS server, like so:

docker service create \
--name myservice \
--network my-overlay-network \
--dns=10.0.0.2 \
myservice:latest

The important thing here is --dns=10.0.0.2. This will tell the Docker engine to use the DNS server at 10.0.0.2:53 as default if it can not resolve the DNS name in the VIP.

Finally, when you say :

I cannot connect to external mongodb server from my docker swarm cluster. As I understand this is because of cluster uses overlay network driver. Am I right?

I would say no, as there is a built in method in docker engine to forward unknown DNS name coming from overlay network to the DNS server you want.

Hope this helps!

ContentLicense: CC BY-SA 4.0


问:
How to call ngOnInit() again in Angular 2?
Please explain in this code, how to call ngOnInit() again when I call another method?

ngOnInit(): void {
  this.route.params.subscribe((params: Params) => {
    this.model = this.userData;
  });
}

update() {
  this.loading = true;
  this.userService.update(this.model).subscribe(
    (data) => {
      alert('Update successful');
    },
    (error) => {
      alert('Not updated');
      this.loading = false;
    },
  );
  this.user_data();
}
```

答:
There are two options from my point of view:

Calling ngOnInit() from another function scope. But I would suggest to do not adopt this approach given ngOnInitis an angular core method that belongs to OnInit Interface.

    public ngOnInit() {
          this.route.params.subscribe((params: Params) => {
          this.model=this.userData;
      });
    }

    update() {
           this.ngOnInit();
    }
```
<blockquote>
<p>Break your functionality into another function, use <code>ngOnInit</code>to call it and, afterwards, any  request can be made from anywhere by calling the function in the following manner: <code>this.<MethodName>();</code>.</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>    public ngOnInit() {
          this.getRouteData();
    }

    update() {
           this.getRouteData();
    }

    getRouteData() {
      this.route.params.subscribe((params: Params) => {
          this.model=this.userData;
      });
    }
</code>```

Body:
There are two options from my point of view:

Calling ngOnInit() from another function scope. But I would suggest to do not adopt this approach given ngOnInitis an angular core method that belongs to OnInit Interface.

    public ngOnInit() {
          this.route.params.subscribe((params: Params) => {
          this.model=this.userData;
      });
    }

    update() {
           this.ngOnInit();
    }

Break your functionality into another function, use ngOnInitto call it and, afterwards, any  request can be made from anywhere by calling the function in the following manner: this.<MethodName>();.

    public ngOnInit() {
          this.getRouteData();
    }

    update() {
           this.getRouteData();
    }

    getRouteData() {
      this.route.params.subscribe((params: Params) => {
          this.model=this.userData;
      });
    }


问:
JavaFX TableView: remove/disable scollbars from the table(using a ScrollPane instead)
I have two tables, of which I would like to connect the scrollbars, so they can be scrolled simultaneously. As far as I know the binding of the TableViews own scrollbars is not possible(correct me if I´m wrong), so i decided to wrap each TableView in a ScrollPane.

However the scrolling of the table is still set to the TableView own scrollbars.

Beneath is a basic code example. As you can see, the bidirectional binding of the ScrollPane scrollbars works. However the data in the table is uneffected by this, due to the problem I described above(main control is TableViews own Scrollbar).

Can someone help me out on this? I would like to move through the TableView with the ScrollPane scrollbars, instead of using TableViews scrollbars(since I can´t bind them).

```<code>public class Main extends Application {
    private TableView<Person> table = new TableView<>();
    private TableView<Person> table2 = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList(
                    new Person("Jacob", "Smith"),
                    new Person("Isabella", "Johnson"),
                    new Person("Ethan", "Williams"),
                    new Person("Emma", "Jones"),
                    new Person("Michael", "Brown")
            );

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(300);
        stage.setHeight(1000);

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setPrefWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setPrefWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        table2.setItems(data);
        table2.getColumns().addAll(firstNameCol, lastNameCol);

        ScrollPane sp = new ScrollPane(table);
        sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        ScrollPane sp2 = new ScrollPane(table2);
        sp2.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp2.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        sp.setHmax(3);
        sp2.setHmax(3);
        sp.hvalueProperty().bindBidirectional(sp2.hvalueProperty());

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(sp, sp2);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }
    }
}
</code>```

答:
it is possible to bind the scrollbars this way :

```<code>void bindScrollBars(TableView<?> firstTable, TableView<?> secondTable, Orienatation orieantation){
    ScrollBar firstScrollBar = null;
    ScrollBar secondScrollBar = null;

    for (Node node : firstTable.lookupAll(".scroll-bar")) {
            if (node instanceof ScrollBar && ((ScrollBar) node).getOrientation().equals(orientation)) {
                firstScrollBar= (ScrollBar) node;
            }
    }

    for (Node node : secondTable.lookupAll(".scroll-bar")) {
            if (node instanceof ScrollBar && ((ScrollBar) node).getOrientation().equals(orientation)) {
               secondScrollBar = (ScrollBar) node;
            }
     }

    if(firstScrollBar != null && secondScrollBar != null) { firstScrollBar.valueProperty().bindBidirectional(secondScrollBar.valueProperty()); }
</code>```

For me it works fine, and you can bind it both horizontally and vertically.

Body:
I have two tables, of which I would like to connect the scrollbars, so they can be scrolled simultaneously. As far as I know the binding of the TableViews own scrollbars is not possible(correct me if I´m wrong), so i decided to wrap each TableView in a ScrollPane.

However the scrolling of the table is still set to the TableView own scrollbars.

Beneath is a basic code example. As you can see, the bidirectional binding of the ScrollPane scrollbars works. However the data in the table is uneffected by this, due to the problem I described above(main control is TableViews own Scrollbar).

Can someone help me out on this? I would like to move through the TableView with the ScrollPane scrollbars, instead of using TableViews scrollbars(since I can´t bind them).

public class Main extends Application {
    private TableView<Person> table = new TableView<>();
    private TableView<Person> table2 = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList(
                    new Person("Jacob", "Smith"),
                    new Person("Isabella", "Johnson"),
                    new Person("Ethan", "Williams"),
                    new Person("Emma", "Jones"),
                    new Person("Michael", "Brown")
            );

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(300);
        stage.setHeight(1000);

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setPrefWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setPrefWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        table2.setItems(data);
        table2.getColumns().addAll(firstNameCol, lastNameCol);

        ScrollPane sp = new ScrollPane(table);
        sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        ScrollPane sp2 = new ScrollPane(table2);
        sp2.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp2.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        sp.setHmax(3);
        sp2.setHmax(3);
        sp.hvalueProperty().bindBidirectional(sp2.hvalueProperty());

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(sp, sp2);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }
    }
}

Body:
it is possible to bind the scrollbars this way :

void bindScrollBars(TableView<?> firstTable, TableView<?> secondTable, Orienatation orieantation){
    ScrollBar firstScrollBar = null;
    ScrollBar secondScrollBar = null;

    for (Node node : firstTable.lookupAll(".scroll-bar")) {
            if (node instanceof ScrollBar && ((ScrollBar) node).getOrientation().equals(orientation)) {
                firstScrollBar= (ScrollBar) node;
            }
    }

    for (Node node : secondTable.lookupAll(".scroll-bar")) {
            if (node instanceof ScrollBar && ((ScrollBar) node).getOrientation().equals(orientation)) {
               secondScrollBar = (ScrollBar) node;
            }
     }

    if(firstScrollBar != null && secondScrollBar != null) { firstScrollBar.valueProperty().bindBidirectional(secondScrollBar.valueProperty()); }

For me it works fine, and you can bind it both horizontally and vertically.


问:
Safari (in-app) browser breaking website rendering
I have some issues with the browser safari(in-app).
I have a website http://www.instylebuzz.com working perfectly.
Somehow I see very different versions of my website when I open it within in-app browser (specifically FB)

When I say different versions, it means depending on the browser version (or maybe the app version), the website style is looking different.
It is right I have a lot of differences between my mobile, tablet, and desktop version, but nevertheless, I should not see broken style,
because the three of them are styled ok.

So, my questions is simple, how can I effectively target in-app browser, knowing the user agent can change per app version/browser/os version?
How can I fix my website rendering on in-app Browser.

I'm searching days and nights for this solution,
it would be very kind if someone know/can help with my problem.

Thanks,

Simon

PS: for purposes, you should check a post rendering on the website, not a category or homepage.

答:
I know this has been some time since this thread.
But if someone encounters the problem, here is the solution.

Because the safari (in-app) and Safari classic on iOS have different default browser styles, if you see some css issues, it is because each browser interpret your css in a different way, and sometimes it might not be the result you expected.

Therefore, you can use:
Meyer Reset CSS, but you will probably have some work to do on your CSS to make everything good again. https://meyerweb.com/eric/tools/css/reset/

User normalize.css https://necolas.github.io/normalize.css/


问:
The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation
i tried to install pod on ios project but getting this errors
diff: /Podfile.lock: No such file or directory
diff: /Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation .
please suggest me something.</p>

答: Try running pod install from the project directory. Error "Podfile.lock: No such file or directory" means you're running it from inappropriate location.


问:
Settype integer changing the value in php
I have a field in my database called time. It contains UNIX timestamp. However the data type is a string and in php the date function expects an integer.

So i tried parsing the string to an integer but the value changes.

```<code>    $time = $value['time'];
    echo "Time string is $time<br/>";

    settype($time,'integer');
    echo "time intenger is".$time."<br/>";
</code>```

This is the output i get

Time string is 1499327190163

time intenger is2147483647

What am i doing wrong here? Or is there a better way to convert timestamp to a date? Thanks

EDIT : I just read the manual on settype and it said Maximum value for "int" is PHP_INT_MAX. Perhaps this could be my issue, would it be alright to change this, or should there be any security related concern in changing the max integer value?

答:
Javascript use 13 digits for unixtime, so you need to convert it 10 digits unixtime</p>

```<code><?php
$timeStr = "1499327190163";
$timeInt = (int) 1499327190163;
$timestamp = $timeInt / 1000;
$date = date("Y-m-d H:i:s", $timestamp);
echo $date;

$dateTime = new  \DateTime();
$dateTime->setTimestamp($timestamp);
echo $dateTime->format("Y-m-d H:i:s");
</code>```

Body:
I have a field in my database called time. It contains UNIX timestamp. However the data type is a string and in php the date function expects an integer.

So i tried parsing the string to an integer but the value changes.

    $time = $value['time'];
    echo "Time string is $time
";

    settype($time,'integer');
    echo "time intenger is".$time."
";

This is the output i get

Time string is 1499327190163

time intenger is2147483647

What am i doing wrong here? Or is there a better way to convert timestamp to a date? Thanks

EDIT : I just read the manual on settype and it said Maximum value for "int" is PHP_INT_MAX. Perhaps this could be my issue, would it be alright to change this, or should there be any security related concern in changing the max integer value?

Body:
Javascript use 13 digits for unixtime, so you need to convert it 10 digits unixtime

<?php
$timeStr = "1499327190163";
$timeInt = (int) 1499327190163;
$timestamp = $timeInt / 1000;
$date = date("Y-m-d H:i:s", $timestamp);
echo $date;

$dateTime = new  \DateTime();
$dateTime->setTimestamp($timestamp);
echo $dateTime->format("Y-m-d H:i:s");


问:
Why can't have I a pure virtual assignment operator?
I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:

```<code>class A {
public:
    virtual A &operator =(const A &a) = 0;
};

class B : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "B" << std::endl;
        return *this;
    }
};

class C : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "C" << std::endl;
        return *this;
    }
};

int main(int argc, char *argv[])
{
    B b;
    C c;
    b = c;

    // leads to a linker error: undefined reference to `A::operator=(A const&)'
    //B b2;
    //b = b2;
}
</code>```

The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:

```<code>virtual A &operator =(const A &a) {
        std::cout << "A" << std::endl;
        return *this;
}
</code>```

I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?

答:
When you assign b = b2;, it tries to call B's default (implicit) assignment.
And the default assignment will invoke base class's default assignment, so it will eventually call A::operator=(const A &a), which is pure virtual.

And so you get the link error.

Body:
I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:

class A {
public:
    virtual A &operator =(const A &a) = 0;
};

class B : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "B" << std::endl;
        return *this;
    }
};

class C : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "C" << std::endl;
        return *this;
    }
};

int main(int argc, char *argv[])
{
    B b;
    C c;
    b = c;

    // leads to a linker error: undefined reference to `A::operator=(A const&)'
    //B b2;
    //b = b2;
}

The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:

virtual A &operator =(const A &a) {
        std::cout << "A" << std::endl;
        return *this;
}

I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?


问:
How to convert NSstring to Nsdate
I am getting response from service that

```<code>"created_at" = "Thu Jul 06 07:26:23 +0000 2017";
</code>```

i want to convert the string  into Nsdate  format
i do not know how to do it

答:
ObjectiveC implemetation

```<code>NSString *dateString = @"Thu Jul 06 07:26:23 +0000 2017";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date =[[NSDate alloc] init];

dateFormatter.dateFormat = @"EEE MMM DD hh:mm:ss Z yyyy";

date = [dateFormatter dateFromString: dateString]; //generates date from dateString
</code>```

Swift implementation goes below

```<code>let dateString = "Thu Jul 06 07:26:23 +0000 2017"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM DD hh:mm:ss Z yyyy"
dateFormatter.date(from: dateString) //"Jan 6, 2017, 12:56 PM"
</code>```

Title: How to convert NSstring to Nsdate

Body:
I am getting response from service that

"created_at" = "Thu Jul 06 07:26:23 +0000 2017";

i want to convert the string  into Nsdate  format
i do not know how to do it

Body:
ObjectiveC implemetation

NSString *dateString = @"Thu Jul 06 07:26:23 +0000 2017";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date =[[NSDate alloc] init];

dateFormatter.dateFormat = @"EEE MMM DD hh:mm:ss Z yyyy";

date = [dateFormatter dateFromString: dateString]; //generates date from dateString

Swift implementation goes below

let dateString = "Thu Jul 06 07:26:23 +0000 2017"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM DD hh:mm:ss Z yyyy"
dateFormatter.date(from: dateString) //"Jan 6, 2017, 12:56 PM"


问:
What does cell.layoutifneeded and cell.layoutSubviews and cell.setneedsdisplay method do in general?
What does cell.layoutIfNeeded() and cell.layoutSubviews() and cell.setNeedsDisplay() method do in general ?

答:
layoutSubviews

Lays out subviews. in short this method lets determine the size and position of any subviews, it also helps to get desired behaviour you want for your view if your have a subclass. Documentation here

2.layoutIfNeeded

Forces view to layout immediately,for example you have changed a constraints constant and to reflect the change you need to call layoutIfNeeded.(it can also be animated :P). Documentation here

setNeedsDisplay

Marks the view need to be redrawn in the next drawing cycle, when you call this method, system is notified that view's content is changed and it will be redrawn in next drawing cycle. Documentation here

Please consider reading documentation for better understanding


问:
Generate date range in between 2 dates
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

```<code>2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...
</code>```

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

```<code>;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]
</code>```

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

```<code>Select *
From (
    TheQuery
) as t1
</code>```

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

答:
You can use a recursive cte if you put it in a table valued function</p>

```<code>CREATE FUNCTION FnDateRange
(
    @startDate date,
    @endDate date
)
RETURNS @DateRange Table
(myDate date)
AS
begin
    with Dates_rte as
    (
        select @startDate myDate
        union all
        select cast(dateadd(day,1,myDate) as date)
        from Dates_rte
        where cast(dateadd(day,1,myDate) as date) <= @endDate
    )
    insert into @DateRange
    select * from Dates_rte option (maxrecursion 0)

    return
end
GO

select * from fnDateRange('2017-07-01','2017-07-06')
</code>```

Title: Generate date range in between 2 dates

Body:
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

Select *
From (
    TheQuery
) as t1

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

Body:
You can use a recursive cte if you put it in a table valued function

CREATE FUNCTION FnDateRange
(
    @startDate date,
    @endDate date
)
RETURNS @DateRange Table
(myDate date)
AS
begin
    with Dates_rte as
    (
        select @startDate myDate
        union all
        select cast(dateadd(day,1,myDate) as date)
        from Dates_rte
        where cast(dateadd(day,1,myDate) as date) <= @endDate
    )
    insert into @DateRange
    select * from Dates_rte option (maxrecursion 0)

    return
end
GO

select * from fnDateRange('2017-07-01','2017-07-06')


问:
Converting MSSQL 'FOR XML PATH' To Oracle
I have a Statement to fill a table on my MSSQL Database. It joins some values together seperated by a semicolon.

```<code>INSERT INTO XXAArcDocSWSB (ArcDocINr, SWorte)
SELECT A.ArcDocINr, B.SWorte FROM XXAArcDoc A
LEFT JOIN (
SELECT DISTINCT T2.ArcDocINr,
SUBSTRING(
    (
        SELECT ';' + T1.SWort  AS [text()]
        FROM (SELECT D.ArcDocINr, SW.SWort FROM XXAArcDoc D, XXAArcSW SW WHERE D.ArcDocINr = SW.ArcDocINr) T1
        WHERE T1.ArcDocINr = T2.ArcDocINr
        For XML PATH ('')
    ), 2, 255) [SWorte]
FROM (SELECT D.ArcDocINr, SW.SWort FROM XXAArcDoc D, XXAArcSW SW WHERE D.ArcDocINr = SW.ArcDocINr) T2
) B ON A.ArcDocINr = B.ArcDocINr
</code>```

I don't have enough Knowledge to convert this to Oracle. It should give me the same Output as from MSSQL.
Can someone help me?

EDIT:

Here is some sample data:

XXAArcDoc:

```<code>ArcDocINr | ...
----------|----------
1         |
2         |
3         |
.         |
.         |
.         |
</code>```

XXAArcSW:

```<code>ArcSWINr | ArcDocINr | SWort
---------|-----------|---------
6        | 1         | Müller
7        | 1         | 100
8        | 2         | 111111
9        | 2         | 13579
10       | 2         | 002
11       | 3         | TM-AH
</code>```

And here is my desired Output:

```<code>ArcDocINr | SWorte
----------|---------
1         | Müller;100
2         | 111111;13579;002
3         | TM-AH
</code>```

答:
Use LISTAGG:

```<code>SELECT ArcDocINr,
       LISTAGG(
          SWort,
          ';'
       ) WITHIN GROUP ( ORDER BY ArcSWINr ) AS SWorte
FROM   XXAArcSW
GROUP BY ArcDocINr;
</code>```

Update:

If you are inserting into the XXAArcDoc table using values from the XXAArcSW table then something like:

```<code>INSERT INTO XXAArcDoc ( ArcDocINr, SWorte )
SELECT ArcDocINr,
       LISTAGG( SWort, ';' ) WITHIN GROUP ( ORDER BY ArcSWINr )
FROM   XXAArcSW
GROUP BY ArcDocINr
</code>```

Body:
I have a Statement to fill a table on my MSSQL Database. It joins some values together seperated by a semicolon.

INSERT INTO XXAArcDocSWSB (ArcDocINr, SWorte)
SELECT A.ArcDocINr, B.SWorte FROM XXAArcDoc A
LEFT JOIN (
SELECT DISTINCT T2.ArcDocINr,
SUBSTRING(
    (
        SELECT ';' + T1.SWort  AS [text()]
        FROM (SELECT D.ArcDocINr, SW.SWort FROM XXAArcDoc D, XXAArcSW SW WHERE D.ArcDocINr = SW.ArcDocINr) T1
        WHERE T1.ArcDocINr = T2.ArcDocINr
        For XML PATH ('')
    ), 2, 255) [SWorte]
FROM (SELECT D.ArcDocINr, SW.SWort FROM XXAArcDoc D, XXAArcSW SW WHERE D.ArcDocINr = SW.ArcDocINr) T2
) B ON A.ArcDocINr = B.ArcDocINr

I don't have enough Knowledge to convert this to Oracle. It should give me the same Output as from MSSQL.
Can someone help me?

EDIT:

Here is some sample data:

XXAArcDoc:

ArcDocINr | ...
----------|----------
1         |
2         |
3         |
.         |
.         |
.         |

XXAArcSW:

ArcSWINr | ArcDocINr | SWort
---------|-----------|---------
6        | 1         | Müller
7        | 1         | 100
8        | 2         | 111111
9        | 2         | 13579
10       | 2         | 002
11       | 3         | TM-AH

And here is my desired Output:

ArcDocINr | SWorte
----------|---------
1         | Müller;100
2         | 111111;13579;002
3         | TM-AH

Body:
Use LISTAGG:

SELECT ArcDocINr,
       LISTAGG(
          SWort,
          ';'
       ) WITHIN GROUP ( ORDER BY ArcSWINr ) AS SWorte
FROM   XXAArcSW
GROUP BY ArcDocINr;

Update:

If you are inserting into the XXAArcDoc table using values from the XXAArcSW table then something like:

INSERT INTO XXAArcDoc ( ArcDocINr, SWorte )
SELECT ArcDocINr,
       LISTAGG( SWort, ';' ) WITHIN GROUP ( ORDER BY ArcSWINr )
FROM   XXAArcSW
GROUP BY ArcDocINr


问:
Why is my DialogFragment not showing the custom layout?
I want to show a DialogFragment with no title, buttons, etc.(i.e, none of what is included in a typical Dialog) but just a ProgressBar spinner on a plain background. For a rough idea, the background's width matches that of the parent and spinner lies at the center of it. For this, I have a custom layout as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <View
        android:id="@+id/search_progress_alpha_indicator"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        android:background="#00ffffff"/>

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        app:layout_constraintGuide_percent="0.20"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="126dp"
        tools:layout_editor_absoluteX="0dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline3"
        app:layout_constraintGuide_percent="0.80"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="378dp"
        tools:layout_editor_absoluteX="0dp" />

</android.support.constraint.ConstraintLayout>
</code>```

Here, View is the background on top of which the ProgressBar is supposed to spin.

But when I inflate this layout in the DialogFragment, it shows something completely different:

Here is the DialogFragment code:

```<code>public static class SearchIndicatorDialogFragment extends DialogFragment{

        public static String FRAGMENT_TAG = "searchIndDiaFragTag";

        private View alphaSearchIndicator;
        private ProgressBar progressBar;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

            View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, false);

            // Obtain the ProgressBar
            progressBar = (ProgressBar) dialogRootView.findViewById(R.id.search_tutors_progress_bar);

            // Obtain the Alpha search indicator
            alphaSearchIndicator = dialogRootView.findViewById(R.id.search_progress_alpha_indicator);

            return dialogRootView;
        }

        @Override
        public void onStop() {

            progressBar.setVisibility(View.GONE);

            alphaSearchIndicator.setBackgroundColor(0x00ffffff);

            super.onStop();
        }

        @Override
        public void onResume() {
            progressBar.setVisibility(View.VISIBLE);

            alphaSearchIndicator.setBackgroundColor(0xA6ffffff);

            super.onResume();
        }

    }
</code>```

Why is it not showing my custom layout as intended?

EDIT: As an additional note, The problem in my case is that the background View is supposed to be occupying 60% area of screen(height wise) and for this I have constrained it in between the Guidelines. This is something, I am unable to achieve with other answers to similar questions regarding DialogFragment. Moreover, I would like to know, why does a DialogFragment doesn't display the correct by default in general?

答:
Try changing

```<code>View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, false);
</code>```

to

```<code> View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, true);
</code>```

I suppose we are the ones responsible for attaching our layout file’s View to its root ViewGroup.

Body:
I want to show a DialogFragment with no title, buttons, etc.(i.e, none of what is included in a typical Dialog) but just a ProgressBar spinner on a plain background. For a rough idea, the background's width matches that of the parent and spinner lies at the center of it. For this, I have a custom layout as follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <View
        android:id="@+id/search_progress_alpha_indicator"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        android:background="#00ffffff"/>

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        app:layout_constraintGuide_percent="0.20"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="126dp"
        tools:layout_editor_absoluteX="0dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline3"
        app:layout_constraintGuide_percent="0.80"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="378dp"
        tools:layout_editor_absoluteX="0dp" />

</android.support.constraint.ConstraintLayout>

Here, View is the background on top of which the ProgressBar is supposed to spin.

But when I inflate this layout in the DialogFragment, it shows something completely different:

Here is the DialogFragment code:

public static class SearchIndicatorDialogFragment extends DialogFragment{

        public static String FRAGMENT_TAG = "searchIndDiaFragTag";

        private View alphaSearchIndicator;
        private ProgressBar progressBar;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

            View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, false);

            // Obtain the ProgressBar
            progressBar = (ProgressBar) dialogRootView.findViewById(R.id.search_tutors_progress_bar);

            // Obtain the Alpha search indicator
            alphaSearchIndicator = dialogRootView.findViewById(R.id.search_progress_alpha_indicator);

            return dialogRootView;
        }

        @Override
        public void onStop() {

            progressBar.setVisibility(View.GONE);

            alphaSearchIndicator.setBackgroundColor(0x00ffffff);

            super.onStop();
        }

        @Override
        public void onResume() {
            progressBar.setVisibility(View.VISIBLE);

            alphaSearchIndicator.setBackgroundColor(0xA6ffffff);

            super.onResume();
        }

    }

Why is it not showing my custom layout as intended?

EDIT: As an additional note, The problem in my case is that the background View is supposed to be occupying 60% area of screen(height wise) and for this I have constrained it in between the Guidelines. This is something, I am unable to achieve with other answers to similar questions regarding DialogFragment. Moreover, I would like to know, why does a DialogFragment doesn't display the correct by default in general?

Body:
Try changing

View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, false);

to

 View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, true);

I suppose we are the ones responsible for attaching our layout file’s View to its root ViewGroup.


问:
Typescript import index.ts is not a module
I am trying to import index.ts in a subfolder which has other imports. But I keep getting a typescript error.

full repo: https://github.com/Shavindra/webpack-react-sw

(5,32): error TS2306: File 'C:/../src/reducers/index.ts' is not a module.

I am not quite sure what I am doing wrong here. I am using TS 2.4.1. I've tried restarting the computer/VSCode but nothing seems to work :-|

```<code>// ./src/reducers/counter.reducer.ts
export const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

// ./src/reducers/index.ts
export * from './counter.reducer';

// ./src/app.ts
import * as React from 'react';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Counter } from './components/counter/counter.component';
import { counterReducer } from './reducers';

const store = createStore(counterReducer);
const rootEl = document.getElementById('root');

const render = () => ReactDOM.render(
    <Counter
        value={store.getState()}
        onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
        onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
    />,
    rootEl
);

render();
store.subscribe(render);

// tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "jsx":"react",
    "lib": [
      "webworker",
      "es6",
      "scripthost",
      "dom"
    ]
  },
  "files": [ "node_modules/@types/react-dom/index.d.ts", "node_modules/@types/react/index.d.ts", "typings/file-loader.d.ts"  ],
  "exclude": [
    "typings/browser.d.ts",
    "typings/browser",
    "node_modules"
  ]
}
</code>```

答:
Some ideas are:

reducers is a folder and tsc is trying to search for ./reducers/index.ts

reducers is a file and is not readable by tsc

recuders is a valid file but has a different export system. check UMD, systemjs, commonjs includes

You can include them via:

import counterReducer = require('./recuders');
import * as counterReducer from './recuders';

If you want to include a single module via import { mod } from 'file'; Be sure that you export this function, class or whatever you want in reducers.ts

I hope this ideas helped. let me know!

Can you please post your tsconfig.json to ensure everything is correctly setup?

Body:
I am trying to import index.ts in a subfolder which has other imports. But I keep getting a typescript error.

full repo: https://github.com/Shavindra/webpack-react-sw

(5,32): error TS2306: File 'C:/../src/reducers/index.ts' is not a module.

I am not quite sure what I am doing wrong here. I am using TS 2.4.1. I've tried restarting the computer/VSCode but nothing seems to work :-|

// ./src/reducers/counter.reducer.ts
export const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

// ./src/reducers/index.ts
export * from './counter.reducer';

// ./src/app.ts
import * as React from 'react';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Counter } from './components/counter/counter.component';
import { counterReducer } from './reducers';

const store = createStore(counterReducer);
const rootEl = document.getElementById('root');

const render = () => ReactDOM.render(
    <Counter
        value={store.getState()}
        onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
        onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
    />,
    rootEl
);

render();
store.subscribe(render);

// tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "jsx":"react",
    "lib": [
      "webworker",
      "es6",
      "scripthost",
      "dom"
    ]
  },
  "files": [ "node_modules/@types/react-dom/index.d.ts", "node_modules/@types/react/index.d.ts", "typings/file-loader.d.ts"  ],
  "exclude": [
    "typings/browser.d.ts",
    "typings/browser",
    "node_modules"
  ]
}


问:
/usr/sbin/apachectl: line 92: 10747 Segmentation fault: 11 $HTTPD "$@"
Cannot start apache on mac ox x 10.13.

/usr/sbin/apachectl: line 92: 10747 Segmentation fault: 11  $HTTPD "$@"

答:
I had the same problem after installing php7.

I have just commented LoadModule php5_module libexec/apache2/libphp5.so in the httpd.conf file and now all is working.


问:
convert date format to 'YYYYMMDD'
In Javascript, I have date string as shown below:

```<code>var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
</code>```

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

答:
A good function for doing that which I found and used it always.</p>

```<code>Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
</code>```

Title: convert date format to 'YYYYMMDD'

Body:
In Javascript, I have date string as shown below:

var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

Body:
A good function for doing that which I found and used it always.

Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();


问:
sql server sp_send_dbmail
I am using SQL Server's sp_send_dbmail stored procedure to send mail via the database.

But when I execute that procedure it's shutting down the db mail procedure. I tried to start it again by sysmail_start_sp. But it's again shutting down in 7-8 seconds.

I tried with the code below:

```<code>EXEC msdb..sp_send_dbmail @profile_name = 'Test',
@recipients = 'abc@gmail.com',
@subject = 'test mail',
@body_format = 'HTML',
@body = 'test mail',
@from_address = 'xyz@yahoo.com'
</code>```

When I tried to check the error log I found the below error:

Message:

The read on the database failed. Reason: The error description is
  'Whitespace is not allowed at this location.'.Data:
  System.Collections.ListDictionaryInternalTargetSite:
  Microsoft.SqlServer.Management.SqlIMail.Server.Objects.QueueItem
  GetQueueItemFromCommand(System.Data.SqlClient.SqlCommand)HelpLink:
  NULLSource: DatabaseMailEngineStackTrace
  Information===================

Also when I checked sql email log history I found this error:

Mail not queued. Database Mail is stopped. Use sysmail_start_sp to start Database
  Mail.

答:
Whenever you try to send Test mail from Database mail;  it throws below error message:

Msg 14641, Level 16, State 1, Procedure sp_send_dbmail,  Mail not
  queued. Database Mail is stopped. Use sysmail_start_sp to start
  Database Mail.

First of all  make sure that Service Broker Message Delivery in Databases is enabled by executing the following command in SSMS:

```<code>SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
</code>```

If the result of above query is 0, then activate the service broker.

Activating Service Broker allows messages to be delivered to the database. A Service Broker endpoint must be created to send and receive messages from outside of the instance.

To activate Service Broker in a database use the following command:

```<code>USE master ;
GO

ALTER DATABASE DatabaseName SET ENABLE_BROKER ;
GO
</code>```

If the Service Broker is enabled then confirm whether Database Mail is enabled or not by executing below queries in SQL Server Management Studio:

```<code>sp_configure 'show advanced', 1
GO

RECONFIGURE
GO

sp_configure
GO
</code>```

If the result set shows run_value as 1 then Database Mail is enabled.

If the Database Mail option is disabled then run the below queries to enable it:

```<code>sp_configure 'Database Mail XPs', 1;
GO

RECONFIGURE;
GO

sp_configure 'show advanced', 0;
GO

RECONFIGURE;
GO
</code>```

Once the Database Mail is enabled then to start Database Mail External Program use the below mentioned query on msdb database:

```<code>USE msdb ;
EXEC msdb.dbo.sysmail_start_sp;
</code>```

To confirm that Database Mail External Program is started, run the query mentioned below :

```<code>EXEC msdb.dbo.sysmail_help_status_sp;
</code>```

If the Database Mail external program is started then check the status of mail queue using below statement:

```<code>EXEC msdb.dbo.sysmail_help_queue_sp @queue_type = 'mail';
</code>```

Title: sql server sp_send_dbmail

Body:
I am using SQL Server's sp_send_dbmail stored procedure to send mail via the database.

But when I execute that procedure it's shutting down the db mail procedure. I tried to start it again by sysmail_start_sp. But it's again shutting down in 7-8 seconds.

I tried with the code below:

EXEC msdb..sp_send_dbmail @profile_name = 'Test',
@recipients = 'abc@gmail.com',
@subject = 'test mail',
@body_format = 'HTML',
@body = 'test mail',
@from_address = 'xyz@yahoo.com'

When I tried to check the error log I found the below error:

Message:

The read on the database failed. Reason: The error description is
  'Whitespace is not allowed at this location.'.Data:
  System.Collections.ListDictionaryInternalTargetSite:
  Microsoft.SqlServer.Management.SqlIMail.Server.Objects.QueueItem
  GetQueueItemFromCommand(System.Data.SqlClient.SqlCommand)HelpLink:
  NULLSource: DatabaseMailEngineStackTrace
  Information===================

Also when I checked sql email log history I found this error:

Mail not queued. Database Mail is stopped. Use sysmail_start_sp to start Database
  Mail.

Body:
Whenever you try to send Test mail from Database mail;  it throws below error message:

Msg 14641, Level 16, State 1, Procedure sp_send_dbmail,  Mail not
  queued. Database Mail is stopped. Use sysmail_start_sp to start
  Database Mail.

First of all  make sure that Service Broker Message Delivery in Databases is enabled by executing the following command in SSMS:

SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'

If the result of above query is 0, then activate the service broker.

Activating Service Broker allows messages to be delivered to the database. A Service Broker endpoint must be created to send and receive messages from outside of the instance.

To activate Service Broker in a database use the following command:

USE master ;
GO

ALTER DATABASE DatabaseName SET ENABLE_BROKER ;
GO

If the Service Broker is enabled then confirm whether Database Mail is enabled or not by executing below queries in SQL Server Management Studio:

sp_configure 'show advanced', 1
GO

RECONFIGURE
GO

sp_configure
GO

If the result set shows run_value as 1 then Database Mail is enabled.

If the Database Mail option is disabled then run the below queries to enable it:

sp_configure 'Database Mail XPs', 1;
GO

RECONFIGURE;
GO

sp_configure 'show advanced', 0;
GO

RECONFIGURE;
GO

Once the Database Mail is enabled then to start Database Mail External Program use the below mentioned query on msdb database:

USE msdb ;
EXEC msdb.dbo.sysmail_start_sp;

To confirm that Database Mail External Program is started, run the query mentioned below :

EXEC msdb.dbo.sysmail_help_status_sp;

If the Database Mail external program is started then check the status of mail queue using below statement:

EXEC msdb.dbo.sysmail_help_queue_sp @queue_type = 'mail';


问:
asp.net mvc 2 web application inside a Web site?
I have a Asp.Net Web Site deployed as a WebSite inside IIS 7.5.

http://localhost/WebSite

Then I have a second Asp.Net MVC 2 web application which is deployed as Sub Application inside the above WebSite. So the mvc aplication should work on the following Url.

http://localhost/WebSite/MvcApp/

The web site works fine but when I browse the mvc Url http://localhost/WebSite/MvcApp/

It gives following error.

HTTP Error 403.14 - Forbidden The Web
  server is configured to not list the
  contents of this directory.

UPDATE: I have got this working. The issue was that I was missing the Web.Config inside the Views folder in the Asp.Net MVC 2 application.

答: It sounds to me like the mvc routing module is not executing on your requests.  You might want to check to make sure that not only is the web.config in your base web application not loading a module to supersede the routing handler, but that the web.config for your mvc application is handling routing properly.  Take a look at this article for a rundown of the dependencies for routing and how it is configured internally within iis.</p>

ContentLicense: CC BY-SA 2.5


问:
Understanding function scopes when it comes to mutables
For some reasons, Python is able to access mutables in the scope of an inner function if the mutable is modified in-place (or is not modified at all).

The same does not apply to immutables, unless they are declared as nonlocal, see f7 and f8.

Modifying a mutable with any operator that does not modify the variale in-place causes an UnboundLocalError exception.

However, I could not find anything specific to this behaviour in the Python docs (or I was unable to identify this information).

What I've been looking at:

https://docs.python.org/3.6/tutorial/classes.html#python-scopes-and-namespaces
https://docs.python.org/3.6/reference/executionmodel.html#resolution-of-names

And what somehow made sense to me was:

When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.
  [...]

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.

I think this explains why f1 and f3 work, while f2 and f4 don't, however, I'm still confused as to why f6 does not work - after all the use of c[0] = c[0] happens before c = c.

So my question is:

Why does f6 not work? Is the later use of c = c somehow "shadowing" the outer scope?

If it is, where is this behaviour described in the docs?

I would really appreciate if you could back up your answer with a reference to an official documentation of the behaviour.

Here are some functions to reproduce my findings:

```<code>import inspect

def f1():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c[0] = c[0]
        return c
    return g
f1()()

def f2():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c = c # UnboundLocalError: local variable 'c' referenced before assignment
        return c
    return g
# f2()()

def f3():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c.append(1)
        return c
    return g
f3()()

def f4():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c = c[0] # UnboundLocalError: local variable 'c' referenced before assignment
        return c
    return g
# f4()()

def f5():
    c = [0]
    def g():
        nonlocal c
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c = c
        return c
    return g
f5()()

def f6():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c[0] = c[0] # UnboundLocalError: local variable 'c' referenced before assignment
        c = c
        return c
    return g
f6()()

def f7():
    c = 1
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c = c # UnboundLocalError: local variable 'c' referenced before assignment
        return c
    return g
# f7()()

def f8():
    c = 1
    def g():
        nonlocal c
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c = c
        return c
    return g
f8()()
</code>```

答:
You seem to have ignored a part of the documentation you quoted. Here is is with added emphasis:

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block.

In your example, the "code block" is the inner function and the "name binding operation" is the c = c assignment. It doesn't matter that the assignment is a no-op. When you do an assignment to the name c anywhere in the function (regardless of what value is assigned), the compiler will note that c is a local variable and so all uses of c (even those that occur earlier) will be treated as local references.

Body:
For some reasons, Python is able to access mutables in the scope of an inner function if the mutable is modified in-place (or is not modified at all).

The same does not apply to immutables, unless they are declared as nonlocal, see f7 and f8.

Modifying a mutable with any operator that does not modify the variale in-place causes an UnboundLocalError exception.

However, I could not find anything specific to this behaviour in the Python docs (or I was unable to identify this information).

What I've been looking at:

https://docs.python.org/3.6/tutorial/classes.html#python-scopes-and-namespaces
https://docs.python.org/3.6/reference/executionmodel.html#resolution-of-names

And what somehow made sense to me was:

When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.
  [...]

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.

I think this explains why f1 and f3 work, while f2 and f4 don't, however, I'm still confused as to why f6 does not work - after all the use of c[0] = c[0] happens before c = c.

So my question is:

Why does f6 not work? Is the later use of c = c somehow "shadowing" the outer scope?

If it is, where is this behaviour described in the docs?

I would really appreciate if you could back up your answer with a reference to an official documentation of the behaviour.

Here are some functions to reproduce my findings:

import inspect

def f1():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c[0] = c[0]
        return c
    return g
f1()()

def f2():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c = c # UnboundLocalError: local variable 'c' referenced before assignment
        return c
    return g
# f2()()

def f3():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c.append(1)
        return c
    return g
f3()()

def f4():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c = c[0] # UnboundLocalError: local variable 'c' referenced before assignment
        return c
    return g
# f4()()

def f5():
    c = [0]
    def g():
        nonlocal c
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c = c
        return c
    return g
f5()()

def f6():
    c = [0]
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c[0] = c[0] # UnboundLocalError: local variable 'c' referenced before assignment
        c = c
        return c
    return g
f6()()

def f7():
    c = 1
    def g():
        print(inspect.currentframe().f_code.co_freevars) # ()
        c = c # UnboundLocalError: local variable 'c' referenced before assignment
        return c
    return g
# f7()()

def f8():
    c = 1
    def g():
        nonlocal c
        print(inspect.currentframe().f_code.co_freevars) # ('c',)
        c = c
        return c
    return g
f8()()


问:
Parsing JSON and creating hashmap
I did a function that parse a JSON and create a hashmap to use my data in some operations. The problem that I found, is that my key is repeted several time and in a hashmap there is only one value per key. The way I want it to be, is like this example :

```<code>12345 : 5
12346 : 4
12346 : 3
</code>```

My function return this : { 12345 : 5 , 12346 : 3 }
So to resume, it overload the key with the last value founded.

In my case i need all this value, so I want to have a result like this :

Result =>

```<code>{ 12345 : 5 , 12346 : [4,3] }
</code>```

Objective : if I find another key, I should change the value into an array and not overload it.

Here is my function :

```<code>getFacingCount: function(iSceneGraph){
                var facingArray = {};
                if (iSceneGraph.children.length > 0){
                    for (var i = 0; i < iSceneGraph.children.length; i++){
                        facingArray = Object.assign(facingArray, this.getFacingCount(iSceneGraph.children[i]));
                    }
                }
                if (iSceneGraph.merch.type === "Facing"){
                    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
                }
                return facingArray;
            }
</code>```

答:
You are overriding the value here:

```<code>if (iSceneGraph.merch.type === "Facing"){
    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
}
</code>```

You need to change those to (based on what you want): First Solution

```<code>if (iSceneGraph.merch.type === "Facing" && (facingArray[iSceneGraph.merch.ean] == undefined || facingArray[iSceneGraph.merch.ean] == null)){
    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
} else if (iSceneGraph.merch.type === "Facing" && Array.isArray(facingArray[iSceneGraph.merch.ean])){
    facingArray[iSceneGraph.merch.ean].push(iSceneGraph.merch.hcount);
} else if (iSceneGraph.merch.type === "Facing") {
    facingArray[iSceneGraph.merch.ean] = [facingArray[iSceneGraph.merch.ean]];
    facingArray[iSceneGraph.merch.ean].push(iSceneGraph.merch.hcount);
}
</code>```

But in my opinion, I'd prefer that you have a consistent structure of hashmap data just like the comment from Jonas says, and your solution is going to be like this: Second Solution

```<code>if (iSceneGraph.merch.type === "Facing"){
    if (facingArray[iSceneGraph.merch.ean] == undefined || facingArray[iSceneGraph.merch.ean] == null) {
        facingArray[iSceneGraph.merch.ean] = [];
    }

    facingArray[iSceneGraph.merch.ean].push(iSceneGraph.merch.hcount);
}
</code>```

If you have a consistent structure of hashmap data, you will be able to handle the data way more easier. See my first solution, it has three condition while the second solution only need two condition. A consistent structure of data allows you to not thinking on the "how you should handle all of the possible types in the data".

----------- UPDATE -----------------

Answering your feedback, if you now want to push an array instead of an integer, you can change

```<code>// `positionList` is an array of integer
facingArray[iSceneGraph.merch.ean].push(positionList);
</code>```

into

```<code>facingArray[iSceneGraph.merch.ean] = facingArray[iSceneGraph.merch.ean].concat(positionList);
</code>```

The result will be in this format: { 12345: [1,2,3], 12346: [4,5,6,7,8,9] }

Title: Parsing JSON and creating hashmap

Body:
I did a function that parse a JSON and create a hashmap to use my data in some operations. The problem that I found, is that my key is repeted several time and in a hashmap there is only one value per key. The way I want it to be, is like this example :

12345 : 5
12346 : 4
12346 : 3

My function return this : { 12345 : 5 , 12346 : 3 }
So to resume, it overload the key with the last value founded.

In my case i need all this value, so I want to have a result like this :

Result =>

{ 12345 : 5 , 12346 : [4,3] }

Objective : if I find another key, I should change the value into an array and not overload it.

Here is my function :

getFacingCount: function(iSceneGraph){
                var facingArray = {};
                if (iSceneGraph.children.length > 0){
                    for (var i = 0; i < iSceneGraph.children.length; i++){
                        facingArray = Object.assign(facingArray, this.getFacingCount(iSceneGraph.children[i]));
                    }
                }
                if (iSceneGraph.merch.type === "Facing"){
                    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
                }
                return facingArray;
            }

Body:
You are overriding the value here:

if (iSceneGraph.merch.type === "Facing"){
    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
}

You need to change those to (based on what you want): First Solution

if (iSceneGraph.merch.type === "Facing" && (facingArray[iSceneGraph.merch.ean] == undefined || facingArray[iSceneGraph.merch.ean] == null)){
    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
} else if (iSceneGraph.merch.type === "Facing" && Array.isArray(facingArray[iSceneGraph.merch.ean])){
    facingArray[iSceneGraph.merch.ean].push(iSceneGraph.merch.hcount);
} else if (iSceneGraph.merch.type === "Facing") {
    facingArray[iSceneGraph.merch.ean] = [facingArray[iSceneGraph.merch.ean]];
    facingArray[iSceneGraph.merch.ean].push(iSceneGraph.merch.hcount);
}

But in my opinion, I'd prefer that you have a consistent structure of hashmap data just like the comment from Jonas says, and your solution is going to be like this: Second Solution

if (iSceneGraph.merch.type === "Facing"){
    if (facingArray[iSceneGraph.merch.ean] == undefined || facingArray[iSceneGraph.merch.ean] == null) {
        facingArray[iSceneGraph.merch.ean] = [];
    }

    facingArray[iSceneGraph.merch.ean].push(iSceneGraph.merch.hcount);
}

If you have a consistent structure of hashmap data, you will be able to handle the data way more easier. See my first solution, it has three condition while the second solution only need two condition. A consistent structure of data allows you to not thinking on the "how you should handle all of the possible types in the data".

----------- UPDATE -----------------

Answering your feedback, if you now want to push an array instead of an integer, you can change

// `positionList` is an array of integer
facingArray[iSceneGraph.merch.ean].push(positionList);

into

facingArray[iSceneGraph.merch.ean] = facingArray[iSceneGraph.merch.ean].concat(positionList);

The result will be in this format: { 12345: [1,2,3], 12346: [4,5,6,7,8,9] }


问:
Automapper from list of object
I have View Model and Class that I have to map.
This is my maping setting:

Mapper.CreateMap<ViewModels.objTest, clsTest>().ReverseMap();
```

<p>I have to map List of View model to my <code>clsTest</code>.</p>

<p>for now I'm using looping like this:</p>

<pre class="lang-cs prettyprint-override"><code>List<clsTest> objListResult = new List<clsTest>();
if (List<objTest> != null)
{
    foreach (var item in objTest)
    {
        objListResult.Add(Mapper.Map<objTest, clsTest>(item));
    }
}
</code>```

Its work fine, but is there anyway to map faster than this? Maybe is there any way mapping from List to List even my setting like above?

Thank you

答:
You can just call Map with the list...

```<code>List<objTest> objListResult = Mapper.Map<List<clsTest>, List<objTest>>(objTest);
</code>```

As you can see in documentation: http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays

Title: Automapper from list of object

Body:
I have View Model and Class that I have to map.
This is my maping setting:

Mapper.CreateMap<ViewModels.objTest, clsTest>().ReverseMap();

I have to map List of View model to my clsTest.

for now I'm using looping like this:

List<clsTest> objListResult = new List<clsTest>();
if (List<objTest> != null)
{
    foreach (var item in objTest)
    {
        objListResult.Add(Mapper.Map<objTest, clsTest>(item));
    }
}

Its work fine, but is there anyway to map faster than this? Maybe is there any way mapping from List to List even my setting like above?

Thank you

Body:
You can just call Map with the list...

List<objTest> objListResult = Mapper.Map<List<clsTest>, List<objTest>>(objTest);

As you can see in documentation: http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays


问:
Generate PDF and sent it through Email as Attachment (PDF is not opening)
I am generating pdf and sent it through email as attachment the code is given below for this i skipped some code for generating pdf (not needed).
Please check the code:

```<code>//pdf generated not given avobe code of how it comes
$pdfdoc = $pdf->Output("confirmation-".$client_code.".pdf", "S");

$attachment = chunk_split(base64_encode($pdfdoc));

$to = $mail_to;

$from        = "From: <info@ksilbd.com>";

$subject     = "Here is your attachment";

$mainMessage = "BUY/SALE CONFIRMATION";

$fileatt     = $attachment;

$fileatttype = "application/pdf";

$fileattname = "confirmation-".$client_code.".pdf";

$headers = "From: $from";

$file = fopen($fileatt, 'rb');

$data = fread($file, filesize($fileatt));

fclose($file);

$semi_rand     = md5(time());

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers      .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage  . "\n\n";
//base_64
//encoding used
//to encode data
$data = chunk_split(base64_encode($data));

//message
//concat the
//message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .

$data . "\n\n" .
"-{$mime_boundary}-\n";

 // Send the email
if(mail($to, $subject, $message, $headers)) {
    echo "EMAIL SENT SUCCESSFUL.";
}
else {
    echo "There was an error sending the mail.";
</code>```

The message showed email sent successful and i got email too but i failed to open the attached pdf file with the mail ....
please check the problem

答:
You may use "phpmailer".
Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer
and Enjoy it.</p>

Body:
I am generating pdf and sent it through email as attachment the code is given below for this i skipped some code for generating pdf (not needed).
Please check the code:

//pdf generated not given avobe code of how it comes
$pdfdoc = $pdf->Output("confirmation-".$client_code.".pdf", "S");

$attachment = chunk_split(base64_encode($pdfdoc));

$to = $mail_to;

$from        = "From: <info@ksilbd.com>";

$subject     = "Here is your attachment";

$mainMessage = "BUY/SALE CONFIRMATION";

$fileatt     = $attachment;

$fileatttype = "application/pdf";

$fileattname = "confirmation-".$client_code.".pdf";

$headers = "From: $from";

$file = fopen($fileatt, 'rb');

$data = fread($file, filesize($fileatt));

fclose($file);

$semi_rand     = md5(time());

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers      .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage  . "\n\n";
//base_64
//encoding used
//to encode data
$data = chunk_split(base64_encode($data));

//message
//concat the
//message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .

$data . "\n\n" .
"-{$mime_boundary}-\n";

 // Send the email
if(mail($to, $subject, $message, $headers)) {
    echo "EMAIL SENT SUCCESSFUL.";
}
else {
    echo "There was an error sending the mail.";

The message showed email sent successful and i got email too but i failed to open the attached pdf file with the mail ....
please check the problem


问:
How can i prevent to get next line in bootstrap panel right icon for the mobile view
here is the image of desktop and mobile version - here

But i want the print icon top right corner. I dont want it move next line.If screen size is reduced then i want like this.

code:

```<code><h5 id="name">
<span class="fa fa-graduation-cap"></span>
   Name of Company Name of the company
<span class="glyphicon glyphicon-print pull-right"></span>
</h5>
</code>```

答:
Try making it as this:</p>

```<code> <h5 id="name">
    <div class="col-xs-9">
        <span class="fa fa-graduation-cap"></span>
        Name of Company Name of the company
    </div>
    <div class="col-xs-3">
        <span class="glyphicon glyphicon-print pull-right"></span>
    </div>
</h5>
</code>```

Body:
here is the image of desktop and mobile version - here

But i want the print icon top right corner. I dont want it move next line.If screen size is reduced then i want like this.

code:

   Name of Company Name of the company

Body:
Try making it as this:

 <h5 id="name">
    <div class="col-xs-9">
        <span class="fa fa-graduation-cap"></span>
        Name of Company Name of the company
    </div>
    <div class="col-xs-3">
        <span class="glyphicon glyphicon-print pull-right"></span>
    </div>
</h5>


问:
JavaFX TableView: remove/disable scollbars from the table(using a ScrollPane instead)
I have two tables, of which I would like to connect the scrollbars, so they can be scrolled simultaneously. As far as I know the binding of the TableViews own scrollbars is not possible(correct me if I´m wrong), so i decided to wrap each TableView in a ScrollPane.

However the scrolling of the table is still set to the TableView own scrollbars.

Beneath is a basic code example. As you can see, the bidirectional binding of the ScrollPane scrollbars works. However the data in the table is uneffected by this, due to the problem I described above(main control is TableViews own Scrollbar).

Can someone help me out on this? I would like to move through the TableView with the ScrollPane scrollbars, instead of using TableViews scrollbars(since I can´t bind them).

```<code>public class Main extends Application {
    private TableView<Person> table = new TableView<>();
    private TableView<Person> table2 = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList(
                    new Person("Jacob", "Smith"),
                    new Person("Isabella", "Johnson"),
                    new Person("Ethan", "Williams"),
                    new Person("Emma", "Jones"),
                    new Person("Michael", "Brown")
            );

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(300);
        stage.setHeight(1000);

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setPrefWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setPrefWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        table2.setItems(data);
        table2.getColumns().addAll(firstNameCol, lastNameCol);

        ScrollPane sp = new ScrollPane(table);
        sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        ScrollPane sp2 = new ScrollPane(table2);
        sp2.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp2.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        sp.setHmax(3);
        sp2.setHmax(3);
        sp.hvalueProperty().bindBidirectional(sp2.hvalueProperty());

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(sp, sp2);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }
    }
}
</code>```

答:
Your first problem is that your VBox is not scaling correctly with the scene, which means that your ScrollPanes will never be smaller than their content. You can fix this by changing this:

```<code>((Group) scene.getRoot()).getChildren().addAll(vbox);
</code>```

to this:

```<code>Scene scene = new Scene(vbox);
</code>```

You will also have to remove your previous declaration at the beginning of start:

```<code>Scene scene = new Scene(new Group()); //Remove this line
</code>```

Now your ScrollPanes scale properly with your scene. However, you still need to bind their vvalues so that they match vertically. Add this line below where you bind their hvalues:

```<code>sp.hvalueProperty().bindBidirectional(sp2.hvalueProperty());
sp.vvalueProperty().bindBidirectional(sp2.vvalueProperty()); //Add this line
</code>```

Now your scrolling works properly:

Body:
I have two tables, of which I would like to connect the scrollbars, so they can be scrolled simultaneously. As far as I know the binding of the TableViews own scrollbars is not possible(correct me if I´m wrong), so i decided to wrap each TableView in a ScrollPane.

However the scrolling of the table is still set to the TableView own scrollbars.

Beneath is a basic code example. As you can see, the bidirectional binding of the ScrollPane scrollbars works. However the data in the table is uneffected by this, due to the problem I described above(main control is TableViews own Scrollbar).

Can someone help me out on this? I would like to move through the TableView with the ScrollPane scrollbars, instead of using TableViews scrollbars(since I can´t bind them).

public class Main extends Application {
    private TableView<Person> table = new TableView<>();
    private TableView<Person> table2 = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList(
                    new Person("Jacob", "Smith"),
                    new Person("Isabella", "Johnson"),
                    new Person("Ethan", "Williams"),
                    new Person("Emma", "Jones"),
                    new Person("Michael", "Brown")
            );

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(300);
        stage.setHeight(1000);

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setPrefWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setPrefWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        table2.setItems(data);
        table2.getColumns().addAll(firstNameCol, lastNameCol);

        ScrollPane sp = new ScrollPane(table);
        sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        ScrollPane sp2 = new ScrollPane(table2);
        sp2.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        sp2.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        sp.setHmax(3);
        sp2.setHmax(3);
        sp.hvalueProperty().bindBidirectional(sp2.hvalueProperty());

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(sp, sp2);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }
    }
}

Body:
Your first problem is that your VBox is not scaling correctly with the scene, which means that your ScrollPanes will never be smaller than their content. You can fix this by changing this:

((Group) scene.getRoot()).getChildren().addAll(vbox);

to this:

Scene scene = new Scene(vbox);

You will also have to remove your previous declaration at the beginning of start:

Scene scene = new Scene(new Group()); //Remove this line

Now your ScrollPanes scale properly with your scene. However, you still need to bind their vvalues so that they match vertically. Add this line below where you bind their hvalues:

sp.hvalueProperty().bindBidirectional(sp2.hvalueProperty());
sp.vvalueProperty().bindBidirectional(sp2.vvalueProperty()); //Add this line

Now your scrolling works properly:


问:
Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python?
I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986.

I get from the user a URL in UTF-8. So if they've typed in http://➡.ws/♥ I get 'http://\xe2\x9e\xa1.ws/\xe2\x99\xa5' in Python. And what I want out is the ASCII version: 'http://xn--hgi.ws/%E2%99%A5'.

What I do at the moment is split the URL up into parts via a regex, and then manually IDNA-encode the domain, and separately encode the path and query string with different urllib.quote() calls.

```<code># url is UTF-8 here, eg: url = u'http://➡.ws/㉌'.encode('utf-8')
match = re.match(r'([a-z]{3,5})://(.+\.[a-z0-9]{1,6})'
                 r'(:\d{1,5})?(/.*?)(\?.*)?$', url, flags=re.I)
if not match:
    raise BadURLException(url)
protocol, domain, port, path, query = match.groups()

try:
    domain = unicode(domain, 'utf-8')
except UnicodeDecodeError:
    return ''  # bad UTF-8 chars in domain
domain = domain.encode('idna')

if port is None:
    port = ''

path = urllib.quote(path)

if query is None:
    query = ''
else:
    query = urllib.quote(query, safe='=&?/')

url = protocol + '://' + domain + port + path + query
# url is ASCII here, eg: url = 'http://xn--hgi.ws/%E3%89%8C'
</code>```

Is this correct? Any better suggestions? Is there a simple standard-library function to do this?

答:
the code given by MizardX isnt 100% correct. This example wont work:

example.com/folder/?page=2

check out django.utils.encoding.iri_to_uri() to convert unicode URL to ASCII urls.

http://docs.djangoproject.com/en/dev/ref/unicode/

Body:
I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986.

I get from the user a URL in UTF-8. So if they've typed in http://➡.ws/♥ I get 'http://\xe2\x9e\xa1.ws/\xe2\x99\xa5' in Python. And what I want out is the ASCII version: 'http://xn--hgi.ws/%E2%99%A5'.

What I do at the moment is split the URL up into parts via a regex, and then manually IDNA-encode the domain, and separately encode the path and query string with different urllib.quote() calls.

# url is UTF-8 here, eg: url = u'http://➡.ws/㉌'.encode('utf-8')
match = re.match(r'([a-z]{3,5})://(.+\.[a-z0-9]{1,6})'
                 r'(:\d{1,5})?(/.*?)(\?.*)?$', url, flags=re.I)
if not match:
    raise BadURLException(url)
protocol, domain, port, path, query = match.groups()

try:
    domain = unicode(domain, 'utf-8')
except UnicodeDecodeError:
    return ''  # bad UTF-8 chars in domain
domain = domain.encode('idna')

if port is None:
    port = ''

path = urllib.quote(path)

if query is None:
    query = ''
else:
    query = urllib.quote(query, safe='=&?/')

url = protocol + '://' + domain + port + path + query
# url is ASCII here, eg: url = 'http://xn--hgi.ws/%E3%89%8C'

Is this correct? Any better suggestions? Is there a simple standard-library function to do this?