问:
Error in visual studio setup project-Could not load file or assembly log4net or one of it's dependencies. The system cannot find the file specified
I know there are lots of thread and question out there. So, Please let me clarify the situation here.

I am working on Ms-Word addin using visual c#, vsto and add-in express framework. I added a log4net assmeble from nuget package manager.
When I try to build or debug the project. It works just fine.

But just when I try to create setup project using add-in express extension (right click on project > add-in express> create setup project). It gives me an error (in a popup) just after the click

Could not load file or assembly "log4net, Version=2.0.8.0
  Cultural=neutral,PublicKeyToken=669e0ddf0bb1aa2a" or one of it's
  dependencies. The system cannot find the file specified.

I have checked the version, multiple references of log4net.dll in my project, path in package.config and in the project.csproj file. All these things are of no issue.

When I try to create a fresh similar project from scratch add log4net. it worked. But not with the current project.
What would be the possible cause?

I would appreciate any help. I am really got stuck at this.

Following are the configuration :

Project target framework is ".Net framework 4"

package.config

```<code><packages>
  <package id="Apache.NMS" version="1.7.1" targetFramework="net40" />
  <package id="Apache.NMS.ActiveMQ" version="1.7.2" targetFramework="net40" />
  <package id="log4net" version="2.0.8" targetFramework="net40" />
  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net40" />
</packages>
</code>```

app.config

```<code><configSections>
...
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL" />
...
</configSections>
<log4net>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <param name="File" value="logFile.log"/>
        <param name="DatePattern" value="'logFile_'yyyy-MM-dd'.log'"/>
        <preserveLogFileNameExtension value="true" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="5" />
        <maximumFileSize value="5MB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %level %logger - %message %newline %exception" />
        </layout>
      </appender>
      <root>
        <level value="INFO"/>
        <appender-ref ref="RollingFileAppender"/>
      </root>
    </log4net>
</code>```

Product.csproj

```<code><ItemGroup>
<Reference Include="Accessibility" />
<Reference Include="AddinExpress.MSO.2005, Version=8.2.4371.0, Culture=neutral, PublicKeyToken=4416dd98f0861965, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\..\..\..\Program Files (x86)\Add-in Express\Add-in Express for .NET\Bin\AddinExpress.MSO.2005.dll</HintPath>
</Reference>
<Reference Include="AddinExpress.OL.2005, Version=8.2.4371.2005, Culture=neutral, PublicKeyToken=e69a7e0f3592d2b8, processorArchitecture=MSIL" />
<Reference Include="AddinExpress.ToolbarControls.2005, Version=8.2.4371.2005, Culture=neutral, PublicKeyToken=16211aef6795d6cc, processorArchitecture=MSIL" />
<Reference Include="AddinExpress.WD.2005, Version=7.5.4072.2005, Culture=neutral, PublicKeyToken=e69a7e0f3592d2b8, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="ADXOLWizard.2005, Version=8.2.4371.2005, Culture=neutral, processorArchitecture=MSIL" />
<Reference Include="Apache.NMS">
  <HintPath>..\packages\Apache.NMS.1.7.1\lib\net40\Apache.NMS.dll</HintPath>
</Reference>
<Reference Include="Apache.NMS.ActiveMQ">
  <HintPath>..\packages\Apache.NMS.ActiveMQ.1.7.2\lib\net40\Apache.NMS.ActiveMQ.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
  <HintPath>..\packages\log4net.2.0.8\lib\net40-full\log4net.dll</HintPath>
  <Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Office.Interop.Outlook, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Office.Interop.Word, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Office.Tools.Word, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Vbe.Interop, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
  <HintPath>..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll</HintPath>
  <Private>True</Private>
</Reference>
<Reference Include="Office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Data" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.DirectoryServices.AccountManagement" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xaml" />
<Reference Include="System.Xml" />
<Reference Include="UIAutomationProvider" />
<Reference Include="WindowsBase" />
<Reference Include="WindowsFormsIntegration" />
</code>```

答:
I had this issue before. In my case the problem was that different versions of the same NuGet were used by different components. The solution was to add assembly binding, basically set up a mapping, saying "when any version of log4net is referenced from 0.0.0.0 up to 2.0.8.0, just use 2.0.8.0".

Try adding the following block in your app.config. If it's already there, ensure the versions are correct (when updating NuGet packages, sometimes it gets out of sync).

```<code><runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0" />
        </dependentAssembly>
        ...
    </assemblyBinding>
</runtime>
</code>```

Body:
I know there are lots of thread and question out there. So, Please let me clarify the situation here.

I am working on Ms-Word addin using visual c#, vsto and add-in express framework. I added a log4net assmeble from nuget package manager.
When I try to build or debug the project. It works just fine.

But just when I try to create setup project using add-in express extension (right click on project > add-in express> create setup project). It gives me an error (in a popup) just after the click

Could not load file or assembly "log4net, Version=2.0.8.0
  Cultural=neutral,PublicKeyToken=669e0ddf0bb1aa2a" or one of it's
  dependencies. The system cannot find the file specified.

I have checked the version, multiple references of log4net.dll in my project, path in package.config and in the project.csproj file. All these things are of no issue.

When I try to create a fresh similar project from scratch add log4net. it worked. But not with the current project.
What would be the possible cause?

I would appreciate any help. I am really got stuck at this.

Following are the configuration :

Project target framework is ".Net framework 4"

package.config

<packages>
  <package id="Apache.NMS" version="1.7.1" targetFramework="net40" />
  <package id="Apache.NMS.ActiveMQ" version="1.7.2" targetFramework="net40" />
  <package id="log4net" version="2.0.8" targetFramework="net40" />
  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net40" />
</packages>

app.config

<configSections>
...

...
</configSections>
<log4net>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <param name="File" value="logFile.log"/>
        <param name="DatePattern" value="'logFile_'yyyy-MM-dd'.log'"/>
        <preserveLogFileNameExtension value="true" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="5" />
        <maximumFileSize value="5MB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %level %logger - %message %newline %exception" />
        </layout>
      </appender>
      <root>
        <level value="INFO"/>
        <appender-ref ref="RollingFileAppender"/>
      </root>
    </log4net>

Product.csproj

<ItemGroup>
<Reference Include="Accessibility" />
<Reference Include="AddinExpress.MSO.2005, Version=8.2.4371.0, Culture=neutral, PublicKeyToken=4416dd98f0861965, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\..\..\..\Program Files (x86)\Add-in Express\Add-in Express for .NET\Bin\AddinExpress.MSO.2005.dll</HintPath>
</Reference>
<Reference Include="AddinExpress.OL.2005, Version=8.2.4371.2005, Culture=neutral, PublicKeyToken=e69a7e0f3592d2b8, processorArchitecture=MSIL" />
<Reference Include="AddinExpress.ToolbarControls.2005, Version=8.2.4371.2005, Culture=neutral, PublicKeyToken=16211aef6795d6cc, processorArchitecture=MSIL" />
<Reference Include="AddinExpress.WD.2005, Version=7.5.4072.2005, Culture=neutral, PublicKeyToken=e69a7e0f3592d2b8, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="ADXOLWizard.2005, Version=8.2.4371.2005, Culture=neutral, processorArchitecture=MSIL" />
<Reference Include="Apache.NMS">
  <HintPath>..\packages\Apache.NMS.1.7.1\lib\net40\Apache.NMS.dll</HintPath>
</Reference>
<Reference Include="Apache.NMS.ActiveMQ">
  <HintPath>..\packages\Apache.NMS.ActiveMQ.1.7.2\lib\net40\Apache.NMS.ActiveMQ.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
  <HintPath>..\packages\log4net.2.0.8\lib\net40-full\log4net.dll</HintPath>
  <Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Office.Interop.Outlook, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Office.Interop.Word, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Office.Tools.Word, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Vbe.Interop, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
  <HintPath>..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll</HintPath>
  <Private>True</Private>
</Reference>
<Reference Include="Office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
  <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Data" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.DirectoryServices.AccountManagement" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xaml" />
<Reference Include="System.Xml" />
<Reference Include="UIAutomationProvider" />
<Reference Include="WindowsBase" />
<Reference Include="WindowsFormsIntegration" />

Body:
I had this issue before. In my case the problem was that different versions of the same NuGet were used by different components. The solution was to add assembly binding, basically set up a mapping, saying "when any version of log4net is referenced from 0.0.0.0 up to 2.0.8.0, just use 2.0.8.0".

Try adding the following block in your app.config. If it's already there, ensure the versions are correct (when updating NuGet packages, sometimes it gets out of sync).

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0" />
        </dependentAssembly>
        ...
    </assemblyBinding>
</runtime>


来源: stackexchange

问:
Check if a string (char *) can be enumerated
I'm trying to find a way to check if a read-in char * can be represented as a number (with or without decimal places) or not.  Essentially I am asking, if I have a text file containing the following:

```<code>-1.9e-3
e9
1e9
1ee9
-1-.9e3
.9e3
.9.e3
</code>```

It would be able to recognize that line 1, line 3, and line 6 can be "enumerated" into valid numbers, whereas all of the other lines contain erroneous inputs.  I know this could be done with brute force, but there is potentially an unlimited number of possibilities that could be wrong.  It would be much easier if there was a function that read in the entire char * and can just say,  "Yes that string of characters can be represented as an actual number" or "No that string of characters cannot be turned into the number that it intends to be."

And by enumerated I mean that the string (char *) can be the number that it wishes to represent.

答:
Just try to convert it with strtold() and use the possibilities to check for errors, e.g.

```<code>char *x = "-1.9e-3";
errno = 0;
char *endptr;
long double xnum = strtold(x, &endptr);
if (*endptr) // (&& *endptr != '\n' if you read with `fgets()`)
{
    // extra / invalid characters;
}
else if (errno == ERANGE)
{
    // out of range;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find a way to check if a read-in char * can be represented as a number (with or without decimal places) or not.  Essentially I am asking, if I have a text file containing the following:

-1.9e-3
e9
1e9
1ee9
-1-.9e3
.9e3
.9.e3

It would be able to recognize that line 1, line 3, and line 6 can be "enumerated" into valid numbers, whereas all of the other lines contain erroneous inputs.  I know this could be done with brute force, but there is potentially an unlimited number of possibilities that could be wrong.  It would be much easier if there was a function that read in the entire char * and can just say,  "Yes that string of characters can be represented as an actual number" or "No that string of characters cannot be turned into the number that it intends to be."

And by enumerated I mean that the string (char *) can be the number that it wishes to represent.

Body:
Just try to convert it with strtold() and use the possibilities to check for errors, e.g.

char *x = "-1.9e-3";
errno = 0;
char *endptr;
long double xnum = strtold(x, &endptr);
if (*endptr) // (&& *endptr != '\n' if you read with `fgets()`)
{
    // extra / invalid characters;
}
else if (errno == ERANGE)
{
    // out of range;
}


问:
Adding some figures/numbers on the colored map with map.text
I am struggling with adding text on a map, which I built with map.text function.

I colored my states, as I wish, but now, I also want to add some numbers/figures on the states, on the map.

This is the code that I’ve used to have it:

```<code>library(“maps”)

win.obama = c( "California", "Colorado", "Connecticut", "District of Columbia",
               "Delaware", "Florida", "Hawaii", "Iowa" ,
               "Illinois", "Massachusetts",  "Maryland", "Maine" ,
               "Michigan", "Minnesota",   "New Hampshire", "New Jersey",
               "New Mexico", "Nevada",   "New York",   "Ohio",
               "Oregon", "Pennsylvania", "Rhode Island", "Virginia",
               "Vermont", "Washington", "Wisconsin")

win.romney = c("Alaska", "Alabama", "Arkansas", "Arizona", "Georgia", "Idaho",
               "Indiana", "Kansas", "Kentucky", "Louisiana", "Missouri", "Mississippi",
               "Montana", "North Carolina", "North Dakota", "Nebraska", "Oklahoma", "South Carolina",
               "South Dakota", "Tennessee", "Texas", "Utah", "West Virginia", "Wyoming")

map(database = "state")

map(database = "state", regions = win.obama, col = "blue", fill=T, add=TRUE)

map(database = "state", regions = win.romney, col = "red2", fill=T, add=TRUE)
</code>```

How can I do it?

答:
You can use map.text to put text on the map in the different regions:

For example:

```<code>map.text(database="state", region="Alabama", labels="Ala", add=TRUE)
</code>```

See ?map.text for details about the function.

As a side note, you can display your map with one call with:

```<code>map(database="state", regions=c(win.obama, win.romney), col=rep(c("blue", "red2"), c(length(win.obama), length(win.romney))), fill=TRUE)
</code>```

Body:
I am struggling with adding text on a map, which I built with map.text function.

I colored my states, as I wish, but now, I also want to add some numbers/figures on the states, on the map.

This is the code that I’ve used to have it:

library(“maps”)

win.obama = c( "California", "Colorado", "Connecticut", "District of Columbia",
               "Delaware", "Florida", "Hawaii", "Iowa" ,
               "Illinois", "Massachusetts",  "Maryland", "Maine" ,
               "Michigan", "Minnesota",   "New Hampshire", "New Jersey",
               "New Mexico", "Nevada",   "New York",   "Ohio",
               "Oregon", "Pennsylvania", "Rhode Island", "Virginia",
               "Vermont", "Washington", "Wisconsin")

win.romney = c("Alaska", "Alabama", "Arkansas", "Arizona", "Georgia", "Idaho",
               "Indiana", "Kansas", "Kentucky", "Louisiana", "Missouri", "Mississippi",
               "Montana", "North Carolina", "North Dakota", "Nebraska", "Oklahoma", "South Carolina",
               "South Dakota", "Tennessee", "Texas", "Utah", "West Virginia", "Wyoming")

map(database = "state")

map(database = "state", regions = win.obama, col = "blue", fill=T, add=TRUE)

map(database = "state", regions = win.romney, col = "red2", fill=T, add=TRUE)

How can I do it?

Body:
You can use map.text to put text on the map in the different regions:

For example:

map.text(database="state", region="Alabama", labels="Ala", add=TRUE)

See ?map.text for details about the function.

As a side note, you can display your map with one call with:

map(database="state", regions=c(win.obama, win.romney), col=rep(c("blue", "red2"), c(length(win.obama), length(win.romney))), fill=TRUE)


问:
passing props with Link in React-Router
Hello i'm trying to pass Props to a Details Component with the Link Component from React Router. I don't want to display the Detail Component  on the page, it should render when a button is clicked but also the url should look like this '/details/KvhNJecsqr6JFMSRTS' when the new Component renders.

```<code> class  Card extends Component {
                    render(props){
                    return(
                   <Col xs={12} md={4}>
                    <Thumbnail src="./someiamge">
                      <h3>{this.props.cardHeading}</h3>
                      <p>{this.props.cardDesc}</p>
                        <Button bsStyle="primary">Mieten</Button>
                        <Button bsStyle="default"><Link to='/details' params={{cardId: this.props.cardId}} 'here i wanna pass some props how i do this ?' >Details</Link></Button>
                    </Thumbnail>
                  </Col>

                    )
                  }
                }

export default Card
</code>```

Here is my Router stuff

```<code><BrowserRouter>
          <div>
              <Route name='details' path='/details/:cardId' component={Details}/>
            </div>
          </div>
</BrowserRouter>
</code>```

hier is my Details Component:

```<code>    class Details extends Component {
      render() {
        return (
          <div >
            <div style={{textAlign: "left"}}>
              <h3>{this.props.cardHeading}</h3>
              <p>{this.props.cardDesc}</p>
              .......
            </div>
          </div>
        );
      }
    }

    export default Details;
</code>```

答:
If want your new route to be like /details/:cardId, then I guess this should be enough:

```<code><Link to={`/details/${this.props.cardId}`} />
</code>```

But, if you want to add some extra properties, then according to documentation, you could pass them in the location.state:

```<code><Link to={{
  pathname: `/details/${this.props.cardId}`,
  state: {
    cardHeading: 'This is a heading',
    cardDesc: 'Description'
  }
}}/>
</code>```

Then, in order to access this state in your component, you can use the this.props.location.state or this.props.history.location.state

Title: passing props with Link in React-Router

Body:
Hello i'm trying to pass Props to a Details Component with the Link Component from React Router. I don't want to display the Detail Component  on the page, it should render when a button is clicked but also the url should look like this '/details/KvhNJecsqr6JFMSRTS' when the new Component renders.

 class  Card extends Component {
                    render(props){
                    return(
                   <Col xs={12} md={4}>
                    <Thumbnail src="./someiamge">

{this.props.cardHeading}

{this.props.cardDesc}

                        <Button bsStyle="primary">Mieten</Button>
                        <Button bsStyle="default"><Link to='/details' params={{cardId: this.props.cardId}} 'here i wanna pass some props how i do this ?' >Details</Link></Button>
                    </Thumbnail>
                  </Col>

                    )
                  }
                }

export default Card

Here is my Router stuff

<BrowserRouter>

              <Route name='details' path='/details/:cardId' component={Details}/>

</BrowserRouter>

hier is my Details Component:

    class Details extends Component {
      render() {
        return (

{this.props.cardHeading}

{this.props.cardDesc}

              .......

        );
      }
    }

    export default Details;

Body:
If want your new route to be like /details/:cardId, then I guess this should be enough:

<Link to={`/details/${this.props.cardId}`} />

But, if you want to add some extra properties, then according to documentation, you could pass them in the location.state:

<Link to={{
  pathname: `/details/${this.props.cardId}`,
  state: {
    cardHeading: 'This is a heading',
    cardDesc: 'Description'
  }
}}/>

Then, in order to access this state in your component, you can use the this.props.location.state or this.props.history.location.state


问:
Average performance measurements for local IPC
We are now assessing different IPC (or rather RPC) methods for our current project, which is in its very early stages. Performance is a big deal, and so we are making some measurements to aid our choice. Our processes that will be communicating will reside on the same machine.

A separate valid option is to avoid IPC altogether (by encapsulating the features of one of the processes in a .NET DLL and having the other one use it), but this is an option we would really like to avoid, as these two pieces of software are developed by two separate companies and we find it very important to maintain good "fences", which make good neighbors.

Our tests consisted of passing messages (which contain variously sized BLOBs) across process boundaries using each method. These are the figures we get (performance range correlates with message size range):

Web Service (SOAP over HTTP):

25-30 MB/s when binary data is encoded as Base64 (default)

70-100 MB/s when MTOM is utilized

.NET Remoting (BinaryFormatter over TCP): 100-115 MB/s

Control group - DLL method call + mem copy: 800-1000 MB/s

Now, we've been looking all over the place for some average performance figures for these (and other) IPC methods, including performance of raw TCP loopback sockets, but couldn't find any. Do these figures look sane? Why is the performance of these local IPC methods at least 10 times slower than copying memory? I couldn't get better results even when I used raw sockets - is the overhead of TCP that big?

答:
Shared memory is the fastest.

A producer process can put its output into memory shared between processes and notify other processes that the shared data has been updated. On Linux you naturally put a mutex and a condition variable in that same shared memory so that other processes can wait for updates on the condition variable.

ContentLicense: CC BY-SA 2.5


问:
MSACCESS 2010 VBA; Syntax Error in date in query expression
I am creating a simple database for tracking working hours. The idea is that:

Every day you need to input only the days that employee did not work (startDate, endDate, absenceType),

Then calculate working days for the whole month or selected period.

Calculation of working days should take into account weekends (saturday, sunday) and holidays from Holiday table.

I took a function sample from MSDN (Counting the Number of Working Days in Access 2007) and put it into a module in my MS Access 2010 db but each time I run a query I have this error.

Typically the same error appears attempting to run a query in another sample database from somewhere.

The problem is in the strWhere clause:

```<code>strWhere = "[Holiday] >=#" & startDate & "# AND [Holiday] <=#" & endDate & "#"

' Count the number of holidays.
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays
</code>```

The error msg  from both databases is available in the link below

Runtime Error 3075 Syntax error in date in query expression

Any help is appreciated.

答:
In the past I have had issues where VBA doesn't always respect the regional date settings. Try forcing it into US format before concatenating it</p>

```<code>strWhere = "[Holiday] >=#" & Format(startDate, "MM/dd/yyyy") & "# AND [Holiday] <=#" & Format(endDate, "MM/dd/yyyy") & "#"
</code>```

Body:
I am creating a simple database for tracking working hours. The idea is that:

Every day you need to input only the days that employee did not work (startDate, endDate, absenceType),

Then calculate working days for the whole month or selected period.

Calculation of working days should take into account weekends (saturday, sunday) and holidays from Holiday table.

I took a function sample from MSDN (Counting the Number of Working Days in Access 2007) and put it into a module in my MS Access 2010 db but each time I run a query I have this error.

Typically the same error appears attempting to run a query in another sample database from somewhere.

The problem is in the strWhere clause:

strWhere = "[Holiday] >=#" & startDate & "# AND [Holiday] <=#" & endDate & "#"

' Count the number of holidays.
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

The error msg  from both databases is available in the link below

Runtime Error 3075 Syntax error in date in query expression

Any help is appreciated.

Body:
In the past I have had issues where VBA doesn't always respect the regional date settings. Try forcing it into US format before concatenating it

strWhere = "[Holiday] >=#" & Format(startDate, "MM/dd/yyyy") & "# AND [Holiday] <=#" & Format(endDate, "MM/dd/yyyy") & "#"


问:
How to convert Excel to semicolon or pipe delimited file using script?
I am trying to automate task of converting an Excel workbook to a CSV file. The resulting file should be semicolon and pipe delimited. However I am getting comma separated files only. I tried playing with SaveAs parameters, but no help.

Can somebody suggest a way to do this in VBScript.

Here is my code that is able to convert workbook to CSV. I even tried to replace comma with pipe or semicolon, but that was super buggy resulting in incorrect data.

```<code>Dim strExcelFileName
Dim strCSVFileName
strDelimiter = "|"

strExcelFileName = "file_temp" '

Set fso = CreateObject ("Scripting.FileSystemObject")
strScript = WScript.ScriptFullName
strScriptPath = fso.GetAbsolutePathName(strScript & "\..")
WScript.Echo strScriptPath

'If the Input file is NOT qualified with a path, default the current path
LPosition = InStrRev(strExcelFileName, "\")
If LPosition = 0 Then 'no folder path
    strExcelFileName = strScriptPath & "\file\" & strExcelFileName
    strScriptPath = strScriptPath & "\"
Else 'there is a folder path, use it for the output folder path also
    strScriptPath = Mid(strExcelFileName, 1, LPosition)
End If
'MsgBox LPosition & " - " & strExcelFileName & " - " & strScriptPath  ' use this for debugging

Set objXL = CreateObject("Excel.Application")
Set objWorkBook = objXL.Workbooks.Open(strExcelFileName)
objXL.DisplayAlerts = False

'loop over worksheets
For Each sheet In objWorkBook.Sheets
    'only saveAS sheets that are NOT empty
    If objXL.Application.WorksheetFunction.CountA(sheet.Cells) <> 0 Then
        sheet.Rows(1).Delete  ' this will remove Row 1 or the header Row
        Select Case sheet.Name
        Case "Sales"
            sheet.SaveAs strScriptPath & "abc_sales.csv", 23, local=true 'CSV
        Case "Goals"
            sheet.SaveAs strScriptPath & "abc_file_goals.csv", 6 'CSV
        Case "Commissions"
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        Case Else
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        End Select
    End If
Next

'clean up
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing
Set fso = Nothing
</code>```

Edit I have tried below code to force local setting and windows csv format. but it is stil generating comma separated file. Local setting is set as pipe.

```<code>sheet.SaveAs strScriptPath & "abc.csv", 23, local=true
</code>```

答:
As pointed out in the comments, you must define the Named Constants as VBScript doesn't have access to the Excel Object Type Library so has no idea how to associate them to their numeric values.

VBScript also doesn't support Named Parameters syntax such as this#;

Sheet.SaveAs Filename:=strScriptPath & "abc_sales" & ".csv", FileFormat:=xlCSVWindows, local:=True
```
<p>will fail with a</p>
<blockquote>
<p>Microsoft VBScript compilation error:<br />
Syntax error</p>
</blockquote>
<p>as <code>Filename:=</code> means nothing to VBScript.</p>
<p>Instead, you want to do something like this;</p>
<pre class="lang-vb prettyprint-override"><code>'Define your Named Constants
'XlFileFormat Enumeration
Const xlCSVWindows = 23

'...

'SaveAs call should match the number of arguments (optional or not).
Call sheet.SaveAs(strScriptPath & "abc.csv", xlCSVWindows, , , , , , , , , , True)
</code>```

... - Denotes existing code not included for the example.

Useful Links

XlFileFormat Enumeration (Excel)

Workbook.SaveAs Method (Excel)

# - Answer based off comments from https://stackoverflow.com/a/47281574/692942

Body:
I am trying to automate task of converting an Excel workbook to a CSV file. The resulting file should be semicolon and pipe delimited. However I am getting comma separated files only. I tried playing with SaveAs parameters, but no help.

Can somebody suggest a way to do this in VBScript.

Here is my code that is able to convert workbook to CSV. I even tried to replace comma with pipe or semicolon, but that was super buggy resulting in incorrect data.

Dim strExcelFileName
Dim strCSVFileName
strDelimiter = "|"

strExcelFileName = "file_temp" '

Set fso = CreateObject ("Scripting.FileSystemObject")
strScript = WScript.ScriptFullName
strScriptPath = fso.GetAbsolutePathName(strScript & "\..")
WScript.Echo strScriptPath

'If the Input file is NOT qualified with a path, default the current path
LPosition = InStrRev(strExcelFileName, "\")
If LPosition = 0 Then 'no folder path
    strExcelFileName = strScriptPath & "\file\" & strExcelFileName
    strScriptPath = strScriptPath & "\"
Else 'there is a folder path, use it for the output folder path also
    strScriptPath = Mid(strExcelFileName, 1, LPosition)
End If
'MsgBox LPosition & " - " & strExcelFileName & " - " & strScriptPath  ' use this for debugging

Set objXL = CreateObject("Excel.Application")
Set objWorkBook = objXL.Workbooks.Open(strExcelFileName)
objXL.DisplayAlerts = False

'loop over worksheets
For Each sheet In objWorkBook.Sheets
    'only saveAS sheets that are NOT empty
    If objXL.Application.WorksheetFunction.CountA(sheet.Cells) <> 0 Then
        sheet.Rows(1).Delete  ' this will remove Row 1 or the header Row
        Select Case sheet.Name
        Case "Sales"
            sheet.SaveAs strScriptPath & "abc_sales.csv", 23, local=true 'CSV
        Case "Goals"
            sheet.SaveAs strScriptPath & "abc_file_goals.csv", 6 'CSV
        Case "Commissions"
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        Case Else
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        End Select
    End If
Next

'clean up
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing
Set fso = Nothing

Edit I have tried below code to force local setting and windows csv format. but it is stil generating comma separated file. Local setting is set as pipe.

sheet.SaveAs strScriptPath & "abc.csv", 23, local=true

Body:
As pointed out in the comments, you must define the Named Constants as VBScript doesn't have access to the Excel Object Type Library so has no idea how to associate them to their numeric values.

VBScript also doesn't support Named Parameters syntax such as this#;

Sheet.SaveAs Filename:=strScriptPath & "abc_sales" & ".csv", FileFormat:=xlCSVWindows, local:=True

will fail with a

Microsoft VBScript compilation error:

Syntax error

as Filename:= means nothing to VBScript.

Instead, you want to do something like this;

'Define your Named Constants
'XlFileFormat Enumeration
Const xlCSVWindows = 23

'...

'SaveAs call should match the number of arguments (optional or not).
Call sheet.SaveAs(strScriptPath & "abc.csv", xlCSVWindows, , , , , , , , , , True)

... - Denotes existing code not included for the example.

Useful Links

XlFileFormat Enumeration (Excel)

Workbook.SaveAs Method (Excel)

# - Answer based off comments from https://stackoverflow.com/a/47281574/692942


问:
How to Keep the date Format in a Particular Formula?
How to Keep the date Format in a Particular Formula ?

Exemple :

NB : I Use French Excel

答:
You could format the date as text in your formula:

=E5&":"&TEXT(F5,"DD/MM/YYYY")

edit: And of course, hypothetically speaking, if you were in France:

=E5&":"&TEXTE(F5;"JJ/MM/AAAA")


问:
VBA: Multiplying by a fraction within a loop
My code works below works but I'd like to add one function.  I've got a large data sheet with each line repeated three times.  Within each set of three I've added a month twice.  The purpose is to smooth out forecasted sales into one month and two months beyond the estimated shipping date.  Now I'd like to multiply my the values in column E by factors into column F.  The original line in each set of three will =50%*E:E  in column F, the second line will have =30%*E:E in column F, and the third line will have =20%*E:E in Column F.   This process should be repeated continually for every set of three lines. Problem: My current code does give me the correct value, however the values are two cells lower than they need to be. Thanks for any help in advance! My current code is below:

```<code>Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1,
Day(dttTemp))
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2,
Day(dttTemp))
Next r

Application.ScreenUpdating = True
</code>```

' This is where my code is bad

```<code>For l = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -3

Quant = ws.Cells(l, "E").Value
ws.Cells(l, "F").Value = Cells(l, "E") * 0.5
ws.Cells(l + 1, "F").Value = Cells(l, "E") * 0.3
ws.Cells(l + 2, "F").Value = Cells(l, "E") * 0.2
Next l

End Sub
</code>```

答:
In this case there is no need to loop backwards. Update the For statement to the following:

```<code>For l = 1 to ws.Range("A" & ws.Rows.Count).End(xlUp).Row Step 3
</code>```

Then it should produce desired results.

Body:
My code works below works but I'd like to add one function.  I've got a large data sheet with each line repeated three times.  Within each set of three I've added a month twice.  The purpose is to smooth out forecasted sales into one month and two months beyond the estimated shipping date.  Now I'd like to multiply my the values in column E by factors into column F.  The original line in each set of three will =50%*E:E  in column F, the second line will have =30%*E:E in column F, and the third line will have =20%*E:E in Column F.   This process should be repeated continually for every set of three lines. Problem: My current code does give me the correct value, however the values are two cells lower than they need to be. Thanks for any help in advance! My current code is below:

Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1,
Day(dttTemp))
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2,
Day(dttTemp))
Next r

Application.ScreenUpdating = True

' This is where my code is bad

For l = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -3

Quant = ws.Cells(l, "E").Value
ws.Cells(l, "F").Value = Cells(l, "E") * 0.5
ws.Cells(l + 1, "F").Value = Cells(l, "E") * 0.3
ws.Cells(l + 2, "F").Value = Cells(l, "E") * 0.2
Next l

End Sub

Body:
In this case there is no need to loop backwards. Update the For statement to the following:

For l = 1 to ws.Range("A" & ws.Rows.Count).End(xlUp).Row Step 3

Then it should produce desired results.


Title: How to Keep the date Format in a Particular Formula?

Body:
How to Keep the date Format in a Particular Formula ?

Exemple :

NB : I Use French Excel

Body: = E5&":"&TEXT(F5,"dd/mm/yyyy")


问:
Ideal merge for different number of columns and rows in dataframe
Some example data of stucture:

```<code>df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))
df2 = data.frame(x=c('f', 'g', 'h'),y = c(0,1,0))
df3 = data.frame(x=c('i', 'j','k','l'), y = c(1,7,5,2,6), z = c(75,3,25,2,1))
</code>```

I have 3 different dataframes.

df1 has 22201 object and 121 variables
df2 has 8403 object and 68 variables
df3 has 50476 object and 157 variables

I try to merge them using merge and I receive this error:

```<code>Error in fix.by(by.x, x) :
  'by' must specify one or more columns as numbers, names or logical
</code>```

using cbind and I received this error:

```<code>Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 22201, 8403, 50476
</code>```

and rbind and I receive this error:

```<code>Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match
</code>```

How can I merge dataframes with different number of rows and columns? I have to refer that columns have the same names in dataframes so in the merge I expect the number of columns be the highest numbers of columns of the dataframe which contains the most.

答:
In this case, use rbind.fill from the library plyr

```<code>library(plyr)
rbind.fill(df1, df2, df3)
</code>```

This will merge all your 3 data frames with different number of columns.

Body:
Some example data of stucture:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))
df2 = data.frame(x=c('f', 'g', 'h'),y = c(0,1,0))
df3 = data.frame(x=c('i', 'j','k','l'), y = c(1,7,5,2,6), z = c(75,3,25,2,1))

I have 3 different dataframes.

df1 has 22201 object and 121 variables
df2 has 8403 object and 68 variables
df3 has 50476 object and 157 variables

I try to merge them using merge and I receive this error:

Error in fix.by(by.x, x) :
  'by' must specify one or more columns as numbers, names or logical

using cbind and I received this error:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 22201, 8403, 50476

and rbind and I receive this error:

Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match

How can I merge dataframes with different number of rows and columns? I have to refer that columns have the same names in dataframes so in the merge I expect the number of columns be the highest numbers of columns of the dataframe which contains the most.

Body:
In this case, use rbind.fill from the library plyr

library(plyr)
rbind.fill(df1, df2, df3)

This will merge all your 3 data frames with different number of columns.


问:
Get the content of iframe which generated on the fly
I have an iframe which is generated on the fly and appended in a div like this:

```<code>content.innerHTML = '<iframe src="' + url + '" id="id_iframe" style="border:0px #BD8D46 dotted;" scrolling="auto" frameborder="no" align="center"></iframe>';
</code>```

The div which is appended in invisible (display: none;)

What I want to do is to change the display of the div according to the content of the iframe.

I try this

```<code>console.log($("#id_iframe").contents());
</code>```

But I get nothing back. No contents. When I use the developers tools I see that the iframe exists in the DOM.

Is it possible to get the iframe content on the fly?

答:
$("#id") can not select dom elemets that where added after dom load

$("document").find("#id_iframe").contents()

Body:
I have an iframe which is generated on the fly and appended in a div like this:

content.innerHTML = '';

The div which is appended in invisible (display: none;)

What I want to do is to change the display of the div according to the content of the iframe.

I try this

console.log($("#id_iframe").contents());

But I get nothing back. No contents. When I use the developers tools I see that the iframe exists in the DOM.

Is it possible to get the iframe content on the fly?


问:
Make movie with data files using gnuplot
I do have many data files. They look  like
1.dat
2.dat
....
....
1000.dat

I want to make a movie using these files plotting them in sequence.
Does anyone have any idea please?
It would be my great pleasure if you can help me.
ND

答:
You need two steps here. The first one is to create jpeg or png plots from the data.
I do not know what your data looks like, but I guess you've already found out how to plot it with gnuplot. Gnuplot has a loop option, but if you're on a linux box, you can easly pass all the files to gnuplot as arguments
for example, run the following in bash:

```<code>for i in {1..1000}
do
   gnuplot "What needs to be done" $i.dat
done
</code>```

Now, you need to create your movie. The easiest way would be:

```<code>ffmpeg -i gnuplotoutput%04d.jpeg movie.mpeg
</code>```

Edit:
After your clarification (the data is 3d etc):

```<code>for i in {1..1000}
do
   gnuplot -e "set terminal jpeg; splot '$i.dat'" > pic$i.jpeg
done

ffmpeg -i pic%04d.jpeg movie.mpeg
</code>```

Indeed, the idea was that "what needs to be done " will be replaced by your own commands. gnuplot is exceptionally capable, but you need to tell it exactly what to do. That depends on your data, and what output you want. I've used splot, to create a 3d grid graph.

Body:
You need two steps here. The first one is to create jpeg or png plots from the data.
I do not know what your data looks like, but I guess you've already found out how to plot it with gnuplot. Gnuplot has a loop option, but if you're on a linux box, you can easly pass all the files to gnuplot as arguments
for example, run the following in bash:

for i in {1..1000}
do
   gnuplot "What needs to be done" $i.dat
done

Now, you need to create your movie. The easiest way would be:

ffmpeg -i gnuplotoutput%04d.jpeg movie.mpeg

Edit:
After your clarification (the data is 3d etc):

for i in {1..1000}
do
   gnuplot -e "set terminal jpeg; splot '$i.dat'" > pic$i.jpeg
done

ffmpeg -i pic%04d.jpeg movie.mpeg

Indeed, the idea was that "what needs to be done " will be replaced by your own commands. gnuplot is exceptionally capable, but you need to tell it exactly what to do. That depends on your data, and what output you want. I've used splot, to create a 3d grid graph.


问:
Angular: Catch a 404 error on file not found
In my Ionic project I am creating a function to find out if a file exists locally or not. I have created the following function:

```<code>$rootScope.eventFieldTemplateExists = function(field) {
    //var templateUrl = 'views/fields/' + field.name + '.html';
    var templateUrl = 'views/fields/testfile.html';

    $http.head(templateUrl).then(function(res) {
      console.log("success");
      console.log(res);
    })
    .catch(function(err) {
      console.log("catch");
      console.log(err);
    });

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

The file testfile.html does not exist. The above works fine when I enter a file that do exist, but I still get a console error when the file does not exist:

```<code>HEAD http://localhost:9000/views/fields/testfile.html 404 (Not Found)
catch
{data: "", status: 404, config: {…}, statusText: "Not Found", headers: ƒ}
</code>```

Is there some way to suppress the error? I was hoping that the .catch would suppress it, but apparently it does not.

答:
You can catch all errors in a $http request with a second parameter for then().

```<code>$http.head(templateUrl).then(function(res) {
    console.log("success");
    console.log(res);
}, function(err) {
    console.log("catch");
    console.log(err);
})
</code>```

AngularJs $http.head works like this:

```<code>$http.head('/someUrl', config).then(successCallback, errorCallback);
</code>```

Documentation on $http

Body:
In my Ionic project I am creating a function to find out if a file exists locally or not. I have created the following function:

$rootScope.eventFieldTemplateExists = function(field) {
    //var templateUrl = 'views/fields/' + field.name + '.html';
    var templateUrl = 'views/fields/testfile.html';

    $http.head(templateUrl).then(function(res) {
      console.log("success");
      console.log(res);
    })
    .catch(function(err) {
      console.log("catch");
      console.log(err);
    });

    return true;
};

The file testfile.html does not exist. The above works fine when I enter a file that do exist, but I still get a console error when the file does not exist:

HEAD http://localhost:9000/views/fields/testfile.html 404 (Not Found)
catch
{data: "", status: 404, config: {…}, statusText: "Not Found", headers: ƒ}

Is there some way to suppress the error? I was hoping that the .catch would suppress it, but apparently it does not.

Body:
You can catch all errors in a $http request with a second parameter for then().

$http.head(templateUrl).then(function(res) {
    console.log("success");
    console.log(res);
}, function(err) {
    console.log("catch");
    console.log(err);
})

AngularJs $http.head works like this:

$http.head('/someUrl', config).then(successCallback, errorCallback);

Documentation on $http


答:
Make sure the date is in MM/DD/YYYY order in VBA. Always. I generally use:

strWhere = "[Holiday] >= " & Format(startDate,"\#mm\/dd\/yyyy\#")

the second argument of DCount is strHolidays. That does not look like the name of a table/query. This argument should be the name of a table/query.

Title: MSACCESS 2010 VBA; Syntax Error in date in query expression


问:
select case doesn't work for one of the values
Why doesn't my 'XXX' value work in this select case statement.  I want it to give back a blank, but it gives back the same string as the 'RNC'. </p>

```<code>SELECT SHORT_DESC =
      CASE
         WHEN MAIL_CODE1 <> 'RNC' THEN SHORT_DESC
         WHEN MAIL_CODE1 = 'XXX' THEN ' '
         ELSE 'Request No Contact'
      END
FROM (select 1 dummy) dummy
left join TMS_MAILING_1 m ON m.MAIL_CODE1 = 'XXX'--${MailCode}
  GROUP BY SHORT_DESC, MAIL_CODE1;
</code>```

答:
How about this?

```<code>SELECT SHORT_DESC =
      CASE
         WHEN MAIL_CODE1 = 'XXX' THEN ' '
         WHEN MAIL_CODE1 <> 'RNC' THEN SHORT_DESC
         ELSE 'Request No Contact'
      END
FROM (SELECT 1 dummy) dummy
    LEFT JOIN TMS_MAILING_1 m ON m.MAIL_CODE1 = 'XXX'--${MailCode}
GROUP BY SHORT_DESC, MAIL_CODE1;
</code>```

Remember there is a condition validation order in a CASE statement, starting from the first and going down to the last.

The first valid condition is returned, which in your case is TRUE.

You should always check for equality first and then non-equality.

Also, your query logic seems a bit strange. I'd rewrite the query like:

```<code>DECLARE @PARAM NVARCHAR(MAX) = 'XXX'--${MailCode}

SELECT
    SHORT_DESC = CASE
        WHEN MAIL_CODE1 = 'XXX'
            THEN ''
        WHEN MAIL_CODE1 <> 'RNC'
            THEN SHORT_DESC
        ELSE 'Request No Contact'
    END
FROM TMS_MAILING_1
WHERE MAIL_CODE1 = @PARAM
</code>```

For testing purposes, you can use the below code and just change the value of the @PARAM variable to see how the query would behave based on your input.

```<code>DECLARE @PARAM NVARCHAR(MAX) = 'XXX'--${MailCode}

SELECT
    SHORT_DESC = CASE
        WHEN MAIL_CODE1 = 'XXX'
            THEN ''
        WHEN MAIL_CODE1 <> 'RNC'
            THEN 'SHORT_DESC'
        ELSE 'Request No Contact'
    END
FROM (SELECT @PARAM AS MAIL_CODE1) X
WHERE MAIL_CODE1 = @PARAM
</code>```

Body:
Why doesn't my 'XXX' value work in this select case statement.  I want it to give back a blank, but it gives back the same string as the 'RNC'.

SELECT SHORT_DESC =
      CASE
         WHEN MAIL_CODE1 <> 'RNC' THEN SHORT_DESC
         WHEN MAIL_CODE1 = 'XXX' THEN ' '
         ELSE 'Request No Contact'
      END
FROM (select 1 dummy) dummy
left join TMS_MAILING_1 m ON m.MAIL_CODE1 = 'XXX'--${MailCode}
  GROUP BY SHORT_DESC, MAIL_CODE1;

Body:
How about this?

SELECT SHORT_DESC =
      CASE
         WHEN MAIL_CODE1 = 'XXX' THEN ' '
         WHEN MAIL_CODE1 <> 'RNC' THEN SHORT_DESC
         ELSE 'Request No Contact'
      END
FROM (SELECT 1 dummy) dummy
    LEFT JOIN TMS_MAILING_1 m ON m.MAIL_CODE1 = 'XXX'--${MailCode}
GROUP BY SHORT_DESC, MAIL_CODE1;

Remember there is a condition validation order in a CASE statement, starting from the first and going down to the last.

The first valid condition is returned, which in your case is TRUE.

You should always check for equality first and then non-equality.

Also, your query logic seems a bit strange. I'd rewrite the query like:

DECLARE @PARAM NVARCHAR(MAX) = 'XXX'--${MailCode}

SELECT
    SHORT_DESC = CASE
        WHEN MAIL_CODE1 = 'XXX'
            THEN ''
        WHEN MAIL_CODE1 <> 'RNC'
            THEN SHORT_DESC
        ELSE 'Request No Contact'
    END
FROM TMS_MAILING_1
WHERE MAIL_CODE1 = @PARAM

For testing purposes, you can use the below code and just change the value of the @PARAM variable to see how the query would behave based on your input.

DECLARE @PARAM NVARCHAR(MAX) = 'XXX'--${MailCode}

SELECT
    SHORT_DESC = CASE
        WHEN MAIL_CODE1 = 'XXX'
            THEN ''
        WHEN MAIL_CODE1 <> 'RNC'
            THEN 'SHORT_DESC'
        ELSE 'Request No Contact'
    END
FROM (SELECT @PARAM AS MAIL_CODE1) X
WHERE MAIL_CODE1 = @PARAM


问:
Reserve flash memory space in TI cc26xx
I am currently trying to reserve a sector of the flash memory in the linker file, to save some data to it (using the driverlib API). I first flash the script writing to the specific memory addresses, then I run my application which reads the saved data.

Unfortunately whenever I flash, the data is lost. Therefore I am trying to change the linker file and reserve some space but I am not sure if I am doing it correctly. I will appreciate any help or hints.

```<code>MEMORY
{
    /* Flash Size 128 KB minus the CCA area below (88 bytes) */
    /* OLD: FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x0001FFA8 */
    FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x0001FF88

    /*
     * Custom reserved memory space with size of 32 bytes
     */
    CNVM (RX)  : ORIGIN = 0x0001FF88, LENGTH = 32

    /*
     * Customer Configuration Area and Bootloader Backdoor configuration
     * in flash, up to 88 bytes
     */
    FLASH_CCFG (RX) : ORIGIN = 0x0001FFA8, LENGTH = 88

    /* RAM Size 20KB */
    SRAM (RWX) : ORIGIN = 0x20000000, LENGTH = 0x00005000

    /* Application can use GPRAM region as RAM if cache is disabled in CCFG */
    GPRAM (RWX) : ORIGIN = 0x11000000, LENGTH = 0x00002000
}

/*. Highest address of the stack. Used in startup file .*/
_estack = ORIGIN(SRAM) + LENGTH(SRAM); /* End of SRAM */

/*. Generate a link error if heap and stack don’t fit into RAM .*/
_Min_Heap_Size = 0;
_Min_Stack_Size = 0x100;

SECTIONS
{
    .text :
    {
        _text = .;
        KEEP(*(.vectors))
        *(.text*)
        *(.rodata*)
        _etext = .;
    } > FLASH = 0

    .text:
    {
        *(.rodata*)
    } > CNVM

    .data :
    {
        _data = .;
        *(vtable)
        *(.data*)
        _edata = .;
    } > SRAM AT > FLASH

    .ARM.exidx :
    {
        *(.ARM.exidx*)
    } > FLASH

    .bss :
    {
        _bss = .;
        *(.bss*)
        *(COMMON)
        _ebss = .;
    } > SRAM

    .ccfg :
    {
        KEEP(*(.ccfg))
    } > FLASH_CCFG

    /* User_heap_stack section, used to check that there is enough RAM left */
    ._user_heap_stack :
    {
      . = ALIGN(4);
      . = . + _Min_Heap_Size;
      . = . + _Min_Stack_Size;
      . = ALIGN(4);
    } > SRAM

    .gpram :
    {
    } > GPRAM

}
</code>```

答:
Using the linker approach didn't provide the desired result in my case. What I ended up doing instead is editing the generated binary file from my code before flashing the sensortag.

Using the hexdump command on linux as follows hexdump generated_binary_file.bin one can notice that each line includes the start memory address (for a certain range of addresses) followed by the data written to this range.

And so using a small python script one can change the values in a certain line and generate its own modified binary file that will be later flashed to the sensortag. The memory address content can be read with a certain function that you include in your initial code (before bin generation & editing) such memcpy() for example.

Title: Reserve flash memory space in TI cc26xx

Body:
I am currently trying to reserve a sector of the flash memory in the linker file, to save some data to it (using the driverlib API). I first flash the script writing to the specific memory addresses, then I run my application which reads the saved data.

Unfortunately whenever I flash, the data is lost. Therefore I am trying to change the linker file and reserve some space but I am not sure if I am doing it correctly. I will appreciate any help or hints.

MEMORY
{
    /* Flash Size 128 KB minus the CCA area below (88 bytes) */
    /* OLD: FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x0001FFA8 */
    FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x0001FF88

    /*
     * Custom reserved memory space with size of 32 bytes
     */
    CNVM (RX)  : ORIGIN = 0x0001FF88, LENGTH = 32

    /*
     * Customer Configuration Area and Bootloader Backdoor configuration
     * in flash, up to 88 bytes
     */
    FLASH_CCFG (RX) : ORIGIN = 0x0001FFA8, LENGTH = 88

    /* RAM Size 20KB */
    SRAM (RWX) : ORIGIN = 0x20000000, LENGTH = 0x00005000

    /* Application can use GPRAM region as RAM if cache is disabled in CCFG */
    GPRAM (RWX) : ORIGIN = 0x11000000, LENGTH = 0x00002000
}

/*. Highest address of the stack. Used in startup file .*/
_estack = ORIGIN(SRAM) + LENGTH(SRAM); /* End of SRAM */

/*. Generate a link error if heap and stack don’t fit into RAM .*/
_Min_Heap_Size = 0;
_Min_Stack_Size = 0x100;

SECTIONS
{
    .text :
    {
        _text = .;
        KEEP(*(.vectors))
        *(.text*)
        *(.rodata*)
        _etext = .;
    } > FLASH = 0

    .text:
    {
        *(.rodata*)
    } > CNVM

    .data :
    {
        _data = .;
        *(vtable)
        *(.data*)
        _edata = .;
    } > SRAM AT > FLASH

    .ARM.exidx :
    {
        *(.ARM.exidx*)
    } > FLASH

    .bss :
    {
        _bss = .;
        *(.bss*)
        *(COMMON)
        _ebss = .;
    } > SRAM

    .ccfg :
    {
        KEEP(*(.ccfg))
    } > FLASH_CCFG

    /* User_heap_stack section, used to check that there is enough RAM left */
    ._user_heap_stack :
    {
      . = ALIGN(4);
      . = . + _Min_Heap_Size;
      . = . + _Min_Stack_Size;
      . = ALIGN(4);
    } > SRAM

    .gpram :
    {
    } > GPRAM

}


问:
Why isn't Date(2015, 11, 1) the first of December?
When I convert that date to ISO string I get the 30th of november 2015. Why wouldn't it be first of december? I have googled and I know that month is 0-indexed and that overflows lead to the next day/month/year. But I cannot explain myself that behaviour and when I google it I find unrelated topics.</p>

答:
Thing is if You type:

```<code>var date = new Date(2015, 11, 1);
console.log(date);
</code>```

You will get output based on your timezone, for me it's:

```<code>Tue Dec 01 2015 00:00:00 GMT+0100 (Central Europe Standard Time)
</code>```

Function toISOString will always output time in UTC. So in this case you will get this date minus one hour.

```<code>2015-11-30T23:00:00.000Z
</code>```

Body:
Thing is if You type:

var date = new Date(2015, 11, 1);
console.log(date);

You will get output based on your timezone, for me it's:

Tue Dec 01 2015 00:00:00 GMT+0100 (Central Europe Standard Time)

Function toISOString will always output time in UTC. So in this case you will get this date minus one hour.

2015-11-30T23:00:00.000Z


问:
Is QListView right for me?
I've been having difficulty trying to find a Qt widget that will allow me to display a list with columns. From what I understand, QListView does indeed display list data, but it doesn't allow for programmers to add a list view header -- in fact, it appears the only widget that does allow one to display headers is QTreeView (which, quite frankly, is a pain in the arse to work with).

Qt certainly must offer an easy way to display a header and data organized by columns, no?

Thanks so much!
--Dany.

答:
Straight from the QListView's docs:

This view does not display horizontal or vertical headers; to display a list of items with a horizontal header, use QTreeView instead.

Title: Is QListView right for me?


问:
Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods
I've developed a small write-only REST api with Flask Restful that accepts PUT request from a handful of clients that can potentially have changing IP addresses. My clients are embedded Chromium clients running an AngularJS front-end; they authenticate with my API with a simple magic key -- it's sufficient for my very limited scale.

I'm testing deploying my API now and I notice that the Angular clients are attempting to send an OPTIONS http methods to my Flask service. My API meanwhile is replying with a 404 (since I didn't write an OPTIONS handler yet, only a PUT handler). It seems that when sending cross-domain requests that are not POST or GET, Angular will send a pre-flight OPTIONS method at the server to make sure the cross-domain request is accepted before it sends the actual request. Is that right?

Anyway, how do I allow all cross-domain PUT requests to Flask Restful API? I've used cross-domaion decorators with a (non-restful) Flask instance before, but do I need to write an OPTIONS handler as well into my API?

答:
Just an update to this comment. Flask CORS is the way to go, but the flask.ext.cors is deprecated.

use:

from flask_cors import CORS


问:
Sql Exception Incorrect syntax near '@errno'
I'm new to Vb.net and Linq2sql,and I searched on google for a solution before posting a question here but I couldn't Fix it ,I'm trying to Insert row into data base using Vb.net and Linq2sql, the SubmitChanges() function returns Incorrect syntax near '@errno' SQl Exception.
table related trigger:

```<code> USE [Roster]
 GO
 /****** Object:  Trigger [dbo].[ti_profile]    Script Date: 11/14/2017
 4:17:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[ti_profile] on [dbo].[PROFILE] AFTER  INSERT
AS

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

declare @ls_profile_code  varchar(6)
declare @errno int
declare @errmsg varchar(255)

--set @ls_profile_code = select inserted.profile_code from inserted

-- insert what ever was added to the object table and not yet been inserted or updated in the profile_access
insert into Profile_access (profile_code , object_code)

    select  (select inserted.profile_code from inserted) ,
            object_code
    from    Objects
    where   object_code not in

        (
            select  object_code
            from    Profile_access
            where   profile_code = @ls_profile_code
        )

return

error:
raiserror @errno @errmsg
rollback transaction

END
</code>```

Any Idea on how to fix this please..

答:
The RAISEERROR() function requires parentheses now. This changed between Sql Server 2008 R2 and Sql Server 2012.

So this:

raiserror @errno @errmsg
```
<p>becomes this:</p>
<pre class="lang-sql prettyprint-override"><code>raiserror(@errmsg, @errno, 1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Vb.net and Linq2sql,and I searched on google for a solution before posting a question here but I couldn't Fix it ,I'm trying to Insert row into data base using Vb.net and Linq2sql, the SubmitChanges() function returns Incorrect syntax near '@errno' SQl Exception.
table related trigger:

 USE [Roster]
 GO
 /****** Object:  Trigger [dbo].[ti_profile]    Script Date: 11/14/2017
 4:17:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[ti_profile] on [dbo].[PROFILE] AFTER  INSERT
AS

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

declare @ls_profile_code  varchar(6)
declare @errno int
declare @errmsg varchar(255)

--set @ls_profile_code = select inserted.profile_code from inserted

-- insert what ever was added to the object table and not yet been inserted or updated in the profile_access
insert into Profile_access (profile_code , object_code)

    select  (select inserted.profile_code from inserted) ,
            object_code
    from    Objects
    where   object_code not in

        (
            select  object_code
            from    Profile_access
            where   profile_code = @ls_profile_code
        )

return

error:
raiserror @errno @errmsg
rollback transaction

END

Any Idea on how to fix this please..

Body:
The RAISEERROR() function requires parentheses now. This changed between Sql Server 2008 R2 and Sql Server 2012.

So this:

raiserror @errno @errmsg

becomes this:

raiserror(@errmsg, @errno, 1)


问:
Multiple inheritance + Multi-Level inheritance in PHP: Is there a pattern or possibility to solve constructor inheritance?
Have a look at the following example:

```<code>class A {
    protected $a;
    public function __construct() {
        $this->a = "foo";
    }
}

trait Q {
    protected $q;
    public function __construct() {
        $this->q = "happy";
    }
}

class B extends A {
    use Q;
    protected $b;
    public function __construct() {
        $this->b = "bar";
    }
}

trait X {
    protected $x;
    public function __construct() {
        $this->x = "lorem";
    }
}

class C extends B {
    use X;
    protected $c;
    public function __construct() {
        $this->c = "sure";
    }

    public function giveMeEverything() {
        echo $this->a." ".$this->b." ".$this->c." ".$this->x." ".$this->q;
    }
}

$c = new C();
$c->giveMeEverything();
</code>```

This works just fine - the output is:

sure

The thing is that I want all classes and and traits within the tree to initialize their member variables. Desired output:

foobarsureloremhappy

It must not be solved with constructors! I just want the member variables to be populated on initialization, but I still had no good idea how to solve this. In a real world example this is more complex, therefore please do not $a = "foo"; just within the variables declaration.

答:
The problem is that traits cannot be instantiated so __construct() is kind of meaningless.

The best approach is to initialize your member variables using the class constructor; that's why constructors exist.

If you want to initialize some members that are declared in a trait, then have a trait function and call it in the appropriate class constructor, example:

```<code>trait Q {
    protected $a;
    public function initQ() { $this->a = "whatever"; }
}

class MyClass {
    use Q;

    public function __construct() {
        $this->initQ();
    }
}
</code>```

Body:
Have a look at the following example:

class A {
    protected $a;
    public function __construct() {
        $this->a = "foo";
    }
}

trait Q {
    protected $q;
    public function __construct() {
        $this->q = "happy";
    }
}

class B extends A {
    use Q;
    protected $b;
    public function __construct() {
        $this->b = "bar";
    }
}

trait X {
    protected $x;
    public function __construct() {
        $this->x = "lorem";
    }
}

class C extends B {
    use X;
    protected $c;
    public function __construct() {
        $this->c = "sure";
    }

    public function giveMeEverything() {
        echo $this->a." ".$this->b." ".$this->c." ".$this->x." ".$this->q;
    }
}

$c = new C();
$c->giveMeEverything();

This works just fine - the output is:

sure

The thing is that I want all classes and and traits within the tree to initialize their member variables. Desired output:

foobarsureloremhappy

It must not be solved with constructors! I just want the member variables to be populated on initialization, but I still had no good idea how to solve this. In a real world example this is more complex, therefore please do not $a = "foo"; just within the variables declaration.

Body:
The problem is that traits cannot be instantiated so __construct() is kind of meaningless.

The best approach is to initialize your member variables using the class constructor; that's why constructors exist.

If you want to initialize some members that are declared in a trait, then have a trait function and call it in the appropriate class constructor, example:

trait Q {
    protected $a;
    public function initQ() { $this->a = "whatever"; }
}

class MyClass {
    use Q;

    public function __construct() {
        $this->initQ();
    }
}


问:
Entity Framework 6 filter the data you access
I have an application which access users and some of their's permission. Those are stored in tables which are used by other applications as well, so it would be disastrous to change anything which would be related to other apps. For instance, if I were to say "User X's permission are R/W on my app" I would not want User X's other applications permissions to disapear.

Is there a way to filter things in such a way ?

Pseudo Data

Permission 1 : UserX, ReadRight, ApplicationA

Permission 2 : UserY, WriteRight, ApplicationA

Permission 3 : UserX, WriteRight, ApplicationB

Permission 4 : UserX, ReadRight, ApplicationB

Application A, pseudo code

```<code>UserX.Permission = [ { WriteRight, ApplicationA }, { WriteRight, ApplicationA } ]
Save UserX
</code>```

Resulting pseudo Data

Permission 1 : UserX, ReadRight, ApplicationA -- Cool, I meant that

Permission 5 : UserX, WriteRight, ApplicationA -- Cool, I meant that

Permission 2 : UserY, WriteRight, ApplicationA

 Permission 3 : UserX, WriteRight, ApplicationB -- Oops!! I didn't mean to delete that.

 Permission 4 : UserX, ReadRight, ApplicationB -- Oops!! I didn't mean to delete that.

Note:

The business nature of Application/User/Permission is not relevant, it could also be  Tree/Farmer/Fruit (If I set the number of fruits of a tree, and it has 5, it doesn't mean Farmer only has 5 fruits)

答:
Disclaimer: I'm the owner of EntityFramework.DynamicFilters

This library allows you to filter data for a specific user.

```<code>modelBuilder.Filter("NotesForCompany", (Note n, int orgID) => n.Person.OrganizationID==orgID, (MyContext ctx) => ctx.CurrentOrganizationID);
modelBuilder.EnableFilter("UserOrg", (MyContext ctx) => !ctx.UserIsAdmin);
</code>```

Body:
I have an application which access users and some of their's permission. Those are stored in tables which are used by other applications as well, so it would be disastrous to change anything which would be related to other apps. For instance, if I were to say "User X's permission are R/W on my app" I would not want User X's other applications permissions to disapear.

Is there a way to filter things in such a way ?

Pseudo Data

Permission 1 : UserX, ReadRight, ApplicationA

Permission 2 : UserY, WriteRight, ApplicationA

Permission 3 : UserX, WriteRight, ApplicationB

Permission 4 : UserX, ReadRight, ApplicationB

Application A, pseudo code

UserX.Permission = [ { WriteRight, ApplicationA }, { WriteRight, ApplicationA } ]
Save UserX

Resulting pseudo Data

Permission 1 : UserX, ReadRight, ApplicationA -- Cool, I meant that

Permission 5 : UserX, WriteRight, ApplicationA -- Cool, I meant that

Permission 2 : UserY, WriteRight, ApplicationA

 Permission 3 : UserX, WriteRight, ApplicationB -- Oops!! I didn't mean to delete that.

 Permission 4 : UserX, ReadRight, ApplicationB -- Oops!! I didn't mean to delete that.

Note:

The business nature of Application/User/Permission is not relevant, it could also be  Tree/Farmer/Fruit (If I set the number of fruits of a tree, and it has 5, it doesn't mean Farmer only has 5 fruits)

Body:
Disclaimer: I'm the owner of EntityFramework.DynamicFilters

This library allows you to filter data for a specific user.

modelBuilder.Filter("NotesForCompany", (Note n, int orgID) => n.Person.OrganizationID==orgID, (MyContext ctx) => ctx.CurrentOrganizationID);
modelBuilder.EnableFilter("UserOrg", (MyContext ctx) => !ctx.UserIsAdmin);


问:
Laravel naming multiple model class name who are related with each other
i'm just thinking here, i had multiple tables related to the student, things like: history, bulletin, parents, course, and a lot more... when i need create a new student, all this tables need to be filled. i'm using Laravel and the recomended is create a model to each table, my problem is now, naming the model name, what's the best aproach? model with table name or a name related to what the model is?

There are only two hard things in Computer Science: cache invalidation
  and naming things.

-- Phil Karlton

答:
There are many conventions for "Models" - Laravel just doesn't bottleneck you or your project into using any one method as long as the model name is clear and has its own table you are following best practices.

for organizational purposes you can add all the related models under the same folder,this is something for you (and your development team, if you're a part of one) to decide on.

```<code>   ├── app
   │   ├── Models <---- folder
   │   │   ├── Students <---- folder
   │   │   │   ├── Student.php    \
   │   │   │   ├── History.php     \ ____ Models
   │   │   │   ├── Bulletin.php    /
   │   │   │   ├── Course.php     /
</code>```

Body:
There are many conventions for "Models" - Laravel just doesn't bottleneck you or your project into using any one method as long as the model name is clear and has its own table you are following best practices.

for organizational purposes you can add all the related models under the same folder,this is something for you (and your development team, if you're a part of one) to decide on.

   ├── app
   │   ├── Models <---- folder
   │   │   ├── Students <---- folder
   │   │   │   ├── Student.php    \
   │   │   │   ├── History.php     \ ____ Models
   │   │   │   ├── Bulletin.php    /
   │   │   │   ├── Course.php     /


答:
If you check the MDN page you'll see that:

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

Your users have different local timezones.
For me new Date(2015, 11, 1) gives Tue Dec 01 2015 00:00:00 GMT+0100 (Romance Standard Time) (I'm in the timezone Central European Time which is GMT+1).

Hence you can follow the MDN hint and use Date.UTC inside of your date call instead:

```<code>var date = new Date(2015, 11, 1);

console.log(date.toString());
// "Tue Dec 01 2015 00:00:00 GMT+0100 (Romance Standard Time)"
//                  00:00:00 in GMT+1 but 23:00:00 in GMT+0

console.log(date.toISOString());
// "2015-11-30T23:00:00.000Z"
//          ^^ 30th of november - that's a nogo!

var utcDate = new Date(Date.UTC(2015, 11, 1));

console.log(utcDate.toString());
// "Tue Dec 01 2015 01:00:00 GMT+0100 (Romance Standard Time) 15:49:26.146"
//                  01:00:00 in GMT+1 but 00:00:00 in GMT+0

console.log(utcDate.toISOString());
// "2015-12-01T00:00:00.000Z"
//          ^^ The first! Not the 30th!
</code>```

Title: Why isn't Date(2015, 11, 1) the first of December?

Body: When I convert that date to ISO string I get the 30th of november 2015. Why wouldn't it be first of december? I have googled and I know that month is 0-indexed and that overflows lead to the next day/month/year. But I cannot explain myself that behaviour and when I google it I find unrelated topics.

Body:
If you check the MDN page you'll see that:

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

Your users have different local timezones.
For me new Date(2015, 11, 1) gives Tue Dec 01 2015 00:00:00 GMT+0100 (Romance Standard Time) (I'm in the timezone Central European Time which is GMT+1).

Hence you can follow the MDN hint and use Date.UTC inside of your date call instead:

var date = new Date(2015, 11, 1);

console.log(date.toString());
// "Tue Dec 01 2015 00:00:00 GMT+0100 (Romance Standard Time)"
//                  00:00:00 in GMT+1 but 23:00:00 in GMT+0

console.log(date.toISOString());
// "2015-11-30T23:00:00.000Z"
//          ^^ 30th of november - that's a nogo!

var utcDate = new Date(Date.UTC(2015, 11, 1));

console.log(utcDate.toString());
// "Tue Dec 01 2015 01:00:00 GMT+0100 (Romance Standard Time) 15:49:26.146"
//                  01:00:00 in GMT+1 but 00:00:00 in GMT+0

console.log(utcDate.toISOString());
// "2015-12-01T00:00:00.000Z"
//          ^^ The first! Not the 30th!


问:
Better way of initialising List of abstract class with inheriting class names
Possibly duplicate, I have an abstract class called FormField which contains some common properties like field value, field label, etc.

My application renders fields dynamically based on an APIs result. So, I can get a JSON which says fieldX of type String, fieldY of type Date, etc. Based on the type I want to automatically render the correct field. I was already able to abstract the logic using an abstract class with static blocks. The abstract class has code like:

```<code>// Common fields
public String label;
public String value;

public static Map<String, Class> fieldTypes = new HashMap<>();

static {
    FormField.fieldTypes.put("String", StringField.class);
    FormField.fieldTypes.put("Date", DateField.class);
}
</code>```

I originally wanted to put the static block in StringField, DateField to add themselves automatically to the fieldTypes array in their parent FormField abstract class but that didn't work since I do not explicitly call these field type classes anywhere so their static blocks never get called at all. I figured the alternative would be to just initialize each inside the FormField static block.

The way the app works, it fetches the data from the API and for each field it calls a create method which takes the type identification string i.e. String, Date and based on that my FormField class initializes the code using this:

```<code>public static FormField create(String type, String label) {
    Class aClass = fieldTypes.get(type);
    if(aClass == null)
        return null;

    FormField field = null;
    try {
        field = (FormField) aClass.newInstance();
        field.label = label;
        return field;
    } catch (InstantiationException e) {
        return null;
    } catch (IllegalAccessException e) {
        return null;
    }
}
</code>```

Then it calls the render method which renders the UI and does further operations. I want to eliminate the static block and want hashmap to fill itself automatically whenever I create (not initialize) a new concrete class that extends it. This would help me to create new concrete classes whenever my business logic needs it i.e. tomorrow I can add any new field type such as photo and just write the specific logic for that rather than having to add a line to the static block each time. I wouldn't mind a better solution which eliminates fieldTypes hashMap too. I know there's some way through reflection to go thro the entire 'fieldTypes' subpackage and initialize one after another but I don't want that (nor do I know how it would be coded) since I feel is bad practice. Any better solutions to this problem?

答:
I can think of two solutions for this problem:

1) This requires an external lib: https://github.com/ronmamo/reflections
Using this libray you can get all instances of a parent class, I assume Field as follows:

```<code>Reflections reflections = new Reflections("your.project.fields");
Set<Class<? extends Field>> allClasses =
     reflections.getSubTypesOf(Field.class);
</code>```

For your case, whenever you introduce a new class to your codebase, this reflective code runs, discovers the class and use it accordingly.

2) Whenever you introduce a new class, you update a file, which contains all BlahField classes. You can initialize your map using this class but, I have to admit that this is less intriguing.

Body:
Possibly duplicate, I have an abstract class called FormField which contains some common properties like field value, field label, etc.

My application renders fields dynamically based on an APIs result. So, I can get a JSON which says fieldX of type String, fieldY of type Date, etc. Based on the type I want to automatically render the correct field. I was already able to abstract the logic using an abstract class with static blocks. The abstract class has code like:

// Common fields
public String label;
public String value;

public static Map<String, Class> fieldTypes = new HashMap<>();

static {
    FormField.fieldTypes.put("String", StringField.class);
    FormField.fieldTypes.put("Date", DateField.class);
}

I originally wanted to put the static block in StringField, DateField to add themselves automatically to the fieldTypes array in their parent FormField abstract class but that didn't work since I do not explicitly call these field type classes anywhere so their static blocks never get called at all. I figured the alternative would be to just initialize each inside the FormField static block.

The way the app works, it fetches the data from the API and for each field it calls a create method which takes the type identification string i.e. String, Date and based on that my FormField class initializes the code using this:

public static FormField create(String type, String label) {
    Class aClass = fieldTypes.get(type);
    if(aClass == null)
        return null;

    FormField field = null;
    try {
        field = (FormField) aClass.newInstance();
        field.label = label;
        return field;
    } catch (InstantiationException e) {
        return null;
    } catch (IllegalAccessException e) {
        return null;
    }
}

Then it calls the render method which renders the UI and does further operations. I want to eliminate the static block and want hashmap to fill itself automatically whenever I create (not initialize) a new concrete class that extends it. This would help me to create new concrete classes whenever my business logic needs it i.e. tomorrow I can add any new field type such as photo and just write the specific logic for that rather than having to add a line to the static block each time. I wouldn't mind a better solution which eliminates fieldTypes hashMap too. I know there's some way through reflection to go thro the entire 'fieldTypes' subpackage and initialize one after another but I don't want that (nor do I know how it would be coded) since I feel is bad practice. Any better solutions to this problem?

Body:
I can think of two solutions for this problem:

1) This requires an external lib: https://github.com/ronmamo/reflections
Using this libray you can get all instances of a parent class, I assume Field as follows:

Reflections reflections = new Reflections("your.project.fields");
Set<Class<? extends Field>> allClasses =
     reflections.getSubTypesOf(Field.class);

For your case, whenever you introduce a new class to your codebase, this reflective code runs, discovers the class and use it accordingly.

2) Whenever you introduce a new class, you update a file, which contains all BlahField classes. You can initialize your map using this class but, I have to admit that this is less intriguing.


问:
Java 9 gives "Main Class not found" ob Ubuntu, but file works on Windows and Mac // how to find main Class in OpenJDK
So I have a jar file that works perfectly fine on Windows and Mac, but not on Ubuntu (the only place where Openjdk is installed)
This question hints at OpenJDK being the problem: Java Application main class not found on Ubuntu
So: how do I show OpenJDK the correct Main Class? (Its Client.class in /chat in the jar file) I know it has something to do with the MetaINF File, but I cant guess the correct input there.
This is what's currently in the MANIFEST.MF file:

Manifest-Version: 1.0

Main-Class: Chat.Client

I cant find anything anywhere on the topic, but I also cant install the proprietary java on the Ubuntu PC, as its the one where the jar HAS to run and the one where I m not admin at.

答:
Not really an answer but an easy workaround for people with the same Problem: Install (installing is optional, you can use it directly after the download) the proprietary JDK from Oracle, and if you dont have admin privileges (I dont): you dont need them, simply download the Java JDK from oracle and start the .Jar with /pathtothedownloadedJDK/bin/java instead of "java" and then the usual -jar yourJarFile.jar

Tl:Dr: Get the JDK from Oracle, you dont need sudo to use it.


问:
find largest value of a tuple element c++
I was wondering if there is a succinct way of finding the max value of one of the elements in a vector of tuples. e.g. for the following, say I want to find the largest second value of the tuple in the vector of tuples.

```<code>vector<tuple<int, int>> foo = { {12,1},{12,5},{5,6} };
</code>```

The result should be 6.

One way I could do this would be something like:

```<code>vector<double> allFoo;
for (int i = 0; i != size(foo); i++) {
    allFoo.emplace_back(get<1>(foo[i]));
}
double maxVal = *max_element(allFoo.begin(), allFoo.end());
</code>```

I feel though, that because you are essentially iterating over things twice, this could be done much more simply?

My tuple skills are a bit limited and it seems like you should be able to do some kind of max_element directly on foo...

答:
a version with structured bindings:</p>

```<code>std::vector<std::tuple<int, int>> tv = { {12, 1}, {13,2}, {11, 1} };

auto [max1, max2] = *max_element(begin(tv), end(tv), [](auto &lhs, auto &rhs) -> int {return std::get<1>(lhs) < std::get<1>(rhs); });

cout << max2 << endl;
</code>```

Body:
I was wondering if there is a succinct way of finding the max value of one of the elements in a vector of tuples. e.g. for the following, say I want to find the largest second value of the tuple in the vector of tuples.

vector<tuple<int, int>> foo = { {12,1},{12,5},{5,6} };

The result should be 6.

One way I could do this would be something like:

vector<double> allFoo;
for (int i = 0; i != size(foo); i++) {
    allFoo.emplace_back(get<1>(foo[i]));
}
double maxVal = *max_element(allFoo.begin(), allFoo.end());

I feel though, that because you are essentially iterating over things twice, this could be done much more simply?

My tuple skills are a bit limited and it seems like you should be able to do some kind of max_element directly on foo...

Body:
a version with structured bindings:

std::vector<std::tuple<int, int>> tv = { {12, 1}, {13,2}, {11, 1} };

auto [max1, max2] = *max_element(begin(tv), end(tv), [](auto &lhs, auto &rhs) -> int {return std::get<1>(lhs) < std::get<1>(rhs); });

cout << max2 << endl;


问:
How to copy a directory structure but only include certain files (using windows batch files)
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:

```<code>folder1
  folder2
    folder3
      data.zip
      info.txt
      abc.xyz
    folder4
    folder5
      data.zip
      somefile.exe
      someotherfile.dll
</code>```

The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?

The resulting directory structure should look like this:

```<code>copy_of_folder1
  folder2
    folder3
      data.zip
      info.txt
    folder4
    folder5
      data.zip
</code>```

答:
That's only two simple commands, but I wouldn't recommend this, unless the files that you DON'T need to copy are small. That's because this will copy ALL files and then remove the files that are not needed in the copy.

```<code>xcopy /E /I folder1 copy_of_folder1
for /F "tokens=1 delims=" %i in ('dir /B /S /A:-D copy_of_files ^| find /V "info.txt" ^| find /V "data.zip"') do del /Q "%i"
</code>```

Sure, the second command is kind of long, but it works!

Also, this approach doesn't require you to download and install any third party tools (Windows 2000+ BATCH has enough commands for this).

OwnerDisplayName: Martin

Body:
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:

folder1
  folder2
    folder3
      data.zip
      info.txt
      abc.xyz
    folder4
    folder5
      data.zip
      somefile.exe
      someotherfile.dll

The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?

The resulting directory structure should look like this:

copy_of_folder1
  folder2
    folder3
      data.zip
      info.txt
    folder4
    folder5
      data.zip

Body:
That's only two simple commands, but I wouldn't recommend this, unless the files that you DON'T need to copy are small. That's because this will copy ALL files and then remove the files that are not needed in the copy.

xcopy /E /I folder1 copy_of_folder1
for /F "tokens=1 delims=" %i in ('dir /B /S /A:-D copy_of_files ^| find /V "info.txt" ^| find /V "data.zip"') do del /Q "%i"

Sure, the second command is kind of long, but it works!

Also, this approach doesn't require you to download and install any third party tools (Windows 2000+ BATCH has enough commands for this).

OwnerDisplayName: Paulius Maruška


问:
Retrieving source code using XMLhttpRequest in javascript
I am trying to get the source code of a website by using XMLhttpRequest in javascript, but I cannot get the response. How do I get source code using XMLhttpRequest? Here is what I have right now:</p>

```<code><script language="Javascript" type="text/javascript">
var req = new XMLHttpRequest();
req.open(
    "GET",
    "http://www.google.com",
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (req.readyState == 4)
    {
        var docx=req.responseXML;
        alert(docx);
    }
}
</script>
</code>```

答:
Use this in place of the given if statement.

```<code>    if (req.readystate == 4) {
        if (req.status == 200) {
            var docx=req.responseXML;
            alert(docx);
            //Can also try this just in case:
            //var doc = req.responseText;
            //alert(doc);
        }
    }
</code>```

You're not checking to make sure the status is ok, this could make the script fail by returning an error (which you might not see if you have debugging off, due to it being Javascript) since the response is not ready until both the ready state is 4 and the status code is 200.  Also, if responseXML doesn't work try responseText, as it might not be properly formatted.

Body:
Use this in place of the given if statement.

    if (req.readystate == 4) {
        if (req.status == 200) {
            var docx=req.responseXML;
            alert(docx);
            //Can also try this just in case:
            //var doc = req.responseText;
            //alert(doc);
        }
    }

You're not checking to make sure the status is ok, this could make the script fail by returning an error (which you might not see if you have debugging off, due to it being Javascript) since the response is not ready until both the ready state is 4 and the status code is 200.  Also, if responseXML doesn't work try responseText, as it might not be properly formatted.