问:
How to generate Java classes from WSDL with jaxb2-maven-plugin 2.x?
I am trying using the pluggin jaxb2-maven-plugin to create the Java class from the wsdl.

With the version 1.5 this code from Generate classes with jaxb2-maven-plugin from WSDL works:

```<code>        <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals><goal>xjc</goal></goals>
                    </execution>
                </executions>
                <configuration>
                    <!-- Package to store the generated file -->
                    <packageName>com.example.demo.wsdl</packageName>
                    <!-- Treat the input as WSDL -->
                    <wsdl>true</wsdl>
                    <!-- Input is not XML schema -->
                    <xmlschema>false</xmlschema>
                    <!-- The WSDL file that you saved earlier -->
                    <schemaFiles>horarios.wsdl</schemaFiles>
                    <!-- The location of the WSDL file -->
                    <schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>
                    <!-- The output directory to store the generated Java files -->
                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
                    <!-- Don't clear output directory on each run -->
                    <clearOutputDir>false</clearOutputDir>
                </configuration>
            </plugin>
</code>```

But when use plugin version 2.3.1, I get this error:

```<code>Failed to execute goal org.codehaus.mojo:jaxb2-maven-plugin:2.3.1:xjc (xjc) on project demo: MojoExecutionException: NoSchemasException -> [Help 1]
</code>```

Does someone know how use WSDL file with this new plugin version?

答:
I have already found the solution.

When the jaxb2-maven-plugin version is >= 2.0 you have to use the follow configuration:

```<code>             <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>2.3.1</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <packageName>com.example.demo.wsdl</packageName>
                    <sourceType>wsdl</sourceType>
                    <sources>
                        <source>src/main/resources/horarios.wsdl</source>
                    </sources>
                    <outputDirectory>target/generated-sources/</outputDirectory>
                    <clearOutputDir>false</clearOutputDir>
                </configuration>
            </plugin>
</code>```

The difference is not only the syntax. That version does not create the class within the project (src/main/java), it creates in the directory that you wrote in outputDirectory and in the package of packageName.

When you use the class generated it is transparent like if it would be in the same project.

Body:
I am trying using the pluggin jaxb2-maven-plugin to create the Java class from the wsdl.

With the version 1.5 this code from Generate classes with jaxb2-maven-plugin from WSDL works:

        <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals><goal>xjc</goal></goals>
                    </execution>
                </executions>
                <configuration>

                    <packageName>com.example.demo.wsdl</packageName>

                    <wsdl>true</wsdl>

                    <xmlschema>false</xmlschema>

                    <schemaFiles>horarios.wsdl</schemaFiles>

                    <schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>

                    <outputDirectory>${project.basedir}/src/main/java</outputDirectory>

                    <clearOutputDir>false</clearOutputDir>
                </configuration>
            </plugin>

But when use plugin version 2.3.1, I get this error:

Failed to execute goal org.codehaus.mojo:jaxb2-maven-plugin:2.3.1:xjc (xjc) on project demo: MojoExecutionException: NoSchemasException -> [Help 1]

Does someone know how use WSDL file with this new plugin version?

Body:
I have already found the solution.

When the jaxb2-maven-plugin version is >= 2.0 you have to use the follow configuration:

             <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>2.3.1</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <packageName>com.example.demo.wsdl</packageName>
                    <sourceType>wsdl</sourceType>
                    <sources>
                        <source>src/main/resources/horarios.wsdl</source>
                    </sources>
                    <outputDirectory>target/generated-sources/</outputDirectory>
                    <clearOutputDir>false</clearOutputDir>
                </configuration>
            </plugin>

The difference is not only the syntax. That version does not create the class within the project (src/main/java), it creates in the directory that you wrote in outputDirectory and in the package of packageName.

When you use the class generated it is transparent like if it would be in the same project.


来源: stackexchange

问:
aws cli run instances with name tag and EBS volumes
I'm trying to launch new EC2 instances into AWS on the command line using the cli. What I need to do is apply a name tag and add EBS volumes. The EBS volumes should also have name tags. This is what I have so far.

And I'm getting a usage error:

```<code>λ aws ec2 run-instances --image-id ami-xxxxx --count 1 --instance-type r3.xlarge --key-name timd --security-group-ids sg-xxxxx --subnet-id subnet-xxxxx --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=ENC_TEST}]' 'ResourceType=volume,Tags=[{Key=Engagement,Value=8000xxxx}]' --block-device-mappings 'DeviceName=/dev/sdf,VirtualName=data,Ebs={Encrypted=yes,DeleteOnTermination=yes,VolumeSize=250,VolumeType=string}' --profile=govcloud-nonprod
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help

Unknown options: --tag-specifications, 'ResourceType=volume,Tags=[{Key=Engagement,Value=800000xxxx}]', 'ResourceType=instance,Tags=[{Key=Name,Value=ENC_TEST}]'
</code>```

Can someone help me past this point?

答:
--tag-specifications was an feature introduced back end of March 2017

Make sure to update your aws CLI version to reflect this change.

Also the --block-device-mapping is incorrect, the definition is

```<code>        {
          "DeviceName": "string",
          "VirtualName": "string",
          "Ebs": {
            "Encrypted": true|false,
            "DeleteOnTermination": true|false,
            "Iops": integer,
            "SnapshotId": "string",
            "VolumeSize": integer,
            "VolumeType": "standard"|"io1"|"gp2"|"sc1"|"st1"
          },
          "NoDevice": "string"
        }
        ...
</code>```

so you should have

```<code>--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"VirtualName\":\"data\",\"Ebs\":{\"Encrypted\"=true,\"DeleteOnTermination\"=true,\"VolumeSize\"=250,/"VolumeType\"=\"standard\"}}]"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to launch new EC2 instances into AWS on the command line using the cli. What I need to do is apply a name tag and add EBS volumes. The EBS volumes should also have name tags. This is what I have so far.

And I'm getting a usage error:

λ aws ec2 run-instances --image-id ami-xxxxx --count 1 --instance-type r3.xlarge --key-name timd --security-group-ids sg-xxxxx --subnet-id subnet-xxxxx --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=ENC_TEST}]' 'ResourceType=volume,Tags=[{Key=Engagement,Value=8000xxxx}]' --block-device-mappings 'DeviceName=/dev/sdf,VirtualName=data,Ebs={Encrypted=yes,DeleteOnTermination=yes,VolumeSize=250,VolumeType=string}' --profile=govcloud-nonprod
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help

Unknown options: --tag-specifications, 'ResourceType=volume,Tags=[{Key=Engagement,Value=800000xxxx}]', 'ResourceType=instance,Tags=[{Key=Name,Value=ENC_TEST}]'

Can someone help me past this point?

Body:
--tag-specifications was an feature introduced back end of March 2017

Make sure to update your aws CLI version to reflect this change.

Also the --block-device-mapping is incorrect, the definition is

        {
          "DeviceName": "string",
          "VirtualName": "string",
          "Ebs": {
            "Encrypted": true|false,
            "DeleteOnTermination": true|false,
            "Iops": integer,
            "SnapshotId": "string",
            "VolumeSize": integer,
            "VolumeType": "standard"|"io1"|"gp2"|"sc1"|"st1"
          },
          "NoDevice": "string"
        }
        ...

so you should have

--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"VirtualName\":\"data\",\"Ebs\":{\"Encrypted\"=true,\"DeleteOnTermination\"=true,\"VolumeSize\"=250,/"VolumeType\"=\"standard\"}}]"


问:
When to delete pointer in try-catch block
Quick best-practice question (note I am not allowed to use any smart pointers in this code). I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated. Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

Example:

```<code>int main() {
  object* myPtr = new object(); //dynamic memory on heap
  foo(*myPtr);  //pass pointer to function foo

  return 0;
}

void foo(object &pointer) {
  try {
    /* do stuff here
    with the pointer */
  }
  catch (const char &e) {
    cout<< "An error occured: " << e << endl;
  }
  catch (...)
    cout<< "Caught unknown exception." << endl;
  }
}
</code>```

Should I delete the pointer after the function returns?

```<code> int main() {
      object* myPtr = new object(); //dynamic memory on heap
      foo(*myPtr);  //pass pointer to function foo
      delete myPtr;

      return 0;
    }
</code>```

Or in the try-catch blocks?

```<code>void foo(object &pointer) {
      try {
        /* do stuff here
        with the pointer */
      }
      catch (const char &e) {
        cout<< "An error occured: " << e << endl;
        delete &pointer;
      }
      catch (...)
        cout<< "Caught unknown exception." << endl;
        delete &pointer;
      }
    }
</code>```

答:
When to delete pointer in try-catch block

Don't.

Delete it in main, after the call to foo.

In short, delete it where you created it. Anything else creates a messy asymmetry.

I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted.

Don't know where you heard that. Forget it. It's nonsense.

Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

You could:

delete the memory at the end of the try and in both catch blocks

delete the memory after the end try/catch chain

and both are perfectly "safe".

But, like I said—

Should I delete the pointer after the function returns?

Right, exactly.

BTW

You have a missing * and a capitalisation typo:

```<code>object* myPtr = new object();
//    ^             ^
</code>```

and in reality a version with smart pointers might look like this:

```<code>#include <iostream>
#include <memory>

struct object {};

void foo(object& obj)
{
   try {
      // do stuff here with the reference (not a pointer)
   }
   catch (const char* e) {
      std::cout << "An error occured: " << e << std::endl;
   }
   catch (...)
      std::cout << "Caught unknown exception." << std::endl;
   }
}

int main()
{
   auto myPtr = std::make_unique<object>();
   foo(*myPtr);
}
</code>```

Body:
Quick best-practice question (note I am not allowed to use any smart pointers in this code). I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated. Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

Example:

int main() {
  object* myPtr = new object(); //dynamic memory on heap
  foo(*myPtr);  //pass pointer to function foo

  return 0;
}

void foo(object &pointer) {
  try {
    /* do stuff here
    with the pointer */
  }
  catch (const char &e) {
    cout<< "An error occured: " << e << endl;
  }
  catch (...)
    cout<< "Caught unknown exception." << endl;
  }
}

Should I delete the pointer after the function returns?

 int main() {
      object* myPtr = new object(); //dynamic memory on heap
      foo(*myPtr);  //pass pointer to function foo
      delete myPtr;

      return 0;
    }

Or in the try-catch blocks?

void foo(object &pointer) {
      try {
        /* do stuff here
        with the pointer */
      }
      catch (const char &e) {
        cout<< "An error occured: " << e << endl;
        delete &pointer;
      }
      catch (...)
        cout<< "Caught unknown exception." << endl;
        delete &pointer;
      }
    }

Body:
When to delete pointer in try-catch block

Don't.

Delete it in main, after the call to foo.

In short, delete it where you created it. Anything else creates a messy asymmetry.

I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted.

Don't know where you heard that. Forget it. It's nonsense.

Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

You could:

delete the memory at the end of the try and in both catch blocks

delete the memory after the end try/catch chain

and both are perfectly "safe".

But, like I said—

Should I delete the pointer after the function returns?

Right, exactly.

BTW

You have a missing * and a capitalisation typo:

object* myPtr = new object();
//    ^             ^

and in reality a version with smart pointers might look like this:

#include <iostream>
#include <memory>

struct object {};

void foo(object& obj)
{
   try {
      // do stuff here with the reference (not a pointer)
   }
   catch (const char* e) {
      std::cout << "An error occured: " << e << std::endl;
   }
   catch (...)
      std::cout << "Caught unknown exception." << std::endl;
   }
}

int main()
{
   auto myPtr = std::make_unique<object>();
   foo(*myPtr);
}


问:
php register to database
I am very new to stackoverflow. I want to create this form which uploads information to the database. When I click submit it does not get uploaded. I have checked my connections file and that is correct. Code below. Please help.</p>

```<code><?php
 include("/connections/db_conx.php");

 if ( isset($_POST['submit']) ) {

$title = mysqli_real_escape_string($_POST['title']);
 $text = mysqli_real_escape_string($_POST['text']);
   $picture = mysqli_real_escape_string($_POST['picture']);

  $sql = "INSERT INTO news  (title, text, picture) VALUES('$title','$text','$picture', now(),now(),now())";

    $query = mysqli_query ($db_conx, $sql);

     echo 'Entered into the news table';
     }
     ?>

  <html>

  <head>

 </head>

 <body>

  <table border="0">
  <tr>
  <form method="post" action="index.php" id="tech">
  <td>Title</td><td> <input type="text" name="title"></td> </tr>
  <tr> <td>Text</td><td> <textarea rows="4" name="text" cols="50"       name="comment"       form="tech"> </textarea>
       </td> </tr>

 <tr> <td>Picture</td><td> <input type="varchar" name="picture"></td> </tr>

 <tr> <td><input id="button" type="submit" name="submit" value="Submit"></td>

 </tr>
 </form>

 </table>

</body>

</html>
</code>```

答:
Try  This :</p>

```<code>$title = mysqli_real_escape_string($db_conx, $_POST['title']);
$text = mysqli_real_escape_string($db_conx, $_POST['text']);
$picture = mysqli_real_escape_string($db_conx, $_POST['picture']);

$sql = "INSERT INTO news  (title, text, picture) VALUES('$title','$text','$picture')";

$query = mysqli_query ($db_conx, $sql);

if($query){
echo 'Entered into the news table'; // Your Success Message
}
else {
    echo mysqli_error($db_conx);
}
</code>```

Title: php register to database

Body:
I am very new to stackoverflow. I want to create this form which uploads information to the database. When I click submit it does not get uploaded. I have checked my connections file and that is correct. Code below. Please help.

<?php
 include("/connections/db_conx.php");

 if ( isset($_POST['submit']) ) {

$title = mysqli_real_escape_string($_POST['title']);
 $text = mysqli_real_escape_string($_POST['text']);
   $picture = mysqli_real_escape_string($_POST['picture']);

  $sql = "INSERT INTO news  (title, text, picture) VALUES('$title','$text','$picture', now(),now(),now())";

    $query = mysqli_query ($db_conx, $sql);

     echo 'Entered into the news table';
     }
     ?>

  <form method="post" action="index.php" id="tech">
  Title	 <input type="text" name="title">

 Text	 <textarea rows="4" name="text" cols="50"       name="comment"       form="tech"> </textarea>

 Picture	 <input type="varchar" name="picture">

 <input id="button" type="submit" name="submit" value="Submit">

 </form>

Body:
Try  This :

$title = mysqli_real_escape_string($db_conx, $_POST['title']);
$text = mysqli_real_escape_string($db_conx, $_POST['text']);
$picture = mysqli_real_escape_string($db_conx, $_POST['picture']);

$sql = "INSERT INTO news  (title, text, picture) VALUES('$title','$text','$picture')";

$query = mysqli_query ($db_conx, $sql);

if($query){
echo 'Entered into the news table'; // Your Success Message
}
else {
    echo mysqli_error($db_conx);
}

ContentLicense: CC BY-SA 4.0


问:
Are technologies like LINQ, WPF, WF just libraries or development changing methodologies
Lately, Microsoft keeps coming out with new technologies Linq, WF, WPF, etc... Seems to me that they are presented like technology inovations that completely change the way your applications are designed and coded.

Yet,they are based on the same underlying framework (2.0) If I look at Java, there are a lot of libraries that provide critical functionality (Hibernate, Spring for example), yet they are considered to be still just libraries.

So my question is, Do people think that these technologies are really changing the way we write windows code? Is it worth learning every development methodology that Microsoft is putting out with Visual Studio releases.

Or is this just hype. As libraries, they are important, however, not critical to get job done. Will they make as big of an impact and ss I learn it, it will considerably effect my future as a developer?

EDIT: The same goes for some of the language futures that are implemented. Some are changing the way we program (Generics) Others, are much less critical (Partial Classes) That makes learning Generics a critical part of learning .NET, unlike learning to use Partial Classes

答: Given a number of new technologies I think it is much more difficult to select "winning" set of technologies rather than learn something new ('cause everything was invented long time ago already :) ) For example I was very interesting in WF - I was looking at this technology as a really great shift in software development, but when I digged it deeper it turned out that I should wait until vNext to take advantage of advertised bonuses. Another technologies like LINQ/WPF really improved my productivity. Developer should be scrupulous when choosing technology. I teach myself to not jump to each bandwagon crossing my street, but it is still very tempting to learn some new "solve all you problem" technology :)</p>

OwnerDisplayName: Timur Fanshteyn

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Timur Fanshteyn

OwnerDisplayName: aku


问:
Why Is XDocument.Descendants().Count() > 0 for an Empty Document?
Here's my method:

```<code>var document = XDocument.Parse(source);
if (document.Descendants().Count() > 0)
{
    // Some code that shouldn't execute
}
else
{
    // Code that should execute
}
</code>```

This code breaks when this is in the 'document' variable:

```<code><ipb></ipb>
</code>```

Since this DOESN'T have descendants, why is it entering the IF conditional? Is shouldn't try to load anything, yet it does and breaks when it finds nothing to scrape.

Using Breakpoints I can confirm that the document variable has the content I posted above when it breaks and it does enter the if.

答:
Have you tried using:

```<code>document.Root.Descendants().Count() > 0;
</code>```

The Root element sits below the XDocument.

OwnerDisplayName: delete

Body:
Here's my method:

var document = XDocument.Parse(source);
if (document.Descendants().Count() > 0)
{
    // Some code that shouldn't execute
}
else
{
    // Code that should execute
}

This code breaks when this is in the 'document' variable:

<ipb></ipb>

Since this DOESN'T have descendants, why is it entering the IF conditional? Is shouldn't try to load anything, yet it does and breaks when it finds nothing to scrape.

Using Breakpoints I can confirm that the document variable has the content I posted above when it breaks and it does enter the if.

Body:
Have you tried using:

document.Root.Descendants().Count() > 0;

The Root element sits below the XDocument.


问:
using shell.openItem() to open a file in an asar archive
I have an electron app that uses an app.asar file.  I want to be able to open files (.xlsx) that are in the asar file in the default Windows application (which is Excel).  I have tried

```<code>let xlsx = path.join(__dirname + '/path/to/app.asar/path/to/file');
shell.openItem(xlsx);
</code>```

but it doesn't work (no error, the file doesn't open).

I can read the file with fs

```<code>let xlsx = path.join(__dirname + '/path/to/app.asar/path/to/file');
fs.readFileSync(xlsx);
</code>```

but I can't get the file to open in Excel.

答:
From the documentation for Application Packaging

An asar archive is a simple tar-like format that concatenates files into a single file. Electron can read arbitrary files from it without unpacking the whole file.

Only Electron can access those files, Excel and other applications simply can not deal with asar archives.

You could copy the file from the asar archive to the system's temp folder and open it from there. Like this:

const fs = require('fs')
const path = require('path')
const {shell, app} = require('electron')

let xlsx = path.join(__dirname,'/path/to/app.asar/path/to/file')
let xlsxtmp = üath.join(app.getPath('temp', 'file')
let ws = fs.createWriteStream(xlsxtmp)

fs.createReadStream(xlsx).pipe(ws)

ws.on('finish', () => {
    shell.openItem(xlsxtmp);
}
```

Another option would be to not pack that xlsx into the archive and instead download it into the userData path.

Body:
I have an electron app that uses an app.asar file.  I want to be able to open files (.xlsx) that are in the asar file in the default Windows application (which is Excel).  I have tried

let xlsx = path.join(__dirname + '/path/to/app.asar/path/to/file');
shell.openItem(xlsx);

but it doesn't work (no error, the file doesn't open).

I can read the file with fs

let xlsx = path.join(__dirname + '/path/to/app.asar/path/to/file');
fs.readFileSync(xlsx);

but I can't get the file to open in Excel.

Body:
From the documentation for Application Packaging

An asar archive is a simple tar-like format that concatenates files into a single file. Electron can read arbitrary files from it without unpacking the whole file.

Only Electron can access those files, Excel and other applications simply can not deal with asar archives.

You could copy the file from the asar archive to the system's temp folder and open it from there. Like this:

const fs = require('fs')
const path = require('path')
const {shell, app} = require('electron')

let xlsx = path.join(__dirname,'/path/to/app.asar/path/to/file')
let xlsxtmp = üath.join(app.getPath('temp', 'file')
let ws = fs.createWriteStream(xlsxtmp)

fs.createReadStream(xlsx).pipe(ws)

ws.on('finish', () => {
    shell.openItem(xlsxtmp);
}

Another option would be to not pack that xlsx into the archive and instead download it into the userData path.


问:
How can I save setting of my menu_toggle using cookie?
I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

```<code>  <div class="nav toggle">
  <a id="menu_toggle"><i class="fa fa-bars"></i></a>
  </div>
</code>```

My Code

```<code> var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });
</code>```

答:
```<code>document.cookie = "togglesetting=John Doe; expires=Thu, 18 Dec 2017 12:00:00 UTC";
</code>```

You can put your setting information into any key value pattern in the cookie.

My suggestion is to put a json there and read the togglesetting key from cookies than set your toogle menu appropriately

Body:
I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

My Code

 var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });

Body:
document.cookie = "togglesetting=John Doe; expires=Thu, 18 Dec 2017 12:00:00 UTC";

You can put your setting information into any key value pattern in the cookie.

My suggestion is to put a json there and read the togglesetting key from cookies than set your toogle menu appropriately


问:
How do you define class variables accessible by all instances
I want to define a array with class-wide scope/access by all instances. Example module (bc.py):

```<code>class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        glist.append(number)

    def printCurrentList():
        print ('Current List:', glist)

class C:
    def __init__(self):
        b1 = B(7)
        b2 = B(2)
        b3 = B(8)

    def printNow(self):
        B.printCurrentList()
</code>```

I am calling this from file a.py, as:

```<code>from bc import C
C().printNow()
</code>```

Getting error as:

```<code>python a.py
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    C().printNow()
  File "/Users/manidipsengupta/pytorials/bc.py", line 16, in __init__
    b1 = B(7)
  File "/Users/manidipsengupta/pytorials/bc.py", line 7, in __init__
    glist.append(number)
NameError: name 'glist' is not defined
</code>```

What should be the correct syntax for this? Thank you.

答:
Either

```<code>B.glist.append(number)
</code>```

or

```<code>self.glist.append(number)
</code>```

will work. I'd prefer the former as it better shows that glist is a static class variable, instead of per instance.

Body:
I want to define a array with class-wide scope/access by all instances. Example module (bc.py):

class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        glist.append(number)

    def printCurrentList():
        print ('Current List:', glist)

class C:
    def __init__(self):
        b1 = B(7)
        b2 = B(2)
        b3 = B(8)

    def printNow(self):
        B.printCurrentList()

I am calling this from file a.py, as:

from bc import C
C().printNow()

Getting error as:

python a.py
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    C().printNow()
  File "/Users/manidipsengupta/pytorials/bc.py", line 16, in __init__
    b1 = B(7)
  File "/Users/manidipsengupta/pytorials/bc.py", line 7, in __init__
    glist.append(number)
NameError: name 'glist' is not defined

What should be the correct syntax for this? Thank you.

Body:
Either

B.glist.append(number)

or

self.glist.append(number)

will work. I'd prefer the former as it better shows that glist is a static class variable, instead of per instance.


问:
Combine sheet 3 from many workbooks into one new workbook
I have 77 workbooks and need to combine sheet 3 in all of them into one sheet in a new workbook. I have not done this in years.  I would really appreciate Any help. I modified some code from other webpages but it is not working for me.</p>

答:
Here is something I had which you can tailor to your needs

```<code>Sub ConslidateWorkbooks()
    'Code to pull sheets from multiple Excel files in one file directory
    'into master "Consolidation" sheet.

    Dim FolderPath As String
    Dim Filename As String
    Dim Sheet As Worksheet

    Application.ScreenUpdating = False
    FolderPath = "[REDACTED]"
    Filename = Dir(FolderPath & "*.xlsx")

    Do While Filename <> ""
        Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
        copyOrRefreshSheet ThisWorkbook, Sheets(3)
        Workbooks(Filename).Close
        Filename = Dir()
    Loop

    Application.ScreenUpdating = True

End Sub

Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
     Dim ws As Worksheet
     On Error Resume Next
     Set ws = destWb.Worksheets(sourceWs.Name)
     On Error GoTo 0
     If ws Is Nothing Then
         sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.Count)
     Else
         ws.Cells.ClearContents
         ws.Range(sourceWs.UsedRange.Address).Value = sourceWs.UsedRange.Value2
     End If
End Sub
</code>```

It may not work perfectly, but it should point you on the right path

Body:
Here is something I had which you can tailor to your needs

Sub ConslidateWorkbooks()
    'Code to pull sheets from multiple Excel files in one file directory
    'into master "Consolidation" sheet.

    Dim FolderPath As String
    Dim Filename As String
    Dim Sheet As Worksheet

    Application.ScreenUpdating = False
    FolderPath = "[REDACTED]"
    Filename = Dir(FolderPath & "*.xlsx")

    Do While Filename <> ""
        Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
        copyOrRefreshSheet ThisWorkbook, Sheets(3)
        Workbooks(Filename).Close
        Filename = Dir()
    Loop

    Application.ScreenUpdating = True

End Sub

Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
     Dim ws As Worksheet
     On Error Resume Next
     Set ws = destWb.Worksheets(sourceWs.Name)
     On Error GoTo 0
     If ws Is Nothing Then
         sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.Count)
     Else
         ws.Cells.ClearContents
         ws.Range(sourceWs.UsedRange.Address).Value = sourceWs.UsedRange.Value2
     End If
End Sub

It may not work perfectly, but it should point you on the right path


问:
How to have n variables in C#
imagine this code

```<code>for (int iDay = 1; iDay <= total_days; iDay++)
{

    question = CheckString(s.challenge_1_q);
    answer = CheckStringA(s.challenge_1_a);

    // more here
}
</code>```

but what I really have is from challenge_1_q to challenge_24_q and challenge_1_a to challenge_24_a

what is my best option to have dynamic variables as today it's 24, "tomorrow" could be only 18.

is the use of dynamic the proper way? or I really need to have a switch and forget about dynamism ?

答:
You can also create Structure

```<code>struct QuestionBank
{
   public string Question;
   public string Answer;
}
</code>```

And use Something like this

```<code> QuestionBank []Quiz = new QuestionBank[n]; //n is number of question and answers
 Quiz[0].Question = "SomeQuestion";
 Quiz[0].Answer = "SomeAnswer";

 Quiz[1].Question = "SomeAnotherQuestion";
 Quiz[1].Answer = "AnswerAsWell";

 .....

 Quiz[n].Question = "nth Question";
 Quiz[n].Answer = "nth AnswerAsWell";
</code>```

Title: How to have n variables in C#

Body:
imagine this code

for (int iDay = 1; iDay <= total_days; iDay++)
{

    question = CheckString(s.challenge_1_q);
    answer = CheckStringA(s.challenge_1_a);

    // more here
}

but what I really have is from challenge_1_q to challenge_24_q and challenge_1_a to challenge_24_a

what is my best option to have dynamic variables as today it's 24, "tomorrow" could be only 18.

is the use of dynamic the proper way? or I really need to have a switch and forget about dynamism ?

Body:
You can also create Structure

struct QuestionBank
{
   public string Question;
   public string Answer;
}

And use Something like this

 QuestionBank []Quiz = new QuestionBank[n]; //n is number of question and answers
 Quiz[0].Question = "SomeQuestion";
 Quiz[0].Answer = "SomeAnswer";

 Quiz[1].Question = "SomeAnotherQuestion";
 Quiz[1].Answer = "AnswerAsWell";

 .....

 Quiz[n].Question = "nth Question";
 Quiz[n].Answer = "nth AnswerAsWell";


问:
How do I select from tables with a specifically named column when that column contains a specific value?
I am trying to select all the tables that has the same column, and there is an instance in that column matches a string format that I specify.

For example,

Table1:

FirstName, LastName, ID

Table2:

ID, Value

Table3:

FirstName, Value

I want my result to show the tables that contains ID in which the ID begin with character 'a'

So far what I have is

```<code>    SELECT SYS.TABLES.NAME FROM SYS.TABLES
    INNER JOIN SYS.COLUMNS
    ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
    WHERE SYS.COLUMS.NAME = 'ID'
</code>```

but then I have no clue how to continue. Any help is appreciated :)

答:
I still don't know if i got your question properly - but let's try!

Use the following query to get all tables with a column ID

```<code>SELECT SYS.TABLES.NAME , SYS.COLUMNS.NAME
FROM SYS.TABLES INNER JOIN SYS.COLUMNS
ON SYS.TABLES.OBJECT_ID = SYS.COLUMNS.OBJECT_ID
WHERE SYS.COLUMNS.NAME = 'ID';
</code>```

You will have to iterate through the table names (think cursor, while etc.)

Inside the loop, try something like this

```<code>declare @resultcount int;
declare @QueryMain as nvarchar(4000)
set @QueryMain = N'SELECT * FROM <TABLE_NAME> WHERE ID LIKE ''a%'''
exec sp_executesql @QueryMain
set @resultcount = @@rowcount;
</code>```

Inspect the value of @resultcount to see if the current table name qualifies and use something like a temporary table to collect it.

You may be use other options in sp_executesql to tweak this query

Body:
I am trying to select all the tables that has the same column, and there is an instance in that column matches a string format that I specify.

For example,

Table1:

FirstName, LastName, ID

Table2:

ID, Value

Table3:

FirstName, Value

I want my result to show the tables that contains ID in which the ID begin with character 'a'

So far what I have is

    SELECT SYS.TABLES.NAME FROM SYS.TABLES
    INNER JOIN SYS.COLUMNS
    ON SYS.TABLES.OBJECT_ID = SYS.COLUMS.OBJECT_ID
    WHERE SYS.COLUMS.NAME = 'ID'

but then I have no clue how to continue. Any help is appreciated :)

Body:
I still don't know if i got your question properly - but let's try!

Use the following query to get all tables with a column ID

SELECT SYS.TABLES.NAME , SYS.COLUMNS.NAME
FROM SYS.TABLES INNER JOIN SYS.COLUMNS
ON SYS.TABLES.OBJECT_ID = SYS.COLUMNS.OBJECT_ID
WHERE SYS.COLUMNS.NAME = 'ID';

You will have to iterate through the table names (think cursor, while etc.)

Inside the loop, try something like this

declare @resultcount int;
declare @QueryMain as nvarchar(4000)
set @QueryMain = N'SELECT * FROM <TABLE_NAME> WHERE ID LIKE ''a%'''
exec sp_executesql @QueryMain
set @resultcount = @@rowcount;

Inspect the value of @resultcount to see if the current table name qualifies and use something like a temporary table to collect it.

You may be use other options in sp_executesql to tweak this query


问:
Preselect a value in a dropdown using knockout
I have multiple 10 dropdowns to be displayed in the page. I am using knockout to build the page. Basically i have a collection of 'sites' obseravablearray. Inside 'site' array i have a collection of 'users' which is an observablearray.
'users' are displayed as dropdown. I need to preselect a value based inside the dropdowns. However it is not working. I am not able to see the selected value in the dropdown. Please let me know for any help. I would not hardcode any id value for the dropdown as the display of the dropdowns is dynamic.</p>

```<code>Below is the sample code using knockout  (aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="Scripts/jquery-3.0.0.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/knockout-3.4.0.js"></script>
    <script src="primarySetup.js"></script>
</head>
<body>
        <form id="frmPrimarySiteUser">
        <div class="container">
            <div class="row">
                <span>Setup </span>
            </div>
            <div class="row">
                <table class="table-bordered table-condensed table-hover table-responsive" id="tblEncode">
                    <thead>
                        <tr>
                            <th>Site Name</th>
                            <th>User Id</th>
                        </tr>
                    </thead>
                    <tbody data-bind="foreach: PrimarySiteUsers">
                        <tr>
                            <td><span data-bind="text: SiteName"></span></td>
                            <td><select name="ddlUsers" data-bind="options: UserParam, selected: 'SelectedUserId', optionsText: 'UserName', optionsValue: 'UserId', optionsCaption:'-Select-'"></select></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </form>
</body>
</html>

js file.

function PrimaryUserViewModel() {
    var self = this;

    self.PrimarySiteUsers = ko.observableArray([]);
    self.Users1 = ko.observableArray([]);
    self.Users2 = ko.observableArray([]);

    function addPrimarySiteUser(siteId, siteName, userParam) {
        return {
            SiteId: ko.observable(siteId),
            SiteName: ko.observable(siteName),
            UserParam: ko.observable(userParam)
        }
    }

    function addUserDropDown(userId, userName, selectedValue) {
        return {
            UserId: ko.observable(userId),
            UserName: ko.observable(userName),
            SelectedUserId: ko.observable(selectedValue)
        }
    }

    self.Users1().push(new addUserDropDown(1, 'jj', false));
    self.Users1().push(new addUserDropDown(2, 'jk', true));

    self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users1()))

    self.Users2().push(new addUserDropDown(1, 'mj', true));
    self.Users2().push(new addUserDropDown(2, 'mk', false));

    self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users2()))
}

$(document).ready(function () {
    var primaryUserModel = new PrimaryUserViewModel();
    ko.applyBindings(primaryUserModel);
})
</code>```

答:
There's a lot of weird code in your example, so I'll start with the basics:

You can set selections in your viewmodel by:

Create a list you want to render as options, and an observable to store the current selection

```<code>var vm = {
  choices: [ 1, 2, 3],
  selection: ko.observable(2)
};
</code>```

Bind the list to options and the observable to value in your <select> box:

```<code><select data-bind="options: choices, value: selection"></select>
</code>```

Write a value to selection that is also in the array bound to options:

```<code>vm.selection(3); // Selects the last element of the dropdown
vm.selection(vm.choices[1]) // Select 2
</code>```

To get this to work in your code:

Add a value binding and selection observable

Store a reference to the prim vm so we can update the selected property

Loop up a user and their UserId to set a new selection

function PrimaryUserViewModel() {
  var self = this;

  self.PrimarySiteUsers = ko.observableArray([]);
  self.Users1 = ko.observableArray([]);
  self.Users2 = ko.observableArray([]);

  function addPrimarySiteUser(siteId, siteName, userParam) {
    return {
      SiteId: ko.observable(siteId),
      SiteName: ko.observable(siteName),
      UserParam: ko.observable(userParam),
      selection: ko.observable(null)
    }
  }

  function addUserDropDown(userId, userName, selectedValue) {
    return {
      UserId: ko.observable(userId),
      UserName: ko.observable(userName),
      SelectedUserId: ko.observable(selectedValue)
    }
  }

  self.Users1().push(new addUserDropDown(1, 'jj', false));
  self.Users1().push(new addUserDropDown(2, 'jk', true));

  var primUser1 = new addPrimarySiteUser(1, 'site1', self.Users1());
  self.PrimarySiteUsers.push(primUser1)

  // Select jk:
  // 1: find reference to user
  var jkUser = self.Users1()[1];
  // 2: get id (because of `optionsValue: 'UserId'`)
  var jkId = jkUser.UserId();
  // 3: write to selection
  primUser1.selection(jkId);

  self.Users2().push(new addUserDropDown(1, 'mj', true));
  self.Users2().push(new addUserDropDown(2, 'mk', false));

  self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users2()))
}

var primaryUserModel = new PrimaryUserViewModel();
ko.applyBindings(primaryUserModel);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form id="frmPrimarySiteUser">
  <div class="container">
    <div class="row">
      <span>Setup </span>
    </div>
    <div class="row">
      <table class="table-bordered table-condensed table-hover table-responsive" id="tblEncode">
        <thead>
          <tr>
            <th>Site Name</th>
            <th>User Id</th>
          </tr>
        </thead>
        <tbody data-bind="foreach: PrimarySiteUsers">
          <tr>
            <td><span data-bind="text: SiteName"></span></td>
            <td><select name="ddlUsers" data-bind="options: UserParam, value: selection, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption:'-Select-'"></select></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</form></code>```

There are many weird things happening in your code that you should also fix:

Don't use new when it's not needed

Remove data-binds as selected that don't do anything

Restructure some of the data definitions and viewmodels

Use lowercase characters for properties' first letters and uppercase ones for constructors...

Body:
I have multiple 10 dropdowns to be displayed in the page. I am using knockout to build the page. Basically i have a collection of 'sites' obseravablearray. Inside 'site' array i have a collection of 'users' which is an observablearray.
'users' are displayed as dropdown. I need to preselect a value based inside the dropdowns. However it is not working. I am not able to see the selected value in the dropdown. Please let me know for any help. I would not hardcode any id value for the dropdown as the display of the dropdowns is dynamic.

Below is the sample code using knockout  (aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" %>

<!DOCTYPE html>

    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />

        <form id="frmPrimarySiteUser">

                Setup

                            Site Name
                            User Id

                            <select name="ddlUsers" data-bind="options: UserParam, selected: 'SelectedUserId', optionsText: 'UserName', optionsValue: 'UserId', optionsCaption:'-Select-'"></select>

    </form>

js file.

function PrimaryUserViewModel() {
    var self = this;

    self.PrimarySiteUsers = ko.observableArray([]);
    self.Users1 = ko.observableArray([]);
    self.Users2 = ko.observableArray([]);

    function addPrimarySiteUser(siteId, siteName, userParam) {
        return {
            SiteId: ko.observable(siteId),
            SiteName: ko.observable(siteName),
            UserParam: ko.observable(userParam)
        }
    }

    function addUserDropDown(userId, userName, selectedValue) {
        return {
            UserId: ko.observable(userId),
            UserName: ko.observable(userName),
            SelectedUserId: ko.observable(selectedValue)
        }
    }

    self.Users1().push(new addUserDropDown(1, 'jj', false));
    self.Users1().push(new addUserDropDown(2, 'jk', true));

    self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users1()))

    self.Users2().push(new addUserDropDown(1, 'mj', true));
    self.Users2().push(new addUserDropDown(2, 'mk', false));

    self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users2()))
}

$(document).ready(function () {
    var primaryUserModel = new PrimaryUserViewModel();
    ko.applyBindings(primaryUserModel);
})

Body:
There's a lot of weird code in your example, so I'll start with the basics:

You can set selections in your viewmodel by:

Create a list you want to render as options, and an observable to store the current selection

var vm = {
  choices: [ 1, 2, 3],
  selection: ko.observable(2)
};

Bind the list to options and the observable to value in your <select> box:

<select data-bind="options: choices, value: selection"></select>

Write a value to selection that is also in the array bound to options:

vm.selection(3); // Selects the last element of the dropdown
vm.selection(vm.choices[1]) // Select 2

To get this to work in your code:

Add a value binding and selection observable

Store a reference to the prim vm so we can update the selected property

Loop up a user and their UserId to set a new selection

function PrimaryUserViewModel() {
  var self = this;

  self.PrimarySiteUsers = ko.observableArray([]);
  self.Users1 = ko.observableArray([]);
  self.Users2 = ko.observableArray([]);

  function addPrimarySiteUser(siteId, siteName, userParam) {
    return {
      SiteId: ko.observable(siteId),
      SiteName: ko.observable(siteName),
      UserParam: ko.observable(userParam),
      selection: ko.observable(null)
    }
  }

  function addUserDropDown(userId, userName, selectedValue) {
    return {
      UserId: ko.observable(userId),
      UserName: ko.observable(userName),
      SelectedUserId: ko.observable(selectedValue)
    }
  }

  self.Users1().push(new addUserDropDown(1, 'jj', false));
  self.Users1().push(new addUserDropDown(2, 'jk', true));

  var primUser1 = new addPrimarySiteUser(1, 'site1', self.Users1());
  self.PrimarySiteUsers.push(primUser1)

  // Select jk:
  // 1: find reference to user
  var jkUser = self.Users1()[1];
  // 2: get id (because of `optionsValue: 'UserId'`)
  var jkId = jkUser.UserId();
  // 3: write to selection
  primUser1.selection(jkId);

  self.Users2().push(new addUserDropDown(1, 'mj', true));
  self.Users2().push(new addUserDropDown(2, 'mk', false));

  self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users2()))
}

var primaryUserModel = new PrimaryUserViewModel();
ko.applyBindings(primaryUserModel);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form id="frmPrimarySiteUser">
  <div class="container">
    <div class="row">
      <span>Setup </span>
    </div>
    <div class="row">
      <table class="table-bordered table-condensed table-hover table-responsive" id="tblEncode">
        <thead>
          <tr>
            <th>Site Name</th>
            <th>User Id</th>
          </tr>
        </thead>
        <tbody data-bind="foreach: PrimarySiteUsers">
          <tr>
            <td><span data-bind="text: SiteName"></span></td>
            <td><select name="ddlUsers" data-bind="options: UserParam, value: selection, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption:'-Select-'"></select></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</form>

There are many weird things happening in your code that you should also fix:

Don't use new when it's not needed

Remove data-binds as selected that don't do anything

Restructure some of the data definitions and viewmodels

Use lowercase characters for properties' first letters and uppercase ones for constructors...


问:
How to split by Replacement Character "" in Ruby?
I have this character , or see screenshot below. Its the "replacement character" in Ruby.

I'm using an external API that does parsing, and unfortunately returns this character instead of - for un-ordered list points.

I would like to split by this character in what is returned, but I've been unsuccessful with below.

```<code>text.split(//)
</code>```

How can I split by this character?

答:
These will match any non ASCII character:

[^\x00-\x7F] or [^[:ascii:]].

As noted by @engineersmnky this may not be the most ideal solution if the data you are parsing could contain more unrecognized characters.

Use this regex if you want to split only the  character:

```<code>[\uF0B7]
</code>```

Body:
I have this character , or see screenshot below. Its the "replacement character" in Ruby.

I'm using an external API that does parsing, and unfortunately returns this character instead of - for un-ordered list points.

I would like to split by this character in what is returned, but I've been unsuccessful with below.

text.split(//)

How can I split by this character?

Body:
These will match any non ASCII character:

[^\x00-\x7F] or [^[:ascii:]].

As noted by @engineersmnky this may not be the most ideal solution if the data you are parsing could contain more unrecognized characters.

Use this regex if you want to split only the  character:

[\uF0B7]


问:
Subsonic load objects by a list of ids
Is it possible to load objects by a list of ids using subsonic ActiveRecord?
My code looks like:

```<code>IList<Video> videos = Video.Find(v => videoIds.Contains(v.ID));
</code>```

I get an exception: The method 'Contains' is not supported

Do I do something wrong ... or I hit one of subsonic's limitations?

Thanks, Radu

答:
This is the one-liner I believe you where looking for.

var colMatchingVideos = Video.Find( objVideo => colVideoIds.Any( iVideoId => objVideo.ID == iVideoId).ToList();

Also I would strongly advise you avoid using string literals for columns, instead you could use Video.Columns.Id or expressions Where( o => o.Id).  This would ensure that if you change your column names in the Database a compile time exception will occur.  Help's a lot with maintainability.

Title: Subsonic load objects by a list of ids

Body:
Is it possible to load objects by a list of ids using subsonic ActiveRecord?
My code looks like:

IList<Video> videos = Video.Find(v => videoIds.Contains(v.ID));

I get an exception: The method 'Contains' is not supported

Do I do something wrong ... or I hit one of subsonic's limitations?

Thanks, Radu


问:
(PureScript) How to create a Union of two separately defined rows of effects
I'm essentially needing to know how to write a function like this...

```<code>joinCommands :: forall e1 e2 e3
   . Union e1 e2 e3
  => Eff e1 Unit
  -> Eff e2 Unit
  -> Eff e3 Unit
joinCommands fn1 fn2 = do
  fn1
  fn2
</code>```

Which doesn't work.  I get this error:

[PureScript] Could not match kind

```<code>Control.Monad.Eff.Effect
</code>```

with kind

```<code>Type
</code>```

More specifically, what I'm trying to do is combine two Arrays of user-supplied functionality.  That is one part of the codebase (user supplied) returns Array (Eff e1 Unit) and another part (also user supplied) returns Array (Eff e2 Unit).  And at the application's entrypoint (the "core" unaccessable to the user) those two sets need to combined so they can be run together.  So really, I'm trying to write a function of type Array (Eff e1 Unit) -> Array (Eff e2 Unit) -> Array (Eff e3 Unit) where e3 unites all the effects of e1 and e2.

答:
I figured it out.  For the general case, I just needed  to specific that each Eff has a type that is compatiable with each other (not necessarily the same).

```<code>joinCommands :: forall e. Eff e Unit -> Eff e Unit -> Eff e Unit
joinCommands fn1 fn2 = do
  fn1
  fn2
</code>```

For the specific case, the answer is the same.  The function signature would be forall e. Array (Eff e Unit) -> Array (Eff e Unit) -> Array (Eff e Unit) and the compiler can work out that the first set of Effs is compatible with the second set.

So if you had...

```<code>type Commands e = Array (Eff e Unit)
a :: forall e. Commands (random :: RANDOM | e)
a = []

b :: forall e. Commands (now :: NOW | e)
b = []

c :: forall e. Commands e -> Commands e -> Commands e
c = a <> b
</code>```

... you can call c a b even though a and b both have different explicit effects.

Body:
I'm essentially needing to know how to write a function like this...

joinCommands :: forall e1 e2 e3
   . Union e1 e2 e3
  => Eff e1 Unit
  -> Eff e2 Unit
  -> Eff e3 Unit
joinCommands fn1 fn2 = do
  fn1
  fn2

Which doesn't work.  I get this error:

[PureScript] Could not match kind

Control.Monad.Eff.Effect

with kind

Type

More specifically, what I'm trying to do is combine two Arrays of user-supplied functionality.  That is one part of the codebase (user supplied) returns Array (Eff e1 Unit) and another part (also user supplied) returns Array (Eff e2 Unit).  And at the application's entrypoint (the "core" unaccessable to the user) those two sets need to combined so they can be run together.  So really, I'm trying to write a function of type Array (Eff e1 Unit) -> Array (Eff e2 Unit) -> Array (Eff e3 Unit) where e3 unites all the effects of e1 and e2.

Body:
I figured it out.  For the general case, I just needed  to specific that each Eff has a type that is compatiable with each other (not necessarily the same).

joinCommands :: forall e. Eff e Unit -> Eff e Unit -> Eff e Unit
joinCommands fn1 fn2 = do
  fn1
  fn2

For the specific case, the answer is the same.  The function signature would be forall e. Array (Eff e Unit) -> Array (Eff e Unit) -> Array (Eff e Unit) and the compiler can work out that the first set of Effs is compatible with the second set.

So if you had...

type Commands e = Array (Eff e Unit)
a :: forall e. Commands (random :: RANDOM | e)
a = []

b :: forall e. Commands (now :: NOW | e)
b = []

c :: forall e. Commands e -> Commands e -> Commands e
c = a <> b

... you can call c a b even though a and b both have different explicit effects.


问:
How to print an array in descending order?
Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how. </p>

```<code>#include <iostream>

using namespace std;

void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);

int main()
{
    int n;
    cin>>n;
    int arr[n];
    fillArray(arr,n);
    printArray(arr,n);
    findSum(arr,n);

    return 0;
}

void fillArray(int arr[], int &n)
{
    int j=1;
    for(int i=0;i<n;i++)
    {
        if(j%2==1)
            arr[i]=j;
        else
            i--;
        j++;
    }
}

void printArray(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<", ";
    }
}

void findSum(int arr[], int &n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum=sum+arr[i];
    }
}
</code>```

答:
You can simply use a sort function. There is one included with the algorithm header.

```<code>#include <algorithm> // this goes at the top

void printArray(int arr[], int n)
{
  sort(arr, arr+n, [](int x, int y){return y<x;});

  for(int i=0;i<n;i++)
    cout << arr[i] << endl;
}
</code>```

the [](int x, int y){return y<x;} part is just to make it descending. Normally it is y>x, at which point you can just omit the third parameter

Here is a repl:
https://repl.it/JQor/0

Body:
Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how.

#include <iostream>

using namespace std;

void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);

int main()
{
    int n;
    cin>>n;
    int arr[n];
    fillArray(arr,n);
    printArray(arr,n);
    findSum(arr,n);

    return 0;
}

void fillArray(int arr[], int &n)
{
    int j=1;
    for(int i=0;i<n;i++)
    {
        if(j%2==1)
            arr[i]=j;
        else
            i--;
        j++;
    }
}

void printArray(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<", ";
    }
}

void findSum(int arr[], int &n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum=sum+arr[i];
    }
}

Body:
You can simply use a sort function. There is one included with the algorithm header.

#include <algorithm> // this goes at the top

void printArray(int arr[], int n)
{
  sort(arr, arr+n, [](int x, int y){return y<x;});

  for(int i=0;i<n;i++)
    cout << arr[i] << endl;
}

the [](int x, int y){return y<x;} part is just to make it descending. Normally it is y>x, at which point you can just omit the third parameter

Here is a repl:
https://repl.it/JQor/0


问:
How to run SQL files in a directory in order by file name in PSQL
Sort of like this question: Run all SQL files in a directory

I have files like: V1__some_migration.sql, V2__some_other_one.sql, etc

I was wondering how I could loop through and import these in some bash script based on the file name (bonus points if you know a way that works both on UNIX [OS X] and Linux [Ubuntu])

答:
Loop through:</p>

```<code>YOUR_DIR="/path/to/your/directory"
for file in $YOUR_DIR/*; do
    psql <insert your options here> "${file}"
done
</code>```

Body:
Loop through:

YOUR_DIR="/path/to/your/directory"
for file in $YOUR_DIR/*; do
    psql <insert your options here> "${file}"
done


问:
How to get value entered in search box In Datatables
How to get value entered in search box In Datatables.
Is there a way to get value entered in search box in Data Tables? </p>

答:
Yes, there is. You call the search method without an argument to get the search term

var query = dataTable.search()

https://datatables.net/reference/api/search()

Get the currently applied global search. If there is more than one
table in the API's context, the search term of the first table will be
returned. Use table() if you require the search term of a different
table in the API's context.


问:
Upgrade / Uninstall NodeJS on Windows
Somehow node version v0.12.2 got installed on my Windows machine and I'd like to upgrade to a newer version, however, it is not in the "Add or Remove Programs" menu.

When I try to install node from the Windows MSI, I get the standard windows 1603 error (below), which I am assuming means windows thinks that this application is already installed.

MSI (s) (64:84): Windows Installer installed the
  product. Product Name: Node.js. Product Version: 6.11.0. Product
  Language: 1033. Manufacturer: Node.js Foundation. Installation success
  or error status: 1603.

Any ideas?  I've tried lots of things like this and this with no luck.

I am trying to install an npm package that depends on a higher version of node and striking out.

答: I installed Node Version Manager for Windows and it recognized this installation of Node. I was able to install alternate versions of node from here.  It also recognized my current installation of node and was able to facilitate an "uninstallation" without going through the windows "add/remove programs" feature. </p>

Title: Upgrade / Uninstall NodeJS on Windows


问:
Macros script Excel, filling in blanks with NULLS, error 400
All i'm trying to do is fill in NULL in the cells that are blank.

source code:

```<code>Sub fillNULLs()

Dim count As Integer
count = 0

Dim col As Integer
col = 2

While count < 23403

If (Cells(count, col) = "") Then

Cells(count, col) = "Null"

End If

count = count + 1

Wend

End Sub
</code>```

I run the macros and i get a 400 and an okay button. Can anyone spot the issue

答: I guess that count should be 1 at first before While loop</p>

Body:
All i'm trying to do is fill in NULL in the cells that are blank.

source code:

Sub fillNULLs()

Dim count As Integer
count = 0

Dim col As Integer
col = 2

While count < 23403

If (Cells(count, col) = "") Then

Cells(count, col) = "Null"

End If

count = count + 1

Wend

End Sub

I run the macros and i get a 400 and an okay button. Can anyone spot the issue


问:
How do I look up a value in a hash based on an array of keys?
With Ruby (2.4), I want to extend the core hash functionality to search for keys based on an array and return the value from the first element that can be found from that array.  I have this in my lib/core_ext/hash_with_indifferent_access.rb file ...

```<code>class CaseInsensitiveHash < HashWithIndifferentAccess
  # This method shouldn't need an override, but my tests say otherwise.
  def [](key)
    if key.kind_of?(Array)
      find_by_arr(arr)
    else
      super convert_key(key)
    end
  end

  protected

  def convert_key(key)
    key.respond_to?(:downcase) ? key.downcase : key
  end

  def find_by_arr(arr)
    arr.inject(self){|h, k| h.to_h[k]}
  end

end
</code>```

However, it is not working as expected. In my code below, the search 'h[["a", "b"]]' should produce "1", because the first element, "a", is a key in my hash.

```<code>2.4.0 :001 > h = {"a" => 1, "b" => 2}
 => {"a"=>1, "b"=>2}
2.4.0 :002 > h["a"]
 => 1
2.4.0 :003 > h[["a", "b"]]
 => nil
</code>```

How do I modify my code so that I can pass in an array as a key to a hash and it will start searching for values iteratively by each element in the array?

答:
You've almost got it, but the problem is that h = { ... } creates a plain-old Hash, not the kind you've added these methods to.

The first fix is to do this:

```<code>h = CaseInsensitiveHash["a" => 1, "b" => 2]
</code>```

Then you get the right type of object and your method actually runs.

There's a typo in your [] method which can be corrected:

```<code>def [](key)
  case key
  when Array
    find_by_arr(key)
  else
    super convert_key(key)
  end
end
</code>```

Your reference to arr doesn't work because that's not defined.

The find_by_arr method also returns the last match, not the first. This can be fixed:

```<code>def find_by_arr(arr)
  self[arr.first { |key| self[key] }]
end
</code>```

Body:
With Ruby (2.4), I want to extend the core hash functionality to search for keys based on an array and return the value from the first element that can be found from that array.  I have this in my lib/core_ext/hash_with_indifferent_access.rb file ...

class CaseInsensitiveHash < HashWithIndifferentAccess
  # This method shouldn't need an override, but my tests say otherwise.
  def [](key)
    if key.kind_of?(Array)
      find_by_arr(arr)
    else
      super convert_key(key)
    end
  end

  protected

  def convert_key(key)
    key.respond_to?(:downcase) ? key.downcase : key
  end

  def find_by_arr(arr)
    arr.inject(self){|h, k| h.to_h[k]}
  end

end

However, it is not working as expected. In my code below, the search 'h[["a", "b"]]' should produce "1", because the first element, "a", is a key in my hash.

2.4.0 :001 > h = {"a" => 1, "b" => 2}
 => {"a"=>1, "b"=>2}
2.4.0 :002 > h["a"]
 => 1
2.4.0 :003 > h[["a", "b"]]
 => nil

How do I modify my code so that I can pass in an array as a key to a hash and it will start searching for values iteratively by each element in the array?

Body:
You've almost got it, but the problem is that h = { ... } creates a plain-old Hash, not the kind you've added these methods to.

The first fix is to do this:

h = CaseInsensitiveHash["a" => 1, "b" => 2]

Then you get the right type of object and your method actually runs.

There's a typo in your [] method which can be corrected:

def [](key)
  case key
  when Array
    find_by_arr(key)
  else
    super convert_key(key)
  end
end

Your reference to arr doesn't work because that's not defined.

The find_by_arr method also returns the last match, not the first. This can be fixed:

def find_by_arr(arr)
  self[arr.first { |key| self[key] }]
end


问:
How can I force NgbCarousel to loop to first after I goes to last picture of slideshow
How can I force NgbCarousel to loop to first picture after It goes to last picture of slideshow ?</p>

答:
It's not clear what is exactly being asked, but if you are wanting the NgbCarousel to be able to navigate to the first slide/image when on the last either by clicking on the next arrow or on it's own when an interval is set, you'd need to have property wrap set to true. From the documentation:

wrap Type: boolean Default value: true — initialized from NgbCarouselConfig
  service Whether can wrap from the last to the first slide.

This can be set on either the the tag like <ngb-carousel wrap="true"> or in a global config using NgbCarouselConfig. It defaults to true.

Here is a Plunker demonstrating it in action.

Hopefully that helps!


问:
how to get the data added verification message at the same page of form
i have this page named courses.php contain the form below (iam using bootstrap):

```<code><form class="" action="coumysql.php" method="post" style="margin-left:100px;">
<input type="hidden" name="act" value="add"/>
    <div class="form-group" >
        <label class="control-label" for="course_id">Course Code:</label>
        <div class="" >
            <div class="col-xs-3">
                <input type="text" class="form-control" id="email" placeholder="" name="course_id" required="">
            </div>
        </div>
    </div> <br>
        <br>
    <div class="form-group">
        <label class="control-label " for="course_name">Course Name:</label>
            <div class="">
                <div class="col-xs-3">
                    <input type="text" class="form-control" id="pwd" placeholder="" name="course_name" required="">
                </div>
            </div>
    </div><br>

        <br>
            <div class="form-group" style="display: inline;">
      <div class="col-sm-offset-1 "><br>
        <button type="submit" class="btn btn-default">Add Subject</button>
      </div>
    </div>
</form>
</code>```

the form processed at the page named coumysql.php

```<code><?php
include 'connect.php';

if(isset($_POST['act'])){
    if($_POST['act'] == 'add'){
        if ($mysqli->query("INSERT INTO courses (course_id, course_name) VALUES ('".$_POST['course_id']."', '".$_POST['course_name']."');")) {
    echo "data added";
}
    }else if($_POST['act'] == 'delete'){
        if ($mysqli->query("DELETE FROM courses WHERE course_id= ('".$_POST['course_id']."');")) {
    echo "data deleted";
}
    }

}

?>
</code>```

i want the message "data added" or "data deleted" to be shown in courses.php after successfully form submitted to database

答:
You could create a session() variable and pass it to the view. Like so:

```<code> <?php
include 'connect.php';
session_start();

if(isset($_POST['act'])){
    if($_POST['act'] == 'add'){
        if ($mysqli->query("INSERT INTO courses (course_id, course_name) VALUES ('".$_POST['course_id']."', '".$_POST['course_name']."');")) {
            $_SESSION['insert']="Data has been successfully created!";
             header('Location: courses.php');
}
    }else if($_POST['act'] == 'delete'){
        if ($mysqli->query("DELETE FROM courses WHERE course_id= ('".$_POST['course_id']."');")) {
            $_SESSION['delete']="Data has been successfully deleted!";
            header('Location: courses.php');

}
    }

}

?>
</code>```

Then catch them on courses.php like so:

```<code><?php
session_start();

$added = $_SESSION['insert'];
$deleted=$_SESSION['delete'];

?>

<form class="" action="coumysql.php" method="post" style="margin-left:100px;">
<input type="hidden" name="act" value="add"/>
    <div class="form-group" >
        <label class="control-label" for="course_id">Course Code:</label>
        <div class="" >
            <div class="col-xs-3">
                <input type="text" class="form-control" id="email" placeholder="" name="course_id" required="">
            </div>
        </div>
    </div> <br>
        <br>
    <div class="form-group">
        <label class="control-label " for="course_name">Course Name:</label>
            <div class="">
                <div class="col-xs-3">
                    <input type="text" class="form-control" id="pwd" placeholder="" name="course_name" required="">
                </div>
            </div>
    </div><br>

        <br>
            <div class="form-group" style="display: inline;">
      <div class="col-sm-offset-1 "><br>
        <button type="submit" class="btn btn-default">Add Subject</button>
      </div>

            <?php
             if(!empty($added)){
                  ?>
                <div class="alert aler-success"><p><?php echo $added;?></p></div>
             <?php }elseif(!empty($deleted)){
                 ?>
                <div class="alert aler-success"><p><?php echo $deleted;?></p></div>
                <?php
             }?>

    </div>
</form>
</code>```

Note: u can customize div tag as u want..

Body:
i have this page named courses.php contain the form below (iam using bootstrap):

<form class="" action="coumysql.php" method="post" style="margin-left:100px;">
<input type="hidden" name="act" value="add"/>

        Course Code:

                <input type="text" class="form-control" id="email" placeholder="" name="course_id" required="">

        Course Name:

                    <input type="text" class="form-control" id="pwd" placeholder="" name="course_name" required="">

        <button type="submit" class="btn btn-default">Add Subject</button>

</form>

the form processed at the page named coumysql.php

<?php
include 'connect.php';

if(isset($_POST['act'])){
    if($_POST['act'] == 'add'){
        if ($mysqli->query("INSERT INTO courses (course_id, course_name) VALUES ('".$_POST['course_id']."', '".$_POST['course_name']."');")) {
    echo "data added";
}
    }else if($_POST['act'] == 'delete'){
        if ($mysqli->query("DELETE FROM courses WHERE course_id= ('".$_POST['course_id']."');")) {
    echo "data deleted";
}
    }

}

?>

i want the message "data added" or "data deleted" to be shown in courses.php after successfully form submitted to database

Body:
You could create a session() variable and pass it to the view. Like so:

 <?php
include 'connect.php';
session_start();

if(isset($_POST['act'])){
    if($_POST['act'] == 'add'){
        if ($mysqli->query("INSERT INTO courses (course_id, course_name) VALUES ('".$_POST['course_id']."', '".$_POST['course_name']."');")) {
            $_SESSION['insert']="Data has been successfully created!";
             header('Location: courses.php');
}
    }else if($_POST['act'] == 'delete'){
        if ($mysqli->query("DELETE FROM courses WHERE course_id= ('".$_POST['course_id']."');")) {
            $_SESSION['delete']="Data has been successfully deleted!";
            header('Location: courses.php');

}
    }

}

?>

Then catch them on courses.php like so:

<?php
session_start();

$added = $_SESSION['insert'];
$deleted=$_SESSION['delete'];

?>

<form class="" action="coumysql.php" method="post" style="margin-left:100px;">
<input type="hidden" name="act" value="add"/>
    <div class="form-group" >
        <label class="control-label" for="course_id">Course Code:</label>
        <div class="" >
            <div class="col-xs-3">
                <input type="text" class="form-control" id="email" placeholder="" name="course_id" required="">
            </div>
        </div>
    </div> <br>
        <br>
    <div class="form-group">
        <label class="control-label " for="course_name">Course Name:</label>
            <div class="">
                <div class="col-xs-3">
                    <input type="text" class="form-control" id="pwd" placeholder="" name="course_name" required="">
                </div>
            </div>
    </div><br>

        <br>
            <div class="form-group" style="display: inline;">
      <div class="col-sm-offset-1 "><br>
        <button type="submit" class="btn btn-default">Add Subject</button>
      </div>

            <?php
             if(!empty($added)){
                  ?>
                <div class="alert aler-success"><p><?php echo $added;?></p></div>
             <?php }elseif(!empty($deleted)){
                 ?>
                <div class="alert aler-success"><p><?php echo $deleted;?></p></div>
                <?php
             }?>

    </div>
</form>

Note: u can customize div tag as u want..


问:
Background does not change onclick function
what's wrong with my code? For some reason my function load() does not change .firstDiv background?

I can't find any mistakes.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }</code>```

  <button onclick="load()">Change background</button>

```

答:
In the load() function, need to change it so that it uses the first element of getElementsByClassName since it returns multiple elements.

```<code>document.getElementsByClassName("firstDiv")[0]...
</code>```

Body:
what's wrong with my code? For some reason my function load() does not change .firstDiv background?

I can't find any mistakes.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }

  <button onclick="load()">Change background</button>

Body:
In the load() function, need to change it so that it uses the first element of getElementsByClassName since it returns multiple elements.

document.getElementsByClassName("firstDiv")[0]...


问:
Capture Flash / Flex redraw DisplayObject event?
I'm trying to capture the redraw event for some MovieClip / Sprite objects that are in a Scroll area.

Ideally, should be able to capture the event when Flash Player itself redraws the objects as can be seen with "Show Redraw Regions" in FP Debug.

I've tried to use the Event.RENDER to capture this, but it even fires when the object is not visible / redrawn.

Is there any native flash event that can help me capture this accurately?

TIA!

答:
So far, looks like there is no way to capture the Flash Player's redraw event.

However, to solve this specific problem I used
- On the display object that I manually redraw, check the bounds with object.transform.pixelBounds

Use Event.RENDER to fire the event so each objects redraws as needed if they are within the display area as per bounds.

Not perfect, but does the job. Wish FP had this feature for people who do detail level work.


问:
How would a compiler optimize temporary objects away?
I am reading about move semantics and this code is given:

```<code>#include <iostream>

using namespace std;

vector<int> doubleValues (const vector<int>& v)
{
    vector<int> new_values;
    new_values.reserve(v.size());
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr; ++itr )
    {
        new_values.push_back( 2 * *itr );
    }
    return new_values;
}

int main()
{
    vector<int> v;
    for ( int i = 0; i < 100; i++ )
    {
        v.push_back( i );
    }
    v = doubleValues( v );
}
</code>```

So the author states that after the return of doubleValues, there could be up to two copies happening

one into a temporary object to be returned, and a second when the
  vector assignment operator runs on the line v = doubleValues( v );

He also states that the first copy may be optimized away.

Here is what I do not get:

What does he mean when saying "one into a temporary object to be returned"? Isn't it a temporary object that is returned by the function? If so, I do not see why anything should be copied to another temporary object.

He states that this temporary object could be optimized away. How would a temporary object be optimized away, like what is considered an optimization?

答:
It is important to understand that what a compiler must do and what a compiler can do are as different things as what a piece of code formally means and what it really means.

Take a much smaller and easier example, right from the code snippet you posted: i++.

What your code formally means is: Make a copy of i, then increment i, and have the expression have the value of the copy that you made previously.

What your code really means is: Increment i and screw the rest (because I'm not using the result).

What the compiler must do is implement exactly the (externally visible) semantics of the "what your code formally means" part. None more and none less.

What the compiler can do is incrementi and screw the rest (because nobody can tell the difference).

Generally, a compiler may make any changes it likes based on the "as if" rule, which, sloppily means that as long as the externally observeable behaviour stays the same, nobody cares. Move semantics are a means to bend the rules a bit further, both implicitly and explicitly.

When you move an object rather than copying it, you are basically cheating. However, the difference between "cheating" and "magic" is whether you're being caught or not (just like the difference between "genius" and "madness" is defined only by success).

You're abusing an object that is going to be destroyed the next instant anyway, claiming it's a copy when it is not. However, nobody will notice because the moved-from object is a rvalue, i.e. it has no name (and thus isn't otherwise accessible) and is destroyed right away, too. On the other hand, the new object that you present to the world which isn't new at all, but it is nevertheless a perfectly good object by all means (the original one!). That's the whole trick.

About your second question: Your doubleValues function takes a std::vector by constant reference. That's not a copy, it's as cheap as a pointer. However, then you copy all the values into a new object new_values.

Then, you return that object by value, which means you formally make a second copy, and finally you invoke the assignment operator of std::vector, which, actually, is even a third copy.

Formally, that is. An optimizing compiler may, and hopefully will, optimize that away (NRVO).

Used to be compilers would only do that with unnamed temporaries, but that was like... 10 years ago. Nowadays, named return value optimization usually/often "just works", luckily.

Under some conditions (although not in your example), the compiler is even required to perform copy elision per the latest standard.

Body:
I am reading about move semantics and this code is given:

#include <iostream>

using namespace std;

vector<int> doubleValues (const vector<int>& v)
{
    vector<int> new_values;
    new_values.reserve(v.size());
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr; ++itr )
    {
        new_values.push_back( 2 * *itr );
    }
    return new_values;
}

int main()
{
    vector<int> v;
    for ( int i = 0; i < 100; i++ )
    {
        v.push_back( i );
    }
    v = doubleValues( v );
}

So the author states that after the return of doubleValues, there could be up to two copies happening

one into a temporary object to be returned, and a second when the
  vector assignment operator runs on the line v = doubleValues( v );

He also states that the first copy may be optimized away.

Here is what I do not get:

What does he mean when saying "one into a temporary object to be returned"? Isn't it a temporary object that is returned by the function? If so, I do not see why anything should be copied to another temporary object.

He states that this temporary object could be optimized away. How would a temporary object be optimized away, like what is considered an optimization?


问:
XML IE11 - Can't Extract Data
So I'm trying to extract data from and XML file using jQuery and everything is working well on Chrome and Firefox and like usual there's a problem with IE. I looked up the answers here on stackoverflow and one seemed like it's working but still returning undefined.

I'm getting the file using ajax. Here is how I'm doing it:

```<code>$('<div>' + xml + '</div>').find('videoNews');
</code>```

Now I look in the dev console and I keep getting context: undefined.

In Chrome or FF, I do it this way and it's working fine as expected:

```<code>$(xml).find('videoNews');
</code>```

Anyone has a solution to that frustrating problem?

Thank you!

答:
I had the same problem and scoured the internet and also found that .innerHTML doesn't work in IE11 and also that it's a quasi hack anyway since it shouldn't be used to read XML nodes.

I didn't like the idea of using different solutions depending on what browser I am using but those are most of the solutions I found. However, one guy on youtube suggested to use .firstChild.data to read a given node. I've implemented that in my own project and it seems to be working fine. I don't know why this method isn't used and suggested more.

Title: XML IE11 - Can't Extract Data

Body:
So I'm trying to extract data from and XML file using jQuery and everything is working well on Chrome and Firefox and like usual there's a problem with IE. I looked up the answers here on stackoverflow and one seemed like it's working but still returning undefined.

I'm getting the file using ajax. Here is how I'm doing it:

$('
' + xml + '
').find('videoNews');

Now I look in the dev console and I keep getting context: undefined.

In Chrome or FF, I do it this way and it's working fine as expected:

$(xml).find('videoNews');

Anyone has a solution to that frustrating problem?

Thank you!


问:
Q: Bash script infinite loop causing ffmpeg spam
Can't seem to figure this one out... I have a set up NGINX server with the excellent RTMP extension and everything is working fine. However, I'm trying to restream/push a copy of a couple specific streams that need to be streamed in another RTMP stream application (specifically, these streams are streamed to application "static" but in the current situation also need to be pushed over to "live"). The process of restreaming/pushing a stream in NGINX-RTMP is relatively simple, however, in my case I need to selectively push a couple of streams instead of every stream being streamed to the application "static".

Idea is to have NGINX-RTMP pass the stream name off to the bash script, which then does the restreaming without interrupting any other streams or services.

With some success, I've tried doing this by creating a bash scrip..

The relevant NGINX config bit that runs the bash script is:

```<code>exec_publish /etc/nginx/rtmp_conf.d/stream_id.sh $name;
</code>```

I tried it with an "if / else"

```<code>if [ $1 == "stream_name_1" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
elif [ $1 == "stream_name_2" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
elif [ $1 == "stream_name_3" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
elif [ $1 == "stream_name_4" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
else
        echo "FAIL" >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
        exit
fi
</code>```

And I tried it with Switches

```<code>case "$1" in
        "stream_name_1")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
        ;;
        "stream_name_2")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
        ;;
        "stream_name_3")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
        ;;
        "stream_name_4")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
        ;;
        echo "FAIL " >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
esac
</code>```

Problem with both is that they both end up spamming a ton of ffmpeg processes ... and I don't know why - I've tried changing the code but I either end up with ffmpeg not firing at all or spamming the server.

答:
It turns out that in my situation ffmpeg didn't like the argument flag "-vcodec  x264" (weird because the source stream is encoded with x264, but oh well), changing it to use "copy" audio and video codec fixed my problem - ffmpeg doesn't spawn tens of processes, each trying to use abnormal resource amounts, anymore.

The examples for the working code in my case is:

To initiate the bash scripts I'm placing this in my NGINX config (which passes the incoming stream name to the bash script as by design of the RTMP module):

```<code> exec_publish /etc/nginx/rtmp_conf.d/stream_id.sh $name;
</code>```

Using switches:

```<code>#!/bin/bash
case "$1" in
    "stream_name_1")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
    ;;
    "stream_name_2")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
    ;;
    "stream_name_3")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
    ;;
    "stream_name_4")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
    ;;
esac
</code>```

And using If/Else:

```<code>#!/bin/bash
if [ $1 == "stream_name_1" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
elif [ $1 == "stream_name_2" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
elif [ $1 == "stream_name_3" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
else [ $1 == "stream_name_4" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
fi
</code>```

Body:
Can't seem to figure this one out... I have a set up NGINX server with the excellent RTMP extension and everything is working fine. However, I'm trying to restream/push a copy of a couple specific streams that need to be streamed in another RTMP stream application (specifically, these streams are streamed to application "static" but in the current situation also need to be pushed over to "live"). The process of restreaming/pushing a stream in NGINX-RTMP is relatively simple, however, in my case I need to selectively push a couple of streams instead of every stream being streamed to the application "static".

Idea is to have NGINX-RTMP pass the stream name off to the bash script, which then does the restreaming without interrupting any other streams or services.

With some success, I've tried doing this by creating a bash scrip..

The relevant NGINX config bit that runs the bash script is:

exec_publish /etc/nginx/rtmp_conf.d/stream_id.sh $name;

I tried it with an "if / else"

if [ $1 == "stream_name_1" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
elif [ $1 == "stream_name_2" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
elif [ $1 == "stream_name_3" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
elif [ $1 == "stream_name_4" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
else
        echo "FAIL" >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
        exit
fi

And I tried it with Switches

case "$1" in
        "stream_name_1")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
        ;;
        "stream_name_2")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
        ;;
        "stream_name_3")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
        ;;
        "stream_name_4")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
        ;;
        echo "FAIL " >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
esac

Problem with both is that they both end up spamming a ton of ffmpeg processes ... and I don't know why - I've tried changing the code but I either end up with ffmpeg not firing at all or spamming the server.

Body:
It turns out that in my situation ffmpeg didn't like the argument flag "-vcodec  x264" (weird because the source stream is encoded with x264, but oh well), changing it to use "copy" audio and video codec fixed my problem - ffmpeg doesn't spawn tens of processes, each trying to use abnormal resource amounts, anymore.

The examples for the working code in my case is:

To initiate the bash scripts I'm placing this in my NGINX config (which passes the incoming stream name to the bash script as by design of the RTMP module):

 exec_publish /etc/nginx/rtmp_conf.d/stream_id.sh $name;

Using switches:

#!/bin/bash
case "$1" in
    "stream_name_1")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
    ;;
    "stream_name_2")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
    ;;
    "stream_name_3")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
    ;;
    "stream_name_4")
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
    ;;
esac

And using If/Else:

#!/bin/bash
if [ $1 == "stream_name_1" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
elif [ $1 == "stream_name_2" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
elif [ $1 == "stream_name_3" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
else [ $1 == "stream_name_4" ]; then
    ffmpeg -re -i rtmp://127.0.0.1:2000/static/$1 -vcodec copy -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
fi


问:
JavaFX Use Chart Legend to toggle show/hide Series possible?
Is it possible to use a chart's legend to toggle show/hide a series?

I got a LineChart with a legend and there are too many Series so you can't read out the information well. I was wondering if there is a possibility to use the legend to toggle the series to show/hide?

Most of the names of my Series are pretty long and it looks very weird if they are written twice once in the legend so you know which color belongs to which Series and a second time besides a CheckBox to toggle them.

Edit1: Maybe I was unclear, even if there is no built in function for this, I could use some input for how a workaround could look like, because I can't come up with anything.

答:
Here is how I solved this - I am not aware of any simpler built-in solution

```<code>LineChart<Number, Number> chart;

for (Node n : chart.getChildrenUnmodifiable()) {
    if (n instanceof Legend) {
        Legend l = (Legend) n;
        for (Legend.LegendItem li : l.getItems()) {
            for (XYChart.Series<Number, Number> s : chart.getData()) {
                if (s.getName().equals(li.getText())) {
                    li.getSymbol().setCursor(Cursor.HAND); // Hint user that legend symbol is clickable
                    li.getSymbol().setOnMouseClicked(me -> {
                        if (me.getButton() == MouseButton.PRIMARY) {
                            s.getNode().setVisible(!s.getNode().isVisible()); // Toggle visibility of line
                            for (XYChart.Data<Number, Number> d : s.getData()) {
                                if (d.getNode() != null) {
                                    d.getNode().setVisible(s.getNode().isVisible()); // Toggle visibility of every node in the series
                                }
                            }
                        }
                    });
                    break;
                }
            }
        }
    }
}
</code>```

You need to run this code once on your chart (LineChart in this example, but you can probably adapt it to any other chart). I find the Legend child, and then iterate over all of its' items. I match the legend item to the correct series based on the name - from my experience they always match, and I couldn't find a better way to match them. Then it's just a matter of adding the correct event handler to that specific legend item.

Body:
Here is how I solved this - I am not aware of any simpler built-in solution

LineChart<Number, Number> chart;

for (Node n : chart.getChildrenUnmodifiable()) {
    if (n instanceof Legend) {
        Legend l = (Legend) n;
        for (Legend.LegendItem li : l.getItems()) {
            for (XYChart.Series<Number, Number> s : chart.getData()) {
                if (s.getName().equals(li.getText())) {
                    li.getSymbol().setCursor(Cursor.HAND); // Hint user that legend symbol is clickable
                    li.getSymbol().setOnMouseClicked(me -> {
                        if (me.getButton() == MouseButton.PRIMARY) {
                            s.getNode().setVisible(!s.getNode().isVisible()); // Toggle visibility of line
                            for (XYChart.Data<Number, Number> d : s.getData()) {
                                if (d.getNode() != null) {
                                    d.getNode().setVisible(s.getNode().isVisible()); // Toggle visibility of every node in the series
                                }
                            }
                        }
                    });
                    break;
                }
            }
        }
    }
}

You need to run this code once on your chart (LineChart in this example, but you can probably adapt it to any other chart). I find the Legend child, and then iterate over all of its' items. I match the legend item to the correct series based on the name - from my experience they always match, and I couldn't find a better way to match them. Then it's just a matter of adding the correct event handler to that specific legend item.