问:
How to use an object of a function inside a class from another script in python?
I am trying to run the below script for generating an email notification:

```<code>class ecom_common_functions_class(sendmailobject):
    def __init__(self):
        count = 0

    def ecom_send_mail_without_attachement(self,email_sender_id,email_reciever_id,mail_body,mail_subj,server):
        print "INSIDE MAIL SENT FUNCTION"
        msg = MIMEMultipart()
        print "in function email_reciever_id =", email_reciever_id
        msg['From'] = email_sender_id
        msg['To'] = email_reciever_id
        msg['Subject'] = mail_subj
        body = mail_body
        msg.attach(MIMEText(body, 'html'))
        part = MIMEBase('application', 'octet-stream')
        encoders.encode_base64(part)
        server = smtplib.SMTP('localhost')
        text = msg.as_string()
        server.sendmail(email_sender_id, email_reciever_id, text)
        server.quit()
</code>```

When I import this function in another script I get this error:

```<code>Traceback (most recent call last):
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_validation_negative.py", line 10, in <module>
    import ecom_nis_common_functions
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_common_functions.py", line 32, in <module>
    class ecom_common_functions_class(sendmailobject):
NameError: name 'sendmailobject' is not defined
</code>```

The result must be printed as a message in an email.

答: you have to import that class from the module, looks like you are not importing it or the code wasn't paste in its totality.</p>

Body:
I am trying to run the below script for generating an email notification:

class ecom_common_functions_class(sendmailobject):
    def __init__(self):
        count = 0

    def ecom_send_mail_without_attachement(self,email_sender_id,email_reciever_id,mail_body,mail_subj,server):
        print "INSIDE MAIL SENT FUNCTION"
        msg = MIMEMultipart()
        print "in function email_reciever_id =", email_reciever_id
        msg['From'] = email_sender_id
        msg['To'] = email_reciever_id
        msg['Subject'] = mail_subj
        body = mail_body
        msg.attach(MIMEText(body, 'html'))
        part = MIMEBase('application', 'octet-stream')
        encoders.encode_base64(part)
        server = smtplib.SMTP('localhost')
        text = msg.as_string()
        server.sendmail(email_sender_id, email_reciever_id, text)
        server.quit()

When I import this function in another script I get this error:

Traceback (most recent call last):
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_validation_negative.py", line 10, in <module>
    import ecom_nis_common_functions
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_common_functions.py", line 32, in <module>
    class ecom_common_functions_class(sendmailobject):
NameError: name 'sendmailobject' is not defined

The result must be printed as a message in an email.


来源: stackexchange

问:
Is this a violation of the Law of Demeter? vs. readable code
The code below brakes apparently the Law of Demeter, i.e. methods getServer().methodx(...). From other side it looks pretty compact = better readable?

```<code>abstract class BaseManager {
    ResultSet find(String searchText) {
        return getServer().find(searchText);
    }

    ResultSet fetch(String fetchText) {
        return getServer().fetch(fetchText);
    }

    void save(String saveText) {
        getServer().save(saveText);
    }

    abstract BaseManager getServer();
}

class Server1Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server1;
    }
}

class Server2Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server2;
    }
}
</code>```

If the law is violated, them how to refactor this code?
Many thanks in advance.

答:
For me it's much better after you have implemented 3 methods in manager.

You can have 1 data manager exposing methods for both servers.

There's another rule I like: Don't ask - tell.

ContentLicense: CC BY-SA 3.0

Body:
The code below brakes apparently the Law of Demeter, i.e. methods getServer().methodx(...). From other side it looks pretty compact = better readable?

abstract class BaseManager {
    ResultSet find(String searchText) {
        return getServer().find(searchText);
    }

    ResultSet fetch(String fetchText) {
        return getServer().fetch(fetchText);
    }

    void save(String saveText) {
        getServer().save(saveText);
    }

    abstract BaseManager getServer();
}

class Server1Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server1;
    }
}

class Server2Manager extends BaseManager {
    @Override
    protected BaseManager getServer() {
        return server2;
    }
}

If the law is violated, them how to refactor this code?
Many thanks in advance.


问:
how to get the triangle vector coordinate if the triangle area is known
i have a triangle, the vector is A(x1,y1), B(x2,y2), C(x3,y3), these are all known
,then i want to move up the Vector A to a new Position D(x1, y4)--just change the coordinate y, if the new triangle(BCD)'s area is known, how can i caculate the y4?

thanks to SaiBot, him share a solution like this:

答:
Geometrically thinking this can be solved in two steps.

move A perpendicular to BC to the upper left until the triangle has the correct size. The size of a triangle is calculated by 1/2 * base * height.

move A parallel to BC until A.x = D.x1. This will not change the area of the rectangle.


问:
VBA to create a dynamic number of copies of a table
I am very new to excel and have hit a wall with this issue. I am trying to copy a template table and make a dynamic number of back-to-back copies of it. I want to make the title of each table the name of a customer, which I will pull from another table. Here is what I mean:

Any help would be highly appreciated. I hope my explanation makes sense, but let me know if I need to clarify what I mean.

答:
If you were to place the Customer list on Column H then this would copy the tables into Sheet2 as you wanted:</p>

```<code>Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "H").End(xlUp).Row ' Count Column H as that's where the customer list is
For i = 2 To LastRow 'loop from row 2 to the last on column H
    NewCustomer = Sheet1.Cells(i, 8).Value 'get the customer Name 8 being Column H
    LastRow2 = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row + 1 'find the next free row in Sheet2
    Sheet1.Range("A1:C4").Copy Destination:=Sheet2.Range("A" & LastRow2) 'paste the range into Sheet2
    Sheet2.Range("A" & LastRow2).Value = NewCustomer 'Replace the Customer Name
Next i
End Sub
</code>```

Body:
If you were to place the Customer list on Column H then this would copy the tables into Sheet2 as you wanted:

Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "H").End(xlUp).Row ' Count Column H as that's where the customer list is
For i = 2 To LastRow 'loop from row 2 to the last on column H
    NewCustomer = Sheet1.Cells(i, 8).Value 'get the customer Name 8 being Column H
    LastRow2 = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row + 1 'find the next free row in Sheet2
    Sheet1.Range("A1:C4").Copy Destination:=Sheet2.Range("A" & LastRow2) 'paste the range into Sheet2
    Sheet2.Range("A" & LastRow2).Value = NewCustomer 'Replace the Customer Name
Next i
End Sub


问:
Angularjs and Spring session management
I'm using angularjs and spring security together.

Everything is fine, but session management problem hasn't been solving.

this is my code => security.xml

```<code><session-management invalid-session-url="/sessionout">
            <concurrency-control expired-url="/login" />
</session-management>
</code>```

angularjs router can't catch a url /sessinout. So I don't know how to deal with this. What I have to do, to deal with that url?

And last question!!
At the first, I thought I didn't need that <session-management> tag.
however, without that tag, front didn't recognize that session had gone out.
How to deal with spring security session with angularjs?

答:
A late response, to help other people searching an answer. You have to distinguish url catch by your java controller and others catch by angularjs.

If in your app.js you've got a path route like

```<code> .when('/error/expired', {
      templateUrl: 'error/expired',
 })
</code>```

Angularjs will catch the following url with hashbang

http://localhost/app/#/error/expired

If you use the following url, in my case using thymeleaf for templating, I have got some java controller.

http://localhost/app/error/expired

You will reach the java controller with the corresponding url

Of course this solution works if the html5 mode in the locationProvider is not used.

To answer to the question

```<code><session-management invalid-session-url="/#/sessionout">
</code>```

Would be redirect to angular rooter.

Title: Angularjs and Spring session management

Body:
I'm using angularjs and spring security together.

Everything is fine, but session management problem hasn't been solving.

this is my code => security.xml

<session-management invalid-session-url="/sessionout">
            <concurrency-control expired-url="/login" />
</session-management>

angularjs router can't catch a url /sessinout. So I don't know how to deal with this. What I have to do, to deal with that url?

And last question!!
At the first, I thought I didn't need that <session-management> tag.
however, without that tag, front didn't recognize that session had gone out.
How to deal with spring security session with angularjs?

Body:
A late response, to help other people searching an answer. You have to distinguish url catch by your java controller and others catch by angularjs.

If in your app.js you've got a path route like

 .when('/error/expired', {
      templateUrl: 'error/expired',
 })

Angularjs will catch the following url with hashbang

http://localhost/app/#/error/expired

If you use the following url, in my case using thymeleaf for templating, I have got some java controller.

http://localhost/app/error/expired

You will reach the java controller with the corresponding url

Of course this solution works if the html5 mode in the locationProvider is not used.

To answer to the question

<session-management invalid-session-url="/#/sessionout">

Would be redirect to angular rooter.


问:
How to read one line at a time from a data file and to perform calculations in it before moving to the next line in C Programming?
I'm a beginner at C programming and I would appreciate some help in order to understand the problem.

Alright so, I have a data file (input.dat) with data like this: (first line) 0 2 3 4 5; (second line) 1 2 3 5 4, (third line and so on...). I'm required to read the data one line at a time until the end of file and print it. This is what I have done so far:

```<code>int main(void)
{
float coeffs[5];
FILE *input;  /* File pointer to the input file */
fopen_s(&input, "input.dat", "r"); /* Location of the input file */
int count = 0;
/* Loops to read data set*/
while (fscanf_s(input, "%f %f %f %f %f ", &coeffs[0], &coeffs[1], &coeffs[2], &coeffs[3], &coeffs[4]) != EOF)
{
    printf("a=%.4f; b=%.4f; c=%.4f; d=%.4f; e=%.4f\n", coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4]);
    count++;
}
return 0;
}
</code>```

This is showing all of the lines in the data file at once. But this is not what I want. I need to read one line at a time and perform some calculations and conditions for that one line first before I move to the next line. So how can I do that?

Next problem is, for the first line, I need to implement a loop from -10 to +10 with increment of 2 (to get 11 results in total). For example the program will read the first line, display it on the screen, then for the first value -10, the program will calculate and again display something . Then it will do the same for -8, then for -6 and so on until +10. After the 11 results are displayed, the program will then and ONLY then, move to the second line and so on. Hence for each line in the data file, the program will have 11 results. How can I use the loop function with increment of 2 to achieve these 11 results?

I would appreciate if anyone can provide me a simple layout of the structure of the codes which I've to write. NOTE: The formats are a bit different than other compilers as I must use Microsoft Visual Studio to do it.

答:
Add your calculations to your while loop. You are reading one line at a time anyway.

If you want to loop from -10 to 10 with increments of 2, use a for loop.

```<code>for(count = -10; count <= 10; count = count + 2)
    {
        // Calculations
    }
</code>```

Body:
I'm a beginner at C programming and I would appreciate some help in order to understand the problem.

Alright so, I have a data file (input.dat) with data like this: (first line) 0 2 3 4 5; (second line) 1 2 3 5 4, (third line and so on...). I'm required to read the data one line at a time until the end of file and print it. This is what I have done so far:

int main(void)
{
float coeffs[5];
FILE *input;  /* File pointer to the input file */
fopen_s(&input, "input.dat", "r"); /* Location of the input file */
int count = 0;
/* Loops to read data set*/
while (fscanf_s(input, "%f %f %f %f %f ", &coeffs[0], &coeffs[1], &coeffs[2], &coeffs[3], &coeffs[4]) != EOF)
{
    printf("a=%.4f; b=%.4f; c=%.4f; d=%.4f; e=%.4f\n", coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4]);
    count++;
}
return 0;
}

This is showing all of the lines in the data file at once. But this is not what I want. I need to read one line at a time and perform some calculations and conditions for that one line first before I move to the next line. So how can I do that?

Next problem is, for the first line, I need to implement a loop from -10 to +10 with increment of 2 (to get 11 results in total). For example the program will read the first line, display it on the screen, then for the first value -10, the program will calculate and again display something . Then it will do the same for -8, then for -6 and so on until +10. After the 11 results are displayed, the program will then and ONLY then, move to the second line and so on. Hence for each line in the data file, the program will have 11 results. How can I use the loop function with increment of 2 to achieve these 11 results?

I would appreciate if anyone can provide me a simple layout of the structure of the codes which I've to write. NOTE: The formats are a bit different than other compilers as I must use Microsoft Visual Studio to do it.

Body:
Add your calculations to your while loop. You are reading one line at a time anyway.

If you want to loop from -10 to 10 with increments of 2, use a for loop.

for(count = -10; count <= 10; count = count + 2)
    {
        // Calculations
    }


问:
Is it possible to use QueryView with EF Code-First?
The title should be self explanatory. QueryView in EDMX allows predefined projections and conditional queries. QueryView creates additional readonly mapping.

Example:

Suppose that we have BlogPost table which has Title, ShortDescription and Content columns. If we want to use BlogPost we will use directly this entity. If we want to show list of recent BlogPosts showing only titles and descriptions we will not want to load contents as well. One way is to use query with projection directly. Other way is to map this projection in EDMX (by using QueryView = reusable projection is part of your mapping) to new entity called BlogPostInfo. Then you can query your context for BlogPostInfo entities when showing list of blog posts.

答: I found that it is possilbe to use QueryView if DbContext is generated from EDMX because in such case DbContext only wrapps mapping in EDMX. But it is not what I was looking for. Code first itself probably doesn't offer any QueryView equivalent so the best way is probably define reusable projection queries as methods directly on derived DbContext implementation.

ContentLicense: CC BY-SA 2.5


问:
No bundle URL present in custom React Native project
I am trying to make an existing iOS app use React Native and therefore I wrote the code for bridging the two manually and not using the CLI tool provided. I want the RCTBundleURLProvider to detect the IP address of the bundle server automatically, like in the apps generated by the CLI tool.

Finally, when I run the app:

```<code>react-native run-ios
react-native start --> the bundle server doesn't start automatically, which is strange
</code>```

When loading the React Native bundle in the simulator or device, the error No bundle URL present comes up.

Doing clean / npm install / running react-native run-ios doesn't help. Setting the URL directly in the code works, so this isn't a firewall/AppTransportSecurity issue.

What am I missing?

AppDelegate.m - jsCodeLocation returned by RCTBundleURLProvider is equal to null:

```<code>...
- (void) loadReact:(NSDictionary*) launchOptions {

    NSURL *jsCodeLocation;

    jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
    // this WORKS --> jsCodeLocation = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx:8081/index.bundle?platform=ios"];

    NSLog(@"JSCodeLocation:%@",jsCodeLocation); // jsCodeLocation equals null

    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                        moduleName:@"MyModule"
                                                 initialProperties:nil
                                                     launchOptions:launchOptions];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;

    rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
}
...
</code>```

RCTBundleURLProvider.m looks for a file named ip.txt, which appears to be missing.

```<code>...
- (NSString *)guessPackagerHost
{
  static NSString *ipGuess;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    NSString *ipPath = [[NSBundle mainBundle] pathForResource:@"ip" ofType:@"txt"];
    ipGuess = [[NSString stringWithContentsOfFile:ipPath encoding:NSUTF8StringEncoding error:nil]
               stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
  });

  NSString *host = ipGuess ?: @"localhost";
  if ([self isPackagerRunning:host]) {
    return host;
  }
  return nil;
}
...
</code>```

package.json:

```<code>{
  "name": "MyModule",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0",
    "react-native": "0.51.0"
  },
  "devDependencies": {
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答:
I've opened an issue on React Native about it some time ago.

Here are some solutions:

Run react-native run-ios

When the error appears, run npm install

Then run react-native run-ios again

Add NSAllowsLocalNetworking to info.plist

Make sure you have 127.0.0.1 localhost in your hosts

Kill any other proccess sudo lsof -i :8081, then kill -9 <PID>

Remove YOUR_PROJECT/ios/build/ then react-native run-ios again

I hope one of these solutions will solve your issue. If not, you can find more options on the issue.

Body:
I am trying to make an existing iOS app use React Native and therefore I wrote the code for bridging the two manually and not using the CLI tool provided. I want the RCTBundleURLProvider to detect the IP address of the bundle server automatically, like in the apps generated by the CLI tool.

Finally, when I run the app:

react-native run-ios
react-native start --> the bundle server doesn't start automatically, which is strange

When loading the React Native bundle in the simulator or device, the error No bundle URL present comes up.

Doing clean / npm install / running react-native run-ios doesn't help. Setting the URL directly in the code works, so this isn't a firewall/AppTransportSecurity issue.

What am I missing?

AppDelegate.m - jsCodeLocation returned by RCTBundleURLProvider is equal to null:

...
- (void) loadReact:(NSDictionary*) launchOptions {

    NSURL *jsCodeLocation;

    jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
    // this WORKS --> jsCodeLocation = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx:8081/index.bundle?platform=ios"];

    NSLog(@"JSCodeLocation:%@",jsCodeLocation); // jsCodeLocation equals null

    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                        moduleName:@"MyModule"
                                                 initialProperties:nil
                                                     launchOptions:launchOptions];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;

    rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
}
...

RCTBundleURLProvider.m looks for a file named ip.txt, which appears to be missing.

...
- (NSString *)guessPackagerHost
{
  static NSString *ipGuess;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    NSString *ipPath = [[NSBundle mainBundle] pathForResource:@"ip" ofType:@"txt"];
    ipGuess = [[NSString stringWithContentsOfFile:ipPath encoding:NSUTF8StringEncoding error:nil]
               stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
  });

  NSString *host = ipGuess ?: @"localhost";
  if ([self isPackagerRunning:host]) {
    return host;
  }
  return nil;
}
...

package.json:

{
  "name": "MyModule",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0",
    "react-native": "0.51.0"
  },
  "devDependencies": {
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

ContentLicense: CC BY-SA 4.0


问:
ORDER BY in statement before UNION ALL
I have this query :

```<code>SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona I')  AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
         OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)

UNION ALL

SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona II') AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND NOT ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
             OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
ORDER BY
    NAZIV
</code>```

This query orders by 'NAZIV' whole statement after union all.

But i want both query to order by 'NAZIV' before UNION ALL

答:
Your query has numerous issues.  I think this is what you want:

```<code>SELECT distinct Cast(ud.[ID_DRZAVE] as varchar(255)) as ID,
       CONCAT(d.NAZIV_DRZAVE, ' - ',
              Cast(ud.[ID_DRZAVE] as varchar(255)),
              (CASE WHEN ud.ID_DRZAVE IN (295, 293) THEN ' - Zona I' ELSE ' - Zona II' END)
             ) as NAZIV
FROM [dbo].[SV_USLUGA_DRZAVA] ud JOIN
     [SIF_DRZAVE] d
     ON ud.[ID_DRZAVE] = d.[ID_DRZAVE]
WHERE d.SIF_VRSTA_USLUGA = 139
ORDER BY (CASE WHEN ud.ID_DRZAVE IN (295, 293) THEN 1 ELSE 0 END),
         NAZIV;
</code>```

Notes:

The FULL JOINs are being undone by the WHERE clause.  Use the appropriate JOIN.

Use IN rather than chained OR conditions.

Never use VARCHAR() with no length in SQL Server.  The default length varies by context and debugging this problem can be really challenging.

Table aliases make the query easier to write and to read.

You don't need a UNION/UNION ALL at all for what you want to accomplish.

Title: ORDER BY in statement before UNION ALL

Body:
I have this query :

SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona I')  AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
         OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)

UNION ALL

SELECT DISTINCT
    CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar) AS ID,
    CONCAT([SIF_DRZAVE].NAZIV_DRZAVE,' - ',CAST([SV_USLUGA_DRZAVA].[ID_DRZAVE] AS varchar),' - Zona II') AS NAZIV
FROM
    [dbo].[SV_USLUGA_DRZAVA]
FULL OUTER JOIN
    [SIF_DRZAVE] ON ([SV_USLUGA_DRZAVA].[ID_DRZAVE]=[SIF_DRZAVE].[ID_DRZAVE])
WHERE
    [SV_USLUGA_DRZAVA].SIF_VRSTA_USLUGA = 139
    AND NOT ([SV_USLUGA_DRZAVA].ID_DRZAVE = 295
             OR [SV_USLUGA_DRZAVA].ID_DRZAVE = 293)
ORDER BY
    NAZIV

This query orders by 'NAZIV' whole statement after union all.

But i want both query to order by 'NAZIV' before UNION ALL

Body:
Your query has numerous issues.  I think this is what you want:

SELECT distinct Cast(ud.[ID_DRZAVE] as varchar(255)) as ID,
       CONCAT(d.NAZIV_DRZAVE, ' - ',
              Cast(ud.[ID_DRZAVE] as varchar(255)),
              (CASE WHEN ud.ID_DRZAVE IN (295, 293) THEN ' - Zona I' ELSE ' - Zona II' END)
             ) as NAZIV
FROM [dbo].[SV_USLUGA_DRZAVA] ud JOIN
     [SIF_DRZAVE] d
     ON ud.[ID_DRZAVE] = d.[ID_DRZAVE]
WHERE d.SIF_VRSTA_USLUGA = 139
ORDER BY (CASE WHEN ud.ID_DRZAVE IN (295, 293) THEN 1 ELSE 0 END),
         NAZIV;

Notes:

The FULL JOINs are being undone by the WHERE clause.  Use the appropriate JOIN.

Use IN rather than chained OR conditions.

Never use VARCHAR() with no length in SQL Server.  The default length varies by context and debugging this problem can be really challenging.

Table aliases make the query easier to write and to read.

You don't need a UNION/UNION ALL at all for what you want to accomplish.


问:
Change Node-RED UI button color via MQTT
I have a node-red flow on a raspberry pi home security network, using MQTT as a message bus. How would one change colors on the UI buttons based on incoming MQTT messages?

I've not been able to find any examples of how to do this anywhere. I imagine this will be tied to CSS and javascript but I'm weak in these areas.

答:
How to do this is described in the info tab for the dashboard ui button:

The colours of the text and background may be set. They can also be set by a message property by setting the field to the name of the property, for example {{msg.background}}.

so you can set the background of the button by configuring the button like this:

Then passing in a message with the msg.backgound set to the colour you want (colours can be any CSS colour safe name).

You can use a function node or a change node to add the background property to the msg before passing it to the ui-button node.


问:
What is the DateTimeStyles operator in .NET?
When I add this code

```<code>DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowInnerWhite
</code>```

Intellisense shows the following message:

```<code>DateTimeStyles DateTimeStyles.operator |(DateTimeStyles left, DateTimeStyles right).
</code>```

What does this operator do?

答:
DateTimeStyles isn't an operator - it's an enum, and all enums have the | operator. All it does is apply a bitwise | for the two values. It should only be used for flag-based enums. For example:

```<code>public enum AccessMode
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4
}
</code>```

If you use:

```<code>AccessMode mode = AccessMode.Write | AccessMode.Delete;
</code>```

then you'll have a value with an underlying integer value of 6.

Basically, it allows you to specify a single value representing multiple flags within the enum - so for you're example, you're saying "I want the result to be adjusted to UTC, and allow inner whitespace when parsing."

Body:
When I add this code

DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowInnerWhite

Intellisense shows the following message:

DateTimeStyles DateTimeStyles.operator |(DateTimeStyles left, DateTimeStyles right).

What does this operator do?

Body:
DateTimeStyles isn't an operator - it's an enum, and all enums have the | operator. All it does is apply a bitwise | for the two values. It should only be used for flag-based enums. For example:

public enum AccessMode
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4
}

If you use:

AccessMode mode = AccessMode.Write | AccessMode.Delete;

then you'll have a value with an underlying integer value of 6.

Basically, it allows you to specify a single value representing multiple flags within the enum - so for you're example, you're saying "I want the result to be adjusted to UTC, and allow inner whitespace when parsing."


问:
Import only Last column of Excel through SSIS
I have an excel file which I receive daily. The number of columns in that file is not specific. My requirement is just to load the last column in my table through SSIS. How will I be able to identify last used column dynamically?</p>

答:
You can use c# script:

Make sure you add Using System.Data.OleDb; to the Namespaces Region
and add output Column LastCol and select data type.

```<code>public override void CreateNewOutputRows()
    {
        /*
          Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
          For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        */
        string fileName = @"C:\test.xlsx";
        string SheetName = "Sheet1";
        string cstr = "Provider.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";

    OleDbConnection xlConn = new OleDbConnection(cstr);
    xlConn.Open();

    OleDbCommand xlCmd = xlConn.CreateCommand();
    xlCmd.CommandText = "Select * from [" + SheetName + "]";
    xlCmd.CommandType = CommandType.Text;
    OleDbDataReader rdr = xlCmd.ExecuteReader();

    int rowCt = 0; //Counter

    while (rdr.Read())
    {
        //skip headers
        if (rowCt != 0)
        {
            int maxCol = rdr.FieldCount;
            Output0Buffer.AddRow();
            Output0Buffer.LastCol = (int)rdr[maxCol];
        }
        rowCt++; //increment counter
    }
}
</code>```

Body:
You can use c# script:

Make sure you add Using System.Data.OleDb; to the Namespaces Region
and add output Column LastCol and select data type.

public override void CreateNewOutputRows()
    {
        /*
          Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
          For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        */
        string fileName = @"C:\test.xlsx";
        string SheetName = "Sheet1";
        string cstr = "Provider.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";

    OleDbConnection xlConn = new OleDbConnection(cstr);
    xlConn.Open();

    OleDbCommand xlCmd = xlConn.CreateCommand();
    xlCmd.CommandText = "Select * from [" + SheetName + "]";
    xlCmd.CommandType = CommandType.Text;
    OleDbDataReader rdr = xlCmd.ExecuteReader();

    int rowCt = 0; //Counter

    while (rdr.Read())
    {
        //skip headers
        if (rowCt != 0)
        {
            int maxCol = rdr.FieldCount;
            Output0Buffer.AddRow();
            Output0Buffer.LastCol = (int)rdr[maxCol];
        }
        rowCt++; //increment counter
    }
}


问:
How to use fancybox to show specific class of webpage?
https://jsfiddle.net/054j0fj7/

As you can see when you click on show catlinks you get the wikipedia page, How ever I would like to show the catlinks at the end of page.This area is defined in HTML as following:

```<code><div id="catlinks" class="catlinks" data-mw="interface">
</code>```

and this is the fancybox

```<code><div> <a href="https://de.wikipedia.org/wiki/British_Broadcasting_Corporation" class="fancybox"  data-fancybox-type="iframe"> Show Catlink</a>  </div>
</code>```

答: If you want to display only part of the external page, then it is not possible to implement directly. You would need to create, for example, php file that reads content of that page, parses and outputs only the part you need. Then you would simply display that page in fancybox.</p>

Body:
https://jsfiddle.net/054j0fj7/

As you can see when you click on show catlinks you get the wikipedia page, How ever I would like to show the catlinks at the end of page.This area is defined in HTML as following:

and this is the fancybox

  Show Catlink


问:
Laravel dingo api group by multiple domains
Is it possible to group dingo api routes with multiple domains? For example</p>

```<code>$api->group(['domain' => ['something.com', 'anotherexample.com]], function ($api) {

  // My routes

});
</code>```

答:
You don't have to repeat code.

```<code>$callback = function() {};

Route::group(['domain' => 'foo.bar.dev'], $callback);
Route::group(['domain' => 'foo.bar'], $callback);
</code>```

But we have one more micro solution

```<code>Route::macro("domain", function(array $domains, \Closure $definition) {
    foreach ($domains as $domain) {
        Route::group(['domain' => $domain], $definition);
    }
});
Route::domain(['foo.bar.dev', 'foo.bar'], function($route) {
    // Do stuff
});
</code>```

Body:
Is it possible to group dingo api routes with multiple domains? For example

$api->group(['domain' => ['something.com', 'anotherexample.com]], function ($api) {

  // My routes

});

Body:
You don't have to repeat code.

$callback = function() {};

Route::group(['domain' => 'foo.bar.dev'], $callback);
Route::group(['domain' => 'foo.bar'], $callback);

But we have one more micro solution

Route::macro("domain", function(array $domains, \Closure $definition) {
    foreach ($domains as $domain) {
        Route::group(['domain' => $domain], $definition);
    }
});
Route::domain(['foo.bar.dev', 'foo.bar'], function($route) {
    // Do stuff
});


问:
Oracle : How to replace a table by another table
I am having two tables with exact same schema(table_from and table_to).Now I need to copy the data of table_from to table table_to in a way that only values of table_from will be there in both tables.

table_to:

```<code>id    name    desc
-----------------------
1     a       abc
2     b       def
3     c       adf
</code>```

table_from:

```<code>id    name    desc
-----------------------
1     x       123
2     y       345
</code>```

Now after replacement, the 'table_to' should be.

```<code>id    name    desc
-----------------------
1     x       123
2     y       345
</code>```

答:
You need to delete everything from table_to and then to copy over the data from table_from.

```<code>truncate table table_to;

insert into table_to
  select * from table_from;
</code>```

Two notes:

You could drop table_to and recreate it with create table table_to as select * from table_from. That is a bad idea; if you have triggers on table_to, or procedures depending on the table, they will be affected.

You could delete from table_to instead of truncate; however, that will create redo and undo, and possibly take a long time. If you do not need to undo your changes or recover from crashes, truncate will work, and it will be quite a bit faster.

Body:
I am having two tables with exact same schema(table_from and table_to).Now I need to copy the data of table_from to table table_to in a way that only values of table_from will be there in both tables.

table_to:

id    name    desc
-----------------------
1     a       abc
2     b       def
3     c       adf

table_from:

id    name    desc
-----------------------
1     x       123
2     y       345

Now after replacement, the 'table_to' should be.

id    name    desc
-----------------------
1     x       123
2     y       345

Body:
You need to delete everything from table_to and then to copy over the data from table_from.

truncate table table_to;

insert into table_to
  select * from table_from;

Two notes:

You could drop table_to and recreate it with create table table_to as select * from table_from. That is a bad idea; if you have triggers on table_to, or procedures depending on the table, they will be affected.

You could delete from table_to instead of truncate; however, that will create redo and undo, and possibly take a long time. If you do not need to undo your changes or recover from crashes, truncate will work, and it will be quite a bit faster.


问:
Changing a checkbox's state programmatically in dashcode
Okay, so I'm trying to change a checkbox's state programmatically in dashcode. I've tried:</p>

```<code>var checkbox = document.getElementById("checkbox");

// I have tried all the following methods.
checkbox.checked = false;
checkbox.selected = false;
checkbox.value = false;
</code>```

答:
```<code>var checkbox = document.getElementById("checkbox");
</code>```

there is a problem with this line, it should be

```<code>var checkbox = document.getElementById('#checkbox");
</code>```

Body:
Okay, so I'm trying to change a checkbox's state programmatically in dashcode. I've tried:

var checkbox = document.getElementById("checkbox");

// I have tried all the following methods.
checkbox.checked = false;
checkbox.selected = false;
checkbox.value = false;

Body:
var checkbox = document.getElementById("checkbox");

there is a problem with this line, it should be

var checkbox = document.getElementById('#checkbox");


问:
Mysql server 5.7 not starting on windows 10 after latest update
I am using mySql server 5.7 and it was working fine ever since it was installed. However, after the latest windows 10 home update over the weekend, the server just cant seem to start (either through the mySql notifier or through mySql Workbench)

Any help is appreciated.

Here's the screen shot of the error log file on mySQL workbench.screenshot of error log file

Please help me out.

Also, here's the startup message log that i got when i tried to start the server form the workbench app.

```<code>2017-12-04 11:34:54 - Workbench will use cmd shell commands to start/stop this instance
2017-12-04 11:34:59 - Starting server...
2017-12-04 11:35:03 - Server start done.

FROM DESKTOP-JVD2PIE.err:
    2017-12-04T06:04:59  0  Warning  option 'read_buffer_size': unsigned value 0 adjusted to 8192
    2017-12-04T06:04:59  0  Warning  option 'read_rnd_buffer_size': unsigned value 0 adjusted to 1
    2017-12-04T06:04:59  0  Warning  TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
    2017-12-04T06:04:59  0  Warning  'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.
    2017-12-04T06:04:59  0  Note  C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe (mysqld 5.7.20-log) starting as process 8716 ...
    2017-12-04T06:04:59  0  Warning  InnoDB: innodb-page-size has been changed from the default value 16384 to 65536.
    2017-12-04T06:04:59  0  Note  InnoDB: Mutexes and rw_locks use Windows interlocked functions
    2017-12-04T06:04:59  0  Note  InnoDB: Uses event mutexes
    2017-12-04T06:04:59  0  Note  InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
    2017-12-04T06:04:59  0  Note  InnoDB: Compressed tables use zlib 1.2.3
    2017-12-04T06:04:59  0  Note  InnoDB: Number of pools: 1
    2017-12-04T06:04:59  0  Note  InnoDB: Not using CPU crc32 instructions
    2017-12-04T06:04:59  0  Note  InnoDB: Initializing buffer pool, total size = 1G, instances = 8, chunk size = 128M
    2017-12-04T06:04:59  0  Note  InnoDB: Completed initialization of buffer pool
    2017-12-04T06:04:59  0  ERROR  InnoDB: Data file '.\ibdata1' uses page size 16384, but the innodb_page_size start-up parameter is 65536
    2017-12-04T06:04:59  0  ERROR] InnoDB: Corrupted page [page id: space=0, page number=0  of datafile '.\ibdata1' could not be found in the doublewrite buffer.
    2017-12-04T06:04:59  0  ERROR  InnoDB: Plugin initialization aborted with error Generic error
    2017-12-04T06:05:00  0  ERROR  Plugin 'InnoDB' init function returned error.
    2017-12-04T06:05:00  0  ERROR  Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
    2017-12-04T06:05:00  0  ERROR  Failed to initialize plugins.
    2017-12-04T06:05:00  0  ERROR  Aborting
    2017-12-04T06:05:00  0  Note  Binlog end
    2017-12-04T06:05:00  0  Note  Shutting down plugin 'CSV'
    2017-12-04T06:05:00  0  Note  C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe: Shutdown complete
2017-12-04 11:35:05 - Checking server status...
2017-12-04 11:35:05 - Trying to connect to MySQL...
2017-12-04 11:35:05 - Can't connect to MySQL server on 'localhost' (10061) (2003)
2017-12-04 11:35:05 - Assuming server is not running
2017-12-04 11:35:09 - Checking server status...
2017-12-04 11:35:09 - Trying to connect to MySQL...
2017-12-04 11:35:09 - Can't connect to MySQL server on 'localhost' (10061) (2003)
2017-12-04 11:35:09 - Assuming server is not running
</code>```

Thanks!

Dishant Shah

答:
I don't know why, but the MySql's service was removed after the update. But you can back up your DataBase following these steps:

Go to the "MySql directory"/bin.

Execute the mysqld.exe file.
(It will open a 'instance' of the MySql temporary.)

Then you have to create an output .bat file with the following script:

/"MySql directory"/bin/mysqldump -u root -p"password" -P "port" "Schemma's name" > C:/"some output directory"/dump.sql

Now you have the back up on the dump.sql file

To restory data when you create a new MySql service, following this to restory data:

create an input .bat file with this script:

/"MySql directory"/bin/mysql -u root -h 127.0.0.1 -p"password" -P "port" "Schemma's name" < C:/"the output directory"/dump.sql

Ignore the "".

Your MySql is installed normmarly on the default directory?

Anynone knows the reason to Windows Update crashing the MySql service?

Body:
I am using mySql server 5.7 and it was working fine ever since it was installed. However, after the latest windows 10 home update over the weekend, the server just cant seem to start (either through the mySql notifier or through mySql Workbench)

Any help is appreciated.

Here's the screen shot of the error log file on mySQL workbench.screenshot of error log file

Please help me out.

Also, here's the startup message log that i got when i tried to start the server form the workbench app.

2017-12-04 11:34:54 - Workbench will use cmd shell commands to start/stop this instance
2017-12-04 11:34:59 - Starting server...
2017-12-04 11:35:03 - Server start done.

FROM DESKTOP-JVD2PIE.err:
    2017-12-04T06:04:59  0  Warning  option 'read_buffer_size': unsigned value 0 adjusted to 8192
    2017-12-04T06:04:59  0  Warning  option 'read_rnd_buffer_size': unsigned value 0 adjusted to 1
    2017-12-04T06:04:59  0  Warning  TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
    2017-12-04T06:04:59  0  Warning  'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.
    2017-12-04T06:04:59  0  Note  C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe (mysqld 5.7.20-log) starting as process 8716 ...
    2017-12-04T06:04:59  0  Warning  InnoDB: innodb-page-size has been changed from the default value 16384 to 65536.
    2017-12-04T06:04:59  0  Note  InnoDB: Mutexes and rw_locks use Windows interlocked functions
    2017-12-04T06:04:59  0  Note  InnoDB: Uses event mutexes
    2017-12-04T06:04:59  0  Note  InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
    2017-12-04T06:04:59  0  Note  InnoDB: Compressed tables use zlib 1.2.3
    2017-12-04T06:04:59  0  Note  InnoDB: Number of pools: 1
    2017-12-04T06:04:59  0  Note  InnoDB: Not using CPU crc32 instructions
    2017-12-04T06:04:59  0  Note  InnoDB: Initializing buffer pool, total size = 1G, instances = 8, chunk size = 128M
    2017-12-04T06:04:59  0  Note  InnoDB: Completed initialization of buffer pool
    2017-12-04T06:04:59  0  ERROR  InnoDB: Data file '.\ibdata1' uses page size 16384, but the innodb_page_size start-up parameter is 65536
    2017-12-04T06:04:59  0  ERROR] InnoDB: Corrupted page [page id: space=0, page number=0  of datafile '.\ibdata1' could not be found in the doublewrite buffer.
    2017-12-04T06:04:59  0  ERROR  InnoDB: Plugin initialization aborted with error Generic error
    2017-12-04T06:05:00  0  ERROR  Plugin 'InnoDB' init function returned error.
    2017-12-04T06:05:00  0  ERROR  Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
    2017-12-04T06:05:00  0  ERROR  Failed to initialize plugins.
    2017-12-04T06:05:00  0  ERROR  Aborting
    2017-12-04T06:05:00  0  Note  Binlog end
    2017-12-04T06:05:00  0  Note  Shutting down plugin 'CSV'
    2017-12-04T06:05:00  0  Note  C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe: Shutdown complete
2017-12-04 11:35:05 - Checking server status...
2017-12-04 11:35:05 - Trying to connect to MySQL...
2017-12-04 11:35:05 - Can't connect to MySQL server on 'localhost' (10061) (2003)
2017-12-04 11:35:05 - Assuming server is not running
2017-12-04 11:35:09 - Checking server status...
2017-12-04 11:35:09 - Trying to connect to MySQL...
2017-12-04 11:35:09 - Can't connect to MySQL server on 'localhost' (10061) (2003)
2017-12-04 11:35:09 - Assuming server is not running

Thanks!

Dishant Shah


问:
$cordovaInAppBrowser open url showing address bar weird
when I click on the url to open url using $cordovaInAppBrowser.open(url, '_blank', options) it retired me to url when it opens the InAppBrowser it shows weird behavior.

this is my code

```<code>    var options = {
        location: 'yes',
        clearcache: 'yes',
        toolbar: 'no'
    };
    $cordovaInAppBrowser.open(url, '_blank', options)
    .then(function (event) {
        // success
    })
    .catch(function (event) {
        // error
    });
</code>```

答:
You can try below options.

iOS :

```<code>cordova.InAppBrowser.open(yourURL, '_blank', 'toolbar=no');
</code>```

Android :

```<code>cordova.InAppBrowser.open(yourURL, '_blank', 'location=no');
</code>```

In your case cordova.InAppBrowser is  $cordovaInAppBrowser.

Body:
when I click on the url to open url using $cordovaInAppBrowser.open(url, '_blank', options) it retired me to url when it opens the InAppBrowser it shows weird behavior.

this is my code

    var options = {
        location: 'yes',
        clearcache: 'yes',
        toolbar: 'no'
    };
    $cordovaInAppBrowser.open(url, '_blank', options)
    .then(function (event) {
        // success
    })
    .catch(function (event) {
        // error
    });

Body:
You can try below options.

iOS :

cordova.InAppBrowser.open(yourURL, '_blank', 'toolbar=no');

Android :

cordova.InAppBrowser.open(yourURL, '_blank', 'location=no');

In your case cordova.InAppBrowser is  $cordovaInAppBrowser.


问:
How to use an object of a function inside a class from another script in python?
I am trying to run the below script for generating an email notification:

```<code>class ecom_common_functions_class(sendmailobject):
    def __init__(self):
        count = 0

    def ecom_send_mail_without_attachement(self,email_sender_id,email_reciever_id,mail_body,mail_subj,server):
        print "INSIDE MAIL SENT FUNCTION"
        msg = MIMEMultipart()
        print "in function email_reciever_id =", email_reciever_id
        msg['From'] = email_sender_id
        msg['To'] = email_reciever_id
        msg['Subject'] = mail_subj
        body = mail_body
        msg.attach(MIMEText(body, 'html'))
        part = MIMEBase('application', 'octet-stream')
        encoders.encode_base64(part)
        server = smtplib.SMTP('localhost')
        text = msg.as_string()
        server.sendmail(email_sender_id, email_reciever_id, text)
        server.quit()
</code>```

When I import this function in another script I get this error:

```<code>Traceback (most recent call last):
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_validation_negative.py", line 10, in <module>
    import ecom_nis_common_functions
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_common_functions.py", line 32, in <module>
    class ecom_common_functions_class(sendmailobject):
NameError: name 'sendmailobject' is not defined
</code>```

The result must be printed as a message in an email.

答:
class ecom_common_functions_class(sendmailobject): This line implies that your class ecom_common_functions_class wants to extends another class called sendmailobject. with sendmailobject name this does not seem to be class.

Class names should normally use the CapWords convention.

Either you have not imported sendmailobject or it is not a class

Body:
I am trying to run the below script for generating an email notification:

class ecom_common_functions_class(sendmailobject):
    def __init__(self):
        count = 0

    def ecom_send_mail_without_attachement(self,email_sender_id,email_reciever_id,mail_body,mail_subj,server):
        print "INSIDE MAIL SENT FUNCTION"
        msg = MIMEMultipart()
        print "in function email_reciever_id =", email_reciever_id
        msg['From'] = email_sender_id
        msg['To'] = email_reciever_id
        msg['Subject'] = mail_subj
        body = mail_body
        msg.attach(MIMEText(body, 'html'))
        part = MIMEBase('application', 'octet-stream')
        encoders.encode_base64(part)
        server = smtplib.SMTP('localhost')
        text = msg.as_string()
        server.sendmail(email_sender_id, email_reciever_id, text)
        server.quit()

When I import this function in another script I get this error:

Traceback (most recent call last):
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_validation_negative.py", line 10, in <module>
    import ecom_nis_common_functions
  File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_common_functions.py", line 32, in <module>
    class ecom_common_functions_class(sendmailobject):
NameError: name 'sendmailobject' is not defined

The result must be printed as a message in an email.


问:
Bind Command for MenuItem in DataTemplate without Tag
I want to bind a command in my ViewModel to a menuItem which is in DataTemplate. I can do that with using Tag. Is there any method which can do the same task but without using tag.

```<code><Window.Resources>
    <DataTemplate x:Key="StudentListBoxItemTemplate">
        <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
            <TextBlock Text="{Binding Name}"/>
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trigger" Command="{Binding PlacementTarget.Tag.TriggerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </StackPanel.ContextMenu>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ListBox
        ItemsSource="{Binding StudentList}"
        ItemTemplate="{StaticResource StudentListBoxItemTemplate}">
    </ListBox>
</StackPanel>
</code>```

My ViewModel

```<code>public class MainViewModel {
    public ICommand TriggerCommand { ... }
    public ObservableList<Student> StudentList { ... }
}
</code>```

答:
With your current design, you need to get from the ContextMenu through the StackPanel and back to the DataContext of the containing ListBox.  What makes this awkward is that the DataContext of the StackPanel is already narrowed down to a particular student.

There are at least two ways to make this easier:

Provide a TriggerCommand property in Student so the command is right there where you need it

Provide a Parent property in the Student to escape the narrowed scope

Body:
I want to bind a command in my ViewModel to a menuItem which is in DataTemplate. I can do that with using Tag. Is there any method which can do the same task but without using tag.

<Window.Resources>
    <DataTemplate x:Key="StudentListBoxItemTemplate">
        <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
            <TextBlock Text="{Binding Name}"/>
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trigger" Command="{Binding PlacementTarget.Tag.TriggerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </StackPanel.ContextMenu>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ListBox
        ItemsSource="{Binding StudentList}"
        ItemTemplate="{StaticResource StudentListBoxItemTemplate}">
    </ListBox>
</StackPanel>

My ViewModel

public class MainViewModel {
    public ICommand TriggerCommand { ... }
    public ObservableList<Student> StudentList { ... }
}


问:
Is it possible to set input field of react-day-picker as required?
I have two DayPickerInput fields in a form and would like to mark them as required field but don't know how. Can anybody please help?

```<code>        <FormGroup row>
            <Col md="4">
                <Label htmlFor="begin">Begin</Label>
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.begin}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>
        <FormGroup row>
            <Col md="4">
                <Label htmlFor="end">End</Label>
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.end}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>
</code>```

UPDATE: I tried with inputProps:

```<code><DayPickerInput inputProps={required} />
</code>```

but got error:

```<code>ReferenceError: required is not defined
</code>```

答:
I tried with inputProps:

```<code><DayPickerInput inputProps={required} />
</code>```

but got error:

```<code>ReferenceError: required is not defined
</code>```

This is how to pass object as prop:

```<code><DayPickerInput
   inputProps={
     { required: true }
   }
/>
</code>```

Body:
I have two DayPickerInput fields in a form and would like to mark them as required field but don't know how. Can anybody please help?

        <FormGroup row>
            <Col md="4">
                Begin
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.begin}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>
        <FormGroup row>
            <Col md="4">
                End
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.end}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>

UPDATE: I tried with inputProps:

<DayPickerInput inputProps={required} />

but got error:

ReferenceError: required is not defined

Body:
I tried with inputProps:

<DayPickerInput inputProps={required} />

but got error:

ReferenceError: required is not defined

This is how to pass object as prop:

<DayPickerInput
   inputProps={
     { required: true }
   }
/>


问:
how to select the checkboxes automatically as per the values in an array?
I have some checkboxes like this in my form...

```<code><label><input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label>
</code>```

Now, in javascript I have a string in a format of comma separated values like,

```<code>var projDepts = "1,2,3,4";
</code>```

after using the split function of javascript i have converted it to an array.

Now, my question is I want to select all those checkboxes as per the values in the array. I have tried something but its not working for me,

```<code>var projDepts = "1,2,3,4";
var projDeptArray = projDepts.split(',');
var project_depts = document.getElementsByName("prdept[]");
for (var i = 0; i < projDeptArray.length; i++) {
  for (var j = 0; j < project_depts.length; j++) {
    if (projDeptArray[i] == project_depts[j]) {
      $(project_depts[i]).prop("checked", true)
    }
  }
}
</code>```

This code is not working and none of the checkboxes got checked, I know I am getting somewhere wrong. Please someone help me to a solution for this.

答:
You can split your string by comma and you can traverse your array to check if element with that id exists and make checked property of that checkbox to true.

var projDepts = "1,3,4";
var arr = projDepts.split(",");
for(i = 0; i < arr.length; i++){
   if($("#project_dept"+arr[i]).length > 0){
      $("#project_dept"+arr[i]).attr("checked", true);
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> <input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label></code>```

EDIT

Here is working code,

```<code>    <?php
    $all_dept_names = [
        ["team_id" => "1",
        "team_name" => "Team 1"
        ],
        ["team_id" => "2",
        "team_name" => "Team 2"
        ],
        ["team_id" => "3",
        "team_name" => "Team 3"
        ],
        ["team_id" => "4",
        "team_name" => "Team 4"
        ],
    ];
    array_walk($all_dept_names, function($item, $key) use (&$all_dept_names){

        $all_dept_names[$key] = (object)$item;
    });

    ?>
<?php foreach ($all_dept_names as $dept_names) {

    ?>
    <label class="checkbox-inline i-checks">
        <input type="checkbox" name="prdept[]" id="prdept<?php echo $dept_names->team_id; ?>" value="<?php echo $dept_names->team_id; ?>" class="form-control required"> <?php echo $dept_names->team_name; ?>
    </label>
<?php }?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    var projDept = "1,2,3";
    var projDeptArray = projDept.split(',');
    for(i = 0; i < projDeptArray.length; i++){
        if($("#prdept"+projDeptArray[i]).length > 0){
            $("#prdept"+projDeptArray[i]).attr("checked", true);
        }
    }
</script>
</code>```

Check this code in link. Its working, else there is some issue in your code.

Body:
I have some checkboxes like this in my form...

<input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development
 <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing
 <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing
 <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance

Now, in javascript I have a string in a format of comma separated values like,

var projDepts = "1,2,3,4";

after using the split function of javascript i have converted it to an array.

Now, my question is I want to select all those checkboxes as per the values in the array. I have tried something but its not working for me,

var projDepts = "1,2,3,4";
var projDeptArray = projDepts.split(',');
var project_depts = document.getElementsByName("prdept[]");
for (var i = 0; i < projDeptArray.length; i++) {
  for (var j = 0; j < project_depts.length; j++) {
    if (projDeptArray[i] == project_depts[j]) {
      $(project_depts[i]).prop("checked", true)
    }
  }
}

This code is not working and none of the checkboxes got checked, I know I am getting somewhere wrong. Please someone help me to a solution for this.

Body:
You can split your string by comma and you can traverse your array to check if element with that id exists and make checked property of that checkbox to true.

var projDepts = "1,3,4";
var arr = projDepts.split(",");
for(i = 0; i < arr.length; i++){
   if($("#project_dept"+arr[i]).length > 0){
      $("#project_dept"+arr[i]).attr("checked", true);
   }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> <input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label>

EDIT

Here is working code,

    <?php
    $all_dept_names = [
        ["team_id" => "1",
        "team_name" => "Team 1"
        ],
        ["team_id" => "2",
        "team_name" => "Team 2"
        ],
        ["team_id" => "3",
        "team_name" => "Team 3"
        ],
        ["team_id" => "4",
        "team_name" => "Team 4"
        ],
    ];
    array_walk($all_dept_names, function($item, $key) use (&$all_dept_names){

        $all_dept_names[$key] = (object)$item;
    });

    ?>
<?php foreach ($all_dept_names as $dept_names) {

    ?>
    <label class="checkbox-inline i-checks">
        <input type="checkbox" name="prdept[]" id="prdept<?php echo $dept_names->team_id; ?>" value="<?php echo $dept_names->team_id; ?>" class="form-control required"> <?php echo $dept_names->team_name; ?>
    </label>
<?php }?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    var projDept = "1,2,3";
    var projDeptArray = projDept.split(',');
    for(i = 0; i < projDeptArray.length; i++){
        if($("#prdept"+projDeptArray[i]).length > 0){
            $("#prdept"+projDeptArray[i]).attr("checked", true);
        }
    }
</script>

Check this code in link. Its working, else there is some issue in your code.


问:
Calling setter once on function static variable
I'm using a function static variable that I want to initialize once by calling a setter:

```<code>void foo() {
    static Obj obj;
    obj.setName("name"); // this should be called once
    // use obj
}
</code>```

I don't want the setter to be called multiple times, also due to multi threading issues and I can't add a constructor to Obj since I don't own the code. So is this reasonable and thread safe:

```<code>void foo() {
    static Obj obj = []() {
        Obj o;
        o.setName("name");
        return o;
    }();
    // use obj
}
</code>```

答:
Yes, it's thread safe. Quoting n3337 - [stmt.dcl]/4, emphasis mine:

...such a variable is initialized the first time control passes
  through its declaration; such a variable is considered initialized
  upon the completion of its initialization. If the initialization exits
  by throwing an exception, the initialization is not complete, so it
  will be tried again the next time control enters the declaration. If
  control enters the declaration concurrently while the variable is
  being initialized, the concurrent execution shall wait for completion
  of the initialization.

You perform copy initialization from a lambda's return value, but it's immaterial. The paragraph above doesn't constrain the initialization of obj to be value or direct initialization. All forms of initialization are applicable.

And as a side note, if you must contend with such poorly written types, I'd argue your solution is very idiomatic. It doesn't artificially introduce a new named function to perform the initialization. Instead it keeps initialization code localized. That is a good thing in my book.

Body:
I'm using a function static variable that I want to initialize once by calling a setter:

void foo() {
    static Obj obj;
    obj.setName("name"); // this should be called once
    // use obj
}

I don't want the setter to be called multiple times, also due to multi threading issues and I can't add a constructor to Obj since I don't own the code. So is this reasonable and thread safe:

void foo() {
    static Obj obj = []() {
        Obj o;
        o.setName("name");
        return o;
    }();
    // use obj
}


问:
Text doesn't fit in UIButton titleLabel height for a specific font
I have had some troubles with a specific font i am using. It's made for Schools so A and Å is not the same height. I think it causes troubles for my UIButtons. I've tried to work around it but can't seem to get it right. This is what I've tried last:

```<code>[self setValue:[UIFont fontWithName:@"fontname" size:220] forKeyPath:@"button1.font"];
[self setValue:[UIFont fontWithName:@"fontname" size:220] forKeyPath:@"button2.font"];
[self setValue:[UIFont fontWithName:@"fontname" size:220] forKeyPath:@"button3.font"];
[button1 setTitle:@"A" forState:UIControlStateNormal];
[button2 setTitle:@"Å" forState:UIControlStateNormal];
[button3 setTitle:@"Å" forState:UIControlStateNormal];
[button2 setBackgroundColor:[UIColor blackColor]];
[button2 setFrame:CGRectMake(button2.frame.origin.x, button2.frame.origin.y, button2.frame.size.width, button2.frame.size.height+100)];
[button2.titleLabel setFrame:CGRectMake(button2.frame.origin.x, button2.frame.origin.y, button2.frame.size.width, button2.frame.size.height)];
button2.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
</code>```

This is the result:

The Å is not displayed properly as you can see. How can I fix this?

Thanks!

Best regards,
Joakim

答:
I have faced same it works as @YuAn Shaolin Maculelê Lai mentioned

Swift 3.2 code is: button.contentVerticalAlignment = .fill

Body:
I have had some troubles with a specific font i am using. It's made for Schools so A and Å is not the same height. I think it causes troubles for my UIButtons. I've tried to work around it but can't seem to get it right. This is what I've tried last:

[self setValue:[UIFont fontWithName:@"fontname" size:220] forKeyPath:@"button1.font"];
[self setValue:[UIFont fontWithName:@"fontname" size:220] forKeyPath:@"button2.font"];
[self setValue:[UIFont fontWithName:@"fontname" size:220] forKeyPath:@"button3.font"];
[button1 setTitle:@"A" forState:UIControlStateNormal];
[button2 setTitle:@"Å" forState:UIControlStateNormal];
[button3 setTitle:@"Å" forState:UIControlStateNormal];
[button2 setBackgroundColor:[UIColor blackColor]];
[button2 setFrame:CGRectMake(button2.frame.origin.x, button2.frame.origin.y, button2.frame.size.width, button2.frame.size.height+100)];
[button2.titleLabel setFrame:CGRectMake(button2.frame.origin.x, button2.frame.origin.y, button2.frame.size.width, button2.frame.size.height)];
button2.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;

This is the result:

The Å is not displayed properly as you can see. How can I fix this?

Thanks!

Best regards,
Joakim


问:
How to break a line of chained methods in Python?
I have a line of the following code (don't blame for naming conventions, they are not mine):

```<code>subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()
</code>```

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

答:
My personal choice would be:</p>

```
subkeyword = Session.query(
    Subkeyword.subkeyword_id,
    Subkeyword.subkeyword_word,
).filter_by(
    subkeyword_company_id=self.e_company_id,
    subkeyword_word=subkeyword_word,
    subkeyword_active=True,
).one()
```

Body:
I have a line of the following code (don't blame for naming conventions, they are not mine):

subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

Body:
My personal choice would be:

subkeyword = Session.query(
    Subkeyword.subkeyword_id,
    Subkeyword.subkeyword_word,
).filter_by(
    subkeyword_company_id=self.e_company_id,
    subkeyword_word=subkeyword_word,
    subkeyword_active=True,
).one()


问:
Does when using dynamic framework increase binary size than using static framework?
This is iOS & Cocoapods question.

My iOS App launching speed was too slow.

So, to reduce the dylib loading time, I changed the dynamic frameworks in Pods to static frameworks by using cocoapods-static-frameworks.

And then,

as I wanted, reduced the app launch time and everything work well as before.

However, unexpectedly the app's binary size has been reduced 20MB. (80MB to 60MB)

Does when using dynamic framework increase binary size than using static framework?

答:
it dose, because dynamic frameworks only links what you actually need.

"When dynamic libraries are linked, none of the library's code is included directly into the linked target. Instead, the libraries are loaded into memory at runtime prior to having symbols getting resolved."


答:
DateTimeStyles is a Flags enumeration. The BITWISE OR operator | combines two flags.

See Enum, Flags and bitwise operators.

Title: What is the DateTimeStyles operator in .NET?

Body:
When I add this code

DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowInnerWhite

Intellisense shows the following message:

DateTimeStyles DateTimeStyles.operator |(DateTimeStyles left, DateTimeStyles right).

What does this operator do?


问:
odd even numbers alternate inverted triangle
I want to print the following pattern in java:

```<code>a+1357+1
b+246+2
a+13+3
b+2+4
</code>```

following is my code, but with this i can only print odd no. or only even no.s

```<code>public static void main(String[] args) {
    int rows = 7;
    for(int i = rows; i >= 1; i=i-2) {
       for(int j = 1; j <= i; j=j+2) {
           System.out.print(j + " ");
       }
       System.out.println();
    }
}
</code>```

答:
DEMO

var rows = 4;
for (var i = 4; i > 0; i--) {
  for (var j = 1; j <= i; j++) {
    document.write((i % 2) + (2 * j) - 1 + " ");
  }
  document.write('
');
}```
</div>
</div>
</p>

```public static void main(String[] args) {
   int rows = 4;
   for(int i = rows; i > 0; i--) {
      for(int j = 1; j <= i; j++) {
          System.out.print((i%2)+(2*j)-1 + " ");
      }
      System.out.println();
   }
}
```

You need to make a pattern for it. here you can use (i%2)+(2*j)-1

Body:
I want to print the following pattern in java:

a+1357+1
b+246+2
a+13+3
b+2+4

following is my code, but with this i can only print odd no. or only even no.s

public static void main(String[] args) {
    int rows = 7;
    for(int i = rows; i >= 1; i=i-2) {
       for(int j = 1; j <= i; j=j+2) {
           System.out.print(j + " ");
       }
       System.out.println();
    }
}

Body:
DEMO

var rows = 4;
for (var i = 4; i > 0; i--) {
  for (var j = 1; j <= i; j++) {
    document.write((i % 2) + (2 * j) - 1 + " ");
  }
  document.write('<br>');
}

public static void main(String[] args) {
   int rows = 4;
   for(int i = rows; i > 0; i--) {
      for(int j = 1; j <= i; j++) {
          System.out.print((i%2)+(2*j)-1 + " ");
      }
      System.out.println();
   }
}

You need to make a pattern for it. here you can use (i%2)+(2*j)-1


问:
VBS to address file on desktop
I am a VBS noob so forgive the simple question. I have created a script to open an .xlsx document on my desktop, and run various actions. I would like to port the script to other users. That said, how can I create a path that will work for all users, i.e. a user desktop variable. In PowerShell I could do '$env:USERPROFILE + '\Desktop'' and it would address the current user's desktop. Is there a VBS equivalent?

What I have so far:

```<code>Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set wb1 = xl.Application.Workbooks.Open("C:\Users\Username\Desktop\Missed_Scans\Reports\Report.xlsx")
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs "C:\Users\Username\Desktop\Missed_Scans\Reports\Missed_Scans.xlsx", 51, , , , False
wb2.Close
wb1.Close False
xl.Quit
Set xl = Nothing
</code>```

Lines 5 and 13 are the areas that need to use some type of user environment variable. I understand that environ("UserName") can provide the username, but I am not sure how to incorporate it.

答:
Just use ExpandEnvironmentStrings:

```<code>Set osh = CreateObject("wscript.shell")
xl.workbooks.open osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Report.xlsx")
</code>```

For line 13 also, you can write something like:

```<code>wb2.SaveAs osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Missed_Scans.xlsx"), 51, , , , False
</code>```

Update:

Note: I did not make any changes to any logic. Just removed the errors.

```<code>Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set osh = CreateObject("wscript.shell")
Set wb1 = xl.Workbooks.Open(osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Report.xlsx"))
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Missed_Scans.xlsx"), 51, , , , False
wb2.Close
wb1.Close False
xl.Quit
Set xl = Nothing
</code>```

Title: VBS to address file on desktop

Body:
I am a VBS noob so forgive the simple question. I have created a script to open an .xlsx document on my desktop, and run various actions. I would like to port the script to other users. That said, how can I create a path that will work for all users, i.e. a user desktop variable. In PowerShell I could do '$env:USERPROFILE + '\Desktop'' and it would address the current user's desktop. Is there a VBS equivalent?

What I have so far:

Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set wb1 = xl.Application.Workbooks.Open("C:\Users\Username\Desktop\Missed_Scans\Reports\Report.xlsx")
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs "C:\Users\Username\Desktop\Missed_Scans\Reports\Missed_Scans.xlsx", 51, , , , False
wb2.Close
wb1.Close False
xl.Quit
Set xl = Nothing

Lines 5 and 13 are the areas that need to use some type of user environment variable. I understand that environ("UserName") can provide the username, but I am not sure how to incorporate it.

Body:
Just use ExpandEnvironmentStrings:

Set osh = CreateObject("wscript.shell")
xl.workbooks.open osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Report.xlsx")

For line 13 also, you can write something like:

wb2.SaveAs osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Missed_Scans.xlsx"), 51, , , , False

Update:

Note: I did not make any changes to any logic. Just removed the errors.

Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set osh = CreateObject("wscript.shell")
Set wb1 = xl.Workbooks.Open(osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Report.xlsx"))
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs osh.ExpandEnvironmentStrings("%userprofile%\Desktop\Missed_Scans\Reports\Missed_Scans.xlsx"), 51, , , , False
wb2.Close
wb1.Close False
xl.Quit
Set xl = Nothing


问:
Ionic 2 Promise - Finishing the first process before executing the second process
For my Ionic 2 project, I have two functions executing one after another. Each function consists of an API call. I want to wait until the first function finishes executing everything before going to the second function.

The issue I'm having is that since the first function takes some time to finish, the second function executes before the first function finishes executing.

I'm learning how to use Promise as I was told it can solve this issue.
I've simplified the code so it's easier to follow:

```<code>const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {

  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});
</code>```

答:
Use the new HttpClient and switchMap to get a unique Observable</p>

```<code>firstAndSecond(){
    return self.pspService.post('/api/Conversation/GetPersonalCalendarData')
          .switchMap((data:any)=>{
            //there you have "data", you can use to change the post
            return self.pspService.post('/api/Conversation/AddPersonalAppointment')
           });
}
//In your component
myService.firstAndSecond().subscribe((data2)=>{
    //data2 it's only the data from self.pspService.post
}
</code>```

Body:
For my Ionic 2 project, I have two functions executing one after another. Each function consists of an API call. I want to wait until the first function finishes executing everything before going to the second function.

The issue I'm having is that since the first function takes some time to finish, the second function executes before the first function finishes executing.

I'm learning how to use Promise as I was told it can solve this issue.
I've simplified the code so it's easier to follow:

const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {

  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});

Body:
Use the new HttpClient and switchMap to get a unique Observable

firstAndSecond(){
    return self.pspService.post('/api/Conversation/GetPersonalCalendarData')
          .switchMap((data:any)=>{
            //there you have "data", you can use to change the post
            return self.pspService.post('/api/Conversation/AddPersonalAppointment')
           });
}
//In your component
myService.firstAndSecond().subscribe((data2)=>{
    //data2 it's only the data from self.pspService.post
}


问:
break-inside: avoid not working with padding in edge
I have a problem to get a column-layout to work correctly with block elements that contain paddings. The problem I'm facing is, that a thin line of white background from the first column breaks into the beginning of the second column. It occurs in IE11 and MS-Edge. Chrome and Firefox display the columns as intended.

.outer {
    -moz-column-count: 2;
    -webkit-column-count: 2;
    column-count: 2;
    -webkit-column-gap: 1.6em;
    -moz-column-gap: 1.6em;
    column-gap: 1.6em;
    background-color: grey;
}
.container {
  break-inside: avoid;
  page-break-inside: avoid;
  -webkit-column-break-inside: avoid;
  padding: 0.75em;
  background-color: white;
}

.container + .container {

  margin-top: 0.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer" style="margin: 40px auto; width: 500px; border: 1px solid red">
    <div class="container">
      This is a rather long text to break into separate lines but - sometimes - not to stay in one. With some additional text for a longer column
    </div>
    <div class="container">
      Next column
    </div>
    <div class="container">
      Another column
    </div>
</div></code>```

How do I get break-inside: avoid to work with IE11 and MS-Edge?
I've also tried to wrap the text into additional DIVs with a margin and removing the padding, but that breaks the text of the first column itself.

Does anyone has a hint? Thanks in advance!

UPDATE

It seems the problem is worse than discribed. break-inside: avoidjust isn't working in edge at all. Here I put block elements into the elements in the columns (also breaks with tables inside):

.column {
  column-count: 2;
  column-gap: 1em;
}

.elem {
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
}

.elem + .elem {
  margin-top: 0.5em;
}

.elem {
  background-color: orange;
}

.elem + .elem {
  background-color: lightblue;
}

.elem + .elem + .elem {
  background-color: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="column">
  <div class="elem">
    <div>one</div>
    <div>two</div>
    <div>three</div>
    <div>four</div>
    <div>five</div>
    <div>six</div>
  </div>
  <div class="elem">
    <div>one</div>
  </div>
  <div class="elem">
    <div>one</div>
  </div>
</div></code>```

The MS documentation for Edge states it is supported, yet it isn't working. Even Can I use states, that it is supported and has no known issues listed.

There has to be some solution to this...

答:
Ok, I finally found a solution: I've build a switch into the CSS which executes only for IE10, IE11 and MS Edge (found here: Browser Strangeness).

Inside that switch I set the elements to display: inline-block with width: 100%. That way it works in Chrome, Firefox and now Edge too.

.column {
  column-count: 2;
  column-gap: 1em;
}

.elem {
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
}

.elem + .elem {
  margin-top: 0.5em;
}

.elem {
  background-color: orange;
}

.elem + .elem {
  background-color: lightblue;
}

.elem + .elem + .elem {
  background-color: lightgreen;
}

/* columns fix for IE10, IE11 and MS Edge*/
_:-ms-lang(x), .column {

 margin-top: -0.5em;
}
_:-ms-lang(x), .elem {

 display: inline-block;
 width: 100%;
 margin-top: 0.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="column">
  <div class="elem">
    <div>one</div>
    <div>two</div>
    <div>three</div>
    <div>four</div>
    <div>five</div>
    <div>six</div>
  </div>
  <div class="elem">
    <div>one</div>
  </div>
  <div class="elem">
    <div>one</div>
  </div>
</div></code>```

Body:
I have a problem to get a column-layout to work correctly with block elements that contain paddings. The problem I'm facing is, that a thin line of white background from the first column breaks into the beginning of the second column. It occurs in IE11 and MS-Edge. Chrome and Firefox display the columns as intended.

.outer {
    -moz-column-count: 2;
    -webkit-column-count: 2;
    column-count: 2;
    -webkit-column-gap: 1.6em;
    -moz-column-gap: 1.6em;
    column-gap: 1.6em;
    background-color: grey;
}
.container {
  break-inside: avoid;
  page-break-inside: avoid;
  -webkit-column-break-inside: avoid;
  padding: 0.75em;
  background-color: white;
}

.container + .container {

  margin-top: 0.5em;
}

      This is a rather long text to break into separate lines but - sometimes - not to stay in one. With some additional text for a longer column

      Next column

      Another column

How do I get break-inside: avoid to work with IE11 and MS-Edge?
I've also tried to wrap the text into additional DIVs with a margin and removing the padding, but that breaks the text of the first column itself.

Does anyone has a hint? Thanks in advance!

UPDATE

It seems the problem is worse than discribed. break-inside: avoidjust isn't working in edge at all. Here I put block elements into the elements in the columns (also breaks with tables inside):

.column {
  column-count: 2;
  column-gap: 1em;
}

.elem {
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
}

.elem + .elem {
  margin-top: 0.5em;
}

.elem {
  background-color: orange;
}

.elem + .elem {
  background-color: lightblue;
}

.elem + .elem + .elem {
  background-color: lightgreen;
}

one

two

three

four

five

six

one

one

The MS documentation for Edge states it is supported, yet it isn't working. Even Can I use states, that it is supported and has no known issues listed.

There has to be some solution to this...

Body:
Ok, I finally found a solution: I've build a switch into the CSS which executes only for IE10, IE11 and MS Edge (found here: Browser Strangeness).

Inside that switch I set the elements to display: inline-block with width: 100%. That way it works in Chrome, Firefox and now Edge too.

.column {
  column-count: 2;
  column-gap: 1em;
}

.elem {
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
}

.elem + .elem {
  margin-top: 0.5em;
}

.elem {
  background-color: orange;
}

.elem + .elem {
  background-color: lightblue;
}

.elem + .elem + .elem {
  background-color: lightgreen;
}

/* columns fix for IE10, IE11 and MS Edge*/
_:-ms-lang(x), .column {

 margin-top: -0.5em;
}
_:-ms-lang(x), .elem {

 display: inline-block;
 width: 100%;
 margin-top: 0.5em;
}

<div class="column">
  <div class="elem">
    <div>one</div>
    <div>two</div>
    <div>three</div>
    <div>four</div>
    <div>five</div>
    <div>six</div>
  </div>
  <div class="elem">
    <div>one</div>
  </div>
  <div class="elem">
    <div>one</div>
  </div>
</div>


问:
Symfony validation: range between two numbers, OR a value
I would like to validate a number to be between 10 and 20, or 30 and 40 or equal to 99.

I could imagine the code to be something similar to this, but it does not work:

In Entity\NameOfFile.php:

```<code>/*
 * @Assert\Range(
 *   min=10,
 *   max=20
 * )
 *
 * @Assert\Range(
 *  min=30,
 *  max=40
 * )
 *
 * @Assert\IdenticalTo(value = 99)
 */
 private $myVariable;
</code>```

Or maybe something similar to this:

```<code> /*
  * @Assert\Choice({
  *  Range({min = 10, max = 20}),
  *  Range({min = 10, max = 20}),
  *  99
  * )}
  */
  private $myVariable;
</code>```

I also added min and max messages.

In the first option, apparently only the first Assert is taken into consideration and the second one is ignored. The second option, does not work at all.

Ps: Please, a solution without Regex

EDIT:
Following the advice of M Khalid Juanid, the code looks like this:

```<code>/**
 * @Assert\Expression(
 *     "this.getmyVariable() in 10..20 or this.getmyVariable() in 30..40 or this.getmyVariable() == 99",
 *     message="Your error message", groups{"groupA"}
 * )
*private $myVariable;
 */

  ***
if($appendForm->isValid(array($groupA))
{
***
}
</code>```

It works fine, but only when the validation is not assigned to groupA. How can, the validation be assigned to a group, in this case?

答:
You can use @Assert\Expression for your mulitple criteria

```<code>/**
 * @Assert\Expression(
 *     "this.checkRange()",
 *     message="Your error message"
 * )
 */
class YourEntityName
{
    public function checkRange(){
        if(
            ($this->yourPorperty >= 10 && $this->yourPorperty <= 20)
            || ($this->yourPorperty >= 30 && $this->yourPorperty <= 40)
            || ($this->yourPorperty == 90)
        ){
            return true;
        }

        return false;
    }
}
</code>```

As per docs The expression option is the expression that must return true in order for validation to pass

Even more simpler according to the documentation

```<code>/**
 * @Assert\Expression(
 *     "this.getYourPorperty() in 10..20 or this.getYourPorperty() in 30..40 or this.getYourPorperty() == 90",
 *     message="Your error message"
 * )
 */
</code>```

Body:
I would like to validate a number to be between 10 and 20, or 30 and 40 or equal to 99.

I could imagine the code to be something similar to this, but it does not work:

In Entity\NameOfFile.php:

/*
 * @Assert\Range(
 *   min=10,
 *   max=20
 * )
 *
 * @Assert\Range(
 *  min=30,
 *  max=40
 * )
 *
 * @Assert\IdenticalTo(value = 99)
 */
 private $myVariable;

Or maybe something similar to this:

 /*
  * @Assert\Choice({
  *  Range({min = 10, max = 20}),
  *  Range({min = 10, max = 20}),
  *  99
  * )}
  */
  private $myVariable;

I also added min and max messages.

In the first option, apparently only the first Assert is taken into consideration and the second one is ignored. The second option, does not work at all.

Ps: Please, a solution without Regex

EDIT:
Following the advice of M Khalid Juanid, the code looks like this:

/**
 * @Assert\Expression(
 *     "this.getmyVariable() in 10..20 or this.getmyVariable() in 30..40 or this.getmyVariable() == 99",
 *     message="Your error message", groups{"groupA"}
 * )
*private $myVariable;
 */

  ***
if($appendForm->isValid(array($groupA))
{
***
}

It works fine, but only when the validation is not assigned to groupA. How can, the validation be assigned to a group, in this case?

Body:
You can use @Assert\Expression for your mulitple criteria

/**
 * @Assert\Expression(
 *     "this.checkRange()",
 *     message="Your error message"
 * )
 */
class YourEntityName
{
    public function checkRange(){
        if(
            ($this->yourPorperty >= 10 && $this->yourPorperty <= 20)
            || ($this->yourPorperty >= 30 && $this->yourPorperty <= 40)
            || ($this->yourPorperty == 90)
        ){
            return true;
        }

        return false;
    }
}

As per docs The expression option is the expression that must return true in order for validation to pass

Even more simpler according to the documentation

/**
 * @Assert\Expression(
 *     "this.getYourPorperty() in 10..20 or this.getYourPorperty() in 30..40 or this.getYourPorperty() == 90",
 *     message="Your error message"
 * )
 */


问:
UIDatePicker changing size
How do I change the size of a UIDatePicker? Setting the frame doesn't seem to work. It only changes the size of the black background on a UIDatePicker, not the actual components within the Picker.</p>

答: It's not possible to change the size of a UIDatePicker, afaik.</p>

Title: UIDatePicker changing size


问:
How can I get gradle to install an IntelliJ plugin?
I would like to make a gradle task that automatically installs the lombok plugin. Is there any way to do that?</p>

答:
To my understanding, the Intellij plugin and Gradle task are two independent separate processes.

However, based on my installation of lombok plugin into Intellij, I think you just need to have the jars copied over to the plugin support directory, and restart the Intellij, it would show the plugin as installed.

```<code>$ ls -lart  ~/Library/Application\ Support/IntelliJIdea2017.2/lombok-plugin/lib/
intellij-patcher-agent-0.15.17.2.jar  lombok-plugin-0.15.17.2.jar
</code>```

You can do that copy over either manually or by Gradle task. But I'd rather do the installation thru Intellij.

Body:
To my understanding, the Intellij plugin and Gradle task are two independent separate processes.

However, based on my installation of lombok plugin into Intellij, I think you just need to have the jars copied over to the plugin support directory, and restart the Intellij, it would show the plugin as installed.

$ ls -lart  ~/Library/Application\ Support/IntelliJIdea2017.2/lombok-plugin/lib/
intellij-patcher-agent-0.15.17.2.jar  lombok-plugin-0.15.17.2.jar

You can do that copy over either manually or by Gradle task. But I'd rather do the installation thru Intellij.


问:
Could not find parent artifact xxxxx:pom:2.0-SNAPSHOT
I have a parent project xxx-third, which has nothing but a pom declaring some dependencies and build configurations.

After I deploy it to the nexus and I can find it in the nexus web,I declare this xxx-thrid as my parent project of myProject.

Howerver, I still have the maven error complaining that Cound not find artifact com.myCom:xxx-third:pom:2.0-SNAPSHOT @ com.myCom:myProject.

But if I do install locally with the code, the problem will resolve, this is annoying! Why and how to solve it?

答:
Your parent POM is not resolved. There are three options to solve this:

1) Add the parent POM to your local repository

2) Add a relativePath to your child POM pointing to your parent POM (only makes sense in a multi-module project where source is in the same repository)

```<code><parent>
    <groupId>...</groupId>
    <artifactId>...</artifactId>
    <version>...</version>
    <relativePath>...</relativePath>
</parent>
</code>```

3) Add a repository configuration to your settings.xml (e.g. makes sense if you have a company wide POM)

```<code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <profiles>
    <profile>
      ...
      <repositories>
        ...
      </repositories>
      ...
    </profile>
  </profiles>
  ...
</code>```

As far as I understand 3) is your solution. See also:
https://maven.apache.org/guides/introduction/introduction-to-the-pom.html
https://maven.apache.org/settings.html

Body:
Your parent POM is not resolved. There are three options to solve this:

1) Add the parent POM to your local repository

2) Add a relativePath to your child POM pointing to your parent POM (only makes sense in a multi-module project where source is in the same repository)

<parent>
    <groupId>...</groupId>
    <artifactId>...</artifactId>
    <version>...</version>
    <relativePath>...</relativePath>
</parent>

3) Add a repository configuration to your settings.xml (e.g. makes sense if you have a company wide POM)

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <profiles>
    <profile>
      ...
      <repositories>
        ...
      </repositories>
      ...
    </profile>
  </profiles>
  ...

As far as I understand 3) is your solution. See also:
https://maven.apache.org/guides/introduction/introduction-to-the-pom.html
https://maven.apache.org/settings.html


问:
Defining controller in namespace still Class App\Http\Controllers error taking place in laravel 5.5
I am working in laravel 5.5. I have created a controller folder with name Abc and inside it created a controller file with name abc.php, inside this file I have written code:

```<code>namespace App\Http\Controllers\Abc;

use App\Http\Controllers\Controller;

//use Illuminate\Support\Facades\DB;

class abcController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function NewPromotion()
    {
        return view('new-promotion');
    }
}
</code>```

And in Route folder under web.php file I am calling its view file, like:-
Route::get('/new-promotion','Abc\abcController@NewPromotion');

In spite of defining in namespace I am still getting error i.e.

"ReflectionException (-1)
  Class App\Http\Controllers\Abc\abcController does not exist".

What could be the possible issue?

答:
You should make sure your file is located in app/Http/Controllers/Abc directory and has name abcController.php (case sensitive).

Also by convention class names start with big letter, so you should rather name your controller AbcController and have this file with name AbcController.php (and also update your route file to use valid case of this controller name).

Body:
I am working in laravel 5.5. I have created a controller folder with name Abc and inside it created a controller file with name abc.php, inside this file I have written code:

namespace App\Http\Controllers\Abc;

use App\Http\Controllers\Controller;

//use Illuminate\Support\Facades\DB;

class abcController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function NewPromotion()
    {
        return view('new-promotion');
    }
}

And in Route folder under web.php file I am calling its view file, like:-
Route::get('/new-promotion','Abc\abcController@NewPromotion');

In spite of defining in namespace I am still getting error i.e.

"ReflectionException (-1)
  Class App\Http\Controllers\Abc\abcController does not exist".

What could be the possible issue?