问:
Running .jar file using Apache POI in Maven project
I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:

My pom.xml looks like this:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>calendar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>calendar</name>
  <url>http://maven.apache.org</url>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.10-FINAL</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
    </dependency>

  </dependencies>
</project>
</code>```

From what I can tell, my dependencies are alright.

This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:

```<code>public class App
{

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main( String[] args ) throws IOException
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");

        Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if(field instanceof String) {
                    cell.setCellValue((String) field);
                }
                else if(field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            //workbook.close()
        } catch (FileNotFoundException e) {
            System.out.println("Couldn't find file to write out to");
        } catch (IOException e) {
            System.out.println("IO Exception in printing");
        }

    }
}
</code>```

I have workbook.close() commented out since this caused an error (deprecated method?).

With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.

I am attempting to run this file using

```<code>java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App
</code>```

...and I get the following error message

```<code>Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more
</code>```

If this question requires any more information let me know. I'm at a loss here.

答:
You need to create a fat/uber jar with Maven Assembly Plugin. Which means create a Jar together with its dependency Jars into a single executable Jar file. When you run it then it would have all the dependencies available.

Add following plugin inside your POM

```<code><build>
    <plugins>
        <!-- Maven Assembly Plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
                <!-- get all project dependencies -->
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <!-- MainClass in mainfest make a executable jar -->
                <archive>
                  <manifest>
                    <mainClass>com.your.path.to.main.App</mainClass>
                  </manifest>
                </archive>

            </configuration>
            <executions>
              <execution>
                <id>make-assembly</id>
                                    <!-- bind to the packaging phase -->
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
              </execution>
            </executions>
        </plugin>

    </plugins>
</build>
</code>```

Run following:

```<code>mvn package
</code>```

Two jar files will be created in the target folder.

```<code>calendar-1.0-SNAPSHOT.jar – Only your project classes
calendar-1.0-SNAPSHOT-with-dependencies.jar – Project and dependency classes in a single jar.
</code>```

You can run it follwoing;

```<code>java -cp target/calendar-1.0-SNAPSHOT-with-dependencies.jarcom.mycompany.app.App
</code>```

You can review the contents of calendar-1.0-SNAPSHOT-with-dependencies.jar

```<code>jar tf target/calendar-1.0-SNAPSHOT-with-dependencies.jar
</code>```

Body:
I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:

My pom.xml looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>calendar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>calendar</name>
  <url>http://maven.apache.org</url>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.10-FINAL</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
    </dependency>

  </dependencies>
</project>

From what I can tell, my dependencies are alright.

This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:

public class App
{

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main( String[] args ) throws IOException
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");

        Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if(field instanceof String) {
                    cell.setCellValue((String) field);
                }
                else if(field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            //workbook.close()
        } catch (FileNotFoundException e) {
            System.out.println("Couldn't find file to write out to");
        } catch (IOException e) {
            System.out.println("IO Exception in printing");
        }

    }
}

I have workbook.close() commented out since this caused an error (deprecated method?).

With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.

I am attempting to run this file using

java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App

...and I get the following error message

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

If this question requires any more information let me know. I'm at a loss here.

Body:
You need to create a fat/uber jar with Maven Assembly Plugin. Which means create a Jar together with its dependency Jars into a single executable Jar file. When you run it then it would have all the dependencies available.

Add following plugin inside your POM

<build>
    <plugins>
        <!-- Maven Assembly Plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
                <!-- get all project dependencies -->
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <!-- MainClass in mainfest make a executable jar -->
                <archive>
                  <manifest>
                    <mainClass>com.your.path.to.main.App</mainClass>
                  </manifest>
                </archive>

            </configuration>
            <executions>
              <execution>
                <id>make-assembly</id>
                                    <!-- bind to the packaging phase -->
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
              </execution>
            </executions>
        </plugin>

    </plugins>
</build>

Run following:

mvn package

Two jar files will be created in the target folder.

calendar-1.0-SNAPSHOT.jar – Only your project classes
calendar-1.0-SNAPSHOT-with-dependencies.jar – Project and dependency classes in a single jar.

You can run it follwoing;

java -cp target/calendar-1.0-SNAPSHOT-with-dependencies.jarcom.mycompany.app.App

You can review the contents of calendar-1.0-SNAPSHOT-with-dependencies.jar

jar tf target/calendar-1.0-SNAPSHOT-with-dependencies.jar


来源: stackexchange

问:
How to prevent Flash Builder from running/debugging from the cache?
I've been bitten by this a few times, and when it shows up it can make simple problems very difficult to solve. For example:

```<code>var x:int = y + 1;
if(x < y) {
  trace("Okay, you got me.");
}
</code>```

Under what conditions will that trace show up? Normally it shouldn't, but if the player is using its cache it might. Sometimes I don't realize what's going on until an unreachable breakpoint gets triggered.

Is there a way to prevent Flash Builder/the debug player from playing out-of-date content?

答: I have never had this problem. But use Build Automatically to force Flash Builder to build every time you change a file. Be sure to setup your Actionscript Applications in the Project properties.

ContentLicense: CC BY-SA 2.5

Body:
I've been bitten by this a few times, and when it shows up it can make simple problems very difficult to solve. For example:

var x:int = y + 1;
if(x < y) {
  trace("Okay, you got me.");
}

Under what conditions will that trace show up? Normally it shouldn't, but if the player is using its cache it might. Sometimes I don't realize what's going on until an unreachable breakpoint gets triggered.

Is there a way to prevent Flash Builder/the debug player from playing out-of-date content?


问:
"The model backing the 'DataContext' context has changed" but I am on the same migration
I have a C# solution. Recently, we moved the solution into a new repository.

In the OLD solution, I have a soon-to-be deprecated console app that accesses my Azure-hosted DB to do some work. We had some new DB migrations in the new repository and had some work that required the console app, so I moved the app project over into a throwaway branch in the new repo just so I could build it with the latest migrations.

It compiles fine. However, when I try to run it, I ALWAYS get the The model backing the 'DataContext' context has changed error.

What's weird about this is that my code and my DB are on the same migration. I can even run the update-database command on that DB and it tells me that I have "no pending migrations". I did compares on the stored procedures in my visual studio and the DB and they are all equal. Same results when trying Add-Migration "SyncTest", it creates a migration with no changes.

I cannot delete the __MigrationHistory table because I need to run this console app on production servers and cannot afford to lose that data/have any downtime.

So if I am on the same migration step between my console app and my DB, then why is it still throwing this error? I dunno where else to check!

答:
I don't know why it is happening in your particular case, but I did stumble across a way to turn off the error, put this line in your DbContext instance ctor:</p>

```<code>Database.SetInitializer<YourDbContextClass>(null);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I don't know why it is happening in your particular case, but I did stumble across a way to turn off the error, put this line in your DbContext instance ctor:

Database.SetInitializer<YourDbContextClass>(null);


问:
How to determine the difference in quarterly row values of a pandas dataframe when quarters are missing
I am trying to find the difference in quarterly balance sheet equity values from the following data frame:

```<code>import pandas as pd
import numpy as np

df2= pd.DataFrame({'FirmID'    : pd.Series(['ID001',  'ID001',  'ID001',  'ID001',  'ID001', 'ID001',  'ID001',   'ID001',  'ID001',  'ID001' ]),
                   'RSSD9999'  : pd.Series([20060331, 20060630, 20060930, 20061231, 20070331,20070630, 20070930,  20080630, 20080930, 20081231]),
                   'year'      : pd.Series([2006,     2006,     2006,     2006,     2007,    2007,     2007,      2008,     2008,     2008    ]),
                   'Q'         : pd.Series([1,        2,        3,        4,        1,       2,        3,         2,        3,        4       ]),
                   'EquityEoQ' : pd.Series([112,      223,      333,      445,      126,     251,      376,       291,      291,      503     ]),
                   'NewEqRight': pd.Series([112,      111,      110,      112,      126,      125,      125,      np.nan,      0  ,      212,    ])})
df2=df2[['FirmID','RSSD9999', 'year', 'Q', 'EquityEoQ','NewEqRight']]
</code>```

The frame shows equity values at the end of quarters per year: EquityEoQ. Note, NewEqRight shows the values as they should be, with missing values for 2007Q4 and 2008Q2.

I can find the change in equity per quarter by taking the difference between row values. For example, firm ID001 issued 111 new equity in 2006Q2 (111 = 223 - 112).

If all quarterly rows in the data are present, then I can use shift to create a new column with last quarter's equity (EquityEoLastQ), and another column that records the difference between EquityEoQ and EquityEoLastQ to obtain the change in equity:

```<code>df2['EquityEoLastQ'] = df2.groupby(['FirmID'])['EquityEoQ'].shift(1)
df2['NewEqWrong']     = df2['EquityEoQ']-df2['EquityEoLastQ']
df2.loc[df2['Q']==1, 'NewEqWrong'] = df2.loc[df2['Q']==1, 'EquityEoQ']
</code>```

The last row corrects values for Q1.

But if quarterly rows are missing, then shift messes up. For example, in the data-frame, the rows for  2007Q4 and 2008Q1 are missing. This leads to incorrect information, because shift refers to the wrong quarter. In this frame this approach gives a negative NewEqWrong value for 2008Q2 is     -85.0, which is the wrong value.

Desired data set:

```<code>In [9]: df2
Out[9]:
  FirmID  RSSD9999  year  Q  EquityEoQ  NewEqRight  EquityEoLastQ  NewEqWrong
0  ID001  20060331  2006  1        112       112.0            NaN       112.0
1  ID001  20060630  2006  2        223       111.0          112.0       111.0
2  ID001  20060930  2006  3        333       110.0          223.0       110.0
3  ID001  20061231  2006  4        445       112.0          333.0       112.0
4  ID001  20070331  2007  1        126       126.0          445.0       126.0
5  ID001  20070630  2007  2        251       125.0          126.0       125.0
6  ID001  20070930  2007  3        376       125.0          251.0       125.0
7  ID001  20080630  2008  2        291         NaN          376.0       -85.0
8  ID001  20080930  2008  3        291         0.0          291.0         0.0
9  ID001  20081231  2008  4        503       212.0          291.0       212.0
</code>```

In Stata one can set the time series frequency to quarterly, and then use L. or D. to find lags and differences respectively.

Is there any way pandas can deal with this problem, more or less like Stata?

答:
Basically, I realised that I want to merge data. It then works as desired:

See this link: lag values and differences and missing quarterly data

Body:
I am trying to find the difference in quarterly balance sheet equity values from the following data frame:

import pandas as pd
import numpy as np

df2= pd.DataFrame({'FirmID'    : pd.Series(['ID001',  'ID001',  'ID001',  'ID001',  'ID001', 'ID001',  'ID001',   'ID001',  'ID001',  'ID001' ]),
                   'RSSD9999'  : pd.Series([20060331, 20060630, 20060930, 20061231, 20070331,20070630, 20070930,  20080630, 20080930, 20081231]),
                   'year'      : pd.Series([2006,     2006,     2006,     2006,     2007,    2007,     2007,      2008,     2008,     2008    ]),
                   'Q'         : pd.Series([1,        2,        3,        4,        1,       2,        3,         2,        3,        4       ]),
                   'EquityEoQ' : pd.Series([112,      223,      333,      445,      126,     251,      376,       291,      291,      503     ]),
                   'NewEqRight': pd.Series([112,      111,      110,      112,      126,      125,      125,      np.nan,      0  ,      212,    ])})
df2=df2[['FirmID','RSSD9999', 'year', 'Q', 'EquityEoQ','NewEqRight']]

The frame shows equity values at the end of quarters per year: EquityEoQ. Note, NewEqRight shows the values as they should be, with missing values for 2007Q4 and 2008Q2.

I can find the change in equity per quarter by taking the difference between row values. For example, firm ID001 issued 111 new equity in 2006Q2 (111 = 223 - 112).

If all quarterly rows in the data are present, then I can use shift to create a new column with last quarter's equity (EquityEoLastQ), and another column that records the difference between EquityEoQ and EquityEoLastQ to obtain the change in equity:

df2['EquityEoLastQ'] = df2.groupby(['FirmID'])['EquityEoQ'].shift(1)
df2['NewEqWrong']     = df2['EquityEoQ']-df2['EquityEoLastQ']
df2.loc[df2['Q']==1, 'NewEqWrong'] = df2.loc[df2['Q']==1, 'EquityEoQ']

The last row corrects values for Q1.

But if quarterly rows are missing, then shift messes up. For example, in the data-frame, the rows for  2007Q4 and 2008Q1 are missing. This leads to incorrect information, because shift refers to the wrong quarter. In this frame this approach gives a negative NewEqWrong value for 2008Q2 is     -85.0, which is the wrong value.

Desired data set:

In [9]: df2
Out[9]:
  FirmID  RSSD9999  year  Q  EquityEoQ  NewEqRight  EquityEoLastQ  NewEqWrong
0  ID001  20060331  2006  1        112       112.0            NaN       112.0
1  ID001  20060630  2006  2        223       111.0          112.0       111.0
2  ID001  20060930  2006  3        333       110.0          223.0       110.0
3  ID001  20061231  2006  4        445       112.0          333.0       112.0
4  ID001  20070331  2007  1        126       126.0          445.0       126.0
5  ID001  20070630  2007  2        251       125.0          126.0       125.0
6  ID001  20070930  2007  3        376       125.0          251.0       125.0
7  ID001  20080630  2008  2        291         NaN          376.0       -85.0
8  ID001  20080930  2008  3        291         0.0          291.0         0.0
9  ID001  20081231  2008  4        503       212.0          291.0       212.0

In Stata one can set the time series frequency to quarterly, and then use L. or D. to find lags and differences respectively.

Is there any way pandas can deal with this problem, more or less like Stata?


问:
python 3 regex - find all overlapping matches' start and end index in a string
This was my original approach:

```<code>string = '1'*15
result = re.finditer(r'(?=11111)', string)      # overlapped = True
                                                # Doesn't work for me
for i in result:                                # python 3.5
   print(i.start(), i.end())
</code>```

It finds all overlapping matches, but fails to get the right end index.
The output:

```<code>1 <_sre.SRE_Match object; span=(0, 0), match=''>
2 <_sre.SRE_Match object; span=(1, 1), match=''>
3 <_sre.SRE_Match object; span=(2, 2), match=''>
4 <_sre.SRE_Match object; span=(3, 3), match=''>
(and so on..)
</code>```

My Question:
How can I find all overlapping matches, and get all the start and end index right as well?

答:
Can you compare with this implementation and see where the differences might be.

```<code>match = re.finditer(r'111','test111 end111 and another 111')
for i in match:
    print(i.start(),i.end()
</code>```

If this is not working for you kindly share a sample of you data

Body:
This was my original approach:

string = '1'*15
result = re.finditer(r'(?=11111)', string)      # overlapped = True
                                                # Doesn't work for me
for i in result:                                # python 3.5
   print(i.start(), i.end())

It finds all overlapping matches, but fails to get the right end index.
The output:

1 <_sre.SRE_Match object; span=(0, 0), match=''>
2 <_sre.SRE_Match object; span=(1, 1), match=''>
3 <_sre.SRE_Match object; span=(2, 2), match=''>
4 <_sre.SRE_Match object; span=(3, 3), match=''>
(and so on..)

My Question:
How can I find all overlapping matches, and get all the start and end index right as well?

Body:
Can you compare with this implementation and see where the differences might be.

match = re.finditer(r'111','test111 end111 and another 111')
for i in match:
    print(i.start(),i.end()

If this is not working for you kindly share a sample of you data


问:
Export devices added in Apple's iOS Provision portal
My apple developer is about to expire in 5 days. And after renewal I want to restore my devices count to 100 but meanwhile I want to export all currently added devices as backup for future use, these are 87 devices.

In new apple developer section I don't see any option to export all devices and I don't want to copy paste all 87 devices :(

Note:
I want to export devices in the format required by the Apple for multiple device inserts.

答:
My solution to this was to create new provisioning profile here
and add all devices to it. Then download it and open with vim (or any other editor). The file will contain some binary style and plist (xml) with all your devices, which can be parsed I guess, but I just c&p device list. Smth like:

```<code><key>ProvisionedDevices</key>
   <array>
       <string>device1 udid</string>
       ....
       <string>deviceN udid</string>
   </array>
</code>```

Delete your provisioning profile if you don't need it after.

Body:
My solution to this was to create new provisioning profile here
and add all devices to it. Then download it and open with vim (or any other editor). The file will contain some binary style and plist (xml) with all your devices, which can be parsed I guess, but I just c&p device list. Smth like:

<key>ProvisionedDevices</key>
   <array>
       <string>device1 udid</string>
       ....
       <string>deviceN udid</string>
   </array>

Delete your provisioning profile if you don't need it after.


问:
Send email with Qt
Hello I am trying to create a method to send emails through my qt app and it works very much ok but when I try to send arabic on non english message it send as "????" question marks
here is my code

```<code>    void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body)
{
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: ar_EG, en_US\n");
    message.append("MIME-Version: 1.0\r\n");
    message = "To: " + to + "\r\n";
    message.append("From: " + from + "\r\n");
    message.append("Subject: " + subject + "\r\n");
    //message.append("Content-Type: text/html; charset=UTF8;\r\n");
    message.append("Message From Smart Clinic\r\n");
    message.append(QString("Build Number: %1 \r\n").arg(BUILD));
    message.append(QString("Version     : %1 \r\n").arg(APPVERSION));
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;
    state = Init;
    socket->connectToHostEncrypted(host, port); //"smtp.gmail.com" and 465 for gmail TLS
    if (!socket->waitForConnected(timeout)) {
        emit status( tr( "Failed to send message" ) );
     }

    t = new QTextStream( socket );
}
</code>```

how to make it able to send english and non english text
thank you

答:
uncomment the below line in your code and try.

```<code>//message.append("Content-Type: text/html; charset=UTF8;\r\n");
</code>```

if not try to use the charset type "ISO_8859-7:1987" and check if it is working,

```<code>message.append("Content-Type: text/html; charset=ISO_8859-7:1987;\r\n");
</code>```

For more character sets refer

http://www.iana.org/assignments/character-sets/character-sets.xhtml

Title: Send email with Qt

Body:
Hello I am trying to create a method to send emails through my qt app and it works very much ok but when I try to send arabic on non english message it send as "????" question marks
here is my code

    void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body)
{
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: ar_EG, en_US\n");
    message.append("MIME-Version: 1.0\r\n");
    message = "To: " + to + "\r\n";
    message.append("From: " + from + "\r\n");
    message.append("Subject: " + subject + "\r\n");
    //message.append("Content-Type: text/html; charset=UTF8;\r\n");
    message.append("Message From Smart Clinic\r\n");
    message.append(QString("Build Number: %1 \r\n").arg(BUILD));
    message.append(QString("Version     : %1 \r\n").arg(APPVERSION));
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;
    state = Init;
    socket->connectToHostEncrypted(host, port); //"smtp.gmail.com" and 465 for gmail TLS
    if (!socket->waitForConnected(timeout)) {
        emit status( tr( "Failed to send message" ) );
     }

    t = new QTextStream( socket );
}

how to make it able to send english and non english text
thank you

Body:
uncomment the below line in your code and try.

//message.append("Content-Type: text/html; charset=UTF8;\r\n");

if not try to use the charset type "ISO_8859-7:1987" and check if it is working,

message.append("Content-Type: text/html; charset=ISO_8859-7:1987;\r\n");

For more character sets refer

http://www.iana.org/assignments/character-sets/character-sets.xhtml


问:
How to deselect all selected rows in a DataGridView control?
I'd like to deselect all selected rows in a DataGridView control when the user clicks on a blank (non-row) part of the control.

How can I do this?

答:
Set

```<code>dgv.CurrentCell = null;
</code>```

when user clicks on a blank part of the dgv.

Body:
Set

dgv.CurrentCell = null;

when user clicks on a blank part of the dgv.


问:
Horizontal LinearLayout inside Vertical LinearLayout
I want to display an horizontal linearlayout which content 3 imageview inside a vertical linearLayout

But i have a problem as you can see

Only the first Imageview is displayed , and he is in the center .

I changed the gravity for the other Imageview (left and right) but nothing changed .

The code :

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        tools:context="info.androidhive.navigationdrawer.activity.FormActivity"
        android:weightSum="1"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Ajouter Votre Annonce"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="22sp"
            />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="34dp"
            android:layout_below="@+id/textView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:entries="@array/cat_arrays"
            android:prompt="@string/cat_prompt"
            />

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="23dp"
            android:text="Offre"
            android:layout_below="@+id/spinner"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:textColor="#000000"
            />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/radioButton"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="Demande"
            android:textColor="#000000"
            />

        <Spinner
            android:id="@+id/spinner4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/spinner3"
            android:layout_marginTop="17dp"
            android:entries="@array/vil_arrays"
            android:prompt="@string/vil_prompt"
            android:textColor="#808080"
            />

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Titre de l'Annonce"
            android:layout_below="@+id/spinner4"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/editText8"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Prix en UM"
            android:layout_below="@+id/spinner4"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/editText"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Description"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentBottom="true"
            android:textColorHint="#808080"
            android:paddingBottom="75dp"
            android:textColor="#000000"/>

        <TextView
            android:id="@+id/textView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="27dp"
            android:text="Vos Photos"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="22sp"

            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/img1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/imgadd"
                android:gravity="left"
                />

            <ImageView
                android:id="@+id/img2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/imgadd"
                android:gravity="center"/>

            <ImageView
                android:id="@+id/img3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/imgadd"
                android:gravity="right"/>

        </LinearLayout>

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button3"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="23dp"
            android:text="Vos Informations"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="22sp"
            />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button3"
            android:layout_alignStart="@+id/button3"
            android:layout_below="@+id/textView5"
            android:text="Professionel"
            android:textColor="#000000"
            />

        <RadioButton
            android:id="@+id/radioButton4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/radioButton3"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="Particulier"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/editText5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button3"
            android:layout_alignStart="@+id/button3"
            android:layout_below="@+id/radioButton3"
            android:layout_marginTop="26dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Nom et Prenom"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            />

        <EditText
            android:id="@+id/editText6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText5"
            android:layout_alignParentBottom="true"
            android:layout_alignStart="@+id/editText5"
            android:layout_marginBottom="10dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Telephone"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            />
        <EditText
            android:id="@+id/editText7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText6"
            android:layout_alignParentBottom="true"
            android:layout_alignStart="@+id/editText6"
            android:layout_marginBottom="10dp"
            android:ems="10"
            android:inputType="textPassword"
            android:hint="Mot de passe"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"/>

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="36dp"
            android:text="Déposez votre Annonce"
            android:background="#a4c639"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:textColorHint="#808080"/>

    </LinearLayout>
</ScrollView>
</code>```

答:
Try this code:   </p>

```<code><LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

        <ImageView
            android:id="@+id/img1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/imgadd"/>

        <ImageView
            android:id="@+id/img2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/imgadd"/>

        <ImageView
            android:id="@+id/img3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/imgadd"/>

    </LinearLayout>
</code>```

Body:
I want to display an horizontal linearlayout which content 3 imageview inside a vertical linearLayout

But i have a problem as you can see

Only the first Imageview is displayed , and he is in the center .

I changed the gravity for the other Imageview (left and right) but nothing changed .

The code :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        tools:context="info.androidhive.navigationdrawer.activity.FormActivity"
        android:weightSum="1"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Ajouter Votre Annonce"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="22sp"
            />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="34dp"
            android:layout_below="@+id/textView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:entries="@array/cat_arrays"
            android:prompt="@string/cat_prompt"
            />

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="23dp"
            android:text="Offre"
            android:layout_below="@+id/spinner"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:textColor="#000000"
            />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/radioButton"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="Demande"
            android:textColor="#000000"
            />

        <Spinner
            android:id="@+id/spinner4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/spinner3"
            android:layout_marginTop="17dp"
            android:entries="@array/vil_arrays"
            android:prompt="@string/vil_prompt"
            android:textColor="#808080"
            />

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Titre de l'Annonce"
            android:layout_below="@+id/spinner4"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/editText8"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Prix en UM"
            android:layout_below="@+id/spinner4"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/editText"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Description"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentBottom="true"
            android:textColorHint="#808080"
            android:paddingBottom="75dp"
            android:textColor="#000000"/>

        <TextView
            android:id="@+id/textView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="27dp"
            android:text="Vos Photos"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="22sp"

            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/img1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/imgadd"
                android:gravity="left"
                />

            <ImageView
                android:id="@+id/img2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/imgadd"
                android:gravity="center"/>

            <ImageView
                android:id="@+id/img3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/imgadd"
                android:gravity="right"/>

        </LinearLayout>

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button3"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="23dp"
            android:text="Vos Informations"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="22sp"
            />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button3"
            android:layout_alignStart="@+id/button3"
            android:layout_below="@+id/textView5"
            android:text="Professionel"
            android:textColor="#000000"
            />

        <RadioButton
            android:id="@+id/radioButton4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/radioButton3"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="Particulier"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/editText5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button3"
            android:layout_alignStart="@+id/button3"
            android:layout_below="@+id/radioButton3"
            android:layout_marginTop="26dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Nom et Prenom"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            />

        <EditText
            android:id="@+id/editText6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText5"
            android:layout_alignParentBottom="true"
            android:layout_alignStart="@+id/editText5"
            android:layout_marginBottom="10dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="Telephone"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"
            />
        <EditText
            android:id="@+id/editText7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText6"
            android:layout_alignParentBottom="true"
            android:layout_alignStart="@+id/editText6"
            android:layout_marginBottom="10dp"
            android:ems="10"
            android:inputType="textPassword"
            android:hint="Mot de passe"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textColorHint="#808080"/>

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="36dp"
            android:text="Déposez votre Annonce"
            android:background="#a4c639"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:textColorHint="#808080"/>

    </LinearLayout>
</ScrollView>

Body:
Try this code:

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

        <ImageView
            android:id="@+id/img1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/imgadd"/>

        <ImageView
            android:id="@+id/img2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/imgadd"/>

        <ImageView
            android:id="@+id/img3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/imgadd"/>

    </LinearLayout>


问:
"Between" Statement in Left Join Returns null
OK, there's GOT to be an answer to this... likely a straightforward solution for one of the many experts here at Stack Overflow! :-)

Background:
I am trying to create a restaurant sales report by shift. I have 2 tables... one with RECEIPT details (restaurant, date, time, receipt#, amount, server, etc.) and another with SHIFT details (restaurant, shift start time, shift end time & shift name). There are Shift Numbers in both tables, but unfortunately the Shift Numbers in the Receipts table are not always accurate, so I am having to come up with a workaround based on which bucket of ShiftStart & ShiftEnd times the ReceiptTime falls into. This code for the join almost works:

```<code>LEFT OUTER JOIN: Receipts.Time BETWEEN ShiftDetails.ShiftStartTime AND ShiftsDetails.ShiftEndTime
</code>```

BUT... my challenge is that the Dinner ShiftEndTime is currently 02:00, which (of course) is less than the Dinner ShiftStartTime of 17:31, so any ReceiptTimes "between" these hours returns a null value. I would also like to keep the query dynamic by avoiding "hard coding" the Start/End times, instead using those in the Shift table, as they are likely to be revised in the future.

FWIW, my data source is SQL Server with Power BI as a front-end, so alternatively I could scrap the SQL code and perform magic with PowerQuery or DAX...

Many thanks in advance!
Danny

答:
Here is one way of handling this logic:

```<code>Receipts r LEFT OUTER JOIN
ShiftDetails sd
ON (sd.ShiftStartTime <= sd.ShiftEndTime AND r.Time BETWEEN sd.ShiftStartTime AND sd.ShiftEndTime) OR
    (sd.ShiftStartTime > sd.ShiftEndTime AND r.Time BETWEEN sd.ShiftEndTime AND sd.ShiftStartTime)
</code>```

You might decide that you really don't want BETWEEN.  Receipts that are exactly on the boundary between shifts will return both of them -- because BETWEEN includes the end points of the range.

Body:
OK, there's GOT to be an answer to this... likely a straightforward solution for one of the many experts here at Stack Overflow! :-)

Background:
I am trying to create a restaurant sales report by shift. I have 2 tables... one with RECEIPT details (restaurant, date, time, receipt#, amount, server, etc.) and another with SHIFT details (restaurant, shift start time, shift end time & shift name). There are Shift Numbers in both tables, but unfortunately the Shift Numbers in the Receipts table are not always accurate, so I am having to come up with a workaround based on which bucket of ShiftStart & ShiftEnd times the ReceiptTime falls into. This code for the join almost works:

LEFT OUTER JOIN: Receipts.Time BETWEEN ShiftDetails.ShiftStartTime AND ShiftsDetails.ShiftEndTime

BUT... my challenge is that the Dinner ShiftEndTime is currently 02:00, which (of course) is less than the Dinner ShiftStartTime of 17:31, so any ReceiptTimes "between" these hours returns a null value. I would also like to keep the query dynamic by avoiding "hard coding" the Start/End times, instead using those in the Shift table, as they are likely to be revised in the future.

FWIW, my data source is SQL Server with Power BI as a front-end, so alternatively I could scrap the SQL code and perform magic with PowerQuery or DAX...

Many thanks in advance!
Danny

Body:
Here is one way of handling this logic:

Receipts r LEFT OUTER JOIN
ShiftDetails sd
ON (sd.ShiftStartTime <= sd.ShiftEndTime AND r.Time BETWEEN sd.ShiftStartTime AND sd.ShiftEndTime) OR
    (sd.ShiftStartTime > sd.ShiftEndTime AND r.Time BETWEEN sd.ShiftEndTime AND sd.ShiftStartTime)

You might decide that you really don't want BETWEEN.  Receipts that are exactly on the boundary between shifts will return both of them -- because BETWEEN includes the end points of the range.


问:
Display a count for each unique value in a table column
How can I grab a count of each unique value from a table's column, plus the actual value, into another cell.

Table 1's status column

```<code>**status**
------
itemA
itemA
itemB
itemC
</code>```

desired results into a single cell:

```<code>Table 1 Status summary |2 itemA, 1 itemB, 1 itemC
</code>```

I would settle for a simple comma separated list of all the distinct values without the count.

BACKGROUND INFO:
I have an excel document we are using to keep track of acceptance testing of a new application. The document which holds multiple worksheets (each representing an area of code that needs to be tested) and each worksheet has multiple tables (which represent test cases where each case should be tested multiple times or in different ways etc.) and then there is a summary worksheet where I want a snap shot of the data. On the summary page there is line for each table in each worksheet and a status column. In that status column I want to display a count of each status selected in the corresponding table. I had originally created a lengthy formula that hard coded the values and their counts if count was > 0, but as we are testing we are finding the need to add new status values and the formula then becomes way to burdensome to keep updated.

EDIT: ADDING FORMULA
Here is the formula that I originally had in there

```<code>=IF(COUNTIF(Table1[Status],"itemA"),COUNTIF(Table1[Status],"itemA")&" itemA"," ") & IF(COUNTIF(Table1[Status],"itemB"), ", " &COUNTIF(Table1[Status],"itemB")&" itemB"," ") & IF(COUNTIF(Table1[Status],"itemC"), ", " &COUNTIF(Table1[Status],"itemC")&" itemC"," ")
</code>```

The problem with this is, the formula was repeated about 100 times on the summary page (once for each table in the underlying worksheets) and every time I wanted to add a status I would need to edit each of the formulas.

答:
This VBA solution uses an User Defined Function which:

.- Validates the Target Range belongs to a ListObject (Excel Table).

.- Uses an Array to hold all Status values from the table.

.- Uses a Control string to validate uniqueness Status.

.- Uses an Output string to hold the list of unique Status with the corresponding count.

Note: The list will have the same order as they appear in the table. Sort is not on the scope of the question but if you want it sorted I suggest to sort the ListObject as required (not included).

Try this procedure (see comments included in the code):

```<code>Private Function Lob_Status_Count(rTrg As Range) As String
Const kStt As String = "Status"
Dim lob As ListObject
Dim sControl As String, sOutput As String
Dim aStt As Variant, vStt As Variant, bStt As Byte
    Rem Validate Input
    On Error Resume Next
    Set lob = rTrg.ListObject               'Set ListObject
    On Error GoTo 0
    If lob Is Nothing Then GoTo ExitTkn     'Exit if Target range is not a ListObject

    With lob.ListColumns(kStt).DataBodyRange

        Rem Set Status Array
        aStt = WorksheetFunction.Transpose(.Value2)

        Rem Set Status Output
        For Each vStt In aStt
            If InStr(sControl, Chr(167) & vStt & Chr(167)) = 0 Then     'Validates uniqueness
                bStt = WorksheetFunction.CountIf(.Cells, vStt)          'Gets Status Count
                sOutput = sOutput & ", " & bStt & " " & vStt            'Adds to Results
                sControl = sControl & Chr(167) & vStt & Chr(167)        'Adds to Control
        End If: Next

        Rem Cleanup Output
        sOutput = Replace(sOutput, ", ", vbNullString, 1, 1)

    End With

    Rem Set Results
    Lob_Status_Count = sOutput

Exit Function
ExitTkn:
    Lob_Status_Count = "!Err ListObject"

End Function
</code>```

Suggest to read the following pages to gain a deeper understanding of the resources used:

Using Arrays,
ListObject Members (Excel),
WorksheetFunction Object (Excel),

For Each...Next Statement, InStr Function,
On Error Statement.

Body:
How can I grab a count of each unique value from a table's column, plus the actual value, into another cell.

Table 1's status column

**status**
------
itemA
itemA
itemB
itemC

desired results into a single cell:

Table 1 Status summary |2 itemA, 1 itemB, 1 itemC

I would settle for a simple comma separated list of all the distinct values without the count.

BACKGROUND INFO:
I have an excel document we are using to keep track of acceptance testing of a new application. The document which holds multiple worksheets (each representing an area of code that needs to be tested) and each worksheet has multiple tables (which represent test cases where each case should be tested multiple times or in different ways etc.) and then there is a summary worksheet where I want a snap shot of the data. On the summary page there is line for each table in each worksheet and a status column. In that status column I want to display a count of each status selected in the corresponding table. I had originally created a lengthy formula that hard coded the values and their counts if count was > 0, but as we are testing we are finding the need to add new status values and the formula then becomes way to burdensome to keep updated.

EDIT: ADDING FORMULA
Here is the formula that I originally had in there

=IF(COUNTIF(Table1[Status],"itemA"),COUNTIF(Table1[Status],"itemA")&" itemA"," ") & IF(COUNTIF(Table1[Status],"itemB"), ", " &COUNTIF(Table1[Status],"itemB")&" itemB"," ") & IF(COUNTIF(Table1[Status],"itemC"), ", " &COUNTIF(Table1[Status],"itemC")&" itemC"," ")

The problem with this is, the formula was repeated about 100 times on the summary page (once for each table in the underlying worksheets) and every time I wanted to add a status I would need to edit each of the formulas.

Body:
This VBA solution uses an User Defined Function which:

.- Validates the Target Range belongs to a ListObject (Excel Table).

.- Uses an Array to hold all Status values from the table.

.- Uses a Control string to validate uniqueness Status.

.- Uses an Output string to hold the list of unique Status with the corresponding count.

Note: The list will have the same order as they appear in the table. Sort is not on the scope of the question but if you want it sorted I suggest to sort the ListObject as required (not included).

Try this procedure (see comments included in the code):

Private Function Lob_Status_Count(rTrg As Range) As String
Const kStt As String = "Status"
Dim lob As ListObject
Dim sControl As String, sOutput As String
Dim aStt As Variant, vStt As Variant, bStt As Byte
    Rem Validate Input
    On Error Resume Next
    Set lob = rTrg.ListObject               'Set ListObject
    On Error GoTo 0
    If lob Is Nothing Then GoTo ExitTkn     'Exit if Target range is not a ListObject

    With lob.ListColumns(kStt).DataBodyRange

        Rem Set Status Array
        aStt = WorksheetFunction.Transpose(.Value2)

        Rem Set Status Output
        For Each vStt In aStt
            If InStr(sControl, Chr(167) & vStt & Chr(167)) = 0 Then     'Validates uniqueness
                bStt = WorksheetFunction.CountIf(.Cells, vStt)          'Gets Status Count
                sOutput = sOutput & ", " & bStt & " " & vStt            'Adds to Results
                sControl = sControl & Chr(167) & vStt & Chr(167)        'Adds to Control
        End If: Next

        Rem Cleanup Output
        sOutput = Replace(sOutput, ", ", vbNullString, 1, 1)

    End With

    Rem Set Results
    Lob_Status_Count = sOutput

Exit Function
ExitTkn:
    Lob_Status_Count = "!Err ListObject"

End Function

Suggest to read the following pages to gain a deeper understanding of the resources used:

Using Arrays,
ListObject Members (Excel),
WorksheetFunction Object (Excel),

For Each...Next Statement, InStr Function,
On Error Statement.


答:
To deselect all rows and cells in a DataGridView, you can use the ClearSelection method:

```<code>myDataGridView.ClearSelection()
</code>```

If you don't want even the first row/cell to appear selected, you can set the CurrentCell property to Nothing/null, which will temporarily hide the focus rectangle until the control receives focus again:

```<code>myDataGridView.CurrentCell = Nothing
</code>```

To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event. In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere. For example:

```<code>Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
    ''# See if the left mouse button was clicked
    If e.Button = MouseButtons.Left Then
        ''# Check the HitTest information for this click location
        If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
            myDataGridView.ClearSelection()
            myDataGridView.CurrentCell = Nothing
        End If
    End If
End Sub
</code>```

Of course, you could also subclass the existing DataGridView control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp method similar to the way shown above. I also like to provide a public DeselectAll method for convenience that both calls the ClearSelection method and sets the CurrentCell property to Nothing.

(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)

Title: How to deselect all selected rows in a DataGridView control?

Body:
I'd like to deselect all selected rows in a DataGridView control when the user clicks on a blank (non-row) part of the control.

How can I do this?

Body:
To deselect all rows and cells in a DataGridView, you can use the ClearSelection method:

myDataGridView.ClearSelection()

If you don't want even the first row/cell to appear selected, you can set the CurrentCell property to Nothing/null, which will temporarily hide the focus rectangle until the control receives focus again:

myDataGridView.CurrentCell = Nothing

To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event. In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere. For example:

Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
    ''# See if the left mouse button was clicked
    If e.Button = MouseButtons.Left Then
        ''# Check the HitTest information for this click location
        If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
            myDataGridView.ClearSelection()
            myDataGridView.CurrentCell = Nothing
        End If
    End If
End Sub

Of course, you could also subclass the existing DataGridView control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp method similar to the way shown above. I also like to provide a public DeselectAll method for convenience that both calls the ClearSelection method and sets the CurrentCell property to Nothing.

(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)


问:
Any way for executing code to know it's running in the eclipse debugger?
I have some Pax Exam tests.  To execute the test normally, I just run the JUnit class in Eclipse.  If I want to step through the code in the Eclipse debugger, I have to make it set the debug options, including the flag to make it wait for the debugger connection, which is a separate process I have to run.  I'm presently having this code check for a "debug" system property to enable this, but that's sort of annoying.

It would be really nice if the @Configuration method can look at a system property or some other condition that will always be true if the code is executing in the debugger, so I could use that as a trigger to enable those flags, instead of a manually set "debug" system property.

I've already tried setting a breakpoint at the top of this method and inspecting all the system properties for something that might be set while in the debugger, but I didn't see anything.

Update:

Just to be clear, I need to point out some details about how Pax Exam tests work, to better explain why I'm looking for a way to improve this process.  When the test runs, it forks a Karaf container to run the test in.  In order to run a test in the debugger, you have to force the code that runs in the container to set the "suspend=y" flag, which will wait for a debugger connection.  You definitely don't want to do that if you're not debugging.

After starting the pax exam test running, you then have to run another debug configuration, to make a remote connection to the karaf container.  Technically, the run configuration for the unit test itself doesn't need to be a debug configuration.

So, the easiest way to make this happen is to have the the code that initiates the container check for a "debug" system property (or whatever you want to call it), and when that is set, to set the debugger port and the "suspend=y" flag.  If the property is not set, it doesn't do that.

So, if you're running the test without debug, you have to make sure that system property is not set.  If you're debugging, you have to make sure it's set.  It's an annoyance to have to edit the run configuration each time you need to go back and forth.

So, what I was intending was to start the unit test run configuration as a debug configuration (even though it doesn't need to be), and for the code that starts the karaf container to detect that it's being run as a debug configuration, and set the "suspend=y" flag in that case.

I've concluded that there is no way for the code itself to detect this, but I'll detail in my own answer how I get the debugger to help me a bit.

答:
I'm going to self-answer to address my original problem, although it isn't quite the answer to my original question, which the first answer does attempt to address.  That answer doesn't help me, however.

My real need was to able to run my Pax Exam test so that when I first run the unit test, which is running the "server" portion of the Pax Exam test, it will know to provide the correct "-Xdebug" parameters to the server if I'm going to be using the debugger, and NOT to if I'm not using the debugger.  I have code that checks for the "debug" system property and uses that to set the correct "-Xdebug" parameters, but I don't want to have to manually add or remove that parameter from the run configuration if I need to change how I'm running the test (going between debugging and not debugging).

So, as far as I can see, the best I can do is make it so that when I run the "server" portion of the unit test in the debugger (which otherwise doesn't actually have to be in the debugger, as it's only the client side that needs it), this will cause the system property I'm checking for to be set, so it will set the correct flags.

I'm not aware of any feature in Eclipse that lets me run particular predefined snippets of code when I start any debugging session (I mean "any", not a "particular" debugging session), but there is something that comes close, even though it's a bit of a hack.

What I did was set a breakpoint at the top of the method that sets the karaf configuration to be started, and I made the breakpoint conditional, with the following expression:

```<code>(System.setProperty("debug", "true") != null) && false
</code>```

This will set the system property I need, but then not stop, as the final expression will be false.

Technically, it doesn't even need to be in this method, it just has to be hit before the karaf options are set.

This stays as a workspace setting, so I don't need to re-add this every time I start Eclipse.

Update:

With the upgrade to Oxygen, this can be slightly simpler, with the new "tracepoints" feature (https://www.eclipse.org/eclipse/news/4.7/jdt.php#toggle-trace-point).  Just "toggle tracepoint" and set the expression to 'System.setProperty("debug", "true")'

Body:
I'm going to self-answer to address my original problem, although it isn't quite the answer to my original question, which the first answer does attempt to address.  That answer doesn't help me, however.

My real need was to able to run my Pax Exam test so that when I first run the unit test, which is running the "server" portion of the Pax Exam test, it will know to provide the correct "-Xdebug" parameters to the server if I'm going to be using the debugger, and NOT to if I'm not using the debugger.  I have code that checks for the "debug" system property and uses that to set the correct "-Xdebug" parameters, but I don't want to have to manually add or remove that parameter from the run configuration if I need to change how I'm running the test (going between debugging and not debugging).

So, as far as I can see, the best I can do is make it so that when I run the "server" portion of the unit test in the debugger (which otherwise doesn't actually have to be in the debugger, as it's only the client side that needs it), this will cause the system property I'm checking for to be set, so it will set the correct flags.

I'm not aware of any feature in Eclipse that lets me run particular predefined snippets of code when I start any debugging session (I mean "any", not a "particular" debugging session), but there is something that comes close, even though it's a bit of a hack.

What I did was set a breakpoint at the top of the method that sets the karaf configuration to be started, and I made the breakpoint conditional, with the following expression:

(System.setProperty("debug", "true") != null) && false

This will set the system property I need, but then not stop, as the final expression will be false.

Technically, it doesn't even need to be in this method, it just has to be hit before the karaf options are set.

This stays as a workspace setting, so I don't need to re-add this every time I start Eclipse.

Update:

With the upgrade to Oxygen, this can be slightly simpler, with the new "tracepoints" feature (https://www.eclipse.org/eclipse/news/4.7/jdt.php#toggle-trace-point).  Just "toggle tracepoint" and set the expression to 'System.setProperty("debug", "true")'


问:
Laravel 5.4 detecting variable in developing mode but not in production mode
I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

```<code>@foreach($product_details as $product_detail)
    <div data-repeater-item class="mt-repeater-item">
        <div class="mt-repeater-row">
            <div class="col-md-2"></div>
            <div class="col-md-3">
                <label class="control-label">Title</label>
                <input type="hidden" name="indicator_id" value="{{$product_detail->id}}">
                <input name="title" type="text" placeholder="Title" class="form-control" value="{{$product_detail->title}}" /> </div>
            <div class="col-md-6">
                <label class="control-label">Description</label>
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" >{{$product_detail->description}}</textarea> </div>
            <div class="col-md-1">
                <a href="javascript:;" data-repeater-delete class="btn btn-danger mt-repeater-delete">
                    <i class="fa fa-close"></i>
                </a>
            </div>
        </div>
    </div>
@endforeach
</code>```

Here is Controller

```<code>$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);
</code>```

And Model

```<code>class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}
</code>```

Thanks in advance.

答: I replaced vendor folder of live server with my local and it worked.

Body:
I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

@foreach($product_details as $product_detail)

                Title
                <input type="hidden" name="indicator_id" value="{{$product_detail->id}}">
                <input name="title" type="text" placeholder="Title" class="form-control" value="{{$product_detail->title}}" />

                Description
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" >{{$product_detail->description}}</textarea>

@endforeach

Here is Controller

$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);

And Model

class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}

Thanks in advance.


问:
What are the necessary special member functions that should to be declared?
I am currently learning about C++. I learnt about some special member functions which are generated by the compiler.

• Default constructor. • Copy constructor • Move Constructor • Copy assignment operator • Move assignment operator • Destructor

I know about the functionalities of each member function. But I wanna know which of these member function are necessary and should be declared (instead of being generated by the compiler), as a part of good coding practices, keeping memory and efficiency in mind.

答:
The default constructor is a special case among these. If some member variables need an initial state that is not the default value of those members, write a default constructor.

The rest of these should really only be overwritten if you know that you need it.

These are some reasonable cases in which you might want to write custom versions of the listed functions:

Your class has member variables that are pointers to dynamic memory that it has allocated.

Your class has data structures as members that the user is not expected to pass completed versions of into the constructor.

Your class has members that you do not want to use the default copy model for (e.g. you want a deep copy but the copy constructor or assignment would make a shallow copy).

Your class has a static data member that should be changed when new instances of it are created.

Examples of each of these use cases include:

STL vectors, which dynamically allocates its underlying array and deallocates in its destructor.

STL lists, which copy data that is added to them onto list nodes, the internals of which are not exposed to the end-user.

Any STL container class is a good example of this.

Something where the number of things which need access to an expensive resource are needed. Similar to the design goal of a std::shared_ptr.

If one class meets too many of these requirements, you should probably consider changing your design to use more of the containers an utilities provided by the standard library. Especially if one class requires the fourth property and any of the other three. The responsibilities related to points 1-3 and point 4 should be handled by different classes. It is important to note that ownership of one large, expensive-to-create resource and ownership of many resources are different types of responsibility.

References:

Explaination of the Rule of Three/Five

A list of STL container classes


问:
C# Windows Forms Binary File
I have a method that is called when a user resets his password. When it is executed, it should see if the user exists in the binary file "PlayerDetails.bin".

The code works as intended and the password is reset, but an error is thrown despite this:

An unhandled exception of type 'System.ObjectDisposedException'
  occurred in mscorlib.dll. Additional information: Cannot access a closed file.

```<code>public static bool ResetPassword(string username, string password)
{
    //open file for read and write
    long pos = -1;
    bool found = false;
    Player readPlayer;
    Stream st;
    try
    {
        st = File.Open("PlayerDetails.bin", FileMode.Open, FileAccess.ReadWrite);
        BinaryFormatter bf = new BinaryFormatter();

        while (st.Position < st.Length && !found)
        {
            pos = st.Position;
            readPlayer = (Player)bf.Deserialize(st);

            if (readPlayer.username.CompareTo(username) == 0)
            {
                found = true;
                readPlayer.password = password;

                st.Seek(pos, SeekOrigin.Begin);
                bf.Serialize(st, readPlayer);

                st.Close();
                st.Dispose();
            }
        }
    }
}
</code>```

答:
move the st.Close(); st.Dispose() out of the while loop.

```<code>Stream st= null;

try
{
    st = File.Open("PlayerDetails.bin", FileMode.Open, FileAccess.ReadWrite);
    BinaryFormatter bf = new BinaryFormatter();

    try
    {
        while (st.Position < st.Length && !found)
        {
            pos = st.Position;
            readPlayer = (Player)bf.Deserialize(st);

            if (readPlayer.username.CompareTo(username) == 0)
            {
                found = true;
                readPlayer.password = password;

                st.Seek(pos, SeekOrigin.Begin);
                bf.Serialize(st, readPlayer);
            }
        }
    }
    finally
    {
        if(st != null)
        {
            st.Close();
            st.Dispose();
        }
    }
}
</code>```

Title: C# Windows Forms Binary File

Body:
I have a method that is called when a user resets his password. When it is executed, it should see if the user exists in the binary file "PlayerDetails.bin".

The code works as intended and the password is reset, but an error is thrown despite this:

An unhandled exception of type 'System.ObjectDisposedException'
  occurred in mscorlib.dll. Additional information: Cannot access a closed file.

public static bool ResetPassword(string username, string password)
{
    //open file for read and write
    long pos = -1;
    bool found = false;
    Player readPlayer;
    Stream st;
    try
    {
        st = File.Open("PlayerDetails.bin", FileMode.Open, FileAccess.ReadWrite);
        BinaryFormatter bf = new BinaryFormatter();

        while (st.Position < st.Length && !found)
        {
            pos = st.Position;
            readPlayer = (Player)bf.Deserialize(st);

            if (readPlayer.username.CompareTo(username) == 0)
            {
                found = true;
                readPlayer.password = password;

                st.Seek(pos, SeekOrigin.Begin);
                bf.Serialize(st, readPlayer);

                st.Close();
                st.Dispose();
            }
        }
    }
}

Body:
move the st.Close(); st.Dispose() out of the while loop.

Stream st= null;

try
{
    st = File.Open("PlayerDetails.bin", FileMode.Open, FileAccess.ReadWrite);
    BinaryFormatter bf = new BinaryFormatter();

    try
    {
        while (st.Position < st.Length && !found)
        {
            pos = st.Position;
            readPlayer = (Player)bf.Deserialize(st);

            if (readPlayer.username.CompareTo(username) == 0)
            {
                found = true;
                readPlayer.password = password;

                st.Seek(pos, SeekOrigin.Begin);
                bf.Serialize(st, readPlayer);
            }
        }
    }
    finally
    {
        if(st != null)
        {
            st.Close();
            st.Dispose();
        }
    }
}


问:
Prevent or remove full screen overlay from bootstrap modal
When opening a bootstrap modal, it contains a shadow/dark backdrop. If you set this backdrop to false it removes the shadow, but the large area behind the modal still remains, preventing anything in the background from being clicked.

Is there a way to limit the size of a modal to the size of the actual .modal-content area?

Here is a fiddle demoing the issue: https://jsfiddle.net/s75L8z1v/

Right click and Inspect the background outside of the modal and you will still it still belongs to the modal object, preventing you from clicking the background behind it.

答:
Override the modal's CSS with your own:

```<code>.modal {
  right: initial;
  bottom:initial;
  width: 200px;
}
</code>```

See the fiddle here

Body:
Override the modal's CSS with your own:

.modal {
  right: initial;
  bottom:initial;
  width: 200px;
}

See the fiddle here


问:
Zipping folders using a Powershell script
Wrote the following code to move files to a specific Year-Month folder on a drive. However, I would also like to zip the folder I wrote to at the end of the operation. How do I do that?

```<code># Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
# $files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}
</code>```

The intention is to move these files into a folder and zip them and archive them for later use. So I will schedule this once a month to run for the previous month

答:
This is the code I am using for unzipping all the files in a directory.  You just need to modify it enough to zip instead of unzipping.

```<code>$ZipReNameExtract = Start-Job {
#Ingoring the directories that a search is not require to check
$ignore = @("Tests\","Old_Tests\")

#Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
 $Files=gci $NewSource -Fecurse | Where {$_.Extension -Match "zip" -And $_.FullName -Notlike $Ignore}
    Foreach ($File in $Files) {
        $NewSource = $File.FullName
        #Join-Path is a standard Powershell cmdLet
        $Destination = Join-Path (Split-Path -parent $File.FullName) $File.BaseName
        Write-Host -Fore Green $Destination
        #Start-Process needs the path to the exe and then the arguments passed seperately.
        Start-Process -FilePath "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x -y -o $NewSource $Destination" -Wait
    }
}
Wait-Job $ZipReNameExtract
Receive-Job $ZipReNameExtract
</code>```

Let me know if it helps.

The UnderDog...

Body:
Wrote the following code to move files to a specific Year-Month folder on a drive. However, I would also like to zip the folder I wrote to at the end of the operation. How do I do that?

# Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
# $files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}

The intention is to move these files into a folder and zip them and archive them for later use. So I will schedule this once a month to run for the previous month

Body:
This is the code I am using for unzipping all the files in a directory.  You just need to modify it enough to zip instead of unzipping.

$ZipReNameExtract = Start-Job {
#Ingoring the directories that a search is not require to check
$ignore = @("Tests\","Old_Tests\")

#Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
 $Files=gci $NewSource -Fecurse | Where {$_.Extension -Match "zip" -And $_.FullName -Notlike $Ignore}
    Foreach ($File in $Files) {
        $NewSource = $File.FullName
        #Join-Path is a standard Powershell cmdLet
        $Destination = Join-Path (Split-Path -parent $File.FullName) $File.BaseName
        Write-Host -Fore Green $Destination
        #Start-Process needs the path to the exe and then the arguments passed seperately.
        Start-Process -FilePath "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x -y -o $NewSource $Destination" -Wait
    }
}
Wait-Job $ZipReNameExtract
Receive-Job $ZipReNameExtract

Let me know if it helps.

The UnderDog...


问:
How does Awk's pattern matching for strings works?
I am trying to understand how the range pattern matching work in Awk
Here is the full data that I am practicing with

```<code>Raw Data
-----------------------------------------
    USSR    8649    275     Asia
    Canada  3852    25      North America
    China   3705    1032    Asia
    USA     3615    237     North America
    Brazil  3286    134     South America
    India   1267    746     Asia
    Mexico  762     78      North America
    France  211     55      Europe
    Japan   144     120     Asia
    Germany 96      61      Europe
    England 94      56      Europe
</code>```

If I write this code

```<code>$ awk '/Asia/, /Europe/' countries.awk
</code>```

I get

```<code>USSR    8649    275     Asia
Canada  3852    25      North America
China   3705    1032    Asia
USA     3615    237     North America
Brazil  3286    134     South America
India   1267    746     Asia
Mexico  762     78      North America
France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe
</code>```

It doesn't output England.

And If I write this

```<code>$ awk '/Europe/, /Asia/' countries.awk
</code>```

I get

```<code>France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe
England 94      56      Europe
</code>```

What is the behavior here? Why do I not get England on the first one?

答:
Awk process input lines one at a time, the syntax you used is likely to print lines from the start to the end pattern, represented by country names. When you used

```<code>awk '/Asia/, /Europe/'
</code>```

The start of pattern Asia happens more than once. As you can see from the line numbers below, numbers 3,5,8 and 11 represent the start of the pattern and the pattern ends at lines 10 and 12. Observe carefully the sub-ranges of lines between 8-10 and 11-12. The last end pattern Europe for the last Asia ends at line 12, that is the reason you are not seeing England in the first case.

But when you used

```<code>awk '/Europe/, /Asia/'
</code>```

The line containing the first start pattern Europe starts at line 10 and ends at 11 another two pattern start at 12 and 13 without an end pattern Asia, so it would obviously print all the lines until Asia appears. So you are seeing England in the second case.

```<code>$ cat -n file
 1  Raw Data
 2  -----------------------------------------
 3      USSR    8649    275     Asia
 4      Canada  3852    25      North America
 5      China   3705    1032    Asia
 6      USA     3615    237     North America
 7      Brazil  3286    134     South America
 8      India   1267    746     Asia
 9      Mexico  762     78      North America
10      France  211     55      Europe
11      Japan   144     120     Asia
12      Germany 96      61      Europe
13      England 94      56      Europe
</code>```

Body:
I am trying to understand how the range pattern matching work in Awk
Here is the full data that I am practicing with

Raw Data
-----------------------------------------
    USSR    8649    275     Asia
    Canada  3852    25      North America
    China   3705    1032    Asia
    USA     3615    237     North America
    Brazil  3286    134     South America
    India   1267    746     Asia
    Mexico  762     78      North America
    France  211     55      Europe
    Japan   144     120     Asia
    Germany 96      61      Europe
    England 94      56      Europe

If I write this code

$ awk '/Asia/, /Europe/' countries.awk

I get

USSR    8649    275     Asia
Canada  3852    25      North America
China   3705    1032    Asia
USA     3615    237     North America
Brazil  3286    134     South America
India   1267    746     Asia
Mexico  762     78      North America
France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe

It doesn't output England.

And If I write this

$ awk '/Europe/, /Asia/' countries.awk

I get

France  211     55      Europe
Japan   144     120     Asia
Germany 96      61      Europe
England 94      56      Europe

What is the behavior here? Why do I not get England on the first one?

Body:
Awk process input lines one at a time, the syntax you used is likely to print lines from the start to the end pattern, represented by country names. When you used

awk '/Asia/, /Europe/'

The start of pattern Asia happens more than once. As you can see from the line numbers below, numbers 3,5,8 and 11 represent the start of the pattern and the pattern ends at lines 10 and 12. Observe carefully the sub-ranges of lines between 8-10 and 11-12. The last end pattern Europe for the last Asia ends at line 12, that is the reason you are not seeing England in the first case.

But when you used

awk '/Europe/, /Asia/'

The line containing the first start pattern Europe starts at line 10 and ends at 11 another two pattern start at 12 and 13 without an end pattern Asia, so it would obviously print all the lines until Asia appears. So you are seeing England in the second case.

$ cat -n file
 1  Raw Data
 2  -----------------------------------------
 3      USSR    8649    275     Asia
 4      Canada  3852    25      North America
 5      China   3705    1032    Asia
 6      USA     3615    237     North America
 7      Brazil  3286    134     South America
 8      India   1267    746     Asia
 9      Mexico  762     78      North America
10      France  211     55      Europe
11      Japan   144     120     Asia
12      Germany 96      61      Europe
13      England 94      56      Europe


问:
Is there a way to apply styles to Safari only?
I'm trying to find a way to apply CSS just to Safari, but everything I find also applies to Chrome. I know these are currently both WebKit browsers, but I'm having problems with div alignments in Chrome and Safari; each displays differently.

I have been trying to use this but it affects Chrome as well:

```<code>@media screen and (-webkit-min-device-pixel-ratio:0) {
  #safari { display: block; }
}
</code>```

Does anyone know of another one that will just apply to Safari?

答:
By the way, for any of you guys that just need to target Safari on mobiles, just add a media query to this hack:

```<code>@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding: 10px; //or any property you need
    }
}
</code>```

And don't forget to add the .safari_only class to the element you want to target, example:

```<code><div class='safari_only'> This div will have a padding:10px in a mobile with Safari  </div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to find a way to apply CSS just to Safari, but everything I find also applies to Chrome. I know these are currently both WebKit browsers, but I'm having problems with div alignments in Chrome and Safari; each displays differently.

I have been trying to use this but it affects Chrome as well:

@media screen and (-webkit-min-device-pixel-ratio:0) {
  #safari { display: block; }
}

Does anyone know of another one that will just apply to Safari?

Body:
By the way, for any of you guys that just need to target Safari on mobiles, just add a media query to this hack:

@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding: 10px; //or any property you need
    }
}

And don't forget to add the .safari_only class to the element you want to target, example:

<div class='safari_only'> This div will have a padding:10px in a mobile with Safari  </div>