问:
How to pass a (*args,**kwargs) type of attribute to a function within class?
I want to create a module for a custom plot drawing for my scientific data, but I do not know how to pass an argument of type (*arg2,**kwarg2) to a method.

Here is the relevant code:

```<code>import numpy as np
import matplotlib.pyplot as plt

# class of figures for channel flow
# with one subfigure

class Homfig:

    # *args: list of plot features for ax1.plot
    #     (xdata,ydata,str linetype,str label)
    # **kwargs: list of axes features for ax1.set_$(STH)
    #     possible keys:
    #     title,xlabel,ylabel,xlim,ylim,xscale,yscale

    def __init__(self,*args,**kwargs):
        self.args = args
        self.kwargs = kwargs
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        for key, val in self.kwargs.iteritems():
            getattr(self.ax,'set_'+key)(val)

    def hdraw(self):
        for arg in self.args:
            self.ax.plot(*arg)
            leg = self.ax.legend(loc=4)
</code>```

The problem is that arg is itself a tuple like (*agr2,**kwarg2) and when I call
    self.ax.plot(*arg)
it does not see named variables.
Function hdraw should operate on the input it got in *args from init, and data for plot lines are passed in arg.
How can I express that arg consists of unnamed and named variables?
self.ax.plot may be called more then once, when I want to have several lines (with different label, linetype, etc., in one plot.)

I call the module from other python script with:

```<code>meanfig = hfig.Homfig((datax,datay),title='test plot')
meanfig.hdraw()
</code>```

How can I add features like label or linetype to the self.ax.plot, for example:

```<code>meanfig = hfig.Homfig((datax,datay,label="test_label",linetype ='o'),title='test plot')
</code>```

答:
You should be able to pass them using double **, i.e.

```<code>def hdraw(self):
    self.ax.plot(*self.args, **self.kwargs)
    leg = self.ax.legend(loc=4)
</code>```

and then call it using

```<code>meanfig = hfig.Homfig(datax, datay, label="test_label", linetype ='o', title='test plot')
</code>```

Update according to comment:

If you want to draw multiple plots in the same figure, that will be hard in the way you wrote, but you could do it like this

```<code>class Homfig:
    def __init__(self, title):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        self.args = []
        self.kwargs = []

    def add_plot(self, *args, **kwargs):
        self.args.append(args)
        self.kwargs.append(kwargs)

    def hdraw(self):
        for args, kwargs in zip(self.args, self.kwargs):
            self.ax.plot(*args, **kwargs)
        leg = self.ax.legend(loc=4)
</code>```

and then call it using

```<code>meanfig = hfig.Homfig(title='test plot')
meanfig.add_plot(datax, datay, label="test_label", linetype ='o')
meanfig.add_plot(datax, 2 * datay, label="test_label_2", linetype ='o')
meanfig.hdraw()
</code>```

Body:
I want to create a module for a custom plot drawing for my scientific data, but I do not know how to pass an argument of type (*arg2,**kwarg2) to a method.

Here is the relevant code:

import numpy as np
import matplotlib.pyplot as plt

# class of figures for channel flow
# with one subfigure

class Homfig:

    # *args: list of plot features for ax1.plot
    #     (xdata,ydata,str linetype,str label)
    # **kwargs: list of axes features for ax1.set_$(STH)
    #     possible keys:
    #     title,xlabel,ylabel,xlim,ylim,xscale,yscale

    def __init__(self,*args,**kwargs):
        self.args = args
        self.kwargs = kwargs
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        for key, val in self.kwargs.iteritems():
            getattr(self.ax,'set_'+key)(val)

    def hdraw(self):
        for arg in self.args:
            self.ax.plot(*arg)
            leg = self.ax.legend(loc=4)

The problem is that arg is itself a tuple like (*agr2,**kwarg2) and when I call
    self.ax.plot(*arg)
it does not see named variables.
Function hdraw should operate on the input it got in *args from init, and data for plot lines are passed in arg.
How can I express that arg consists of unnamed and named variables?
self.ax.plot may be called more then once, when I want to have several lines (with different label, linetype, etc., in one plot.)

I call the module from other python script with:

meanfig = hfig.Homfig((datax,datay),title='test plot')
meanfig.hdraw()

How can I add features like label or linetype to the self.ax.plot, for example:

meanfig = hfig.Homfig((datax,datay,label="test_label",linetype ='o'),title='test plot')

Body:
You should be able to pass them using double **, i.e.

def hdraw(self):
    self.ax.plot(*self.args, **self.kwargs)
    leg = self.ax.legend(loc=4)

and then call it using

meanfig = hfig.Homfig(datax, datay, label="test_label", linetype ='o', title='test plot')

Update according to comment:

If you want to draw multiple plots in the same figure, that will be hard in the way you wrote, but you could do it like this

class Homfig:
    def __init__(self, title):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        self.args = []
        self.kwargs = []

    def add_plot(self, *args, **kwargs):
        self.args.append(args)
        self.kwargs.append(kwargs)

    def hdraw(self):
        for args, kwargs in zip(self.args, self.kwargs):
            self.ax.plot(*args, **kwargs)
        leg = self.ax.legend(loc=4)

and then call it using

meanfig = hfig.Homfig(title='test plot')
meanfig.add_plot(datax, datay, label="test_label", linetype ='o')
meanfig.add_plot(datax, 2 * datay, label="test_label_2", linetype ='o')
meanfig.hdraw()


来源: stackexchange

问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答:
Switch can be optimized "Better" by some compilers. There are pitfalls with using the switch statement in certain languages. In Java, the  switch cannot handle strings and in VB2005 the switch statement will not work with radio buttons.<br>
Switch can be faster and easier to read, If-Then is more generic and will work in more places. </p>

OwnerDisplayName: Casey

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Casey

Body:
Switch can be optimized "Better" by some compilers. There are pitfalls with using the switch statement in certain languages. In Java, the  switch cannot handle strings and in VB2005 the switch statement will not work with radio buttons.

Switch can be faster and easier to read, If-Then is more generic and will work in more places.

OwnerDisplayName: WolfmanDragon

ContentLicense: CC BY-SA 2.5


问:
In Objective-C, how can I change the property of an instance inside of class via UIControl?
This question is about the exercise 6.9 of iOS Programming 4th Edition.
I have a class that can draw concentric circles and respond to touches by changing its color randomly.

Here is the implementation of the view:

```<code>@implementation LTHypnosisView
- (instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = [UIColor clearColor];
        self.circleColor = [UIColor lightGrayColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    //Draw the circles
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    float red = (arc4random() % 100) /100.0;
    float green = (arc4random() % 100) /100.0;
    float blue = (arc4random() % 100) /100.0;
    UIColor *randomColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    self.circleColor = randomColor;
}

- (void) setCircleColor:(UIColor *)circleColor{
    _circleColor = circleColor;
    [self setNeedsDisplay];
}
@end
</code>```

Here is the implementation of the viewController:

```<code>@implementation LTHypnosisViewController
- (void) viewDidLoad{
    CGRect screenRect = self.view.bounds;
    LTHypnosisView *mainView = [[LTHypnosisView alloc] initWithFrame:screenRect];
    [self addSubview:mainView]
    NSArray *items = @[@"Red",@"Green",@"Blue"];
    UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:items];
    [segControl addTarget:self
                   action:@selector(change:)
         forControlEvents:UIControlEventValueChanged];
    segControl.frame = CGRectMake(10, 50, self.view.bounds.size.width-20, 60);
    segControl.selectedSegmentIndex = 0;
    segControl.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:segControl];
}

- (void) change:(UISegmentedControl*)sender{
    switch (sender.selectedSegmentIndex) {
        //How should I write here??
    }
}

@end
</code>```

I want to change the color of the concentric circles with the UISegmentedControl. Consequently I need a method within the viewController to change the _circleColor property of the LTHypnosisView instance. How can I do that?

答:
A simple way, I'd make LTHypnosisView *mainView a property of the view controller, make setCircleColor public, and then in change: method call [self.mainView setCircleColor:myColor];

You could also do something more involved, like define a protocol on LTHypnosisView and set the view controller as the datasource.  Whenever the change: method is called, call something like [mainView updateColor] and within updateColor have it read the color from it's datasource.

Body:
This question is about the exercise 6.9 of iOS Programming 4th Edition.
I have a class that can draw concentric circles and respond to touches by changing its color randomly.

Here is the implementation of the view:

@implementation LTHypnosisView
- (instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = [UIColor clearColor];
        self.circleColor = [UIColor lightGrayColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    //Draw the circles
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    float red = (arc4random() % 100) /100.0;
    float green = (arc4random() % 100) /100.0;
    float blue = (arc4random() % 100) /100.0;
    UIColor *randomColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    self.circleColor = randomColor;
}

- (void) setCircleColor:(UIColor *)circleColor{
    _circleColor = circleColor;
    [self setNeedsDisplay];
}
@end

Here is the implementation of the viewController:

@implementation LTHypnosisViewController
- (void) viewDidLoad{
    CGRect screenRect = self.view.bounds;
    LTHypnosisView *mainView = [[LTHypnosisView alloc] initWithFrame:screenRect];
    [self addSubview:mainView]
    NSArray *items = @[@"Red",@"Green",@"Blue"];
    UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:items];
    [segControl addTarget:self
                   action:@selector(change:)
         forControlEvents:UIControlEventValueChanged];
    segControl.frame = CGRectMake(10, 50, self.view.bounds.size.width-20, 60);
    segControl.selectedSegmentIndex = 0;
    segControl.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:segControl];
}

- (void) change:(UISegmentedControl*)sender{
    switch (sender.selectedSegmentIndex) {
        //How should I write here??
    }
}

@end

I want to change the color of the concentric circles with the UISegmentedControl. Consequently I need a method within the viewController to change the _circleColor property of the LTHypnosisView instance. How can I do that?


问:
Regular expression for "not in a list of values" without negative lookahead
I want to search for a string that doesn't exist in a list of strings by using regex. Is it possible to make a regex for that case without using negative lookahead?

答: Just use the regular expression for "in a list of values", and return False if there's a match.


问:
T-sql :get SUM of Columns
I have a table that looks something like the following :

```<code>          W1  W2 w3
Gold      10    2    3
Silver     3    1    1
</code>```

but i need a result :

```<code>          W1  W2  w3
Gold      10  12  15
Silver     3  4  5
</code>```

Is there any way i can get that result?

My sql query :

```<code>SELECT
   week1=[1],week2=[2],week3=[3]
FROM
(
    SELECT
    [week]=DATEPART(ISO_WEEK,ta.enddate),ta.id
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(id) FOR week IN (
        [1],[2],[3])
) piv
</code>```

答:
Does this do what you want?

```<code>select t.??, t.w1, (t.w1 + t.w2) as w2, (t.w1 + t.w2 + t.w3) as w3
from table1 t;
</code>```

I don't know what the name of the first column is, so I just used ??.

Title: T-sql :get SUM of Columns

Body:
I have a table that looks something like the following :

          W1  W2 w3
Gold      10    2    3
Silver     3    1    1

but i need a result :

          W1  W2  w3
Gold      10  12  15
Silver     3  4  5

Is there any way i can get that result?

My sql query :

SELECT
   week1=[1],week2=[2],week3=[3]
FROM
(
    SELECT
    [week]=DATEPART(ISO_WEEK,ta.enddate),ta.id
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(id) FOR week IN (
        [1],[2],[3])
) piv

Body:
Does this do what you want?

select t.??, t.w1, (t.w1 + t.w2) as w2, (t.w1 + t.w2 + t.w3) as w3
from table1 t;

I don't know what the name of the first column is, so I just used ??.


问:
WebException Could not establish trust relationship for the SSL/TLS secure channel
My company has developed a .NET web service and a client dll that uses that web service. The webservice is hosted on our server over ssl and the cert is provided and signed by GoDaddy.  We have some clients in a hosted environment that are getting the following error message from the client dll when it tries to access our web service.

System.Net.WebException The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Our fix has been to have them open IE on the server, which is a challenge in and of itself for a lot of the hosted services, and go to the WSDL url. IE then prompts them with a security alert dialog. It says the cert date is valid and a valid name matching the name of the page, but was issued by a company you have not chosen to trust. When they click Yes to proceed, the client dll can then succesfully connect to the web service and operate as normal.

Does anyone have any idea why GoDaddy would not have been in there valid publishers list? All of the servers we have running has GoDaddy as a valid authority. I'm guessing, for security reasons, they've uninstalled the authority for GoDaddy, but not totally convinced that there's not some other underlying issue.

Unfortunately, I haven't had much luck trying to recreate this locally. If I go into Internet Options and remove the GoDaddy authorities and hit our service, ssl works just fine. I go back into the list of publishers and GoDaddy gets put right back in. So my second question is, How the heck do you get rid of GoDaddy so I can get an invalid cert warning?

Okay, last question. Is there a way in code I can tell the web service to ignore invalid certs. I've seen some posts on doing this programatically with WCF but not old web services.

答:
You may need to install on your servers the intermediate certificates used to sign your SSL certs.

Browsers will attempt to validate the SSL certificate by checking the validation of the chain of certs that signed the SSL cert.  If the server doesn't supply the certificate chain with the SSL certificate, the browser may reject the SSL cert.  (More of an issue for Firefox than IE).  The root certificate must still be installed on the client machine for any of this to work.


问:
How to Initialize and Set Options in hammer.js in Angular 2 with TypeScript
I want to use hammer.js in my Angular app. I did successfully install jquery, but I am new to all of this and I don't really know how to proceed with something more complex that requires setting options on it. I'm stuck on getting a hammerjs object that I can manipulate after it is made. According to the docs, setting options after initializing is recommended.

Here is what I did so far:

I installed hammerjs and hammer-timejs with npm.

I imported into my component this way:

```<code>import 'hammerjs';
import 'hammer-timejs';
</code>```

Some of index.html to show what I try to attach hammer to:

```<code><body>
    <div id="main">
        <app-root></app-root>
    </div>
</body>
</code>```

Do I just do exactly what the docs say to install and set options? Like this?

```<code>let hammertime = new Hammer(
    document.getElementById('main')
);
hammertime.get('swipe').set({ threshold: 100 });
</code>```

Do I have to do this in ngOnInit or one of the other hooks?

How do I define myElement if I want to install hammer.js for the entire app? Just regular JS?

```<code>document.getElementById('main')
</code>```

or is there a better Angular way?

答:
Angular application operates only on self or child elements.

Component element itself can be addressed with ElementRef:

```<code>private hammerManager;

constructor(private elementRef: ElementRef) {}

ngOnInit() {
  this.hammerManager = new Hammer(this.elementRef.nativeElement);
  this.hammerManager.get('swipe').set({ threshold: 100 });
}

ngOnDestroy() {
  this.hammerManager.destroy();
}
</code>```

Body:
I want to use hammer.js in my Angular app. I did successfully install jquery, but I am new to all of this and I don't really know how to proceed with something more complex that requires setting options on it. I'm stuck on getting a hammerjs object that I can manipulate after it is made. According to the docs, setting options after initializing is recommended.

Here is what I did so far:

I installed hammerjs and hammer-timejs with npm.

I imported into my component this way:

import 'hammerjs';
import 'hammer-timejs';

Some of index.html to show what I try to attach hammer to:

        <app-root></app-root>

Do I just do exactly what the docs say to install and set options? Like this?

let hammertime = new Hammer(
    document.getElementById('main')
);
hammertime.get('swipe').set({ threshold: 100 });

Do I have to do this in ngOnInit or one of the other hooks?

How do I define myElement if I want to install hammer.js for the entire app? Just regular JS?

document.getElementById('main')

or is there a better Angular way?

Body:
Angular application operates only on self or child elements.

Component element itself can be addressed with ElementRef:

private hammerManager;

constructor(private elementRef: ElementRef) {}

ngOnInit() {
  this.hammerManager = new Hammer(this.elementRef.nativeElement);
  this.hammerManager.get('swipe').set({ threshold: 100 });
}

ngOnDestroy() {
  this.hammerManager.destroy();
}


问:
Changed ***key-certbot.pem file caused server offline
Server: Nginx on Ubuntu 16.04 Xenial

Our sites "crashed" just now due to a certificate issue:

```<code>nginx: [emerg] SSL_CTX_use_PrivateKey_file("/etc/letsencrypt/keys/0000_key-certbot.pem") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)
nginx: configuration file /etc/nginx/nginx.conf test failed
</code>```

In the Virtual hosts, we have these lines:

```<code>ssl_certificate_key /etc/letsencrypt/keys/0003_key-certbot.pem;
ssl_certificate /etc/letsencrypt/live/[domain]/fullchain.pem;
</code>```

On checking the /etc/letsencrypt/keys/ folder, I found these results

```<code>/etc/letsencrypt/keys # ls -la
total 40
drwx------  2 root root 4096 Jul  5 15:33 .
drwxr-xr-x 11 root root 4096 Apr 18 10:58 ..
-rw-------  1 root root 1704 Apr 18 11:01 0000_key-certbot.pem
-rw-------  1 root root 1708 Jan 31 14:37 0000_key-letsencrypt.pem
-rw-------  1 root root 1704 Apr 18 11:18 0001_key-certbot.pem
-rw-------  1 root root 1704 Jan 31 14:37 0001_key-letsencrypt.pem
-rw-------  1 root root 1704 Apr 18 11:19 0002_key-certbot.pem
-rw-------  1 root root 1708 Feb  2 11:47 0002_key-letsencrypt.pem
-rw-------  1 root root 1708 Jun 17 12:01 0003_key-certbot.pem
-rw-------  1 root root 1704 Jul  5 15:33 0004_key-certbot.pem
</code>```

The (3) virtual host files were all referencing 0000_key-certbot.pem, after changing that to 0003_key-certbot.pem the sites were working again.

How can we prevent the sites from crashing every 90 days?

答:
While typing this I think I found the solution, I shouldn't have been using

```<code>ssl_certificate_key /etc/letsencrypt/keys/0003_key-certbot.pem;
ssl_certificate /etc/letsencrypt/live/[domain]/fullchain.pem;
</code>```

But instead

```<code>ssl_certificate_key /etc/letsencrypt/live/[domain]/privkey.pem;
ssl_certificate /etc/letsencrypt/live/[domain]/fullchain.pem;
</code>```

Hope this helps someone

Body:
Server: Nginx on Ubuntu 16.04 Xenial

Our sites "crashed" just now due to a certificate issue:

nginx: [emerg] SSL_CTX_use_PrivateKey_file("/etc/letsencrypt/keys/0000_key-certbot.pem") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)
nginx: configuration file /etc/nginx/nginx.conf test failed

In the Virtual hosts, we have these lines:

ssl_certificate_key /etc/letsencrypt/keys/0003_key-certbot.pem;
ssl_certificate /etc/letsencrypt/live/[domain]/fullchain.pem;

On checking the /etc/letsencrypt/keys/ folder, I found these results

/etc/letsencrypt/keys # ls -la
total 40
drwx------  2 root root 4096 Jul  5 15:33 .
drwxr-xr-x 11 root root 4096 Apr 18 10:58 ..
-rw-------  1 root root 1704 Apr 18 11:01 0000_key-certbot.pem
-rw-------  1 root root 1708 Jan 31 14:37 0000_key-letsencrypt.pem
-rw-------  1 root root 1704 Apr 18 11:18 0001_key-certbot.pem
-rw-------  1 root root 1704 Jan 31 14:37 0001_key-letsencrypt.pem
-rw-------  1 root root 1704 Apr 18 11:19 0002_key-certbot.pem
-rw-------  1 root root 1708 Feb  2 11:47 0002_key-letsencrypt.pem
-rw-------  1 root root 1708 Jun 17 12:01 0003_key-certbot.pem
-rw-------  1 root root 1704 Jul  5 15:33 0004_key-certbot.pem

The (3) virtual host files were all referencing 0000_key-certbot.pem, after changing that to 0003_key-certbot.pem the sites were working again.

How can we prevent the sites from crashing every 90 days?

Body:
While typing this I think I found the solution, I shouldn't have been using

ssl_certificate_key /etc/letsencrypt/keys/0003_key-certbot.pem;
ssl_certificate /etc/letsencrypt/live/[domain]/fullchain.pem;

But instead

ssl_certificate_key /etc/letsencrypt/live/[domain]/privkey.pem;
ssl_certificate /etc/letsencrypt/live/[domain]/fullchain.pem;

Hope this helps someone


问:
Simplifiying JQuery
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <span id="first">Blah blah blah, please <span id="span1">click here</span>.</span>
    <span id="second" style="display:none;">Cancel</span>
    <div id="third" style="display:none;">Test</div></code>```

This code is taken from accepted answer from original post.

答:
You can use one click event for both operation</p>

```<code>$(document).ready(function () {
            $("#span1,#second").on('click', function () {
                $("#first,#second, #third").fadeToggle();
            });
        });
</code>```

Title: Simplifiying JQuery

Body:
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });

    Blah blah blah, please click here.
    Cancel

Test

This code is taken from accepted answer from original post.

Body:
You can use one click event for both operation

$(document).ready(function () {
            $("#span1,#second").on('click', function () {
                $("#first,#second, #third").fadeToggle();
            });
        });


问:
Find size of binary file, function tellg() returns -1
I've written a function which initialize some fields of FileDataTransfer object and also finds size of file.

Here is a code:

```<code>bool FileTransferData::initialize(const string& fileName, string& errMsg)
{
   if (this->transferInProgress)
   {
       errMsg = "\nFile Transfer already in progress. File Transfer Request denied.\a";
       return false;
   }
   this->inFileStream.open(fileName, ios::binary | ios::ate);
   if (!inFileStream.is_open())
   {
       errMsg = "\nRequested file: " + fileName + " does not exist or was not found.\a";
       return false;
   }
   this->fileName = fileName;
   this->fileSize = (int)this->inFileStream.tellg();
   this->inFileStream.seekg(0);
   this->fileOffset = 0;
   this->transferInProgress = true;
   return true;
}
</code>```

But field this->fileSize become -1 after completion of my function, I think tellg() returns -1, but why ?

答:
The -1 value for std::istream::tellg indicates an error which you can check with std::ios::fail and std::ios::bad member functions:

If either the stream buffer associated to the stream does not support the operation, or if it fails, the function returns -1.

I couldn't reproduce the error so I intend to suggest you another approach. The platform you use knows the size of your file and many more about it (last access time, etc.). The following example shows how to determine the size of a file in a platform dependent way (like the boost::filesystem::file_size does too):

```<code>#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif

#include <cstdint>

intmax_t fsizeof(const std::string& fileName) {
    intmax_t fileSize = -1;

#ifdef _WIN32
    WIN32_FILE_ATTRIBUTE_DATA fileData;

    if(GetFileAttributesEx(fileName.c_str(), GetFileExInfoStandard, &fileData) &&
            !(fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
        fileSize = fileData.nFileSizeHigh;
        fileSize <<= sizeof(fileData.nFileSizeLow) * 8;
        fileSize += fileData.nFileSizeLow;
    }
#else
    struct stat fileStat;

    if(stat(fileName.c_str(), &fileStat) == 0 && S_ISREG(fileStat.st_mode))
        fileSize = fileStat.st_size;
#endif

    return fileSize;
}
</code>```

Body:
I've written a function which initialize some fields of FileDataTransfer object and also finds size of file.

Here is a code:

bool FileTransferData::initialize(const string& fileName, string& errMsg)
{
   if (this->transferInProgress)
   {
       errMsg = "\nFile Transfer already in progress. File Transfer Request denied.\a";
       return false;
   }
   this->inFileStream.open(fileName, ios::binary | ios::ate);
   if (!inFileStream.is_open())
   {
       errMsg = "\nRequested file: " + fileName + " does not exist or was not found.\a";
       return false;
   }
   this->fileName = fileName;
   this->fileSize = (int)this->inFileStream.tellg();
   this->inFileStream.seekg(0);
   this->fileOffset = 0;
   this->transferInProgress = true;
   return true;
}

But field this->fileSize become -1 after completion of my function, I think tellg() returns -1, but why ?

Body:
The -1 value for std::istream::tellg indicates an error which you can check with std::ios::fail and std::ios::bad member functions:

If either the stream buffer associated to the stream does not support the operation, or if it fails, the function returns -1.

I couldn't reproduce the error so I intend to suggest you another approach. The platform you use knows the size of your file and many more about it (last access time, etc.). The following example shows how to determine the size of a file in a platform dependent way (like the boost::filesystem::file_size does too):

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif

#include <cstdint>

intmax_t fsizeof(const std::string& fileName) {
    intmax_t fileSize = -1;

#ifdef _WIN32
    WIN32_FILE_ATTRIBUTE_DATA fileData;

    if(GetFileAttributesEx(fileName.c_str(), GetFileExInfoStandard, &fileData) &&
            !(fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
        fileSize = fileData.nFileSizeHigh;
        fileSize <<= sizeof(fileData.nFileSizeLow) * 8;
        fileSize += fileData.nFileSizeLow;
    }
#else
    struct stat fileStat;

    if(stat(fileName.c_str(), &fileStat) == 0 && S_ISREG(fileStat.st_mode))
        fileSize = fileStat.st_size;
#endif

    return fileSize;
}


问:
Java: Extract json values as individuals
I have this json in java:

```<code>jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
</code>```

jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.

Is there an easy way to extract all the values as individuals like jsonObj [1]?

答:
You may Use Gson parsing library as below :

```<code>Gson gson = new Gson();

// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);

// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);

// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
    String result = gson.toJson(json);

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
</code>```

or simply use:

example

```<code>JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse  = object.getString("getIMEIResult");
</code>```

for Array use :

```<code>//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
</code>```

Body:
I have this json in java:

jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}

jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.

Is there an easy way to extract all the values as individuals like jsonObj [1]?

Body:
You may Use Gson parsing library as below :

Gson gson = new Gson();

// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);

// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);

// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
    String result = gson.toJson(json);

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);

or simply use:

example

JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse  = object.getString("getIMEIResult");

for Array use :

//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();


问:
Un-/Check behavior in C# TreeView
I found a lot about treeview and checkboxes in treeviews...

but one thing seems to be undiscussed.

I have my treeview like

```<code>[x] Foo
 L [x] One
 L [x] Two
 L [x] Three
[x] Bar
 L [ ] One
 L [x] Two
 L [x] Three
[ ] Hello
 L [ ] One
 L [ ] Two
 L [ ] Three
</code>```

Now when I check my parent checkbox e.g. Foo than all child get selected. Also they get deselected by unchecking Foo. To do this I have this Method

```<code>private void TreeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
    foreach (TreeNode childNode in e.Node.Nodes)
    {
        childNode.Checked = e.Node.Checked;
    }
}
</code>```

I tried a lot with using count and others but could not achive what i'm trying to achive.

So what I want is, when I check Two in TreeNode Hello than Hello should get checked. Without checking One and Three. Check-/Unchecking Hello should select/deselect all childs.

Is this even possible?

Because when Hello gets checked, it fires the TreeView1_AfterCheck-event! What actually check/unchecks all childs.

And most of my tries ended up in an endless loop.

So my Question actually is:

Can I achive the above described behavior?

Ask me if something is unclear.

答:
I made a similar application where I had to do the same thing which you are trying to achieve. Its in VB.Net. Here's the snippet. If it did help, do accept this answer, comment further if you couldn't understand any part of it.

VB.NET :

```<code>Private isChildCheck As Boolean = False
Private Sub TREE_VIEW_AfterCheck(sender As Object, e As TreeViewEventArgs)
    If e.Action <> TreeViewAction.Unknown Then   ' The code only executes if the user caused the checked state to change.
        If e.Node.Nodes.Count > 0 Then
            If isChildCheck Then
                isChildCheck = False
                Exit Sub 'This will check the parent to exit AfterCheck loop
            End If
            ' Calls the CheckAllChildNodes method, passing in the current
            ' checked value of the TreeNode whose checked state changed.
            CheckAllChildNodes(e.Node, e.Node.Checked)
        Else
            e.Node.Parent.Checked = True
            isChildCheck = True
        End If
    End If
End Sub   'After a tree node's Checked property is changed, all its child nodes are updated to the same value.

Private Sub CheckAllChildNodes(treeNode As TreeNode, nodeChecked As Boolean)

    For Each node As TreeNode In treeNode.Nodes
        node.Checked = nodeChecked

        If node.Nodes.Count > 0 Then
            ' If the current node has child nodes, call the CheckAllChildsNodes method recursively.
            CheckAllChildNodes(node, nodeChecked)
        End If
    Next node
End Sub  'Checks the childnodes of a node recursively
</code>```

C#.NET (Edit by Dwza after clearing behavior changes for thoese who need it)

```<code>private bool isChildCheck = false;
private void TREE_VIEW_AfterCheck(object sender, TreeViewEventArgs e)
{
    // The code only executes if the user caused the checked state to change.
    if (e.Action != TreeViewAction.Unknown)
    {
        if (e.Node.Nodes.Count > 0)
        {
            if (isChildCheck)
            {
                isChildCheck = false;
                return;
               //This will check the parent to exit AfterCheck loop
            }
            // Calls the CheckAllChildNodes method, passing in the current
            // checked value of the TreeNode whose checked state changed.
            CheckAllChildNodes(e.Node, e.Node.Checked);
        }
        else
        {
            e.Node.Parent.Checked = GetCheckStateOfChildNodes(e.Node.Parent);
            isChildCheck = !e.Node.Parent.Checked;
        }
    }
}
//After a tree node's Checked property is changed, all its child nodes are updated to the same value.

private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
{
    foreach (TreeNode node in treeNode.Nodes)
    {
        node.Checked = nodeChecked;
        if (node.Nodes.Count > 0)
        {
            // If the current node has child nodes, call the CheckAllChildsNodes method recursively.
            CheckAllChildNodes(node, nodeChecked);
        }
    }
} //Checks the childnodes of a node recursively

//Additional Method to react on behavior when all childs are checked/unchecked
//This part was added by dwza and is not in the VB part
private bool GetCheckStateOfChildNodes(TreeNode treeNode)
{
    foreach(TreeNode node in treeNode.Nodes)
    {
        if (node.Checked)
        {
            return true;
        }
    }
    return false;
}
</code>```

Hope this conversion will help you.(Converted using CodeConverter)

Title: Un-/Check behavior in C# TreeView

Body:
I found a lot about treeview and checkboxes in treeviews...

but one thing seems to be undiscussed.

I have my treeview like

[x] Foo
 L [x] One
 L [x] Two
 L [x] Three
[x] Bar
 L [ ] One
 L [x] Two
 L [x] Three
[ ] Hello
 L [ ] One
 L [ ] Two
 L [ ] Three

Now when I check my parent checkbox e.g. Foo than all child get selected. Also they get deselected by unchecking Foo. To do this I have this Method

private void TreeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
    foreach (TreeNode childNode in e.Node.Nodes)
    {
        childNode.Checked = e.Node.Checked;
    }
}

I tried a lot with using count and others but could not achive what i'm trying to achive.

So what I want is, when I check Two in TreeNode Hello than Hello should get checked. Without checking One and Three. Check-/Unchecking Hello should select/deselect all childs.

Is this even possible?

Because when Hello gets checked, it fires the TreeView1_AfterCheck-event! What actually check/unchecks all childs.

And most of my tries ended up in an endless loop.

So my Question actually is:

Can I achive the above described behavior?

Ask me if something is unclear.

Body:
I made a similar application where I had to do the same thing which you are trying to achieve. Its in VB.Net. Here's the snippet. If it did help, do accept this answer, comment further if you couldn't understand any part of it.

VB.NET :

Private isChildCheck As Boolean = False
Private Sub TREE_VIEW_AfterCheck(sender As Object, e As TreeViewEventArgs)
    If e.Action <> TreeViewAction.Unknown Then   ' The code only executes if the user caused the checked state to change.
        If e.Node.Nodes.Count > 0 Then
            If isChildCheck Then
                isChildCheck = False
                Exit Sub 'This will check the parent to exit AfterCheck loop
            End If
            ' Calls the CheckAllChildNodes method, passing in the current
            ' checked value of the TreeNode whose checked state changed.
            CheckAllChildNodes(e.Node, e.Node.Checked)
        Else
            e.Node.Parent.Checked = True
            isChildCheck = True
        End If
    End If
End Sub   'After a tree node's Checked property is changed, all its child nodes are updated to the same value.

Private Sub CheckAllChildNodes(treeNode As TreeNode, nodeChecked As Boolean)

    For Each node As TreeNode In treeNode.Nodes
        node.Checked = nodeChecked

        If node.Nodes.Count > 0 Then
            ' If the current node has child nodes, call the CheckAllChildsNodes method recursively.
            CheckAllChildNodes(node, nodeChecked)
        End If
    Next node
End Sub  'Checks the childnodes of a node recursively

C#.NET (Edit by Dwza after clearing behavior changes for thoese who need it)

private bool isChildCheck = false;
private void TREE_VIEW_AfterCheck(object sender, TreeViewEventArgs e)
{
    // The code only executes if the user caused the checked state to change.
    if (e.Action != TreeViewAction.Unknown)
    {
        if (e.Node.Nodes.Count > 0)
        {
            if (isChildCheck)
            {
                isChildCheck = false;
                return;
               //This will check the parent to exit AfterCheck loop
            }
            // Calls the CheckAllChildNodes method, passing in the current
            // checked value of the TreeNode whose checked state changed.
            CheckAllChildNodes(e.Node, e.Node.Checked);
        }
        else
        {
            e.Node.Parent.Checked = GetCheckStateOfChildNodes(e.Node.Parent);
            isChildCheck = !e.Node.Parent.Checked;
        }
    }
}
//After a tree node's Checked property is changed, all its child nodes are updated to the same value.

private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
{
    foreach (TreeNode node in treeNode.Nodes)
    {
        node.Checked = nodeChecked;
        if (node.Nodes.Count > 0)
        {
            // If the current node has child nodes, call the CheckAllChildsNodes method recursively.
            CheckAllChildNodes(node, nodeChecked);
        }
    }
} //Checks the childnodes of a node recursively

//Additional Method to react on behavior when all childs are checked/unchecked
//This part was added by dwza and is not in the VB part
private bool GetCheckStateOfChildNodes(TreeNode treeNode)
{
    foreach(TreeNode node in treeNode.Nodes)
    {
        if (node.Checked)
        {
            return true;
        }
    }
    return false;
}

Hope this conversion will help you.(Converted using CodeConverter)


问:
Div leak parent container max width
I need to make a child div leak the parent container max width.
Now, i can only leak parent padding (knowing it).

I need this to wrap all the page on a container and make some sections leak.

Without this, i will need to set the container on every section.

Here is some snippets

Better snippet on codepen

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
}

.child {
  background: lightcoral;
  height: 200px;
}

.child.cancel-padding {
  margin: 0 -30px;
}

.child.leaked {
}

html,
body {
  margin: 0;
  padding: 0;
}

* {
  text-align: center;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><small>note: see in fullscreen or on codepen</small>
<h1>what i have</h1>
<div class="container">
  <div class="child">A element inside a container</div>
</div>

<h1>what i need</h1>
<div class="container-leaked">
  <div class="child leaked">
    a element inside the container, but leaking all view width (100vw)
  </div>
</div>

<h1>what i can do now</h1>
<div class="container">
  <div class="child cancel-padding">Make the element cancel the parent padding, that's all</div>
</div>

<h1>Why i need</h1>
<p>
  i will wrap all the page in the container, but sometimes i need sections to leak the container with full view width.
</p></code>```

Note: on the demo, i've set the child height, but i will not have control of it. it's a dynamic content div, so height is dynamic.

答:
Here is an approach you can try:

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
}

.child {
  background: lightcoral;
  height: 200px;
  width: 400%;
  margin-left: -150%; /* (width of child - 100) / 2 */
}

html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden; /* prevent horizontal scroll bar */
}

* {
  text-align: center;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">I am outside the parent</div>
</div></code>```

Title: Div leak parent container max width

Body:
I need to make a child div leak the parent container max width.
Now, i can only leak parent padding (knowing it).

I need this to wrap all the page on a container and make some sections leak.

Without this, i will need to set the container on every section.

Here is some snippets

Better snippet on codepen

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
}

.child {
  background: lightcoral;
  height: 200px;
}

.child.cancel-padding {
  margin: 0 -30px;
}

.child.leaked {
}

html,
body {
  margin: 0;
  padding: 0;
}

* {
  text-align: center;
  font-family: sans-serif;
}

note: see in fullscreen or on codepen

what i have

A element inside a container

what i need

    a element inside the container, but leaking all view width (100vw)

what i can do now

Make the element cancel the parent padding, that's all

Why i need

  i will wrap all the page in the container, but sometimes i need sections to leak the container with full view width.

Note: on the demo, i've set the child height, but i will not have control of it. it's a dynamic content div, so height is dynamic.

Body:
Here is an approach you can try:

.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 0 30px;
  background: lightblue;
}

.child {
  background: lightcoral;
  height: 200px;
  width: 400%;
  margin-left: -150%; /* (width of child - 100) / 2 */
}

html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden; /* prevent horizontal scroll bar */
}

* {
  text-align: center;
  font-family: sans-serif;
}

<div class="container">
  <div class="child">I am outside the parent</div>
</div>


问:
Python format date string from postgresql db
I have the following code that extracts a postgres CURRENT_TIMESTAMP from a database

```<code>cursor.execute("SELECT submitdate FROM journeys WHERE display = true")
submitDate = cursor.fetchone()['submitdate']
</code>```

which returns

```<code>2015-08-11 12:44:31.790462
</code>```

How would I format this to show as 11-08-2015 for example?

I've read about and tried things such as this but they don't work

```<code>print(
    datetime.datetime.fromtimestamp(
        int("1284101485")
    ).strftime('%Y-%m-%d %H:%M:%S')
)
</code>```

答:
The solution that worked comes from Abhis's comment above.</p>

```<code>submitDate.strftime("%d-%m-%Y")
</code>```

Body:
I have the following code that extracts a postgres CURRENT_TIMESTAMP from a database

cursor.execute("SELECT submitdate FROM journeys WHERE display = true")
submitDate = cursor.fetchone()['submitdate']

which returns

2015-08-11 12:44:31.790462

How would I format this to show as 11-08-2015 for example?

I've read about and tried things such as this but they don't work

print(
    datetime.datetime.fromtimestamp(
        int("1284101485")
    ).strftime('%Y-%m-%d %H:%M:%S')
)

Body:
The solution that worked comes from Abhis's comment above.

submitDate.strftime("%d-%m-%Y")


问:
Cancel NSOperation in for loop?
I am trying to implement search on a background thread using NSOperation on iOS. I didn't want to subclass NSOperation so this is what I'm doing:

```<code>[searchQueue cancelAllOperations];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                  elector:@selector(filterContentForSearchText:)
                                                                   object:self.searchDisplayController.searchBar.text];
[searchQueue addOperation:op];
[op release];
</code>```

The search method includes a for loop that checks whether what is being searched is in an array. Now when I cancel the NSOperation by calling cancelAllOperations, the for loop continues to run through the array. I would like to prevent this and was wondering whether it is legit to call this from within the for loop:

```<code>if ([[[searchQueue operations] objectAtIndex:0] isCancelled]) {
    [tmp_array release];   // tmp_array is used to hold temporary results
    [pool drain];          // pool is my autorelease pool
    return;
}
</code>```

答:
One of the reasons to subclass NSOperation is to implement proper cancellation. You could do your approach, but it violates several good design principles. Basically, since cancellation requires the cooperation of the operation itself, NSInvocationOperation isn't built to cancel the invocation while it's already executing (though it can be successfully cancelled before it starts executing), as the running method shouldn't know anything about how it's called.

Instead, if you subclass NSOperation, you can put most of this functionality into the main method very easily:

```<code>@implementation MyOperation
- (void)main {
    if ([self isCancelled])
        return;

    for (...) {
        // do stuff

        if ([self isCancelled]) {
            [tmp_array release];
            return;
        }
    }
}

@end
</code>```

Note also that you don't have to maintain your own autorelease pool with such an implementation.

Title: Cancel NSOperation in for loop?

Body:
I am trying to implement search on a background thread using NSOperation on iOS. I didn't want to subclass NSOperation so this is what I'm doing:

[searchQueue cancelAllOperations];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                  elector:@selector(filterContentForSearchText:)
                                                                   object:self.searchDisplayController.searchBar.text];
[searchQueue addOperation:op];
[op release];

The search method includes a for loop that checks whether what is being searched is in an array. Now when I cancel the NSOperation by calling cancelAllOperations, the for loop continues to run through the array. I would like to prevent this and was wondering whether it is legit to call this from within the for loop:

if ([[[searchQueue operations] objectAtIndex:0] isCancelled]) {
    [tmp_array release];   // tmp_array is used to hold temporary results
    [pool drain];          // pool is my autorelease pool
    return;
}

Body:
One of the reasons to subclass NSOperation is to implement proper cancellation. You could do your approach, but it violates several good design principles. Basically, since cancellation requires the cooperation of the operation itself, NSInvocationOperation isn't built to cancel the invocation while it's already executing (though it can be successfully cancelled before it starts executing), as the running method shouldn't know anything about how it's called.

Instead, if you subclass NSOperation, you can put most of this functionality into the main method very easily:

@implementation MyOperation
- (void)main {
    if ([self isCancelled])
        return;

    for (...) {
        // do stuff

        if ([self isCancelled]) {
            [tmp_array release];
            return;
        }
    }
}

@end

Note also that you don't have to maintain your own autorelease pool with such an implementation.


问:
Index beyond bounds while setting up a cell in my table view
While setting up a cell in my table view, I had this issue:

Log:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'
  *** First throw call stack:
  (0x18696afd8 0x1853cc538 0x1868491f0 0x100918a30 0x10091960c 0x18cddf114 0x18cddf32c 0x18cdcca30 0x18cde431c 0x18cb7c92c 0x18ca97158 0x189c87274 0x189c7bde8 0x189c7bca8 0x189bf7360 0x189c1e3c0 0x189c1ee8c 0x1869189a0 0x186916628 0x186846db4 0x1882b0074 0x18caff130 0x1006920bc 0x18585559c)
  libc++abi.dylib: terminating with uncaught exception of type NSException

```<code>internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (tableView == tableview) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "table", for: indexPath as IndexPath) as! homeTableViewCell

        if (titlearray.count != 0) {
            let tit: NSString = self.titlearray[indexPath.row] as! NSString

            print("titlearraytitlearray\(titlearray)")

            appDelegate.trendseetitarray = titlearray

            print("appDelegatetrendseearray\(appDelegate.trendseetitarray)")

            cell.treadingtitle.text! = tit as String
        }

        if (pricearray.count != 0) {
            let tit: NSString = self.pricearray[indexPath.row] as! NSString

            appDelegate.trendseepricearray = pricearray

            cell.trendingprice.text! = tit as String
        }

        if (addressarraylist.count != 0) {
            let tit: NSString = self.addressarraylist[indexPath.row] as! NSString

            appDelegate.addressarraylist = addressarraylist
        }

        if (imagearray.count != 0 && imagearray.count != nil ) {
            print(imagearray)

            let roomurl=URL(string: "\(imagearray[indexPath.row])")
            //  print("Room URL:\(roomurl!)")
            appDelegate.trendseeimagearray = imagearray

            cell.Trendingimg.sd_setImage(
                with: roomurl,
                placeholderImage: UIImage(named:"no_image.png"),
                options: SDWebImageOptions.refreshCached,
                completed: { (image1: UIImage?, error1: Error?, cacheType1: SDImageCacheType, imageURL1: URL?) -> Void in
                }
            )

            cell.Trendingimg.clipsToBounds = true;
            cell.Trendingimg.sd_setImage(with: roomurl, completed: self.block1)
        }

        return cell
    }

    return UITableViewCell()
}
</code>```

Error in:

```<code>if (addressarraylist.count != 0) {
    let tit: NSString = self.addressarraylist[indexPath.row] as! NSString

    appDelegate.addressarraylist = addressarraylist
}
</code>```

Issue as image:

答:
Why are you checking if the size of the Array is nonzero instead of testing if the count is at least as large as indexPath.row? Try this instead:

```<code>// array index must be less than the count since the index is zero-based
if indexPath.row < addressarraylist.count {
  let tit: NSString = addressarraylist[indexPath.row] as! NSString
  appDelegate.addressarraylist = addressarraylist
}
</code>```

You also should be testing your Optional values before unwrapping them. Force unwrapping could lead to a run-time crash. Test them like this:

```<code>if let tit: NSString = addressarraylist[indexPath.row] as? NSString { ... }
</code>```

Body:
While setting up a cell in my table view, I had this issue:

Log:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'
  *** First throw call stack:
  (0x18696afd8 0x1853cc538 0x1868491f0 0x100918a30 0x10091960c 0x18cddf114 0x18cddf32c 0x18cdcca30 0x18cde431c 0x18cb7c92c 0x18ca97158 0x189c87274 0x189c7bde8 0x189c7bca8 0x189bf7360 0x189c1e3c0 0x189c1ee8c 0x1869189a0 0x186916628 0x186846db4 0x1882b0074 0x18caff130 0x1006920bc 0x18585559c)
  libc++abi.dylib: terminating with uncaught exception of type NSException

internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (tableView == tableview) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "table", for: indexPath as IndexPath) as! homeTableViewCell

        if (titlearray.count != 0) {
            let tit: NSString = self.titlearray[indexPath.row] as! NSString

            print("titlearraytitlearray\(titlearray)")

            appDelegate.trendseetitarray = titlearray

            print("appDelegatetrendseearray\(appDelegate.trendseetitarray)")

            cell.treadingtitle.text! = tit as String
        }

        if (pricearray.count != 0) {
            let tit: NSString = self.pricearray[indexPath.row] as! NSString

            appDelegate.trendseepricearray = pricearray

            cell.trendingprice.text! = tit as String
        }

        if (addressarraylist.count != 0) {
            let tit: NSString = self.addressarraylist[indexPath.row] as! NSString

            appDelegate.addressarraylist = addressarraylist
        }

        if (imagearray.count != 0 && imagearray.count != nil ) {
            print(imagearray)

            let roomurl=URL(string: "\(imagearray[indexPath.row])")
            //  print("Room URL:\(roomurl!)")
            appDelegate.trendseeimagearray = imagearray

            cell.Trendingimg.sd_setImage(
                with: roomurl,
                placeholderImage: UIImage(named:"no_image.png"),
                options: SDWebImageOptions.refreshCached,
                completed: { (image1: UIImage?, error1: Error?, cacheType1: SDImageCacheType, imageURL1: URL?) -> Void in
                }
            )

            cell.Trendingimg.clipsToBounds = true;
            cell.Trendingimg.sd_setImage(with: roomurl, completed: self.block1)
        }

        return cell
    }

    return UITableViewCell()
}

Error in:

if (addressarraylist.count != 0) {
    let tit: NSString = self.addressarraylist[indexPath.row] as! NSString

    appDelegate.addressarraylist = addressarraylist
}

Issue as image:

Body:
Why are you checking if the size of the Array is nonzero instead of testing if the count is at least as large as indexPath.row? Try this instead:

// array index must be less than the count since the index is zero-based
if indexPath.row < addressarraylist.count {
  let tit: NSString = addressarraylist[indexPath.row] as! NSString
  appDelegate.addressarraylist = addressarraylist
}

You also should be testing your Optional values before unwrapping them. Force unwrapping could lead to a run-time crash. Test them like this:

if let tit: NSString = addressarraylist[indexPath.row] as? NSString { ... }


问:
Uses of static variables inside functions
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

```<code>int count(){
    static int n;
    n = n + 1;
    return n;
}
</code>```

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!

答: I have used static variables in test code for lazy initialization of state.  Using static local variables in production code is fraught with peril and can lead to subtle bugs. It seems (at least in the code that I generally work on) that nearly any bit of code that starts out as a single-threaded only chunk of code has a nasty habit of eventually ending up working in a concurrent situation. And using a static variable in a concurrent environment can result in difficult issues to debug.  The reason for this is because the resulting state change is essentially a hidden side effect.  </p>

Body:
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

int count(){
    static int n;
    n = n + 1;
    return n;
}

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!


问:
Outputting conditionally from merge
I want to update a history file in SAS. I have new observations, which may overlap with existing data lines.

What is needed, is a file, which would have lines from dataset (new_data) where they exist and in case the lines do not exist, then from old set (old_data). What I've come up is a clunky merge operation, which is conditional on the order of the datasets. (==Works only if New_data is after Old_data. :?)

```<code>data new_data;
    input key value;
datalines;
    1 10
    1 11
    2 20
    2 21
    ;
run;

data old_data;
    input key value;
    datalines;
    2 50
    2 51
    3 30
    3 31
    ;
run;
</code>```

So I'd like to have the following:

```<code>key value
1 10
1 11
2 20
2 21
3 30
3 31
</code>```

However the following does not work. It produces the output below it.

```<code>data updated_history;
    merge New_data(in=a) old_data(in=b) ;
    by key;
    if a or (b and not a );
run;

....
2 50
2 51
...
</code>```

But for some reason this does:

```<code>data updated_history;
    merge old_data(in=b) New_data(in=a);
    by key;
    if a or (b and not a );
run;
</code>```

Question: Is there an intelligent way to manage from which dataset the values are select from. Something like: if a then value_from_dataset a;

答: The order in which you list the data sets in the MERGE is the order the data is taken.  So when the order is old, new values from old are read and then values from new overwrite the values from old. This is why your second version works and the first does not.

Title: Outputting conditionally from merge

Body:
I want to update a history file in SAS. I have new observations, which may overlap with existing data lines.

What is needed, is a file, which would have lines from dataset (new_data) where they exist and in case the lines do not exist, then from old set (old_data). What I've come up is a clunky merge operation, which is conditional on the order of the datasets. (==Works only if New_data is after Old_data. :?)

data new_data;
    input key value;
datalines;
    1 10
    1 11
    2 20
    2 21
    ;
run;

data old_data;
    input key value;
    datalines;
    2 50
    2 51
    3 30
    3 31
    ;
run;

So I'd like to have the following:

key value
1 10
1 11
2 20
2 21
3 30
3 31

However the following does not work. It produces the output below it.

data updated_history;
    merge New_data(in=a) old_data(in=b) ;
    by key;
    if a or (b and not a );
run;

....
2 50
2 51
...

But for some reason this does:

data updated_history;
    merge old_data(in=b) New_data(in=a);
    by key;
    if a or (b and not a );
run;

Question: Is there an intelligent way to manage from which dataset the values are select from. Something like: if a then value_from_dataset a;


问:
Calling C# Function from XAML
In my XAML I have an expander like this

```<code><Expander ExpandDirection="Down" Width="Auto" Padding="4">
    <Expander.Style>
        <Style TargetType="Expander">
            <Setter Property="IsExpanded" Value="{Binding XPath=@Expand}" />
            <Setter Property="Header" Value="{Binding XPath=@Name}" />
            <Setter Property="FontWeight" Value="Bold" />

            <Style.Triggers>
                <DataTrigger Binding="{Binding IsExpanded,RelativeSource={RelativeSource Self}}" Value="True">
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Expander.Style>
    <ListBox Name="itemsList"
    ItemsSource="{Binding XPath=UpgradeAction}"
    ItemTemplate="{StaticResource dtListItemTemplate}"
    SelectionChanged="listItems_SelectionChanged"
    Style="{StaticResource styleListBoxUpgradeAction}"
    ItemContainerStyle="{StaticResource styleListBoxItemUpgradeAction}">
    </ListBox>
</Expander>
</code>```

Instead of the value of Header to come from @Name I want to have a C# function to take in the @Name from the XAML, do some things, then output a new string which will be used as the Value. So it would look something like this

```<code><Setter Property="Header" Value="C_Sharp_Function({Binding XPath=@Name})" />
</code>```

I have the function that I need to use but how do I execute this in the XAML?Sorry if this sounds like a stupid question, I'm new to C# and XAML.  Any help is much appreciated!

EDIT

Here is some of the things I tried in the Setter to substitute a multi-value converter. I assume it should look something like the answer in this.

```<code><Setter Property="Header" Value="{{Binding XPath=@Name, Converter={StaticResource NameConverter}}, {Binding XPath=@Value, Converter={StaticResource NameConverter}}}" />

 <Setter Property="Header" Value="{Binding XPath={@Name, @Value}, Converter={StaticResource NameConverter}}" />
</code>```

答:
What you're describing is a value converter. It looks a little different, but logically it's the same thing.

```<code>public class NameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var name = (XmlAttribute)value;

        //  Do anything you like in here. This is just an example.

        return "something based on " + name.Value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

XAML:

```<code><Window.Resources>
    <local:NameConverter x:Key="NameConverter" />

    <!-- ... -->
</code>```

...

```<code><Expander ExpandDirection="Down" Width="Auto" Padding="4">
    <Expander.Style>
        <Style TargetType="Expander">
            <Setter Property="IsExpanded" Value="{Binding XPath=@Expand}" />
            <Setter
                Property="Header"
                Value="{Binding XPath=@Name, Converter={StaticResource NameConverter}}"
                />
</code>```

If you want to pass in more than one parameter, you can use a multi-binding with a multi-value converter.

I'm not sure why you'd doing all your bindings in the Expander's Style. The following should work equally well. I also included a simpler way to do the IsExpanded trigger.

```<code>public class NameValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var attrName = (XmlAttribute)values[0];
        var attrValue = (XmlAttribute)values[1];

        //  Do stuff here.

        return attrName.Value + " -> " + attrValue.Value;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

<Window.Resources>
    <local:NameValueConverter x:Key="NameValueConverter" />
</Window.Resources>
</code>```

...

```<code><Expander
    ExpandDirection="Down"
    Width="Auto"
    Padding="4"
    IsExpanded="{Binding XPath=@Expand}"
    >
    <Expander.Style>
        <Style TargetType="Expander">
            <Setter Property="FontWeight" Value="Bold" />

            <Style.Triggers>
                <!--
                You can do a regular Trigger instead of a DataTrigger and not
                have to bother with RelativeSource=Self
                -->
                <Trigger
                    Property="IsExpanded"
                    Value="True">
                    <!-- stuff -->
                </Trigger>
            </Style.Triggers>
        </Style>
    </Expander.Style>
    <Expander.Header>
        <MultiBinding Converter="{StaticResource NameValueConverter}">
            <Binding XPath="@Name" />
            <Binding XPath="@Value" />
        </MultiBinding>
    </Expander.Header>
</Expander>
</code>```

Here's where Window.Resources goes:

```<code><Window
    ...x:Class="..." and other attributes...
    >
    <Window.Resources>
        <local:NameConverter x:Key="NameConverter" />

        <!-- other resources -->
    </Window.Resources>
    <Grid>
        <!-- The controls that go in the window -->
    </Grid>
</Window
</code>```

Title: Calling C# Function from XAML

Body:
In my XAML I have an expander like this

<Expander ExpandDirection="Down" Width="Auto" Padding="4">
    <Expander.Style>

        </Style>
    </Expander.Style>
    <ListBox Name="itemsList"
    ItemsSource="{Binding XPath=UpgradeAction}"
    ItemTemplate="{StaticResource dtListItemTemplate}"
    SelectionChanged="listItems_SelectionChanged"
    Style="{StaticResource styleListBoxUpgradeAction}"
    ItemContainerStyle="{StaticResource styleListBoxItemUpgradeAction}">
    </ListBox>
</Expander>

Instead of the value of Header to come from @Name I want to have a C# function to take in the @Name from the XAML, do some things, then output a new string which will be used as the Value. So it would look something like this

<Setter Property="Header" Value="C_Sharp_Function({Binding XPath=@Name})" />

I have the function that I need to use but how do I execute this in the XAML?Sorry if this sounds like a stupid question, I'm new to C# and XAML.  Any help is much appreciated!

EDIT

Here is some of the things I tried in the Setter to substitute a multi-value converter. I assume it should look something like the answer in this.

<Setter Property="Header" Value="{{Binding XPath=@Name, Converter={StaticResource NameConverter}}, {Binding XPath=@Value, Converter={StaticResource NameConverter}}}" />

 <Setter Property="Header" Value="{Binding XPath={@Name, @Value}, Converter={StaticResource NameConverter}}" />

Body:
What you're describing is a value converter. It looks a little different, but logically it's the same thing.

public class NameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var name = (XmlAttribute)value;

        //  Do anything you like in here. This is just an example.

        return "something based on " + name.Value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

<Window.Resources>
    <local:NameConverter x:Key="NameConverter" />

    <!-- ... -->

...

<Expander ExpandDirection="Down" Width="Auto" Padding="4">
    <Expander.Style>
        <Style TargetType="Expander">
            <Setter Property="IsExpanded" Value="{Binding XPath=@Expand}" />
            <Setter
                Property="Header"
                Value="{Binding XPath=@Name, Converter={StaticResource NameConverter}}"
                />

If you want to pass in more than one parameter, you can use a multi-binding with a multi-value converter.

I'm not sure why you'd doing all your bindings in the Expander's Style. The following should work equally well. I also included a simpler way to do the IsExpanded trigger.

public class NameValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var attrName = (XmlAttribute)values[0];
        var attrValue = (XmlAttribute)values[1];

        //  Do stuff here.

        return attrName.Value + " -> " + attrValue.Value;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

<Window.Resources>
    <local:NameValueConverter x:Key="NameValueConverter" />
</Window.Resources>

...

<Expander
    ExpandDirection="Down"
    Width="Auto"
    Padding="4"
    IsExpanded="{Binding XPath=@Expand}"
    >
    <Expander.Style>
        <Style TargetType="Expander">
            <Setter Property="FontWeight" Value="Bold" />

            <Style.Triggers>
                <!--
                You can do a regular Trigger instead of a DataTrigger and not
                have to bother with RelativeSource=Self
                -->
                <Trigger
                    Property="IsExpanded"
                    Value="True">
                    <!-- stuff -->
                </Trigger>
            </Style.Triggers>
        </Style>
    </Expander.Style>
    <Expander.Header>
        <MultiBinding Converter="{StaticResource NameValueConverter}">
            <Binding XPath="@Name" />
            <Binding XPath="@Value" />
        </MultiBinding>
    </Expander.Header>
</Expander>

Here's where Window.Resources goes:

<Window
    ...x:Class="..." and other attributes...
    >
    <Window.Resources>
        <local:NameConverter x:Key="NameConverter" />

        <!-- other resources -->
    </Window.Resources>
    <Grid>
        <!-- The controls that go in the window -->
    </Grid>
</Window


问:
How to skip first few elements from array?
I have an array with total 5000 elements and at one functionality, I only need last 3000 elements only to proceed further.

for that I have tried following solution.

```<code>//skipping first 2000 elements
list = list.Skip(5000 - 3000).ToArray();
</code>```

This solution is actually giving me desired solution, but when I ran profiler on my code, It is showing huge amount memory allocation on this line.

I have to use Array only due to carried on legacy. and very frequent ToArray() doesn't seem to be good for performance.

there is also possible solution,

```<code>//reversing whole list
Array.Reverse(list);
//restricting size of an array to 3000,
//so first (as reversed the list, they are last 3000 elements)
Array.Resize(ref list, 3000);
//again reversing list to make it proper order
Array.Reverse(list);
</code>```

but this is even worse in time complexity.

Is there any better solution for this, which doesn't need casting from List to Array ?

答:
If list is a List<> you can use List.GetRange:

```<code>int lastN = 3000;
var sublist = list.GetRange(list.Count - lastN, lastN);
var array = sublist.ToArray();
</code>```

This is more efficient because  List.ToArray uses Array.Copy.

If list is an int[] as commented it's even more efficient:

```<code>int lastN = 3000;
int[] result = new int[lastN];
Array.Copy(list, list.Length - lastN, result, 0, lastN);
</code>```

Body:
I have an array with total 5000 elements and at one functionality, I only need last 3000 elements only to proceed further.

for that I have tried following solution.

//skipping first 2000 elements
list = list.Skip(5000 - 3000).ToArray();

This solution is actually giving me desired solution, but when I ran profiler on my code, It is showing huge amount memory allocation on this line.

I have to use Array only due to carried on legacy. and very frequent ToArray() doesn't seem to be good for performance.

there is also possible solution,

//reversing whole list
Array.Reverse(list);
//restricting size of an array to 3000,
//so first (as reversed the list, they are last 3000 elements)
Array.Resize(ref list, 3000);
//again reversing list to make it proper order
Array.Reverse(list);

but this is even worse in time complexity.

Is there any better solution for this, which doesn't need casting from List to Array ?

Body:
If list is a List<> you can use List.GetRange:

int lastN = 3000;
var sublist = list.GetRange(list.Count - lastN, lastN);
var array = sublist.ToArray();

This is more efficient because  List.ToArray uses Array.Copy.

If list is an int[] as commented it's even more efficient:

int lastN = 3000;
int[] result = new int[lastN];
Array.Copy(list, list.Length - lastN, result, 0, lastN);


问:
undefined reference to `__stack_chk_fail'
Getting this error while compiling C++ code:

```<code>undefined reference to `__stack_chk_fail'
</code>```

Options already tried:

added -fno-stack-protector while compiling - did not work, error persists

added a dummy implementation of void __stack_chk_fail(void) in my code. Still getting the same error.

Detailed Error:

```<code>/u/ac/alanger/gurobi/gurobi400/linux64/lib/libgurobi_c++.a(Env.o)(.text+0x1034): In function `GRBEnv::getPar/u/ac/alanger/gurobi/gurobi400/linux64/lib/libgurobi_c++.a(Env.o)(.text+0x1034): In function `GRBEnv::getParamInfo(GRB_StringParam, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
: undefined reference to `__stack_chk_fail'
amInfo(GRB_StringParam, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
: **undefined reference to `__stack_chk_fail'**
</code>```

Earlier, I was getting 10's of such errors. Found out that there was a version mismatch between the gcc of the pre-compiled libraries I am using and the gcc version I was using to compile the code. Updated gcc and now I am getting only 2 of these errors.

Any help, please?

答:
libgurobi_c++.a was compiled with -fno-stack-protector (obviously).

A few things come to mind:

add -fstack-protector when linking.  This will make sure that libssp gets linked.

Manually link -lssp

Make your dummy version of __stack_chk_fail(void) in it's own object file and and add this .o file to your linker command AFTER libgurobi_c++.a.  GCC/G++ resolves symbols from left to right during linking so despite your code having the function defined, a copy of an object containing the __stack_chk_fail symbol needs to be on the linker line to the right of libgurobi_c++.a.

Body:
Getting this error while compiling C++ code:

undefined reference to `__stack_chk_fail'

Options already tried:

added -fno-stack-protector while compiling - did not work, error persists

added a dummy implementation of void __stack_chk_fail(void) in my code. Still getting the same error.

Detailed Error:

/u/ac/alanger/gurobi/gurobi400/linux64/lib/libgurobi_c++.a(Env.o)(.text+0x1034): In function `GRBEnv::getPar/u/ac/alanger/gurobi/gurobi400/linux64/lib/libgurobi_c++.a(Env.o)(.text+0x1034): In function `GRBEnv::getParamInfo(GRB_StringParam, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
: undefined reference to `__stack_chk_fail'
amInfo(GRB_StringParam, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
: **undefined reference to `__stack_chk_fail'**

Earlier, I was getting 10's of such errors. Found out that there was a version mismatch between the gcc of the pre-compiled libraries I am using and the gcc version I was using to compile the code. Updated gcc and now I am getting only 2 of these errors.

Any help, please?

ContentLicense: CC BY-SA 4.0


问:
MERGE statement DELETE alternative in SQL Server
I have a Query using T-SQL MERGE Statement. Due to performance issues I am re writing the Query using IF Exists Update and If Not Exists Insert. I am able to write Insert/Update without any issue. But I am unable to handle the DELETE. Can some one please help me on this?

Here is the sample

```<code>---SAMPLE MERGE STATEMENT
MERGE
   member_topic AS target
USING
   someOtherTable AS source
ON
   target.mt_member = source.mt_member

WHEN MATCHED THEN
   UPDATE SET target.mt_notes = source.mt_notes
WHEN NOT MATCHED THEN
   INSERT (mt_member, mt_topic, mt_notes) VALUES (source.mt_member, source.mt_notes)

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

--UPDATE

UPDATE T SET T.mt_notes = S.mt_notes
FROM member_topic T
JOIN someOtherTable S ON T.mt_member=S.mt_member

--INSERT

INSERT INTO member_topic(mt_member, mt_topic, mt_notes)
SELECT mt_member, mt_topic, mt_notes
FROM someOtherTable S
WHERE NOT EXISTS(SELECT 1
                 FROM member_topic T
                 WHERE T.mt_member=S.mt_member)
</code>```

How to handle

```<code>WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;
</code>```

in single DELETE Statement.

答:
a sample script to be embedded between begin and end in proc</p>

```<code>   MERGE dbo.Tablet AS TARGET
     USING dbo.QueryView AS SOURCE
    ON (
        TARGET.[ID] = SOURCE.[ID]
        )

 WHEN MATCHED

  THEN
 UPDATE SET

 TARGET.[ID] = SOURCE.[ID]

 WHEN NOT MATCHED BY TARGET THEN
 INSERT (ID, [Name]  )
 VALUES (SOURCE.[ID], SOURCE.[Name]  )

 WHEN NOT MATCHED BY SOURCE THEN
 DELETE;
</code>```

Body:
I have a Query using T-SQL MERGE Statement. Due to performance issues I am re writing the Query using IF Exists Update and If Not Exists Insert. I am able to write Insert/Update without any issue. But I am unable to handle the DELETE. Can some one please help me on this?

Here is the sample

---SAMPLE MERGE STATEMENT
MERGE
   member_topic AS target
USING
   someOtherTable AS source
ON
   target.mt_member = source.mt_member

WHEN MATCHED THEN
   UPDATE SET target.mt_notes = source.mt_notes
WHEN NOT MATCHED THEN
   INSERT (mt_member, mt_topic, mt_notes) VALUES (source.mt_member, source.mt_notes)

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

--UPDATE

UPDATE T SET T.mt_notes = S.mt_notes
FROM member_topic T
JOIN someOtherTable S ON T.mt_member=S.mt_member

--INSERT

INSERT INTO member_topic(mt_member, mt_topic, mt_notes)
SELECT mt_member, mt_topic, mt_notes
FROM someOtherTable S
WHERE NOT EXISTS(SELECT 1
                 FROM member_topic T
                 WHERE T.mt_member=S.mt_member)

How to handle

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

in single DELETE Statement.

Body:
a sample script to be embedded between begin and end in proc

   MERGE dbo.Tablet AS TARGET
     USING dbo.QueryView AS SOURCE
    ON (
        TARGET.[ID] = SOURCE.[ID]
        )

 WHEN MATCHED

  THEN
 UPDATE SET

 TARGET.[ID] = SOURCE.[ID]

 WHEN NOT MATCHED BY TARGET THEN
 INSERT (ID, [Name]  )
 VALUES (SOURCE.[ID], SOURCE.[Name]  )

 WHEN NOT MATCHED BY SOURCE THEN
 DELETE;


问:
Delete duplicate rows based on a condition
I have a table that has ID and EventDate. It has duplicate rows as I used Union of two tables. Now I got to have the rows with the minimum Eventdate and remove the other duplicates.

the table for eg

ID  | Date

--- | ---

1     | 10/27/1993

1      | 10/27/1994

2      | 10/17/1993

2      | 08/15/1993

Delete duplicate rows based on condition

答:
You can use ROW_NUMBER:

```<code>;WITH CTE AS
(
   SELECT *,
          RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY EventDate)
   FROM dbo.YourTable
)
DELETE FROM CTE
WHERE RN > 1;
</code>```

Body:
You can use ROW_NUMBER:

;WITH CTE AS
(
   SELECT *,
          RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY EventDate)
   FROM dbo.YourTable
)
DELETE FROM CTE
WHERE RN > 1;


问:
Using xpath with python lxml to query html
I am reading a html page as a string and use tree = html.fromstring(data)

I now want to use lxml xpath to query. Below are an example of the part i am interested in.

```<code><table class="class">
 <tbody>
  <tr>
   <th class="classTh">
    Overall
   </th>
   <td class="classTd">
    <span class="classSpan">
     GREEN
    </span>
   </td>
  </tr>
 </tbody>
</table>
</code>```

with the call

```<code> xpath = '//table/tbody/tr[th="Overall"]/td/span'
 e = tree.xpath(xpath)
  for i in e:
   print(i.text)
</code>```

I am using xpath to get the data i need. But i cannot get the xpath to work. Using this exact code + xpath in any online tester works for me.

I have tried with xpath:

```<code>xpath = '//table/tbody/tr[th]/td/span'
</code>```

which gets me all elements instead of the ones with the correct filter value.

```<code> xpath ='//table/tbody/tr[td/span]/th'
</code>```

gets me all the filter values.

So my question. How to i apply the text value filter in my xpath correctly?

答:
The syntax for this xpath in lxml is the following:        </p>

```<code>xpath = "//table/tbody/tr[th[contains(text(), 'Overall')]]/td/span"
</code>```

<p>Which solved my problem. </p>

Body:
I am reading a html page as a string and use tree = html.fromstring(data)

I now want to use lxml xpath to query. Below are an example of the part i am interested in.

    Overall

     GREEN

with the call

 xpath = '//table/tbody/tr[th="Overall"]/td/span'
 e = tree.xpath(xpath)
  for i in e:
   print(i.text)

I am using xpath to get the data i need. But i cannot get the xpath to work. Using this exact code + xpath in any online tester works for me.

I have tried with xpath:

xpath = '//table/tbody/tr[th]/td/span'

which gets me all elements instead of the ones with the correct filter value.

 xpath ='//table/tbody/tr[td/span]/th'

gets me all the filter values.

So my question. How to i apply the text value filter in my xpath correctly?

Body:
The syntax for this xpath in lxml is the following:

xpath = "//table/tbody/tr[th[contains(text(), 'Overall')]]/td/span"

Which solved my problem.


问:
use addEventListener to replace each onClick
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

```<code><ul>
   <li><button class="bb" value="apple" onClick="aJax(value)">Apple</button></li>
   <li>Banana
      <ul>
         <li><button class="bb" value="green_banana" onClick="aJax(value)">Green_banana</button></li>
         <li><button class="bb" value="yellow_banana" onClick="aJax(value)">Yellow Banana</button></li>
      </ul>
   </li>
   <li><button class="bb" value="cherry" onClick="aJax(value)">Cherry</button></li>
   <li><button class="bb" value="cow..................and more....
</ul>
</code>```

If clicked, I want to pass value to Ajax to return data from mySql:

```<code>  <script>
  function aJax(value)
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET","some_page.php?q="+value,true);
      xmlhttp.send();
      xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       document.getElementById("some_id").innerHTML = xmlhttp.responseText;}
                                                }
                 }
  </script>
</code>```

Is it possible to use addEventListener in my case above to replace each onClick? How to do it if I want to put the JS code on the header? Pls help, I need it in native JS. Thanks.

答:
While other answers are right, if your list is long, you might delegate the click to the ul element :

function logValue(evt){
  let target = evt.target;
  // only console.log if the click target has class "bb"
  if(target.classList.contains("bb")){
    console.log(target.value)
  }
}

// wait for the document to be loaded
window.addEventListener("load",()=>{
  let list = document.querySelector(".my-list");
  if(list){
    //delegate click handler to the
 element
    list.addEventListener("click", logValue);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="my-list">
  <li><button class="bb" value="apple">Apple</button></li>
  <li>Banana
    <ul>
       <li><button class="bb" value="green_banana">Green_banana</button></li>
       <li><button class="bb" value="yellow_banana">Yellow Banana</button></li>
    </ul>
  </li>
  <li><button class="bb" value="cherry">Cherry</button></li>
</ul></code>```

Body:
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

<button class="bb" value="apple" onClick="aJax(value)">Apple</button>

Banana

<button class="bb" value="green_banana" onClick="aJax(value)">Green_banana</button>

<button class="bb" value="yellow_banana" onClick="aJax(value)">Yellow Banana</button>

<button class="bb" value="cherry" onClick="aJax(value)">Cherry</button>

<button class="bb" value="cow..................and more....

If clicked, I want to pass value to Ajax to return data from mySql:

Is it possible to use addEventListener in my case above to replace each onClick? How to do it if I want to put the JS code on the header? Pls help, I need it in native JS. Thanks.

Body:
While other answers are right, if your list is long, you might delegate the click to the ul element :

function logValue(evt){
  let target = evt.target;
  // only console.log if the click target has class "bb"
  if(target.classList.contains("bb")){
    console.log(target.value)
  }
}

// wait for the document to be loaded
window.addEventListener("load",()=>{
  let list = document.querySelector(".my-list");
  if(list){
    //delegate click handler to the <ul> element
    list.addEventListener("click", logValue);
  }
});

<ul class="my-list">
  <li><button class="bb" value="apple">Apple</button></li>
  <li>Banana
    <ul>
       <li><button class="bb" value="green_banana">Green_banana</button></li>
       <li><button class="bb" value="yellow_banana">Yellow Banana</button></li>
    </ul>
  </li>
  <li><button class="bb" value="cherry">Cherry</button></li>
</ul>


问:
How do I create a custom web part from a custom list in sharepoint 2007
I want to create a custom web part in SharePoint 2007 that allows me to take items from an existing custom list (i.e. Title, Hyperlink, Description and photo) and then render it in a format of my choice. How can I do this using C# asp.net and a web part?</p>

答: you can use sharepoint object model to achieve the same SPList class will provide you all informations you need refer the attached link. You can use also use DVWP for the same</p>


问:
Add a node to specific key xml using sed
I am trying to edit the XML file using sed. Here is the file content which I am trying to edit.

```<code><configuration key="student1">
   <list>
     <value>abc</value>
     <value>def</value>
   </list>
</configuration>
</code>```

I want to add the following value to the existing node by comparing the key value.

```<code><configuration key="student1">
    <list>
      <value>abc</value>
      <value>NEWVALUE</value>
      <value>def</value>
    </list>
</configuration>
</code>```

How can I achieve it using the sed command? After going to lot of posts, xmlstarlet is the best one to edit the xml files. but I am not able to install due to permission issue. Can someone help me for the solution?

Update:

What I have tried is :

```<code>sed -i "s/\<\list\>/ \<value\> NEWVALUE\<\/VALUE\>/" xmlfile
</code>```

This is not working as expected, its replacing the list tag with the NEWVALUE. But I need to compare the key value, then traverse through the lists, then add the new value.

答:
If you are desperate and the order of the values isn't important you could use sed and insert the value before the closing list tag and so:

```<code>sed -r '/\<\list\>/ i\ \t<value>NEWVAL</value>' xmlfile
</code>```

Search the the closing list tag and then enter the value tags along with the NEWVAL value.

Body:
I am trying to edit the XML file using sed. Here is the file content which I am trying to edit.

<configuration key="student1">
   <list>
     <value>abc</value>
     <value>def</value>
   </list>
</configuration>

I want to add the following value to the existing node by comparing the key value.

<configuration key="student1">
    <list>
      <value>abc</value>
      <value>NEWVALUE</value>
      <value>def</value>
    </list>
</configuration>

How can I achieve it using the sed command? After going to lot of posts, xmlstarlet is the best one to edit the xml files. but I am not able to install due to permission issue. Can someone help me for the solution?

Update:

What I have tried is :

sed -i "s/\<\list\>/ \<value\> NEWVALUE\<\/VALUE\>/" xmlfile

This is not working as expected, its replacing the list tag with the NEWVALUE. But I need to compare the key value, then traverse through the lists, then add the new value.

Body:
If you are desperate and the order of the values isn't important you could use sed and insert the value before the closing list tag and so:

sed -r '/\<\list\>/ i\ \t<value>NEWVAL</value>' xmlfile

Search the the closing list tag and then enter the value tags along with the NEWVAL value.


问:
How to apply decimal and thousand separator to numbers in cbar?
I want to apply decimal and thousands separator to cbar in Seaborm plot in order to see numbers formatted like this: 4.294.967.295,00.
I know how to format xaxis and yaxis, but cannot apply this formating to cbar.

```<code>plt.figure(figsize=(12,8))
ax = sns.heatmap(df, annot=False, linewidths=.5)
ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: str(int(x))+":00"))
plt.show()
</code>```

答:
This template code should help you out.  Takes an unformatted number, adds the "," before the last 2 digits, then goes through and adds the "." every 3 characters.

```<code>number = "1000000000"
temp = ""
temp += number[:-2] + "," + number[-2:]
e = list(temp.split(",")[0])
for i in range(len(e))[::-3][1:]:
    e.insert(i+1,".")
result = "".join(e)+","+temp.split(",")[1]
print(result)
</code>```

This is result for the static number I gave.: 10.000.000,00

Body:
I want to apply decimal and thousands separator to cbar in Seaborm plot in order to see numbers formatted like this: 4.294.967.295,00.
I know how to format xaxis and yaxis, but cannot apply this formating to cbar.

plt.figure(figsize=(12,8))
ax = sns.heatmap(df, annot=False, linewidths=.5)
ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: str(int(x))+":00"))
plt.show()

Body:
This template code should help you out.  Takes an unformatted number, adds the "," before the last 2 digits, then goes through and adds the "." every 3 characters.

number = "1000000000"
temp = ""
temp += number[:-2] + "," + number[-2:]
e = list(temp.split(",")[0])
for i in range(len(e))[::-3][1:]:
    e.insert(i+1,".")
result = "".join(e)+","+temp.split(",")[1]
print(result)

This is result for the static number I gave.: 10.000.000,00


问:
What are the design patterns for Rest API automation using java
I am a new to REST API automation project, as part of that I have learned using jayway rest assured instead of jersy client. Now, the problem is I am able to use protocol methods and getting response to parse and checking required data is not.

Now,

I want to explore more to implement project setup like a pro, by using structured java classes or by using any class designs.

I want to use this project for load testing
I want to learn parameterization, i.e., First request's response may be input to 4th request (ex: login token id used for subsequent requests)
I also want to know how to feed data as input from external files

Note: I have searched for sample projects on other channels but they are not as per my requirement and I spent time to understand those project but going over my head, couldn't able to understand their style of implementation  :(

答:
Well, there are several things that you need to learn/understand:

It is not about design patterns, them you should learn in any case to consider yourself as a good developer or software engineer in test

REST Assured - is indeed for API testing, yes, but not the best
choice, or even, is the last choice for load/performance testing

Haveing request based dependencies, more sound like component testing or end-to-end testing which is usually also the last choice
and have to be as minimum as possible

Load/performance tools that you can choose and learn by your preferences are (not a full list, but ones that I used to use)

Blazemeter

Gatling

Jmeter