问:
replacing a string deletes everything in text
I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."

This is what I have so far:

```<code>    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.*;

    public class RemoveText {
        public static void main(String[] args){

    //creates a scanner to read the user's file name
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a file name: ");
    String fileName = input.nextLine();

    java.io.File file = new java.io.File(fileName);
    java.io.File newFile = new java.io.File(fileName);
    Scanner stringToRemove = new Scanner(System.in);
    System.out.println("Enter a string you wish to remove: ");
    String s1 = stringToRemove.nextLine();

    //creating input and output files
    try {
        Scanner inputFile = new Scanner(file);
        //reads data from a file
        while(inputFile.hasNext()) {
            s1 += inputFile.nextLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //supposed to replace each instance of the user input string
    //but instead deletes everything on the file and i don't know why
    String s2 = s1.replaceAll(s1, "");

    try {
        PrintWriter output = new PrintWriter(newFile);
        output.write(s2);
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //closing various scanners
    input.close();
    stringToRemove.close();
  }
}
</code>```

But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?

Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.

```<code>   Scanner s1 = new Scanner(System.in);
   String stringToRemove = s1.nextLine();
   String fileContents = null;

   try {
    //stuff here
      while (inputFile.hasNextLine()) {
      fileContents += inputFile.nextLine();
    } catch { //more stuff }

   String outputContent = fileContents.replaceAll(stringToRemove, "");
</code>```

My issue now is that the beginning of the new file starts with "null" before relaying the new content.

答:
```<code>String s2 = s1.replaceAll(s1, "");
</code>```

the first parameter of replaceAll method is what you are looking for to replace, and you are looking for s1, you are saying with this code clean all s1 content...

Body:
I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."

This is what I have so far:

    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.*;

    public class RemoveText {
        public static void main(String[] args){

    //creates a scanner to read the user's file name
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a file name: ");
    String fileName = input.nextLine();

    java.io.File file = new java.io.File(fileName);
    java.io.File newFile = new java.io.File(fileName);
    Scanner stringToRemove = new Scanner(System.in);
    System.out.println("Enter a string you wish to remove: ");
    String s1 = stringToRemove.nextLine();

    //creating input and output files
    try {
        Scanner inputFile = new Scanner(file);
        //reads data from a file
        while(inputFile.hasNext()) {
            s1 += inputFile.nextLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //supposed to replace each instance of the user input string
    //but instead deletes everything on the file and i don't know why
    String s2 = s1.replaceAll(s1, "");

    try {
        PrintWriter output = new PrintWriter(newFile);
        output.write(s2);
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //closing various scanners
    input.close();
    stringToRemove.close();
  }
}

But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?

Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.

   Scanner s1 = new Scanner(System.in);
   String stringToRemove = s1.nextLine();
   String fileContents = null;

   try {
    //stuff here
      while (inputFile.hasNextLine()) {
      fileContents += inputFile.nextLine();
    } catch { //more stuff }

   String outputContent = fileContents.replaceAll(stringToRemove, "");

My issue now is that the beginning of the new file starts with "null" before relaying the new content.

Body:
String s2 = s1.replaceAll(s1, "");

the first parameter of replaceAll method is what you are looking for to replace, and you are looking for s1, you are saying with this code clean all s1 content...


来源: stackexchange

问:
Invoking cucumber from Spring boot
I am trying to invoke cucumber from a Spring boot app. I have all the dependencies in my gradle build file.
    compile("info.cukes:cucumber-java8:1.2.5")
    compile("info.cukes:cucumber-junit:1.2.5")
    compile("info.cukes:cucumber-spring:1.2.5")
And on examing my app's spring boot jar, I see the cucumber jars.

In the main class I have

```<code>        String[] cucumberOptions = new String[]{"--glue","mypackage.steps","--plugin", "pretty",
                "--plugin", "html:target/cucumber-html-report","--plugin", "json:target/cucumber.json",
                "--plugin", "junit:target_junit/cucumber.xml",
                "classpath:mypackage.features"
               };

 cucumber.api.cli.Main.main(cucumberOptions );
</code>```

On executing my jar, I get the error -
No backends were found. Please make sure you have a backend module on your CLASSPATH.

I also have a runner class and corresponding step classes.
I have my step classes with the following annotation-

```<code>@ContextConfiguration(
        loader = SpringApplicationContextLoader.class,
        classes={Application.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class MySteps{
....
}
My runner class is below.

@RunWith(Cucumber.class)
public class MyRunner{

}
</code>```

Question - is how do I invoke cucumber from my Spring boot app?

答:
I got this to work by instructing spring=boot-maven-plugin to unpack the cucumber-java jar</p>

```<code><plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <requiresUnpack>
                <dependency>
                    <groupId>info.cukes</groupId>
                    <artifactId>cucumber-java</artifactId>
                </dependency>
            </requiresUnpack>
        </configuration>
    </plugin>
</plugins>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Invoking cucumber from Spring boot

Body:
I am trying to invoke cucumber from a Spring boot app. I have all the dependencies in my gradle build file.
    compile("info.cukes:cucumber-java8:1.2.5")
    compile("info.cukes:cucumber-junit:1.2.5")
    compile("info.cukes:cucumber-spring:1.2.5")
And on examing my app's spring boot jar, I see the cucumber jars.

In the main class I have

        String[] cucumberOptions = new String[]{"--glue","mypackage.steps","--plugin", "pretty",
                "--plugin", "html:target/cucumber-html-report","--plugin", "json:target/cucumber.json",
                "--plugin", "junit:target_junit/cucumber.xml",
                "classpath:mypackage.features"
               };

 cucumber.api.cli.Main.main(cucumberOptions );

On executing my jar, I get the error -
No backends were found. Please make sure you have a backend module on your CLASSPATH.

I also have a runner class and corresponding step classes.
I have my step classes with the following annotation-

@ContextConfiguration(
        loader = SpringApplicationContextLoader.class,
        classes={Application.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class MySteps{
....
}
My runner class is below.

@RunWith(Cucumber.class)
public class MyRunner{

}

Question - is how do I invoke cucumber from my Spring boot app?

Body:
I got this to work by instructing spring=boot-maven-plugin to unpack the cucumber-java jar

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <requiresUnpack>
                <dependency>
                    <groupId>info.cukes</groupId>
                    <artifactId>cucumber-java</artifactId>
                </dependency>
            </requiresUnpack>
        </configuration>
    </plugin>
</plugins>


问:
How to move the differing and absent files while comparing two directories?
I have an archived folder, named "dir1".

I have an new data folder, named "dir2".

I have a differences folder, named "dir3".

The data are jpgs, there are no sub folders.

```<code>dir1
1.jpg
2.jpg
3.jpg
4.jpg

dir2
1.jpg (edited file)
2.jpg (edited file)
3.jpg (same file as in dir1)
4.jpg (same file as in dir1)
5.jpg (new file)
6.jpg (new file)
</code>```

I need to move the new, missing, edited and differing files to dir3.

The result would be:

```<code>dir3
1.jpg
2.jpg
5.jpg
6.jpg
</code>```

Here is what i have:

```<code>from filecmp import dircmp

dcmp = dircmp('dir1', 'dir2')

def main(dcmp):
    for name in dcmp.diff_files, dcmp.right_only:
        print (name)

if __name__ == "__main__":
    main(dcmp)
</code>```

The result is:

```<code>['2.jpg', '1.JPG']
['6.jpg', '5.jpg']
</code>```

Insted of "print", how do i move these to dir3.

I've tried "shutil" and "os.rename", but i cant get it to work.

Information from "filecmp" and "dircmp".

```<code>import filecmp

filecmp.dircmp('dir1', 'dir2').report()
</code>```

The result is:

```<code>diff dir1 dir2
Only in dir2 : ['5.jpg', '6.jpg']
Identical files : ['3.JPG', '4.JPG']
Differing files : ['1.JPG', '2.jpg']
</code>```

This is just fyi.

答: Here is a reference to answer on how to create a new directory and move files to it.</p>

Body:
I have an archived folder, named "dir1".

I have an new data folder, named "dir2".

I have a differences folder, named "dir3".

The data are jpgs, there are no sub folders.

dir1
1.jpg
2.jpg
3.jpg
4.jpg

dir2
1.jpg (edited file)
2.jpg (edited file)
3.jpg (same file as in dir1)
4.jpg (same file as in dir1)
5.jpg (new file)
6.jpg (new file)

I need to move the new, missing, edited and differing files to dir3.

The result would be:

dir3
1.jpg
2.jpg
5.jpg
6.jpg

Here is what i have:

from filecmp import dircmp

dcmp = dircmp('dir1', 'dir2')

def main(dcmp):
    for name in dcmp.diff_files, dcmp.right_only:
        print (name)

if __name__ == "__main__":
    main(dcmp)

The result is:

['2.jpg', '1.JPG']
['6.jpg', '5.jpg']

Insted of "print", how do i move these to dir3.

I've tried "shutil" and "os.rename", but i cant get it to work.

Information from "filecmp" and "dircmp".

import filecmp

filecmp.dircmp('dir1', 'dir2').report()

The result is:

diff dir1 dir2
Only in dir2 : ['5.jpg', '6.jpg']
Identical files : ['3.JPG', '4.JPG']
Differing files : ['1.JPG', '2.jpg']

This is just fyi.


问:
Passing variables through many activities
on MainActivity I have two edit texts which I get name and age values

now I have in this activity for example name="Mohamed" age=26

my questions is how to use these variables freely in other activities without passing them through Intent

答:
Use the Shared Preferences.

Set the values:

```<code>SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();
</code>```

Retrieve values:

```<code>SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredName = prefs.getString("name", null); //null is the default value.
int age = prefs.getInt("age", 0); //0 is the default value.
</code>```

For more information visit Android Doc Shared Preferences

Body:
Use the Shared Preferences.

Set the values:

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();

Retrieve values:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredName = prefs.getString("name", null); //null is the default value.
int age = prefs.getInt("age", 0); //0 is the default value.

For more information visit Android Doc Shared Preferences


问:
errors while connecting java with sql server 2017
```<code>public class RDF2Connection {

     static Connection connection=null;
     final static String connectionUrl = "jdbc:sqlserver://DESKTOP-Q5K9FE6:1433;" +
             "databaseName=RDFDB;";
    public static Connection getRdf2Connected(){

            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                connection = DriverManager.getConnection(connectionUrl, "sa", "root");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }

}
</code>```

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection
  to the host DESKTOP-Q5K9FE6, port 1433 has failed. Error: "Connection
  refused: no further information. Verify the connection properties.
  Make sure that an instance of SQL Server is running on the host and
  accepting TCP/IP connections at the port. Make sure that TCP
  connections to the port are not blocked by a firewall.".
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:206)
        at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:257)
        at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2385)
        at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:567)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1955)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1616)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1447)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:788)
        at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1187)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at com.rdf2.databaseconnection.RDF2Connection.getRdf2Connected(RDF2Connection.java:22)
        at MainClass.main(MainClass.java:53)
      java.lang.NullPointerException
        at MainClass.main(MainClass.java:54)

Process finished with exit code 0

答:
Can you see if the SQL Server is only listening on an IPv6 port?  If so you can use the following

```<code>System.setProperty("java.net.preferIPv6Addresses", "true");
</code>```

That would be my only suggestion as far as code changes.  Possibly try and use the IP as opposed to the name.  If that doesn't work you need to go to your SQL Server and verify that it accepts TCP/IP connections, or check your local firewall settings.  At that point the question would be more appropriate for server exchange.

Body:
public class RDF2Connection {

     static Connection connection=null;
     final static String connectionUrl = "jdbc:sqlserver://DESKTOP-Q5K9FE6:1433;" +
             "databaseName=RDFDB;";
    public static Connection getRdf2Connected(){

            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                connection = DriverManager.getConnection(connectionUrl, "sa", "root");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }

}

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection
  to the host DESKTOP-Q5K9FE6, port 1433 has failed. Error: "Connection
  refused: no further information. Verify the connection properties.
  Make sure that an instance of SQL Server is running on the host and
  accepting TCP/IP connections at the port. Make sure that TCP
  connections to the port are not blocked by a firewall.".
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:206)
        at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:257)
        at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2385)
        at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:567)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1955)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1616)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1447)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:788)
        at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1187)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at com.rdf2.databaseconnection.RDF2Connection.getRdf2Connected(RDF2Connection.java:22)
        at MainClass.main(MainClass.java:53)
      java.lang.NullPointerException
        at MainClass.main(MainClass.java:54)

Process finished with exit code 0

Body:
Can you see if the SQL Server is only listening on an IPv6 port?  If so you can use the following

System.setProperty("java.net.preferIPv6Addresses", "true");

That would be my only suggestion as far as code changes.  Possibly try and use the IP as opposed to the name.  If that doesn't work you need to go to your SQL Server and verify that it accepts TCP/IP connections, or check your local firewall settings.  At that point the question would be more appropriate for server exchange.


问:
Is declaring an header file essential?
Is declaring an header file essential? This code:

```<code>main()
{
  int i=100;

  printf("%d\n",i);
}
</code>```

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

答: As paxidiablo said its not necessary but this is only true for functions and variables but if your header file provides some types or macros (#define) that you use then you must include the header file to use them because they are needed before linking happens i.e during pre-processing or compiling</p>

ContentLicense: CC BY-SA 2.5

Title: Is declaring an header file essential?

Body:
Is declaring an header file essential? This code:

main()
{
  int i=100;

  printf("%d\n",i);
}

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?


问:
how to Disable special keyboard keys?
I'm looking for a script or a program that runs in background and blocks special keys on my keyboard (calculator, mute, etc) I have searched a lot on this on the internet but didn't found anything useful or working for me, I tried sharpkeys but didn't detected those keys on my keyboard, key id is 173 for mute on my keyboard and I can get others IDs if I find anything to block them with IDs.

P.S. I don't know much about programming and most likely don't know what I am doing, I'm looking for basic help from anyone. thank you!

答: To disable special keyboard keys via registry on Windows 10 go to  HKLM:\SYSTEM\CurrentControlSet\Services\hidserv and change "Start" DWORD value to 4. Once you restart the system, special function keys should be disabled. </p>

Title: how to Disable special keyboard keys?


问:
Cannot encode object: pymongo.cursor.Cursor object at
I am trying to retrieve an audio file stored in MongoDB when above error is thrown.

The code is as follows:

```<code>elif json_data != None and 'retriever' in json_data:
    query_param = json_data['retriever']
    data = db.soundData
    x = data.find({'name': query_param})
    y = data.find({'data': x})
    return Response(y, mimetype='audio/mp3')
</code>```

Under name I have the name of the file and under data is audio file itself.
As I am new to pymongo can somebody point to where an error could be coming from?

答:
First of all, you need not be saving your file itself in mongo what you should be saving is the filename and the file itself is better off on the file system.

The error appears because, both x and y are indeed mongodb cursors rather than the data that you expect. You should be using find_one instead.

find_one(filter=None, *args, **kwargs) Get a single document from the
  database.

All arguments to find() are also valid arguments for find_one(),
  although any limit argument will be ignored. Returns a single
  document, or None if no matching document is found.

```<code>y = data.find_one({'data': x})
</code>```

You can make your code a bit more concise with

```<code>y = data.find_one({'data': {'name': query_param}})
</code>```

Body:
I am trying to retrieve an audio file stored in MongoDB when above error is thrown.

The code is as follows:

elif json_data != None and 'retriever' in json_data:
    query_param = json_data['retriever']
    data = db.soundData
    x = data.find({'name': query_param})
    y = data.find({'data': x})
    return Response(y, mimetype='audio/mp3')

Under name I have the name of the file and under data is audio file itself.
As I am new to pymongo can somebody point to where an error could be coming from?

Body:
First of all, you need not be saving your file itself in mongo what you should be saving is the filename and the file itself is better off on the file system.

The error appears because, both x and y are indeed mongodb cursors rather than the data that you expect. You should be using find_one instead.

find_one(filter=None, *args, **kwargs) Get a single document from the
  database.

All arguments to find() are also valid arguments for find_one(),
  although any limit argument will be ignored. Returns a single
  document, or None if no matching document is found.

y = data.find_one({'data': x})

You can make your code a bit more concise with

y = data.find_one({'data': {'name': query_param}})


答:
It seems like you already have the part to make the list of files that you want to move.

```<code>import shutil

for file in file_list:
    shutil.move(file, dir3) # shutil.copy if you want
</code>```

Note: file should be the path to the file and dir3 can be a directory or file path if you want to change the name or the like.

Title: How to move the differing and absent files while comparing two directories?

Body:
It seems like you already have the part to make the list of files that you want to move.

import shutil

for file in file_list:
    shutil.move(file, dir3) # shutil.copy if you want

Note: file should be the path to the file and dir3 can be a directory or file path if you want to change the name or the like.


问:
Can not open project?
I have visual studio 2015 update 1 .I download the MVC project which is done in .net core. but i can't open the project . it give s following error.

Another one is this

C:\Users\Anushka\Source\Repos\GuestManagement\GuestManagement\src\GuestManagement\GuestManagement.xproj : error  : The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Props" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk.  C:\Users\Anushka\Source\Repos\GuestManagement\GuestManagement\src\GuestManagement\GuestManagement.xproj

How can i reload this?

答:
You need to be running VS2015 with update 3 in order to open .Net Core 1.0/project.json solutions. If the project is .Net Core 1.0 or 1.0.1 with csproj then you must have VS2017.

In your case your running a project.json solution, so update to version 3.

Title: Can not open project?


问:
Can I make this script even faster?
I wrote a simple script for an internship, which trawls through a provided directory and deletes any file older than a specified number of days.  I've spent all my free time today attempting to tighten it up. Here's what I've got so far:

```<code>function delOld($dir, $numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    get-childItem $dir -Recurse -file |
    where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
    remove-Item -whatif
}
</code>```

Here is an example of a call of the function:

```<code>delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5
</code>```

Sorry for the difficulty of reading, I found that condensing the operations into one line was more efficient than reassigning them to legible variables each iteration. The remove-item is whatif'd at the moment for testing purposes. I'm aware that at this point, I probably cannot speed it up much, however, I am running it on over a TB of files, so every operation counts.

Thanks in advance for any advice you have to offer!

答:
Staying in the realm of PowerShell and .NET methods, here's how you can speed up your function:

Calculate the cut-off time stamp once, up front.

Use the [IO.DirectoryInfo] type's EnumerateFiles() method (PSv3+ / .NET4+) in combination with a foreach statement. Tip of the hat to wOxxOm.

EnumerateFiles() enumerates files one at a time, keeping memory use constant, similar to, but faster than Get-ChildItem.

Caveats:

EnumerateFiles() invariably includes hidden files, whereas Get-ChildItem excludes them by default, and only includes them if -Force is specified.

EnumerateFiles() is unsuitable if there's a chance of encountering inaccessible directories due to lack of permissions, because even if you enclose the entire foreach statement in a try / catch block, you'll only get partial output, given that the iteration stops on encountering the first inaccessible directory.

The enumeration order can differ from that of Get-ChildItem.

PowerShell's foreach statement is much faster than the ForEach-Object cmdlet, and also faster than the PSv4+ .ForEach() collection method.

Invoke the .Delete() method directly on each [System.IO.FileInfo] instance inside the loop body.

Note: For brevity, there are no error checks in the function below, such as for whether $numDays has a permissible value and whether $dir refers to an existing directory (if it's a path based on a custom PS drive, you'd have to resolve it with Convert-Path first).

```<code>function delOld($dir, $numDays) {
    $dtCutoff = [datetime]::now - [timespan]::FromDays($numDays)
    # Make sure that the .NET framework's current dir. is the same as PS's:
    [System.IO.Directory]::SetCurrentDirectory($PWD.ProviderPath)
    # Enumerate all files recursively.
    # Replace $file.FullName with $file.Delete() to perform actual deletion.
    foreach ($file in ([IO.DirectoryInfo] $dir).EnumerateFiles('*', 'AllDirectories')) {
     if ($file.LastWriteTime -lt $dtCutOff) { $file.FullName }
    }
}
</code>```

Note: The above simply outputs the paths of the files to delete; replace $file.FullName with $file.Delete() to perform actual deletion.

Title: Can I make this script even faster?

Body:
I wrote a simple script for an internship, which trawls through a provided directory and deletes any file older than a specified number of days.  I've spent all my free time today attempting to tighten it up. Here's what I've got so far:

function delOld($dir, $numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    get-childItem $dir -Recurse -file |
    where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
    remove-Item -whatif
}

Here is an example of a call of the function:

delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5

Sorry for the difficulty of reading, I found that condensing the operations into one line was more efficient than reassigning them to legible variables each iteration. The remove-item is whatif'd at the moment for testing purposes. I'm aware that at this point, I probably cannot speed it up much, however, I am running it on over a TB of files, so every operation counts.

Thanks in advance for any advice you have to offer!

Body:
Staying in the realm of PowerShell and .NET methods, here's how you can speed up your function:

Calculate the cut-off time stamp once, up front.

Use the [IO.DirectoryInfo] type's EnumerateFiles() method (PSv3+ / .NET4+) in combination with a foreach statement. Tip of the hat to wOxxOm.

EnumerateFiles() enumerates files one at a time, keeping memory use constant, similar to, but faster than Get-ChildItem.

Caveats:

EnumerateFiles() invariably includes hidden files, whereas Get-ChildItem excludes them by default, and only includes them if -Force is specified.

EnumerateFiles() is unsuitable if there's a chance of encountering inaccessible directories due to lack of permissions, because even if you enclose the entire foreach statement in a try / catch block, you'll only get partial output, given that the iteration stops on encountering the first inaccessible directory.

The enumeration order can differ from that of Get-ChildItem.

PowerShell's foreach statement is much faster than the ForEach-Object cmdlet, and also faster than the PSv4+ .ForEach() collection method.

Invoke the .Delete() method directly on each [System.IO.FileInfo] instance inside the loop body.

Note: For brevity, there are no error checks in the function below, such as for whether $numDays has a permissible value and whether $dir refers to an existing directory (if it's a path based on a custom PS drive, you'd have to resolve it with Convert-Path first).

function delOld($dir, $numDays) {
    $dtCutoff = [datetime]::now - [timespan]::FromDays($numDays)
    # Make sure that the .NET framework's current dir. is the same as PS's:
    [System.IO.Directory]::SetCurrentDirectory($PWD.ProviderPath)
    # Enumerate all files recursively.
    # Replace $file.FullName with $file.Delete() to perform actual deletion.
    foreach ($file in ([IO.DirectoryInfo] $dir).EnumerateFiles('*', 'AllDirectories')) {
     if ($file.LastWriteTime -lt $dtCutOff) { $file.FullName }
    }
}

Note: The above simply outputs the paths of the files to delete; replace $file.FullName with $file.Delete() to perform actual deletion.

ContentLicense: CC BY-SA 4.0


问:
Preventing duplicate commits on subsequent pull requests
So from what I understand, after I've made a pull request and it has been merged, GitHub creates a "Merge Commit" to signify this.

However, if I make another pull request down the line, even after merging the merge commit into my local fork, it shows all of the commits from previous pull requests as well.

The only way I can seem to get around this is directly after having a pull request merged, resetting my local head to the original repo's merge commit in GitKraken, and then force-pushing to my fork.

The issue is, this feels like it's a very wrong way of doing things. Is that true? And if so, how should I be going about it instead?

答:
Force pushing usually means something isn't quite right.

It sounds like you aren't updating your local upstream branch after you hit the merge button on GitHub.com.

Short version

```<code>git checkout master
git pull --all
git checkout -b feature-branch
git add stuff
git commit -m "cool feature"
git push origin feature-branch
<click merge on GitHub.com>
git checkout master
git pull --all -p
git branch -d feature-branch
<see refs move, your feature branch get cleaned>
</code>```

If you branch again from this point, you won't see the "cool feature" commit in later PRs since your local master has it.

More Details.

After you merge, run
git pull --all -p
to update your local repo with all the remotes and their refs.
-p will also prune merged branch refs to clean up your tab complete list.

So, the sequence usually goes:

git checkout master
git pull --all -p
; This should update your local master unless it differs from upstream
if you do have local changes on master, you should either push them, or through them away.

if you want to throw them away, and make your master a copy of the upstream on

git reset --hard origin/master will make the current local branch a copy of the remote ref.

Body:
Force pushing usually means something isn't quite right.

It sounds like you aren't updating your local upstream branch after you hit the merge button on GitHub.com.

Short version

git checkout master
git pull --all
git checkout -b feature-branch
git add stuff
git commit -m "cool feature"
git push origin feature-branch
<click merge on GitHub.com>
git checkout master
git pull --all -p
git branch -d feature-branch
<see refs move, your feature branch get cleaned>

If you branch again from this point, you won't see the "cool feature" commit in later PRs since your local master has it.

More Details.

After you merge, run
git pull --all -p
to update your local repo with all the remotes and their refs.
-p will also prune merged branch refs to clean up your tab complete list.

So, the sequence usually goes:

git checkout master
git pull --all -p
; This should update your local master unless it differs from upstream
if you do have local changes on master, you should either push them, or through them away.

if you want to throw them away, and make your master a copy of the upstream on

git reset --hard origin/master will make the current local branch a copy of the remote ref.


问:
convert html to image in byte array java
How can i easily convert html to image and then to byte array without create it

thanks

答:
This is nontrivial because rendering a HTML page can be quite complex: you have text, images, CSS, possibly even JavaScript to evaluate.

I don't know the answer, but I do have something that might help you: code for iText (a PDF writing library) to convert a HTML page to a PDF file.

```<code>public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
    final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
    final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
    final ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(xhtmlUrl);
    renderer.layout();
    renderer.createPDF(reportPdfStream);
    reportPdfStream.close();
}
</code>```

Body:
This is nontrivial because rendering a HTML page can be quite complex: you have text, images, CSS, possibly even JavaScript to evaluate.

I don't know the answer, but I do have something that might help you: code for iText (a PDF writing library) to convert a HTML page to a PDF file.

public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
    final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
    final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
    final ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(xhtmlUrl);
    renderer.layout();
    renderer.createPDF(reportPdfStream);
    reportPdfStream.close();
}


问:
API Route available with Any token JWT+PASSPORT
I'm building api for my app and trying to use passport jwt.
I can register new users and login(get the token back) but when I use the Postman to check the "protected" route I can use Any Token like this 'any any'
Pasport.js

```<code>const   JwtStrategy = require('passport-jwt').Strategy,
        ExtractJwt = require('passport-jwt').ExtractJwt;

const   User = require('../api/models/user/userModel'),// load up the user model
        config = require('../config/database'); // get db config file

module.exports = (passport)=> {
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findOne({id: jwt_payload.id}, (err, user)=> {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        });
    }));
};
</code>```

Server.js

```<code>const   express = require('express'),
        app = express(),
        port = process.env.PORT || 3000,
        mongoose = require('mongoose'),
        morgan = require('morgan'),
        passport = require('passport'),
        bodyParser = require('body-parser'),
        jwt = require('jsonwebtoken'),
        config = require('./config/database'),
        Event = require('./api/models/event/eventModel'),
        User = require('./api/models/user/userModel');

mongoose.Promise = global.Promise;

mongoose.connect(config.database);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(passport.initialize());

/* Routers registration */

const routesEvent = require('./api/routes/event/eventRoutes');
routesEvent(app);

const routesUser = require('./api/routes/user/userRoutes');
routesUser(app);

/* END Routers registration */

/* Express middleware
 * which used to return more interactive messages */

app.use((req, res, next)=>{
    res.status(404).send({url: req.originalUrl + ' not found'});
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/* END Express middleware */

// Launch the server on port 3000
const server = app.listen(3000, () => {
    const { address, port } = server.address();
    console.log(`RESTful API server Listening at http://${address}:${port}`);
});
</code>```

EventRouter.js

```<code>const   jwt = require('jsonwebtoken'),
    passport = require('passport');

require('../../../config/passport')(passport); // as strategy in ./passport.js needs passport object

module.exports = (app)=> {
    const event = require('../../controllers/event/eventController');

    // Routes
    app.route('/events' )
        .get( event.list_all_events, passport.authenticate('jwt', { session: false}));

};
</code>```

EventController

```<code>const   mongoose = require('mongoose'),
        Event = mongoose.model('Events'),
        getToken = require('../../../config/getToken');

exports.list_all_events = (req, res)=> {
    let token = getToken(req.headers);
    if(token){
        Event.find({}, (err, event)=> {
            if (err)
                res.send(err);
            res.json(event);
        });
    } else {
        return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }

};
</code>```

I'm definitely doing something wrong in controller or in this file

GetToken.js

```<code>module.exports = getToken = (headers)=> {
    console.log(headers);
    if (headers && headers.authorization) {
        let parted = headers.authorization.split(' ');
//Here I can see my Token from the Postman
        if (parted.length === 2) {
            return parted[1];
        } else {
            return null;
        }
    } else {
        return null;
    }
};
</code>```

Please, any ideas about a mistake that I'm making above?

答:
Looks strange but when I changed code to this

```<code>EventRouter.js

app.route('/events' )
        .get(  passport.authenticate('jwt', { session: false}), event.list_all_events)
        .post(event.create_event);
</code>```

It's works like expected
The only one difference is the order in get(passport, function)

Body:
I'm building api for my app and trying to use passport jwt.
I can register new users and login(get the token back) but when I use the Postman to check the "protected" route I can use Any Token like this 'any any'
Pasport.js

const   JwtStrategy = require('passport-jwt').Strategy,
        ExtractJwt = require('passport-jwt').ExtractJwt;

const   User = require('../api/models/user/userModel'),// load up the user model
        config = require('../config/database'); // get db config file

module.exports = (passport)=> {
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findOne({id: jwt_payload.id}, (err, user)=> {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        });
    }));
};

Server.js

const   express = require('express'),
        app = express(),
        port = process.env.PORT || 3000,
        mongoose = require('mongoose'),
        morgan = require('morgan'),
        passport = require('passport'),
        bodyParser = require('body-parser'),
        jwt = require('jsonwebtoken'),
        config = require('./config/database'),
        Event = require('./api/models/event/eventModel'),
        User = require('./api/models/user/userModel');

mongoose.Promise = global.Promise;

mongoose.connect(config.database);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(passport.initialize());

/* Routers registration */

const routesEvent = require('./api/routes/event/eventRoutes');
routesEvent(app);

const routesUser = require('./api/routes/user/userRoutes');
routesUser(app);

/* END Routers registration */

/* Express middleware
 * which used to return more interactive messages */

app.use((req, res, next)=>{
    res.status(404).send({url: req.originalUrl + ' not found'});
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/* END Express middleware */

// Launch the server on port 3000
const server = app.listen(3000, () => {
    const { address, port } = server.address();
    console.log(`RESTful API server Listening at http://${address}:${port}`);
});

EventRouter.js

const   jwt = require('jsonwebtoken'),
    passport = require('passport');

require('../../../config/passport')(passport); // as strategy in ./passport.js needs passport object

module.exports = (app)=> {
    const event = require('../../controllers/event/eventController');

    // Routes
    app.route('/events' )
        .get( event.list_all_events, passport.authenticate('jwt', { session: false}));

};

EventController

const   mongoose = require('mongoose'),
        Event = mongoose.model('Events'),
        getToken = require('../../../config/getToken');

exports.list_all_events = (req, res)=> {
    let token = getToken(req.headers);
    if(token){
        Event.find({}, (err, event)=> {
            if (err)
                res.send(err);
            res.json(event);
        });
    } else {
        return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }

};

I'm definitely doing something wrong in controller or in this file

GetToken.js

module.exports = getToken = (headers)=> {
    console.log(headers);
    if (headers && headers.authorization) {
        let parted = headers.authorization.split(' ');
//Here I can see my Token from the Postman
        if (parted.length === 2) {
            return parted[1];
        } else {
            return null;
        }
    } else {
        return null;
    }
};

Please, any ideas about a mistake that I'm making above?

Body:
Looks strange but when I changed code to this

EventRouter.js

app.route('/events' )
        .get(  passport.authenticate('jwt', { session: false}), event.list_all_events)
        .post(event.create_event);

It's works like expected
The only one difference is the order in get(passport, function)


问:
why I can't set locale in Laravel?
I'm using the following simple codes to change the language in my laravel application, But it doesn't change anything. the language still the default 'en'

Route

```<code>Route::get('lang/{local}','LanguageController@setlanguage');
</code>```

Controller

```<code>public function setlanguage(Request $request)
    {
        \App::setLocale($request->local);

        return back()->withInput();
    }
</code>```

View

```<code> @if(App::getLocale() == 'en')
    <a href="{{url('/lang/ar')}}">العربية</a>
 @elseif(App::getLocale() == 'ar')
    <a href="{{url('/lang/en')}}">English</a>
 @endif
</code>```

Am I missing anything?

答:
When you use \App::setLocale() it will change the language for this specific request and after you return back() the request finished, and the language returned to default value.

If you want to save this changes, save the language in the session, and add a middleware to change it if there is a language in the session.

Ex:

Controller:

```<code>public function setlanguage(Request $request)
{
    \Session::put('language', $request->local);

    return back();
}
</code>```

Middleware:

```<code>public function handle($request, Closure $next)
{
    if (\Session::has('language')) {
        \App::setLocale(\Session::get('language'));
    }

    return $next($request);
}
</code>```

Title: why I can't set locale in Laravel?

Body:
I'm using the following simple codes to change the language in my laravel application, But it doesn't change anything. the language still the default 'en'

Route

Route::get('lang/{local}','LanguageController@setlanguage');

Controller

public function setlanguage(Request $request)
    {
        \App::setLocale($request->local);

        return back()->withInput();
    }

View

 @if(App::getLocale() == 'en')
    العربية
 @elseif(App::getLocale() == 'ar')
    English
 @endif

Am I missing anything?

Body:
When you use \App::setLocale() it will change the language for this specific request and after you return back() the request finished, and the language returned to default value.

If you want to save this changes, save the language in the session, and add a middleware to change it if there is a language in the session.

Ex:

Controller:

public function setlanguage(Request $request)
{
    \Session::put('language', $request->local);

    return back();
}

Middleware:

public function handle($request, Closure $next)
{
    if (\Session::has('language')) {
        \App::setLocale(\Session::get('language'));
    }

    return $next($request);
}


问:
R add a legend to a france map
Hi I just want to add a legend to this map which represents the fecundity of young women by departments in France :

With this code :

```<code>library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)
</code>```

I dont know how to add that legend.

答:
```<code>locator(n=1)
legend(-6.780717,45.01717,legend=classes,
fill=fr$cols, cex=0.6, bty="n")
</code>```

Title: R add a legend to a france map

Body:
Hi I just want to add a legend to this map which represents the fecundity of young women by departments in France :

With this code :

library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)

I dont know how to add that legend.


问:
Resizing markers given traffic data on Google Maps API
I'm not an experienced programmer at all so pardon me if I use some terms wrong.

Currently creating a map on train crossings, number of trains per day, and the daily traffic that goes thru those crossings. I have them all laid out in 5 separate fusion tables (100+ trains, 80-99, 60-79, 40-59, under 40 trains), and have a different colour marker for each category.

I'm trying to find a way to have the markers change in size given the traffic data going thru the crossings, and haven't figured out how to do that. I've laid out the sizes I want for the circles given traffic data, but don't know how to incorporate it in the markers themselves.

Here's the jsfiddle and some of the coding I have. Since I was in a rush I copied everything into the javascript section, but there's some CSS and HTML stuff in the coding too. Currently the coding properly shows the map, legend, and where all the crossings are.

Thanks!

https://jsfiddle.net/jdg9zz0y/

```<code>  var styledMapType = new google.maps.StyledMapType(style, {
    map: map,
    name: 'Styled Map'
  });
  map.mapTypes.set('map-style', styledMapType);
  map.setMapTypeId('map-style');

 <!-- 100+ layer -->
var layer_CandidateCrossingO100 = new google.maps.FusionTablesLayer ({
    query: {
    select: "col1",
    from: "1DMatlMkpGhAkaAhPx_6sjXW_CGzN71P92tzbvoNk",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

  <!-- 80 to 99 layer -->
var layer_CandidateCrossing80to99 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "11gfA9J0jlRQyvhXiRxvZD90ApIonAveGfOGW5bGG",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

  <!-- 60 to 79 layer -->
var layer_CandidateCrossing60to79 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "1fth-vFws0sfpfd0SDn1PHow9WMlyGuImClxpYpiG",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

  <!-- 40 to 59 layer -->
var layer_CandidateCrossing40to59 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "168C1S6zxRyWqnDxriSnaF36EnMV17S1wPjrXf9hz",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

<!-- Under 40 layer -->
var layer_CandidateCrossingU40 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "1mm9ZoqTVQH1LPDhUPM8PQ3ydHooRfxBtvvv8UOgs",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });
</code>```

答:
While you create the marker, you can specify the icon. But it is possible through the bees to create the icon object as well, so you can choose the size

Below the example

```<code>var image = {
  url: place.icon,
  size: new google.maps.Size(71, 71),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(17, 34),
  scaledSize: new google.maps.Size(25, 25)
};

var marker = new google.maps.Marker({
    map: map,
    icon: image,
    title: place.name,
    position: place.geometry.location
});
</code>```

Body:
I'm not an experienced programmer at all so pardon me if I use some terms wrong.

Currently creating a map on train crossings, number of trains per day, and the daily traffic that goes thru those crossings. I have them all laid out in 5 separate fusion tables (100+ trains, 80-99, 60-79, 40-59, under 40 trains), and have a different colour marker for each category.

I'm trying to find a way to have the markers change in size given the traffic data going thru the crossings, and haven't figured out how to do that. I've laid out the sizes I want for the circles given traffic data, but don't know how to incorporate it in the markers themselves.

Here's the jsfiddle and some of the coding I have. Since I was in a rush I copied everything into the javascript section, but there's some CSS and HTML stuff in the coding too. Currently the coding properly shows the map, legend, and where all the crossings are.

Thanks!

https://jsfiddle.net/jdg9zz0y/

  var styledMapType = new google.maps.StyledMapType(style, {
    map: map,
    name: 'Styled Map'
  });
  map.mapTypes.set('map-style', styledMapType);
  map.setMapTypeId('map-style');

var layer_CandidateCrossingO100 = new google.maps.FusionTablesLayer ({
    query: {
    select: "col1",
    from: "1DMatlMkpGhAkaAhPx_6sjXW_CGzN71P92tzbvoNk",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

var layer_CandidateCrossing80to99 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "11gfA9J0jlRQyvhXiRxvZD90ApIonAveGfOGW5bGG",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

var layer_CandidateCrossing60to79 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "1fth-vFws0sfpfd0SDn1PHow9WMlyGuImClxpYpiG",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

var layer_CandidateCrossing40to59 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "168C1S6zxRyWqnDxriSnaF36EnMV17S1wPjrXf9hz",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

var layer_CandidateCrossingU40 = new google.maps.FusionTablesLayer({
    query: {
    select: "col1",
    from: "1mm9ZoqTVQH1LPDhUPM8PQ3ydHooRfxBtvvv8UOgs",
    },
    map: map,
    styleId: 2,
    templateId: 2
  });

Body:
While you create the marker, you can specify the icon. But it is possible through the bees to create the icon object as well, so you can choose the size

Below the example

var image = {
  url: place.icon,
  size: new google.maps.Size(71, 71),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(17, 34),
  scaledSize: new google.maps.Size(25, 25)
};

var marker = new google.maps.Marker({
    map: map,
    icon: image,
    title: place.name,
    position: place.geometry.location
});


问:
Why exactly is this syntax error happening in C++ for me..?
why exactly is this happening?

```<code>cout << "Your choice of numbers is...?" << endl;
</code>```

error C2143: syntax error : missing
  ';' before '<<'

答:
I would not recommend using namespace std;

Using the fully qualified name i.e std::cout would be a better alternative

Body:
why exactly is this happening?

cout << "Your choice of numbers is...?" << endl;

error C2143: syntax error : missing
  ';' before '<<'


问:
php http post response for web hook
I'm trying to create a web hook notification. The documentation of the service i want to use requires that i specify a URL where POST requests can be performed. This URL will receive the following object, in json format, and must respond with a Status Code between 200-299.

```<code>{
  "type": "ping"
}
</code>```

I don't know how to proceed making my server on localhost respond with a 200 status code. http_response_code(200) works well on live server but nothing seem to be happening on localhost.
Is there any way i can make it work with localhost?
I've included the link to the documentation here (i hope it's not against the rule).

答: I am thinking that you wouldn't have to send them the response. The webhook would know about the response. If it reached your URL successfully, it would be a 200 OK right off the bat. If the API is requesting a response back then I imagine that you would have to call it back somehow. Is this a well-known API? Any documentation?

Title: php http post response for web hook

Body:
I'm trying to create a web hook notification. The documentation of the service i want to use requires that i specify a URL where POST requests can be performed. This URL will receive the following object, in json format, and must respond with a Status Code between 200-299.

{
  "type": "ping"
}

I don't know how to proceed making my server on localhost respond with a 200 status code. http_response_code(200) works well on live server but nothing seem to be happening on localhost.
Is there any way i can make it work with localhost?
I've included the link to the documentation here (i hope it's not against the rule).


问:
How to generate any color in PyX
Many Visualisation libraries and languages provide easy ways of generating any color. for example you could simple add a style tag with a css color code to set the color of an object in html.

Is there a similiar way to set the color of a pyx drawing to any wanted color code instead of the predefined pyx color codes?

(for example something like color.code = #1122DD instead of color.rgb.blue)

答: PyX provides several color schemes for defining colors, if you want to use RGB as a hex string you can provide it as: pyx.color.rgbfromhexstring("#1122DD").

Title: How to generate any color in PyX


问:
golang - Rest update request using http patch semantics
```<code>type A struct {
    Id int64
    Email sql.NullString
    Phone sql.NullString
}
</code>```

Assume I have one record in the database

```<code>A{1, "x@x.com", "1112223333"}
</code>```

Send an update request via PUT

```<code>curl -X PUT -d '{"Email": "y@y.com", "Phone": null}' http://localhost:3000/a/1
</code>```

Here is the psuedo algorithm that would work with a full PUT request (i.e. update all fields of the record A - but it will cause difficulties with the PATCH request semantics - delta update)

-- Unmarshal json into empty record

```<code>  a := A{}
  json.Unmarshal([]byte(request.body), &a)
</code>```

-- Load the record from the database

```<code>aFromDb = <assume we got record from db> //A{1, "x@x.com", "1112223333"}
</code>```

-- Compare a and aFromDB

-- Notice the email change and set it on aFromDb - ok

-- Notice the phone number change -- but wait! Was it set to NULL in the JSON explicitly or was it not even included in the JSON? i.e. was the json request - {"Email": "y@y.com", "Phone": null} or was it {"Email": "y@y.com"}?

How can we tell by just looking at the unmarshaled json into the struct a?

Is there another method to do the update via rest (with patch semantics)? I am looking for a generic way to do it (not tied to a particular struct).

答:
You could potentially write your own marshalling/uinmarshalling of your struct and react to the raw response within, although it might be non-obvious witgh inspection what that those functions are manipulating.

Alternatively, you could not omitempty within your fields and force null populated fields.

Or, maybe leveraging a different flavor of patching, perhaps http://jsonpatch.com/, which is more explicit in the nature of your modifications.  This would require the client to be more understanding of the state of changes than say for a put.

Body:
type A struct {
    Id int64
    Email sql.NullString
    Phone sql.NullString
}

Assume I have one record in the database

A{1, "x@x.com", "1112223333"}

Send an update request via PUT

curl -X PUT -d '{"Email": "y@y.com", "Phone": null}' http://localhost:3000/a/1

Here is the psuedo algorithm that would work with a full PUT request (i.e. update all fields of the record A - but it will cause difficulties with the PATCH request semantics - delta update)

-- Unmarshal json into empty record

  a := A{}
  json.Unmarshal([]byte(request.body), &a)

-- Load the record from the database

aFromDb = <assume we got record from db> //A{1, "x@x.com", "1112223333"}

-- Compare a and aFromDB

-- Notice the email change and set it on aFromDb - ok

-- Notice the phone number change -- but wait! Was it set to NULL in the JSON explicitly or was it not even included in the JSON? i.e. was the json request - {"Email": "y@y.com", "Phone": null} or was it {"Email": "y@y.com"}?

How can we tell by just looking at the unmarshaled json into the struct a?

Is there another method to do the update via rest (with patch semantics)? I am looking for a generic way to do it (not tied to a particular struct).


问:
DEP0600: Deployment failed. XmlException – Data at the root level is invalid
When I deploy a UWP from VS 2017, I’m seeing the following error:

```<code>DEP0600: Deployment failed. XmlException - Data at the root level is invalid. Line 24, position 11.
</code>```

Any clues on how to resolve?

答:
After much debugging and Binging, an SDE pointed out that I was hitting a known bug in Windows 10 Creators Update – which will be fixed in the upcoming Fall Creators update. At install time, all of the installed package are enumerated to see if the package has already been installed. This enumeration fails if the installed app’s AppxManifest.xml file is malformed.
I had several test apps installed on my machine, some deployed with Visual Studio, some installed with PowerShell using the command:

```<code>Add-AppxPackage -Register .\PackageLayout\AppxManifest.xml
</code>```

After uninstalling several of the test apps, I was able to deploy my app with Visual Studio 2017 without problems.

Body:
When I deploy a UWP from VS 2017, I’m seeing the following error:

DEP0600: Deployment failed. XmlException - Data at the root level is invalid. Line 24, position 11.

Any clues on how to resolve?

Body:
After much debugging and Binging, an SDE pointed out that I was hitting a known bug in Windows 10 Creators Update – which will be fixed in the upcoming Fall Creators update. At install time, all of the installed package are enumerated to see if the package has already been installed. This enumeration fails if the installed app’s AppxManifest.xml file is malformed.
I had several test apps installed on my machine, some deployed with Visual Studio, some installed with PowerShell using the command:

Add-AppxPackage -Register .\PackageLayout\AppxManifest.xml

After uninstalling several of the test apps, I was able to deploy my app with Visual Studio 2017 without problems.


问:
Read binary data and convert it into .wav or mp3 audio file
i am developing an web application in which i have to read binary from database base actually this is audio which is saved in the form or binary. how to convert this binary into wav or mp3 file </p>

答:
If you didn't touch the binary data and it's still in its original binary wav/mp3 form, you have the audio file. Just write it to a file to make it an actual file:

```<code>file_put_contents('sound.wav', $binaryData);
</code>```

Body:
If you didn't touch the binary data and it's still in its original binary wav/mp3 form, you have the audio file. Just write it to a file to make it an actual file:

file_put_contents('sound.wav', $binaryData);


问:
Looping over a huge list, check string equal to true
I have a requirement as below:

```<code>List<User> userList = listOfUsers(); // Morethan 50,000 users
</code>```

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

答:
The efficient way is to do that filter with SQL if you are using that. Select just the active users....

When you have all that list to work with java it will be slow as hell and there is no magic here, you will need to iterate.

```<code>public User getActiveUserFromList(userList) {
  for (User user : userList) {
    if (user.isActive()) {
      return user;
    }
    return null;
  }
}
</code>```

If you have that list anyway ordered you can try to hack it, let's assume it is ordered by active status

```<code>public Boolean isAnyActive(userList) {
   if (userList.first().isActive()) { // try first
     return true;
   }
   if (userList.last().isActive()) {  // if its ordered and there is an active user, the last surely will be active, since first wasn't
     return true;
   }
   return false;
}
</code>```

Body:
I have a requirement as below:

List<User> userList = listOfUsers(); // Morethan 50,000 users

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

Body:
The efficient way is to do that filter with SQL if you are using that. Select just the active users....

When you have all that list to work with java it will be slow as hell and there is no magic here, you will need to iterate.

public User getActiveUserFromList(userList) {
  for (User user : userList) {
    if (user.isActive()) {
      return user;
    }
    return null;
  }
}

If you have that list anyway ordered you can try to hack it, let's assume it is ordered by active status

public Boolean isAnyActive(userList) {
   if (userList.first().isActive()) { // try first
     return true;
   }
   if (userList.last().isActive()) {  // if its ordered and there is an active user, the last surely will be active, since first wasn't
     return true;
   }
   return false;
}


问:
Unable to load an image into NSImageView
I wrote the following and no image comes up.  I displayed the pointer and it comes out as "0".
In the next code block I checked the path and made shore the image was present there.  Still nothing loads.

```<code>NSImageView *vi = [[NSImageView alloc] initWithFrame:CGRectMake(10, 10, 220, 220)];
[self.view addSubview:vi];
NSImage *dog = [NSImage imageNamed:@"airnow3.jpg"];
NSLog(@"pointer %d", dog);

[vi setImage:dog];
</code>```

```<code>NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];
NSLog(@"%@", currentpath);
</code>```

答: Why don't you use InitWithImage:(NSImage) instead of InitWithFrame

Body:
I wrote the following and no image comes up.  I displayed the pointer and it comes out as "0".
In the next code block I checked the path and made shore the image was present there.  Still nothing loads.

NSImageView *vi = [[NSImageView alloc] initWithFrame:CGRectMake(10, 10, 220, 220)];
[self.view addSubview:vi];
NSImage *dog = [NSImage imageNamed:@"airnow3.jpg"];
NSLog(@"pointer %d", dog);

[vi setImage:dog];

NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];
NSLog(@"%@", currentpath);


问:
Views are not displayed in the ViewPager
I have a simple ViewPager backed with a PagerAdapter, but for the views i instantiate never display in the view pager.

I have a requirement to develop the UI purely in code.  So i can't inflate an xml layout in the instantiateItem method.  Unfortunately almost all the examples i've seen are inflating xml, which obviously doesn't work.

So i have an PagerAdapter, (i do NOT want to use fragments) with a ViewPager as below.  The adapter takes some data

```<code>val viewAdapter = ViewPagerAdapter(data)
viewPager.adapter = viewAdapter
</code>```

ViewPagerAdapter looks like this:

```<code>inner class ViewPagerAdapter(val data: List<Item>) : PagerAdapter() {
    override fun isViewFromObject(view: View?, obj: Any?): Boolean {
        return obj == view
    }

    override fun getCount(): Int {
        return data.count()
    }

    override fun instantiateItem(container: ViewGroup?, position: Int): Any {
        val rootLayout = LinearLayout(container?.context)
        rootLayout.layoutParams = rootLayout.setDimensions(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        rootLayout.orientation = LinearLayout.HORIZONTAL

        val title = Button(container?.context)
        title.text = "Title"
        title.textSize = 13f
        title.setTextColor(Color.WHITE)
        rootLayout.addView(title)

        val subtitle = Button(container?.context)
        subtitle.text = "Subtitle"
        subtitle.textSize = 13f
        subtitle.setTextColor(Color.WHITE)
        rootLayout.addView(subtitle)

        (container as ViewPager).addView(rootLayout)
        return rootLayout
    }

    override fun getPageTitle(position: Int): CharSequence {
        return data[position].title
    }

    override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) {
        if (obj == null) return
           container?.removeView(obj as View?)
        }
    }
}
</code>```

For the life of me i can't see what's wrong with this code.  I've tried changing the layouts, textview to a button but nothing works.

I'm hoping someone can point me in the right direction?

Thanks!

Update:

I've created a simple app to prove that i'm not doing anything silly.  Should be able to copy and paste this and run it, provided you've added the relevant libs.

```<code>import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.TabLayout
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val rootLayout = CoordinatorLayout(this)
    rootLayout.layoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)

    val appBarLayout = AppBarLayout(this)
    rootLayout.addView(appBarLayout)
    appBarLayout.layoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT)

    val tabLayout = TabLayout(this)

    tabLayout.tabMode = TabLayout.MODE_FIXED
    tabLayout.tabGravity = TabLayout.GRAVITY_FILL
    appBarLayout.addView(tabLayout)
    tabLayout.layoutParams = AppBarLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    //add viewpager
    val viewPager = ViewPager(this)
    viewPager.id = 11122

    val viewAdapter = ViewPagerAdapter()
    viewPager.adapter = viewAdapter

    rootLayout.addView(viewPager)
    viewPager.layoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)
    tabLayout.setupWithViewPager(viewPager)

    rootLayout.setBackgroundColor(Color.BLACK)
    setContentView(rootLayout)
}

inner class ViewPagerAdapter : PagerAdapter() {

    override fun isViewFromObject(view: View?, obj: Any?): Boolean {
        return obj == view
    }

    override fun getCount(): Int {
        return 3
    }

    override fun instantiateItem(container: ViewGroup?, position: Int): Any {
        val rootLayout = LinearLayout(container?.context)
        rootLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        rootLayout.orientation = LinearLayout.HORIZONTAL

        val title = Button(container?.context)
        title.text = "Title"
        title.textSize = 13f
        title.setTextColor(Color.WHITE)
        rootLayout.addView(title)

        val subtitle = Button(container?.context)
        subtitle.text = "Subtitle"
        subtitle.textSize = 13f
        subtitle.setTextColor(Color.WHITE)
        rootLayout.addView(subtitle)

        val viewPager = container as ViewPager
        viewPager.addView(rootLayout, 0)
        return rootLayout
    }

    override fun getPageTitle(position: Int): CharSequence {
        return "Title: $position"
    }

    override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) {
        if (obj == null) return
        when (obj) {
            is ArrayList<*> -> for (item in obj) {
                container?.removeView(item as View?)
            }
            else -> container?.removeView(obj as View?)
        }
    }
}
</code>```

}

答:
Looking at your full activity code. It appears you are setting a CoordinatorLayout layout params on your view pager, but you are forgetting to set the behavior, seeing that you also have an AppBarLayout in the hierarchy. Hence, the view pager content is being drawn behind the tab layout. You can verify this by using the layout inspector in AS.

Doing the following should fix your issue

```<code>val pagerParams = CoordinatorLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
pagerParams.behavior = AppBarLayout.ScrollingViewBehavior()
viewPager.layoutParams = pagerParams
</code>```

You could also take advantage of Kotlin's apply function

```<code>viewPager.layoutParams = CoordinatorLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT).apply {
    behavior = AppBarLayout.ScrollingViewBehavior()
}
</code>```

Hope that helps

Body:
I have a simple ViewPager backed with a PagerAdapter, but for the views i instantiate never display in the view pager.

I have a requirement to develop the UI purely in code.  So i can't inflate an xml layout in the instantiateItem method.  Unfortunately almost all the examples i've seen are inflating xml, which obviously doesn't work.

So i have an PagerAdapter, (i do NOT want to use fragments) with a ViewPager as below.  The adapter takes some data

val viewAdapter = ViewPagerAdapter(data)
viewPager.adapter = viewAdapter

ViewPagerAdapter looks like this:

inner class ViewPagerAdapter(val data: List<Item>) : PagerAdapter() {
    override fun isViewFromObject(view: View?, obj: Any?): Boolean {
        return obj == view
    }

    override fun getCount(): Int {
        return data.count()
    }

    override fun instantiateItem(container: ViewGroup?, position: Int): Any {
        val rootLayout = LinearLayout(container?.context)
        rootLayout.layoutParams = rootLayout.setDimensions(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        rootLayout.orientation = LinearLayout.HORIZONTAL

        val title = Button(container?.context)
        title.text = "Title"
        title.textSize = 13f
        title.setTextColor(Color.WHITE)
        rootLayout.addView(title)

        val subtitle = Button(container?.context)
        subtitle.text = "Subtitle"
        subtitle.textSize = 13f
        subtitle.setTextColor(Color.WHITE)
        rootLayout.addView(subtitle)

        (container as ViewPager).addView(rootLayout)
        return rootLayout
    }

    override fun getPageTitle(position: Int): CharSequence {
        return data[position].title
    }

    override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) {
        if (obj == null) return
           container?.removeView(obj as View?)
        }
    }
}

For the life of me i can't see what's wrong with this code.  I've tried changing the layouts, textview to a button but nothing works.

I'm hoping someone can point me in the right direction?

Thanks!

Update:

I've created a simple app to prove that i'm not doing anything silly.  Should be able to copy and paste this and run it, provided you've added the relevant libs.

import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.TabLayout
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val rootLayout = CoordinatorLayout(this)
    rootLayout.layoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)

    val appBarLayout = AppBarLayout(this)
    rootLayout.addView(appBarLayout)
    appBarLayout.layoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT)

    val tabLayout = TabLayout(this)

    tabLayout.tabMode = TabLayout.MODE_FIXED
    tabLayout.tabGravity = TabLayout.GRAVITY_FILL
    appBarLayout.addView(tabLayout)
    tabLayout.layoutParams = AppBarLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    //add viewpager
    val viewPager = ViewPager(this)
    viewPager.id = 11122

    val viewAdapter = ViewPagerAdapter()
    viewPager.adapter = viewAdapter

    rootLayout.addView(viewPager)
    viewPager.layoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)
    tabLayout.setupWithViewPager(viewPager)

    rootLayout.setBackgroundColor(Color.BLACK)
    setContentView(rootLayout)
}

inner class ViewPagerAdapter : PagerAdapter() {

    override fun isViewFromObject(view: View?, obj: Any?): Boolean {
        return obj == view
    }

    override fun getCount(): Int {
        return 3
    }

    override fun instantiateItem(container: ViewGroup?, position: Int): Any {
        val rootLayout = LinearLayout(container?.context)
        rootLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        rootLayout.orientation = LinearLayout.HORIZONTAL

        val title = Button(container?.context)
        title.text = "Title"
        title.textSize = 13f
        title.setTextColor(Color.WHITE)
        rootLayout.addView(title)

        val subtitle = Button(container?.context)
        subtitle.text = "Subtitle"
        subtitle.textSize = 13f
        subtitle.setTextColor(Color.WHITE)
        rootLayout.addView(subtitle)

        val viewPager = container as ViewPager
        viewPager.addView(rootLayout, 0)
        return rootLayout
    }

    override fun getPageTitle(position: Int): CharSequence {
        return "Title: $position"
    }

    override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) {
        if (obj == null) return
        when (obj) {
            is ArrayList<*> -> for (item in obj) {
                container?.removeView(item as View?)
            }
            else -> container?.removeView(obj as View?)
        }
    }
}

}

Body:
Looking at your full activity code. It appears you are setting a CoordinatorLayout layout params on your view pager, but you are forgetting to set the behavior, seeing that you also have an AppBarLayout in the hierarchy. Hence, the view pager content is being drawn behind the tab layout. You can verify this by using the layout inspector in AS.

Doing the following should fix your issue

val pagerParams = CoordinatorLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
pagerParams.behavior = AppBarLayout.ScrollingViewBehavior()
viewPager.layoutParams = pagerParams

You could also take advantage of Kotlin's apply function

viewPager.layoutParams = CoordinatorLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT).apply {
    behavior = AppBarLayout.ScrollingViewBehavior()
}

Hope that helps


问:
How to write an output of a grep from an openssl command?
Consider you have list of thousand IP addresses in a text file - one per line. I want to be able to grab all possible anomalies from each IP address using openssl s_client command. So far, anomalies are certificate expired, self signed certificate, and issuer CN to include emailAddress=root@localhost.localdomain.

Overall, I want to be able to obtain concise error message per IP address if there is any. My current bash script looks like:

```<code>for ip in `awk '{print $1}' < general_certs.txt`; do
# Print IP address currently checking
echo -e $ip;
    if timeout 30 openssl s_client -connect $ip:443| grep -i 'error' ; then
# Write error information and IP address to a file
        echo `openssl s_client -connect $ip:443| grep -i 'error'` $ip >> general_errors;
    else
# Write noerror information and IP address to another file
        echo "noerror" $ip >> general_noerror;
    fi;
done
</code>```

First issue I have with the code is that it is not optimized and that I am  skeptical if it returns accurate results. The end goal with the above script is to identify all untrusted certificate containing IPs.

Second issue I had with the above code that I could not echo $ip first because it would get truncated by the message itself. So, I ended up writing out $ip after the error message.

It is not necessary to use openssl if there is a more genuine solution to my question.

答:
You can try to run them all in one shot by putting the processes in the background:

```<code>#!/bin/bash
max=100
counter=0
for ip in `awk '{print $1}' < general_certs.txt`; do
    (( counter++ ))
    (
        results=$( timeout 30 openssl s_client -connect $ip:443 2> /dev/null )
        if [ "$results" = "" ]; then
            echo "$ip noresponse"
        else
            echo -n "$ip "
            echo "$results" | grep -i 'error' || echo "noerror"
        fi
    )  >> general_errors &
    if [ $counter -eq $max ]; then
        wait
        counter=0
    fi
done
wait
</code>```

This was the input:

```<code>$ cat general_certs.txt
stackoverflow.com
redhat.com
google.com
8.8.8.8
vt.edu
bls.gov
8.8.4.4
</code>```

This was the output:

```<code>$ cat general_errors
8.8.4.4 noerror
stackoverflow.com noerror
google.com noerror
vt.edu noerror
bls.gov noerror
redhat.com noerror
8.8.8.8 noresponse
</code>```

If you have some that fail, I can test them.

Body:
Consider you have list of thousand IP addresses in a text file - one per line. I want to be able to grab all possible anomalies from each IP address using openssl s_client command. So far, anomalies are certificate expired, self signed certificate, and issuer CN to include emailAddress=root@localhost.localdomain.

Overall, I want to be able to obtain concise error message per IP address if there is any. My current bash script looks like:

for ip in `awk '{print $1}' < general_certs.txt`; do
# Print IP address currently checking
echo -e $ip;
    if timeout 30 openssl s_client -connect $ip:443| grep -i 'error' ; then
# Write error information and IP address to a file
        echo `openssl s_client -connect $ip:443| grep -i 'error'` $ip >> general_errors;
    else
# Write noerror information and IP address to another file
        echo "noerror" $ip >> general_noerror;
    fi;
done

First issue I have with the code is that it is not optimized and that I am  skeptical if it returns accurate results. The end goal with the above script is to identify all untrusted certificate containing IPs.

Second issue I had with the above code that I could not echo $ip first because it would get truncated by the message itself. So, I ended up writing out $ip after the error message.

It is not necessary to use openssl if there is a more genuine solution to my question.

Body:
You can try to run them all in one shot by putting the processes in the background:

#!/bin/bash
max=100
counter=0
for ip in `awk '{print $1}' < general_certs.txt`; do
    (( counter++ ))
    (
        results=$( timeout 30 openssl s_client -connect $ip:443 2> /dev/null )
        if [ "$results" = "" ]; then
            echo "$ip noresponse"
        else
            echo -n "$ip "
            echo "$results" | grep -i 'error' || echo "noerror"
        fi
    )  >> general_errors &
    if [ $counter -eq $max ]; then
        wait
        counter=0
    fi
done
wait

This was the input:

$ cat general_certs.txt
stackoverflow.com
redhat.com
google.com
8.8.8.8
vt.edu
bls.gov
8.8.4.4

This was the output:

$ cat general_errors
8.8.4.4 noerror
stackoverflow.com noerror
google.com noerror
vt.edu noerror
bls.gov noerror
redhat.com noerror
8.8.8.8 noresponse

If you have some that fail, I can test them.


问:
How to resize UITableViewCell to fit its content?
I have a UITableview with multiple reusable TableViewCells.
In one cell I have a UITextView, that resizes itself to fit its content. Now I "just" have to resize the contentView of the TableViewCell, so I can read the while text. I already tried:

```<code>cell2.contentView.bounds.size.height = cell2.discriptionTextView.bounds.size.height;
</code>```

Or:

```<code>cell2.contentView.frame = CGRectMake(0, cell2.discriptionTextView.bounds.origin.y,
cell2.discriptionTextView.bounds.size.width,
cell2.discriptionTextView.bounds.size.height);
</code>```

In the method:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {}
</code>```

But it won't work.

Does anyone know how to do this?

New code:

```<code>    @implementation AppDetail

    CGFloat height;
    …

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {…

    cell2.TextView.text = self.text;
            [cell2.TextView sizeToFit];
            height = CGRectGetHeight(cell2.TextView.bounds);
     …
    }

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        if (indexPath.row == 0) {
            return 143;
        }
        if (indexPath.row == 1) {
            return height;
        }

        return 0;
    }
</code>```

答:
In case of UILabel subview in the UITableViewCell, I accomplished auto resize of the label just by setting the label's constraints (using storyboard, Xcode 8.3.2).

This is working since apparently the label's and the cell's default behavior is sizeToFit. Same should work for UITextView as well.

Body:
I have a UITableview with multiple reusable TableViewCells.
In one cell I have a UITextView, that resizes itself to fit its content. Now I "just" have to resize the contentView of the TableViewCell, so I can read the while text. I already tried:

cell2.contentView.bounds.size.height = cell2.discriptionTextView.bounds.size.height;

Or:

cell2.contentView.frame = CGRectMake(0, cell2.discriptionTextView.bounds.origin.y,
cell2.discriptionTextView.bounds.size.width,
cell2.discriptionTextView.bounds.size.height);

In the method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {}

But it won't work.

Does anyone know how to do this?

New code:

    @implementation AppDetail

    CGFloat height;
    …

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {…

    cell2.TextView.text = self.text;
            [cell2.TextView sizeToFit];
            height = CGRectGetHeight(cell2.TextView.bounds);
     …
    }

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        if (indexPath.row == 0) {
            return 143;
        }
        if (indexPath.row == 1) {
            return height;
        }

        return 0;
    }


问:
Why does a curried constructor throw an error on partial function application?
when I try to create a curried constructor, like

```<code>class MyClass(a: Int, b: Int)(c: String) {
  // Some Implementation
}
</code>```

why does partial application like

```<code>val partialConstructor = new MyClass(x, y)
</code>```

result in the error message

```<code>missing argument list for constructor MyClass in class MyClass
</code>```

答:
You confuse curried functions with functions of multiple argument lists. Take a look at this answer why there are function with multiple argument lists.

For your example you should explicitly say that you want a curried function

```<code>val partialConstructor = new MyClass(x, y)(_)
</code>```

Body:
when I try to create a curried constructor, like

class MyClass(a: Int, b: Int)(c: String) {
  // Some Implementation
}

why does partial application like

val partialConstructor = new MyClass(x, y)

result in the error message

missing argument list for constructor MyClass in class MyClass

Body:
You confuse curried functions with functions of multiple argument lists. Take a look at this answer why there are function with multiple argument lists.

For your example you should explicitly say that you want a curried function

val partialConstructor = new MyClass(x, y)(_)


问:
replacing a string deletes everything in text
I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."

This is what I have so far:

```<code>    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.*;

    public class RemoveText {
        public static void main(String[] args){

    //creates a scanner to read the user's file name
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a file name: ");
    String fileName = input.nextLine();

    java.io.File file = new java.io.File(fileName);
    java.io.File newFile = new java.io.File(fileName);
    Scanner stringToRemove = new Scanner(System.in);
    System.out.println("Enter a string you wish to remove: ");
    String s1 = stringToRemove.nextLine();

    //creating input and output files
    try {
        Scanner inputFile = new Scanner(file);
        //reads data from a file
        while(inputFile.hasNext()) {
            s1 += inputFile.nextLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //supposed to replace each instance of the user input string
    //but instead deletes everything on the file and i don't know why
    String s2 = s1.replaceAll(s1, "");

    try {
        PrintWriter output = new PrintWriter(newFile);
        output.write(s2);
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //closing various scanners
    input.close();
    stringToRemove.close();
  }
}
</code>```

But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?

Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.

```<code>   Scanner s1 = new Scanner(System.in);
   String stringToRemove = s1.nextLine();
   String fileContents = null;

   try {
    //stuff here
      while (inputFile.hasNextLine()) {
      fileContents += inputFile.nextLine();
    } catch { //more stuff }

   String outputContent = fileContents.replaceAll(stringToRemove, "");
</code>```

My issue now is that the beginning of the new file starts with "null" before relaying the new content.

答:
Where you went wrong is that you appended the file content to s1 which is the string you want to remove.
Try introduce s3 and then do

s2 = s3.replaceAll(s1, "");

Body:
I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."

This is what I have so far:

    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.*;

    public class RemoveText {
        public static void main(String[] args){

    //creates a scanner to read the user's file name
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a file name: ");
    String fileName = input.nextLine();

    java.io.File file = new java.io.File(fileName);
    java.io.File newFile = new java.io.File(fileName);
    Scanner stringToRemove = new Scanner(System.in);
    System.out.println("Enter a string you wish to remove: ");
    String s1 = stringToRemove.nextLine();

    //creating input and output files
    try {
        Scanner inputFile = new Scanner(file);
        //reads data from a file
        while(inputFile.hasNext()) {
            s1 += inputFile.nextLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //supposed to replace each instance of the user input string
    //but instead deletes everything on the file and i don't know why
    String s2 = s1.replaceAll(s1, "");

    try {
        PrintWriter output = new PrintWriter(newFile);
        output.write(s2);
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //closing various scanners
    input.close();
    stringToRemove.close();
  }
}

But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?

Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.

   Scanner s1 = new Scanner(System.in);
   String stringToRemove = s1.nextLine();
   String fileContents = null;

   try {
    //stuff here
      while (inputFile.hasNextLine()) {
      fileContents += inputFile.nextLine();
    } catch { //more stuff }

   String outputContent = fileContents.replaceAll(stringToRemove, "");

My issue now is that the beginning of the new file starts with "null" before relaying the new content.


答:
Java 8 solution with method reference:

userList.stream().filter(User::isActive).findFirst()

It'll return Optional so you could map over it.

Title: Looping over a huge list, check string equal to true


问:
C++: difference between 0. and 0.0?
I am well aware of the difference between 0 and 0.0 (int and double).

But is there any difference between 0. and 0.0 ( please note the . )?

Thanks a lot in advance,

Axel

答:
There is no difference. Both literals are double. From the C++-Grammar:

```<code>fractional-constant:
    digit-sequenceopt . digit-sequence
    digit-sequence .
</code>```

See: Hyperlinked C++ BNF Grammar

Title: C++: difference between 0. and 0.0?

Body:
There is no difference. Both literals are double. From the C++-Grammar:

fractional-constant:
    digit-sequenceopt . digit-sequence
    digit-sequence .

See: Hyperlinked C++ BNF Grammar


问:
Get a reference to an object while instantiating it
I'd like to reference an object while instantiating it in order to pass it to another object I'm instantiating.  What I mean:

```<code>A.new(B.new(self))
</code>```

In this case, self would refer to the scope in which I'm actually calling A.new.  What I want is for self (or whatever other keyword) to refer to the newly instantiated A object, so that B would have a reference to A.  Is there a way to do this?

答:
The way you have written it (A.new(B.new(self))) is impossible, due to a circular reference.

In order to create an instance of A, you need an instance of B; in order to create the instance of B, you need the instance of A.

There are a few ways you tweak the implementation to make this possible, but you must first resolve this chicken-and-egg problem between the A and B. For example:

```<code>class A
  def initialize
    @b = yield(self)
  end
end

class B
  def initialize(a)
    @a = a
  end
end

A.new { |a| B.new(a) }
</code>```

Note that in the above code, a is being initialized first. It is only being yielded in the scope after the object has been created.

Or, here's another way:

```<code>class A
  def initialize
    @b = B.new(self)
  end
end

class B
  def initialize(a)
    @a = a
  end
end

A.new
</code>```

Like above, the instance of A is being created first. But this time, I've done all the initialization in one go rather than building it within the new() methed call.

One final example:

```<code>class A
  attr_writer :b
  def initialize
  end
end

class B
  def initialize(a)
    @a = a
  end
end

A.new.tap { |a| a.b = B.new(a) }
</code>```

In this example, I have fully initialized a before defining its attribute of b. This could just as easily have been written in two lines of code, with a regular variable instead of the closure:

```<code>a = A.new
a.b = B.new(a)
</code>```

Body:
I'd like to reference an object while instantiating it in order to pass it to another object I'm instantiating.  What I mean:

A.new(B.new(self))

In this case, self would refer to the scope in which I'm actually calling A.new.  What I want is for self (or whatever other keyword) to refer to the newly instantiated A object, so that B would have a reference to A.  Is there a way to do this?

Body:
The way you have written it (A.new(B.new(self))) is impossible, due to a circular reference.

In order to create an instance of A, you need an instance of B; in order to create the instance of B, you need the instance of A.

There are a few ways you tweak the implementation to make this possible, but you must first resolve this chicken-and-egg problem between the A and B. For example:

class A
  def initialize
    @b = yield(self)
  end
end

class B
  def initialize(a)
    @a = a
  end
end

A.new { |a| B.new(a) }

Note that in the above code, a is being initialized first. It is only being yielded in the scope after the object has been created.

Or, here's another way:

class A
  def initialize
    @b = B.new(self)
  end
end

class B
  def initialize(a)
    @a = a
  end
end

A.new

Like above, the instance of A is being created first. But this time, I've done all the initialization in one go rather than building it within the new() methed call.

One final example:

class A
  attr_writer :b
  def initialize
  end
end

class B
  def initialize(a)
    @a = a
  end
end

A.new.tap { |a| a.b = B.new(a) }

In this example, I have fully initialized a before defining its attribute of b. This could just as easily have been written in two lines of code, with a regular variable instead of the closure:

a = A.new
a.b = B.new(a)