问:
Multiple Uncaught Errors Using the react-rails Gem
To preface my question, I am following this guide.

When trying to build a CRUD interface using Rails and React, I receive this error when trying to create a new item:

addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded.

I wasn't improperly adding a ref attribute to any JSX not inside of a render method, so I must have multiple copies of React within my asset pipeline.

Research yielded the following potential results:

Introducing webpack or Searchkit, suggested in this SO answer, seemed to be clunky workarounds for my simple CRUD interface.

This unselected SO answer suggested removing the //= require react line from ./app/assets/javascripts/application.js.  This proved to be unsuccessful.

Issue #671, from the official GitHub react-rails repo. here, outlines the first part of my issue perfectly.  I followed this potential solution, which suggests removing the //= require react-server line of the ./app/assets/javascripts/server_rendering.js file.  This lead to a new error, outlined below:

Uncaught ReferenceError: $ is not defined

Which I assume means that react_server not only contains a second copy of React, but also loads something vital for my AJAX calls.

For reference, here are the contents of ./app/assets/javascripts/application.js:

```<code>// This is a manifest file that'll be compiled into application.js, which will include all the files
...
// about supported directives.
//
//= require rails-ujs
//= require react
//= require components
//= require turbolinks
//= require_tree .
</code>```

and ./app/assets/javascripts/server_rendering.js:

```<code>//= require react_ujs
//= require react-server
//= require ./components
...
</code>```

Where a set of ellipses, or ..., are used to shorten known comment sections.

Ruby version: 2.3.3p222 (2016-11-21 revision 56859)

Rails version: 5.1.1

react-rails version: 2.2.0

答:
The third potential answer, or removing the //= require react-server from ./app/assets/javascripts/server_rendering.js, was a step in the right direction.

Removing this line doesn't yield a new issue, it just reveals another error you had the entire time.  react_server doesn't define the $ variable for AJAX calls, the jQuery gem does.

Found here.  I am confident in this solution because the error:

Uncaught ReferenceError: $ is not defined

is a jQuery issue, as the AJAX calls you are probably making take a form referenced in their official doc. here.

Therefore, after running gem install jquery-rails in your shell, your ./app/assets/javascripts/application.js should look like this:

```<code>...
//= require rails-ujs
//= require jquery
//= require react
//= require components
//= require turbolinks
//= require_tree .
</code>```

Your ./app/assets/javascripts/server_rendering.js file should look like this:

```<code>//= require react_ujs
// require react-server
//= require ./components
...
</code>```

Note that require react-server is commented out.

And make sure to follow the solution found in this SO answer regarding the .\app\views\layouts\application.html.erb file.

Body:
To preface my question, I am following this guide.

When trying to build a CRUD interface using Rails and React, I receive this error when trying to create a new item:

addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded.

I wasn't improperly adding a ref attribute to any JSX not inside of a render method, so I must have multiple copies of React within my asset pipeline.

Research yielded the following potential results:

Introducing webpack or Searchkit, suggested in this SO answer, seemed to be clunky workarounds for my simple CRUD interface.

This unselected SO answer suggested removing the //= require react line from ./app/assets/javascripts/application.js.  This proved to be unsuccessful.

Issue #671, from the official GitHub react-rails repo. here, outlines the first part of my issue perfectly.  I followed this potential solution, which suggests removing the //= require react-server line of the ./app/assets/javascripts/server_rendering.js file.  This lead to a new error, outlined below:

Uncaught ReferenceError: $ is not defined

Which I assume means that react_server not only contains a second copy of React, but also loads something vital for my AJAX calls.

For reference, here are the contents of ./app/assets/javascripts/application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files
...
// about supported directives.
//
//= require rails-ujs
//= require react
//= require components
//= require turbolinks
//= require_tree .

and ./app/assets/javascripts/server_rendering.js:

//= require react_ujs
//= require react-server
//= require ./components
...

Where a set of ellipses, or ..., are used to shorten known comment sections.

Ruby version: 2.3.3p222 (2016-11-21 revision 56859)

Rails version: 5.1.1

react-rails version: 2.2.0

Body:
The third potential answer, or removing the //= require react-server from ./app/assets/javascripts/server_rendering.js, was a step in the right direction.

Removing this line doesn't yield a new issue, it just reveals another error you had the entire time.  react_server doesn't define the $ variable for AJAX calls, the jQuery gem does.

Found here.  I am confident in this solution because the error:

Uncaught ReferenceError: $ is not defined

is a jQuery issue, as the AJAX calls you are probably making take a form referenced in their official doc. here.

Therefore, after running gem install jquery-rails in your shell, your ./app/assets/javascripts/application.js should look like this:

...
//= require rails-ujs
//= require jquery
//= require react
//= require components
//= require turbolinks
//= require_tree .

Your ./app/assets/javascripts/server_rendering.js file should look like this:

//= require react_ujs
// require react-server
//= require ./components
...

Note that require react-server is commented out.

And make sure to follow the solution found in this SO answer regarding the .\app\views\layouts\application.html.erb file.


来源: stackexchange

问:
What is the difference between ?matrix and ?matrix()
I was going through swirl() again as a refresher, and I've noticed that the author of swirl says the command ?matrix is the correct form to calling for a help screen. But, when I run ?matrix(), it still works? Is there a difference between having and not having a pair of parenthesis?

答:
It's not specific to the swirl environment (about which I was entirely unaware until 5 minutes ago) That is standard for R. The help page for the ? shortcut says:

Arguments

topic

Usually, a name or character string specifying the topic for which help is sought.

Alternatively, a function call to ask for documentation on a corresponding S4 method: see the section on S4 method documentation. The calls pkg::topic and pkg:::topic are treated specially, and look for help on topic in package pkg.

It something like the second option that is being invoked with the command:

```<code>?matrix()
</code>```

Since ?? is actually a different shortcut one needs to use this code to bring up that page, just as one needs to use quoted strings for help with for, if, next or any of the other reserved words in R:

```<code>?'?'   # See ?Reserved
</code>```

This is not based on a "fuzzy logic" search in hte help system. Using help instead of ? gets a different response:

```<code>> help("str()")
No documentation for ‘str()’ in specified packages and libraries:
you could try ‘??str()’
</code>```

You can see the full code for the ? function by typing ? at the command line, but I am just showing how it starts the language level processing of the expressions given to it:

```<code>`?`
function (e1, e2)
{
    if (missing(e2)) {
        type <- NULL
        topicExpr <- substitute(e1)
    }
 #further output omitted
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's not specific to the swirl environment (about which I was entirely unaware until 5 minutes ago) That is standard for R. The help page for the ? shortcut says:

Arguments

topic

Usually, a name or character string specifying the topic for which help is sought.

Alternatively, a function call to ask for documentation on a corresponding S4 method: see the section on S4 method documentation. The calls pkg::topic and pkg:::topic are treated specially, and look for help on topic in package pkg.

It something like the second option that is being invoked with the command:

?matrix()

Since ?? is actually a different shortcut one needs to use this code to bring up that page, just as one needs to use quoted strings for help with for, if, next or any of the other reserved words in R:

?'?'   # See ?Reserved

This is not based on a "fuzzy logic" search in hte help system. Using help instead of ? gets a different response:

> help("str()")
No documentation for ‘str()’ in specified packages and libraries:
you could try ‘??str()’

You can see the full code for the ? function by typing ? at the command line, but I am just showing how it starts the language level processing of the expressions given to it:

`?`
function (e1, e2)
{
    if (missing(e2)) {
        type <- NULL
        topicExpr <- substitute(e1)
    }
 #further output omitted


问:
How to check whether string a is a substring of but not equal to string b?
I know that if we would like to know whether string a is contained in b we can use:

```<code>a in b
</code>```

When a equals to b, the above express still returns True. I would like an expression that would return False when a == b and return True when a is a substring of b. So I used the following expression:

```<code>a in b and a != b
</code>```

I just wonder is there a simpler expression in Python that works in the same way?

答:
This is going to be a short answer, but it is what it is. What you have is enough.

While there might be other alternatives, the way you did it is easy enough to understand, simple and more readable than anything else (of course this is subjective to each and everyone). IMO a simpler expression in Python that works in the same way doesn't exist. That's just my personal perspective on this subject. I'm usually encouraged to follow KISS:

The KISS principle states that most systems work best if they are kept
  simple rather than made complicated; therefore simplicity should be a
  key goal in design and unnecessary complexity should be avoided.

As an example, the other answer it's not any different from the explicit and, and the chaining can be confusing when used with in and == because many people will see that as (a1 in b) != a1, at least at first glance.

Body:
I know that if we would like to know whether string a is contained in b we can use:

a in b

When a equals to b, the above express still returns True. I would like an expression that would return False when a == b and return True when a is a substring of b. So I used the following expression:

a in b and a != b

I just wonder is there a simpler expression in Python that works in the same way?


问:
std::sort function not working in char array
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used  std::sort function .but it's not working.

here is my code

```<code>#include <bits/stdc++.h>

using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
    {
    cin>>n;
    cin>>str;
    low[0]='\0';
    upr[0]='\0';
    int i=0,j=0,k=0;
    while(i<n)
        {
        (str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
        ++i;
        }
    low[j]='\0';
    upr[k]='\0';
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    sort(low,low+j);
    sort(upr,upr+k);
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    }
return 0;
}
</code>```

test case:

```<code>1    // number of test cases
15   // length of string
abHJUdjKIpwlaKm
</code>```

output:

```<code>lowercase=abdjpw    //before sorting
uppercase=HJUKIK    //before sorting
lowercase=abdjpw     //after sorting
uppercase=          //after sorting
</code>```

after sorting uppercase string don't even print.

答: Better variable names would help.  Try replacing j and k with something more descriptive like lowIndex and uprIndex.  Then you should see the problem.

Body:
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used  std::sort function .but it's not working.

here is my code

#include <bits/stdc++.h>

using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
    {
    cin>>n;
    cin>>str;
    low[0]='\0';
    upr[0]='\0';
    int i=0,j=0,k=0;
    while(i<n)
        {
        (str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
        ++i;
        }
    low[j]='\0';
    upr[k]='\0';
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    sort(low,low+j);
    sort(upr,upr+k);
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    }
return 0;
}

test case:

1    // number of test cases
15   // length of string
abHJUdjKIpwlaKm

output:

lowercase=abdjpw    //before sorting
uppercase=HJUKIK    //before sorting
lowercase=abdjpw     //after sorting
uppercase=          //after sorting

after sorting uppercase string don't even print.


问:
How to create a Dependency Property for Binding
I'm working on a "simple" case. I like to create a new custom control which implements a DependencyProperty. In the next step I like to create a binding for updating the properties in both directions. I've builded a simple sample for this case, but the binding doesn't seem to work. I've found a way for updating the DPControl's property by using the FrameworkPropertyMetadata, but I don't know whether it's also a good idea to use the OnPropertyChanged event.

HERE is my sample project:

My control contains simply a Label

```<code><UserControl x:Class="WPF_MVVM_ListBoxMultiSelection.DPControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WPF_MVVM_ListBoxMultiSelection"
             mc:Ignorable="d" Height="84.062" Width="159.641">
    <Grid Margin="0,0,229,268">
        <Label Content="TEST" x:Name="label" Margin="0,0,-221,-102"/>
    </Grid>
</UserControl>
</code>```

and implement a custom dependency property. Currently, I have also implemented the PropertyChanged method for the FramePropertyMetadata and set in this method the label's content, but I like to get it work in both directions.

```<code>public partial class DPControl : UserControl
{
    public DPControl()
    {
        InitializeComponent();
    }

    public string MyCustomLabelContent
    {
        get { return (string)GetValue(MyCustomLabelContentProperty);}
        set
        {
            SetValue(MyCustomLabelContentProperty, value);
        }
    }

    private static void OnMyCustomLabelContentPropertyChanged(DependencyObject source,
    DependencyPropertyChangedEventArgs e)
    {
        DPControl control = (DPControl)source;
        control.label.Content = e.NewValue;
    }

    public static readonly DependencyProperty MyCustomLabelContentProperty = DependencyProperty.Register(
          "MyCustomLabelContent",
          typeof(string),
          typeof(DPControl),
          new FrameworkPropertyMetadata(null,
              OnMyCustomLabelContentPropertyChanged
          )
        );
</code>```

I use this control simply in a Window by:

```<code><local:DPControl MyCustomLabelContent="{Binding MyLabelContent, Mode=TwoWay}" Margin="72,201,286,34"/>
</code>```

MyLabelContent is a property in the ViewModel, which has implemented also the INotifyPropertyChanged interface.

```<code>public class ViewModel_MainWindow:NotifyPropertyChanged
{

    private string _myLabelContent;

    public string MyLabelContent
    {
        get { return _myLabelContent; }
        set { _myLabelContent = value;
            RaisePropertyChanged();
        }
    }...
</code>```

So how can I get it work: Using the binding feature with my new control on custom properties.

答:
In your UserControl:

```<code><Label
    Content="{Binding MyCustomLabelContent, RelativeSource={RelativeSource AncestorType=UserControl}}"
    x:Name="label" Margin="0,0,-221,-102"/>
</code>```

And get rid of that property-changed callback. All you need is the Binding.

I like to get it work in both directions

To make the dependency property two-way by default:

```<code>public static readonly DependencyProperty MyCustomLabelContentProperty =
    DependencyProperty.Register(
        "MyCustomLabelContent",
        typeof(string),
        typeof(DPControl),
        new FrameworkPropertyMetadata(null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
    );
</code>```

I omitted the unnecessary property change handler.

It can't usefully be two-way now, because Label.Content can't generate its own value. If you want your UserControl to set the value in its codebehind, that's easy:

```<code>MyCustomLabelContent = "Some arbitrary value";
</code>```

If you did the binding like I showed you, that will update the Label in the UserControl XAML as well as the viewmodel property bound to the UserControl's dependency property.

If you want the XAML to set it, you'll need to

Lastly, this:

```<code>Margin="0,0,-221,-102"
</code>```

Is not a good way to do layout. WPF layout with Grid, StackPanel, etc. is much easier and more robust.

Body:
I'm working on a "simple" case. I like to create a new custom control which implements a DependencyProperty. In the next step I like to create a binding for updating the properties in both directions. I've builded a simple sample for this case, but the binding doesn't seem to work. I've found a way for updating the DPControl's property by using the FrameworkPropertyMetadata, but I don't know whether it's also a good idea to use the OnPropertyChanged event.

HERE is my sample project:

My control contains simply a Label

<UserControl x:Class="WPF_MVVM_ListBoxMultiSelection.DPControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WPF_MVVM_ListBoxMultiSelection"
             mc:Ignorable="d" Height="84.062" Width="159.641">
    <Grid Margin="0,0,229,268">

    </Grid>
</UserControl>

and implement a custom dependency property. Currently, I have also implemented the PropertyChanged method for the FramePropertyMetadata and set in this method the label's content, but I like to get it work in both directions.

public partial class DPControl : UserControl
{
    public DPControl()
    {
        InitializeComponent();
    }

    public string MyCustomLabelContent
    {
        get { return (string)GetValue(MyCustomLabelContentProperty);}
        set
        {
            SetValue(MyCustomLabelContentProperty, value);
        }
    }

    private static void OnMyCustomLabelContentPropertyChanged(DependencyObject source,
    DependencyPropertyChangedEventArgs e)
    {
        DPControl control = (DPControl)source;
        control.label.Content = e.NewValue;
    }

    public static readonly DependencyProperty MyCustomLabelContentProperty = DependencyProperty.Register(
          "MyCustomLabelContent",
          typeof(string),
          typeof(DPControl),
          new FrameworkPropertyMetadata(null,
              OnMyCustomLabelContentPropertyChanged
          )
        );

I use this control simply in a Window by:

<local:DPControl MyCustomLabelContent="{Binding MyLabelContent, Mode=TwoWay}" Margin="72,201,286,34"/>

MyLabelContent is a property in the ViewModel, which has implemented also the INotifyPropertyChanged interface.

public class ViewModel_MainWindow:NotifyPropertyChanged
{

    private string _myLabelContent;

    public string MyLabelContent
    {
        get { return _myLabelContent; }
        set { _myLabelContent = value;
            RaisePropertyChanged();
        }
    }...

So how can I get it work: Using the binding feature with my new control on custom properties.

Body:
In your UserControl:

<Label
    Content="{Binding MyCustomLabelContent, RelativeSource={RelativeSource AncestorType=UserControl}}"
    x:Name="label" Margin="0,0,-221,-102"/>

And get rid of that property-changed callback. All you need is the Binding.

I like to get it work in both directions

To make the dependency property two-way by default:

public static readonly DependencyProperty MyCustomLabelContentProperty =
    DependencyProperty.Register(
        "MyCustomLabelContent",
        typeof(string),
        typeof(DPControl),
        new FrameworkPropertyMetadata(null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
    );

I omitted the unnecessary property change handler.

It can't usefully be two-way now, because Label.Content can't generate its own value. If you want your UserControl to set the value in its codebehind, that's easy:

MyCustomLabelContent = "Some arbitrary value";

If you did the binding like I showed you, that will update the Label in the UserControl XAML as well as the viewmodel property bound to the UserControl's dependency property.

If you want the XAML to set it, you'll need to

Lastly, this:

Margin="0,0,-221,-102"

Is not a good way to do layout. WPF layout with Grid, StackPanel, etc. is much easier and more robust.


问:
How do you replace unsupported html tags inside a switch statement in an SSRS expression
I have an SSRS textbox currently using the following expression:

```<code>=Switch
(
    First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 0, First(Fields!MyAwesomeNonmessage.Value, "MyAwesomeDataset"),
    First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 1, First(Fields!MyAwesomeMessage.Value, "MyAwesomeDataset")
)
</code>```

with it's markup type set to HTML.

The MyAwesomeMessage and MyAwesomeNonmessage fields both contain html break tags which according microsoft, don't render as such.

https://msdn.microsoft.com/en-us/library/cc645967.aspx

How might I replace all the break tags in the data fields MyAwesomeMessage and MyAwesomeNonmessage with the correct characters to cause a line break on the finished report?

答:
You can wrap your switch expression in a replace that will swap out all the text you specify.

In your case this would probably look like this:

```<code>=Replace(Switch(
                First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 0
               ,First(Fields!MyAwesomeNonmessage.Value, "MyAwesomeDataset")

               ,First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 1
               ,First(Fields!MyAwesomeMessage.Value, "MyAwesomeDataset")
               )
        ,"<br>"
        ,vbcrlf
        )
</code>```

Body:
I have an SSRS textbox currently using the following expression:

=Switch
(
    First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 0, First(Fields!MyAwesomeNonmessage.Value, "MyAwesomeDataset"),
    First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 1, First(Fields!MyAwesomeMessage.Value, "MyAwesomeDataset")
)

with it's markup type set to HTML.

The MyAwesomeMessage and MyAwesomeNonmessage fields both contain html break tags which according microsoft, don't render as such.

https://msdn.microsoft.com/en-us/library/cc645967.aspx

How might I replace all the break tags in the data fields MyAwesomeMessage and MyAwesomeNonmessage with the correct characters to cause a line break on the finished report?

Body:
You can wrap your switch expression in a replace that will swap out all the text you specify.

In your case this would probably look like this:

=Replace(Switch(
                First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 0
               ,First(Fields!MyAwesomeNonmessage.Value, "MyAwesomeDataset")

               ,First(Fields!MyAwesomeId.Value, "MyAwesomeDataset") = 1
               ,First(Fields!MyAwesomeMessage.Value, "MyAwesomeDataset")
               )
        ,"<br>"
        ,vbcrlf
        )


问:
Publishoptions recursively creating cshtml files
I have ASP.NET Core application. In project.json i have the publish option configured as below

```<code>"publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "appsettings.development.json",
      "appsettings.staging.json",
      "appsettings.production.json",
      "web.config"
    ]
  },
</code>```

I am using the default project template created by vs 2015 for asp.net core web projects. So all the .cshtml files are under Views folder.

when i execute dotnet publish -c Development command dotnet publishes Views under

C:\MySolutionDir\Src\MyUIProjectDir\bin\Development\netcoreapp1.0\publish\Views

then i execute the same command again. This time there are cshtml files already exists under bin\Development\netcoreapp1.0\publish\Views so this time publish command additionally creates the following folder structure

C:\MySolutionDir\Src\MyUIProjectDir\bin\Development\netcoreapp1.0\publish\bin\Development\netcoreapp1.0\publish\Views

if i execute the command again then it creates

C:\MySolutionDir\Src\MyUIProjectDir\bin\Development\netcoreapp1.0\publish\bin\Development\netcoreapp1.0\publish\bin\Development\netcoreapp1.0\publish\Views

it basically recursively finds .cshtml files under "MyUIProjectDir" and keep creating deep hierarchy of Views folder.

Also i have other environments, there are folders like

```<code> C:\MySolutionDir\Src\MyUIProjectDir\bin\Staging
 C:\MySolutionDir\Src\MyUIProjectDir\bin\Production
</code>```

The publish command also copies cshtml from "Staging" and "Production" into development.

How do i fix this issue so publish command only copies cshtml from 'MyUIProjectDir\Views' folder (but not from bin)

答:
The only thing that worked for me was to exclude the bin and obj folders explicitly.

```<code>"publishOptions": {
"include": [
  "wwwroot",
  "Views",
  "appsettings.json",
  "web.config"
],
"exclude": [
  "bin",
  "obj"
]  }
</code>```

I also had to delete everthing in AppData\Local\temp\PublishTemp folder before publishing. It was still using the old settings for some reason till i deleted everything from the PublishTemp folder.

Body:
I have ASP.NET Core application. In project.json i have the publish option configured as below

"publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "appsettings.development.json",
      "appsettings.staging.json",
      "appsettings.production.json",
      "web.config"
    ]
  },

I am using the default project template created by vs 2015 for asp.net core web projects. So all the .cshtml files are under Views folder.

when i execute dotnet publish -c Development command dotnet publishes Views under

C:\MySolutionDir\Src\MyUIProjectDir\bin\Development\netcoreapp1.0\publish\Views

then i execute the same command again. This time there are cshtml files already exists under bin\Development\netcoreapp1.0\publish\Views so this time publish command additionally creates the following folder structure

C:\MySolutionDir\Src\MyUIProjectDir\bin\Development\netcoreapp1.0\publish\bin\Development\netcoreapp1.0\publish\Views

if i execute the command again then it creates

C:\MySolutionDir\Src\MyUIProjectDir\bin\Development\netcoreapp1.0\publish\bin\Development\netcoreapp1.0\publish\bin\Development\netcoreapp1.0\publish\Views

it basically recursively finds .cshtml files under "MyUIProjectDir" and keep creating deep hierarchy of Views folder.

Also i have other environments, there are folders like

 C:\MySolutionDir\Src\MyUIProjectDir\bin\Staging
 C:\MySolutionDir\Src\MyUIProjectDir\bin\Production

The publish command also copies cshtml from "Staging" and "Production" into development.

How do i fix this issue so publish command only copies cshtml from 'MyUIProjectDir\Views' folder (but not from bin)

Body:
The only thing that worked for me was to exclude the bin and obj folders explicitly.

"publishOptions": {
"include": [
  "wwwroot",
  "Views",
  "appsettings.json",
  "web.config"
],
"exclude": [
  "bin",
  "obj"
]  }

I also had to delete everthing in AppData\Local\temp\PublishTemp folder before publishing. It was still using the old settings for some reason till i deleted everything from the PublishTemp folder.


问:
Run Python Gtk3 Dialog or message dialog without no transient parent warning
I use Python 2.7 and Gtk3 and every time I launch a Gtk.Dialog I get the warning:

```<code>Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
</code>```

I read this is because the dialog needs a parent window - until I call it with Gtk.DialogFlags.MODAL.

But how?

```<code>#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Question():
    def __init__(self):
        self.message_dialog = Gtk.Dialog(
            "Dialog Title",
            None,
            Gtk.DialogFlags.MODAL,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK)
            )
        self.message_dialog.set_modal(1)
        response = self.message_dialog.run()
        self.message_dialog.destroy()

if __name__ == "__main__":
    q = Question()
</code>```

#

Why not set parent to Gtk.Window() so it runs without warning?

```<code>#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Question():
    def __init__(self):
        self.message_dialog = Gtk.Dialog(
            "Dialog Title",
            Gtk.Window(),
            None,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK)
            )
        response = self.message_dialog.run()
        self.message_dialog.destroy()

if __name__ == "__main__":
    q = Question()
</code>```

答:
What you are seeing is just a warning. The main goal of dialogs is to refer to an already existing UI Window, nevertheless, you can create a dialog without a parent as indicated on the API reference, not recommended but possible:

...and transient parent parent (or NULL for none...

The advantage is that if you set it then you can set if it's modal or not (possible to do it afterwards too). With modal meaning:

A “modal” dialog (that is, one which freezes the rest of the
  application from user input), can be created by calling
  gtk_window_set_modal() on the dialog...

If the dialog is not modal, then you can interact with the parent which sometimes ain't a good thing due to eventual inconsistencies.

Conclusion: if you really need it that way, go ahead, it's just a warning, and don't mind to hide it, or silence it, with a Gtk.Window.

EDIT (to theGtkNerd comment):

The message is indeed a warning, not a compile warning or error but a run-time message. To test it i've done a simple c program and compiled it with Gtk+ version 2 and 3. The result is:

```<code>[...]$ gcc -o dialog dialog.c `pkg-config --cflags --libs gtk+-2.0`
[...]$ ./dialog

[...]$ gcc -o dialog dialog.c `pkg-config --cflags --libs gtk+-3.0`
[...]$ ./dialog
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
</code>```

This message was introduced in Gtk+ 3, not sure which minor version number.

Plus, the documentation is very precise on that. Let's check GtkMessageDialog which inherits from GtkDialog:

parent   transient parent, or NULL for none. [allow-none]

This being said and as i and theGtkNerd pointed out, it's not recommended to use a GtkDialog without a parent for several reasons but as concluded, if you REALLY need it, then go ahead but mind the risks.

Body:
I use Python 2.7 and Gtk3 and every time I launch a Gtk.Dialog I get the warning:

Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.

I read this is because the dialog needs a parent window - until I call it with Gtk.DialogFlags.MODAL.

But how?

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Question():
    def __init__(self):
        self.message_dialog = Gtk.Dialog(
            "Dialog Title",
            None,
            Gtk.DialogFlags.MODAL,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK)
            )
        self.message_dialog.set_modal(1)
        response = self.message_dialog.run()
        self.message_dialog.destroy()

if __name__ == "__main__":
    q = Question()

#

Why not set parent to Gtk.Window() so it runs without warning?

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class Question():
    def __init__(self):
        self.message_dialog = Gtk.Dialog(
            "Dialog Title",
            Gtk.Window(),
            None,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK)
            )
        response = self.message_dialog.run()
        self.message_dialog.destroy()

if __name__ == "__main__":
    q = Question()

Body:
What you are seeing is just a warning. The main goal of dialogs is to refer to an already existing UI Window, nevertheless, you can create a dialog without a parent as indicated on the API reference, not recommended but possible:

...and transient parent parent (or NULL for none...

The advantage is that if you set it then you can set if it's modal or not (possible to do it afterwards too). With modal meaning:

A “modal” dialog (that is, one which freezes the rest of the
  application from user input), can be created by calling
  gtk_window_set_modal() on the dialog...

If the dialog is not modal, then you can interact with the parent which sometimes ain't a good thing due to eventual inconsistencies.

Conclusion: if you really need it that way, go ahead, it's just a warning, and don't mind to hide it, or silence it, with a Gtk.Window.

EDIT (to theGtkNerd comment):

The message is indeed a warning, not a compile warning or error but a run-time message. To test it i've done a simple c program and compiled it with Gtk+ version 2 and 3. The result is:

[...]$ gcc -o dialog dialog.c `pkg-config --cflags --libs gtk+-2.0`
[...]$ ./dialog

[...]$ gcc -o dialog dialog.c `pkg-config --cflags --libs gtk+-3.0`
[...]$ ./dialog
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.

This message was introduced in Gtk+ 3, not sure which minor version number.

Plus, the documentation is very precise on that. Let's check GtkMessageDialog which inherits from GtkDialog:

parent   transient parent, or NULL for none. [allow-none]

This being said and as i and theGtkNerd pointed out, it's not recommended to use a GtkDialog without a parent for several reasons but as concluded, if you REALLY need it, then go ahead but mind the risks.


问:
Load CSV from Blob to Azure SQL Server - Referenced external data source not found
I'm trying to bulk insert a CSV hosted in blob storage into Azure SQL Server, as is described in this MSDN post.

My code is taken almost entirely from this Microsoft Github sample.

When running it I receive the following error:

Referenced external data source "MyAzureBlobStorage" not found.

```<code>-- Create Database Master Key
IF (select Count(*) from sys.symmetric_keys where name like '%DatabaseMasterKey%') = 0
BEGIN
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'MYPASSWORD';
END

-- Create Storage Credential
IF (select Count(*) from sys.database_credentials where name = 'MyAzureBlobStorageCredential') = 0
BEGIN
print 'Creating credential'
CREATE DATABASE SCOPED CREDENTIAL MyAzureBlobStorageCredential
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = '<secret>';
END

-- Create External Data Source
IF (select Count(*) from sys.external_data_sources where name = 'MyAzureBlobStorage') = 0
BEGIN
print 'creating external data source'
CREATE EXTERNAL DATA SOURCE MyAzureBlobStorage
WITH ( TYPE = BLOB_STORAGE,
    LOCATION = 'https://myaccount.blob.core.windows.net/upload',
    CREDENTIAL= MyAzureBlobStorageCredential);
END

-- Create temp table to hold data
IF OBJECT_ID('tempdb..#mytemptable') IS NOT NULL DROP TABLE #mytemptable
CREATE TABLE #mytemptable(
    [Id] [uniqueidentifier] NOT NULL
    -- etc
)

-- Bulk insert into temp table
BULK INSERT #mytemptable
FROM 'mycsv.csv'
WITH ( DATA_SOURCE = 'MyAzureBlobStorage',
        FORMAT='CSV', CODEPAGE = 65001, --UTF-8 encoding
        FIRSTROW=2,
        TABLOCK);
</code>```

Any ideas?

答:
I had the same issue. I found the answer in the comments by @DavidBrowne-Microsoft, pasting it here to make it more visible:

I repro'd, and BULK INSERT currently doesn't work against temp tables. Create a permanent table and try.

Body:
I'm trying to bulk insert a CSV hosted in blob storage into Azure SQL Server, as is described in this MSDN post.

My code is taken almost entirely from this Microsoft Github sample.

When running it I receive the following error:

Referenced external data source "MyAzureBlobStorage" not found.

-- Create Database Master Key
IF (select Count(*) from sys.symmetric_keys where name like '%DatabaseMasterKey%') = 0
BEGIN
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'MYPASSWORD';
END

-- Create Storage Credential
IF (select Count(*) from sys.database_credentials where name = 'MyAzureBlobStorageCredential') = 0
BEGIN
print 'Creating credential'
CREATE DATABASE SCOPED CREDENTIAL MyAzureBlobStorageCredential
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = '<secret>';
END

-- Create External Data Source
IF (select Count(*) from sys.external_data_sources where name = 'MyAzureBlobStorage') = 0
BEGIN
print 'creating external data source'
CREATE EXTERNAL DATA SOURCE MyAzureBlobStorage
WITH ( TYPE = BLOB_STORAGE,
    LOCATION = 'https://myaccount.blob.core.windows.net/upload',
    CREDENTIAL= MyAzureBlobStorageCredential);
END

-- Create temp table to hold data
IF OBJECT_ID('tempdb..#mytemptable') IS NOT NULL DROP TABLE #mytemptable
CREATE TABLE #mytemptable(
    [Id] [uniqueidentifier] NOT NULL
    -- etc
)

-- Bulk insert into temp table
BULK INSERT #mytemptable
FROM 'mycsv.csv'
WITH ( DATA_SOURCE = 'MyAzureBlobStorage',
        FORMAT='CSV', CODEPAGE = 65001, --UTF-8 encoding
        FIRSTROW=2,
        TABLOCK);

Any ideas?


问:
C++ safe boolean idiom cannot compile with Visual C++ 10(2010)
Hey guys, I have derived my class from the C++ safe bool idiom class from this page : The Safe Bool Idiom by Bjorn Karlsson

```<code>class Element : public safe_bool<>
{
public:
    bool Exists() const;
    // boolean_test() is a safe_bool method
    bool boolean_test() const { return Exists(); };
};
</code>```

When I tried to use it in the if expression like below

```<code>Element ele;
...
if(ele)
</code>```

I got an error C2451: conditional expression of type 'Element' is illegal. If I try to cast it to bool like below, I got this error

```<code>Element ele;
...
if((bool)ele)
</code>```

error C2440: 'type cast' : cannot convert from 'Element' to 'bool'

This is the 1st time I am using safe bool idiom, I am not sure if this is not allowed or a bug in Visual C++ 10. Any comments? Thanks in advance!

答:
It doesn't seem to compile with any compiler. Apparently safe_bool cannot return the address of a protected method in its base. You should add a public method to safe_bool_base and return the address of that.

Also, it seems that operators == and != are disabled using a non-dependent construct (may cause an error even if not instantiated).

Perhaps this fixes things:

```<code> class safe_bool_base {
  protected:
    typedef void (safe_bool_base::*bool_type)() const;
  private:
    void cannot_compare_boolean_results() const {}
  public:
    void public_func() const {}
  protected:
    safe_bool_base() {}
    safe_bool_base(const safe_bool_base&) {}
    safe_bool_base& operator=(const safe_bool_base&) {return *this;}
    ~safe_bool_base() {}
  };

  template <typename T=void> class safe_bool : public safe_bool_base {
  public:
    operator bool_type() const {
      return (static_cast<const T*>(this))->boolean_test()
        ? &safe_bool_base::public_func : 0;
    }
  protected:
    ~safe_bool() {}
  };

  template<> class safe_bool<void> : public safe_bool_base {
  public:
    operator bool_type() const {
      return boolean_test()==true ?
        &safe_bool_base::public_func : 0;
    }
  protected:
    virtual bool boolean_test() const=0;
    virtual ~safe_bool() {}
  };

  template <typename T, typename U>
    bool operator==(const safe_bool<T>& lhs,const safe_bool<U>& rhs) {
      lhs.cannot_compare_boolean_results(); //call private method to produce error
      return false;
  }

  template <typename T,typename U>
  bool operator!=(const safe_bool<T>& lhs,const safe_bool<U>& rhs) {
    lhs.cannot_compare_boolean_results(); //call private method to produce error
    return false;
  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hey guys, I have derived my class from the C++ safe bool idiom class from this page : The Safe Bool Idiom by Bjorn Karlsson

class Element : public safe_bool<>
{
public:
    bool Exists() const;
    // boolean_test() is a safe_bool method
    bool boolean_test() const { return Exists(); };
};

When I tried to use it in the if expression like below

Element ele;
...
if(ele)

I got an error C2451: conditional expression of type 'Element' is illegal. If I try to cast it to bool like below, I got this error

Element ele;
...
if((bool)ele)

error C2440: 'type cast' : cannot convert from 'Element' to 'bool'

This is the 1st time I am using safe bool idiom, I am not sure if this is not allowed or a bug in Visual C++ 10. Any comments? Thanks in advance!

Body:
It doesn't seem to compile with any compiler. Apparently safe_bool cannot return the address of a protected method in its base. You should add a public method to safe_bool_base and return the address of that.

Also, it seems that operators == and != are disabled using a non-dependent construct (may cause an error even if not instantiated).

Perhaps this fixes things:

 class safe_bool_base {
  protected:
    typedef void (safe_bool_base::*bool_type)() const;
  private:
    void cannot_compare_boolean_results() const {}
  public:
    void public_func() const {}
  protected:
    safe_bool_base() {}
    safe_bool_base(const safe_bool_base&) {}
    safe_bool_base& operator=(const safe_bool_base&) {return *this;}
    ~safe_bool_base() {}
  };

  template <typename T=void> class safe_bool : public safe_bool_base {
  public:
    operator bool_type() const {
      return (static_cast<const T*>(this))->boolean_test()
        ? &safe_bool_base::public_func : 0;
    }
  protected:
    ~safe_bool() {}
  };

  template<> class safe_bool<void> : public safe_bool_base {
  public:
    operator bool_type() const {
      return boolean_test()==true ?
        &safe_bool_base::public_func : 0;
    }
  protected:
    virtual bool boolean_test() const=0;
    virtual ~safe_bool() {}
  };

  template <typename T, typename U>
    bool operator==(const safe_bool<T>& lhs,const safe_bool<U>& rhs) {
      lhs.cannot_compare_boolean_results(); //call private method to produce error
      return false;
  }

  template <typename T,typename U>
  bool operator!=(const safe_bool<T>& lhs,const safe_bool<U>& rhs) {
    lhs.cannot_compare_boolean_results(); //call private method to produce error
    return false;
  }


问:
Put results as column names in R
I want to convert the result of this function:

```<code>> combn(1:9,6)
         [,75] [,76] [,77] [,78] [,79] [,80] [,81] [,82] [,83] [,84]
[1,]     2     2     2     3     3     3     3     3     3     4
[2,]     4     4     5     4     4     4     4     4     5     5
[3,]     5     6     6     5     5     5     5     6     6     6
[4,]     7     7     7     6     6     6     7     7     7     7
[5,]     8     8     8     7     7     8     8     8     8     8
[6,]     9     9     9     8     9     9     9     9     9     9
</code>```

In a vector containing the results of every column as a "text". I'm using the "paste" function but I only can do it for a unique column:

```<code> > paste(combn(1:9,6)[,84], collapse = '-')
 [1] "4-5-6-7-8-9"
</code>```

And I want to have a vector with 84 values like this:

```<code> > comb
 [1] "4-5-6-7-8-9" "3-4-5-6-7-8"....
</code>```

Thank you so much.

答:
We can use the FUN argument in combn

```<code>v1 <- combn(1:9,6, FUN = paste, collapse="-")
length(v1)
#[1] 84
v1[84]
#[1] "4-5-6-7-8-9"
</code>```

Title: Put results as column names in R

Body:
I want to convert the result of this function:

> combn(1:9,6)
         [,75] [,76] [,77] [,78] [,79] [,80] [,81] [,82] [,83] [,84]
[1,]     2     2     2     3     3     3     3     3     3     4
[2,]     4     4     5     4     4     4     4     4     5     5
[3,]     5     6     6     5     5     5     5     6     6     6
[4,]     7     7     7     6     6     6     7     7     7     7
[5,]     8     8     8     7     7     8     8     8     8     8
[6,]     9     9     9     8     9     9     9     9     9     9

In a vector containing the results of every column as a "text". I'm using the "paste" function but I only can do it for a unique column:

 > paste(combn(1:9,6)[,84], collapse = '-')
 [1] "4-5-6-7-8-9"

And I want to have a vector with 84 values like this:

 > comb
 [1] "4-5-6-7-8-9" "3-4-5-6-7-8"....

Thank you so much.

Body:
We can use the FUN argument in combn

v1 <- combn(1:9,6, FUN = paste, collapse="-")
length(v1)
#[1] 84
v1[84]
#[1] "4-5-6-7-8-9"


问:
Customizing ASP.NET Identity
I'm using Identity Server 4 and I've customised my ASP.NET Identity user as follows:

```<code>public class ApplicationUser : IdentityUser
{
    [MaxLength(100)]
    public virtual string FirstName { get; set; }

    [MaxLength(100)]
    public virtual string LastName { get; set; }
}
</code>```

I can't see where I would configure Identity Server 4 to include these 2 properties in the claims collection.  I've had a look through some of the Identity Server 4 samples but can't see any examples.

I'd ideally like to map these 2 user properties to the given_name and family_name claims.

I'm currently hooking up to the notifications and querying the userinfo endpoint (hybrid flow?).  So I'm not sure if this is configuration of Identity Server or customization of the userinfo endpoint?

答:
Here's what I've done: In AccountController.ExternalLoginCallback I added this:

```<code>//Add claim even if client didn't ask for it
additionalClaims.Add(new Claim(JwtClaimTypes.Email, "email@email.com"));
</code>```

then I added the claim to the access_token by dependency injecting my ProfileService class and adding the claims in the MyProfileService.GetProfileDataAsync like this:

```<code>public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    var claims = new List<Claim>();

    Claim emailClaim = context.Subject.Claims.Where<Claim>(claim => claim.Type.Equals(JwtClaimTypes.Email)).FirstOrDefault();

    if (emailClaim != null)
    {
        claims.Add(emailClaim);
    }

    context.IssuedClaims = claims;
    return Task.FromResult(0);
}
</code>```

Title: Customizing ASP.NET Identity

Body:
I'm using Identity Server 4 and I've customised my ASP.NET Identity user as follows:

public class ApplicationUser : IdentityUser
{
    [MaxLength(100)]
    public virtual string FirstName { get; set; }

    [MaxLength(100)]
    public virtual string LastName { get; set; }
}

I can't see where I would configure Identity Server 4 to include these 2 properties in the claims collection.  I've had a look through some of the Identity Server 4 samples but can't see any examples.

I'd ideally like to map these 2 user properties to the given_name and family_name claims.

I'm currently hooking up to the notifications and querying the userinfo endpoint (hybrid flow?).  So I'm not sure if this is configuration of Identity Server or customization of the userinfo endpoint?

Body:
Here's what I've done: In AccountController.ExternalLoginCallback I added this:

//Add claim even if client didn't ask for it
additionalClaims.Add(new Claim(JwtClaimTypes.Email, "email@email.com"));

then I added the claim to the access_token by dependency injecting my ProfileService class and adding the claims in the MyProfileService.GetProfileDataAsync like this:

public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    var claims = new List<Claim>();

    Claim emailClaim = context.Subject.Claims.Where<Claim>(claim => claim.Type.Equals(JwtClaimTypes.Email)).FirstOrDefault();

    if (emailClaim != null)
    {
        claims.Add(emailClaim);
    }

    context.IssuedClaims = claims;
    return Task.FromResult(0);
}


问:
How to change returned ContentType in ASP.NET MVC controller (ActionResult)
I have ASP.NET MVC controller named dictionary with method ControlsLangJsFile.
Method returns view of users control (ASCX) which contain JavaScript variables.

When i call the method it returns variables with parsed strings, but Content Type is html/text. It should be: application/x-javascript

```<code>public ActionResult ControlsLangJsFile()
    {
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
    }
</code>```

How do i achieve this?

答:
Like this, just change the content type accordingly:

ASP.NET MVC and text/xml content type

Body:
I have ASP.NET MVC controller named dictionary with method ControlsLangJsFile.
Method returns view of users control (ASCX) which contain JavaScript variables.

When i call the method it returns variables with parsed strings, but Content Type is html/text. It should be: application/x-javascript

public ActionResult ControlsLangJsFile()
    {
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
    }

How do i achieve this?


答: I noticed you were using j variable for uppercase and k for lowercase in the while loop then proceeded to do the opposite later.  Was this intentional?  Wondering if that's causing a bug.</p>

Title: std::sort function not working in char array

Body:
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used  std::sort function .but it's not working.

here is my code

#include <bits/stdc++.h>

using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
    {
    cin>>n;
    cin>>str;
    low[0]='\0';
    upr[0]='\0';
    int i=0,j=0,k=0;
    while(i<n)
        {
        (str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
        ++i;
        }
    low[j]='\0';
    upr[k]='\0';
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    sort(low,low+j);
    sort(upr,upr+k);
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    }
return 0;
}

test case:

1    // number of test cases
15   // length of string
abHJUdjKIpwlaKm

output:

lowercase=abdjpw    //before sorting
uppercase=HJUKIK    //before sorting
lowercase=abdjpw     //after sorting
uppercase=          //after sorting

after sorting uppercase string don't even print.


问:
Passing a bash value into Python
I'm running the following bash script to restart my Perforce server whenever it crashes, but what I want to do is make it so the bash script runs a Python script to send a webhook with the exit code of the application to my Slack channel.

The Python script allows you to do something like python app.py 225 and it works, but what I want to do is pass $? into that script, such as python app.py $?.

Whenever the service restarts the echo line reports the exit code properly (In the terminal it shows 225), but when passed into the Python script $? appears as 0.

```<code>#!/bin/bash

until ~/Desktop/shell/p4d; do
    echo "Perforce Server crashed with exit code $?.  Respawning.." >&2
    sleep 1
    python ~/Desktop/shell/app.py $?
done
</code>```

Snippet of the Python script which fetches the argument:

```<code>if __name__ == "__main__":
    error = str(sys.argv[1])
    print error
    post_message(error)
</code>```

How would I do this?

答:
The $? behaves like a variable. After each call to an program (e.g. p4d, sleep, python), the return value of that command is stored in $? by bash.

In your case, $? contains the return value of p4d, when you "echo" it. Afterwards you call the "sleep", which is actually a program "/bin/sleep", so the value of $? gets replaced by the return code of sleep, which is 0.
Therefore the python script gets called with "0" as well.

To solve your problem, you could cache the return code in a local variable, like this:

```<code>#!/bin/bash

until ~/Desktop/shell/p4d; do
    P4D_RETURN=$?
    echo "Perforce Server crashed with exit code $?.  Respawning.." >&2
    sleep 1
    python ~/Desktop/shell/app.py $P4D_RETURN
done
</code>```

Title: Passing a bash value into Python

Body:
I'm running the following bash script to restart my Perforce server whenever it crashes, but what I want to do is make it so the bash script runs a Python script to send a webhook with the exit code of the application to my Slack channel.

The Python script allows you to do something like python app.py 225 and it works, but what I want to do is pass $? into that script, such as python app.py $?.

Whenever the service restarts the echo line reports the exit code properly (In the terminal it shows 225), but when passed into the Python script $? appears as 0.

#!/bin/bash

until ~/Desktop/shell/p4d; do
    echo "Perforce Server crashed with exit code $?.  Respawning.." >&2
    sleep 1
    python ~/Desktop/shell/app.py $?
done

Snippet of the Python script which fetches the argument:

if __name__ == "__main__":
    error = str(sys.argv[1])
    print error
    post_message(error)

How would I do this?

Body:
The $? behaves like a variable. After each call to an program (e.g. p4d, sleep, python), the return value of that command is stored in $? by bash.

In your case, $? contains the return value of p4d, when you "echo" it. Afterwards you call the "sleep", which is actually a program "/bin/sleep", so the value of $? gets replaced by the return code of sleep, which is 0.
Therefore the python script gets called with "0" as well.

To solve your problem, you could cache the return code in a local variable, like this:

#!/bin/bash

until ~/Desktop/shell/p4d; do
    P4D_RETURN=$?
    echo "Perforce Server crashed with exit code $?.  Respawning.." >&2
    sleep 1
    python ~/Desktop/shell/app.py $P4D_RETURN
done


问:
URL redirect C# based on variable
I don't work with C# so please forgive my ignorance.

Currently have this:

///// Layout /////

```<code> @Html.ActionLink("Help", "Help", new { controller = "Help", topic = ViewBag.Topic }, new { target = "_blank" })
</code>```

 //// Controller Help /////

```<code> @if (Request.QueryString.GetValues(0)[0] == "Dash")
 {
     //HTML code
 }
 @if (Request.QueryString.GetValues(0)[0] == "Manage")
 {
     //HTML code2
 }
</code>```

From what I understand, the @Html.ActionLink is pulling a query into the "Help" controller and thus rendering HTML code (internal link) and page based on the topic.

Is there a simple way to turn that into an external URL instead. Thus @if="dash" then url="www.foo.com" instead of HTML code.

Best other option if this is not possible? The key aspect is that each page topic needs to create a URL link to a different page.

答:
If you have many topics I find that the current approach is more clear and easy to mantain, maybe you could change those @if...@if to a if/else-if and store that first parameter of the querystring into a variable</p>

```<code>@{
    String topic ;

    topic = Request.QueryString.GetValues(0)[0] ;

    if (topic.Equals("Dash"))
    {
        //HTML code
    }
    else if (topic.Equals("Manage"))
    {
        //HTML code2
    }
}
</code>```

Title: URL redirect C# based on variable

Body:
I don't work with C# so please forgive my ignorance.

Currently have this:

///// Layout /////

 @Html.ActionLink("Help", "Help", new { controller = "Help", topic = ViewBag.Topic }, new { target = "_blank" })

 //// Controller Help /////

 @if (Request.QueryString.GetValues(0)[0] == "Dash")
 {
     //HTML code
 }
 @if (Request.QueryString.GetValues(0)[0] == "Manage")
 {
     //HTML code2
 }

From what I understand, the @Html.ActionLink is pulling a query into the "Help" controller and thus rendering HTML code (internal link) and page based on the topic.

Is there a simple way to turn that into an external URL instead. Thus @if="dash" then url="www.foo.com" instead of HTML code.

Best other option if this is not possible? The key aspect is that each page topic needs to create a URL link to a different page.

Body:
If you have many topics I find that the current approach is more clear and easy to mantain, maybe you could change those @if...@if to a if/else-if and store that first parameter of the querystring into a variable

@{
    String topic ;

    topic = Request.QueryString.GetValues(0)[0] ;

    if (topic.Equals("Dash"))
    {
        //HTML code
    }
    else if (topic.Equals("Manage"))
    {
        //HTML code2
    }
}


问:
warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) in MFC(VC++)
I am getting this warning "warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)" on below line of code :

```<code>if (g_objConfigurationDetails.bAutoScan !=  m_objScanNASBtn.GetCheck())
        {
            g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck();
}
</code>```

both the lines are giving the same warning.
where bAutoScan  = bool
m_objScanNASBtn = CButton

答:
The following:

```<code>g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck();
</code>```

should be

```<code>g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck() == BST_CHECKED;
</code>```

The problem is GetCheck() doesn't return bool so you have to write a comparison - at least in the form of != 0.

Body:
I am getting this warning "warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)" on below line of code :

if (g_objConfigurationDetails.bAutoScan !=  m_objScanNASBtn.GetCheck())
        {
            g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck();
}

both the lines are giving the same warning.
where bAutoScan  = bool
m_objScanNASBtn = CButton

Body:
The following:

g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck();

should be

g_objConfigurationDetails.bAutoScan = m_objScanNASBtn.GetCheck() == BST_CHECKED;

The problem is GetCheck() doesn't return bool so you have to write a comparison - at least in the form of != 0.


问:
How to create a list where each new element is obtained as the last element plus a constant?
Given these variables:

```<code>a_4th =  6.08
delta_a = 0.052
</code>```

I would like to create a list that contains:

```<code>a = [a_4th, a_5th, a_6th, a_7th ... ]
</code>```

where:

```<code>a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a
</code>```

This code:

```<code>a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a
</code>```

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a
IndexError: list assignment index out of range
```

答:
How about this comprehension?

```<code>a_4th =  6.08
delta_a = 0.052
a = [a_4th + i * delta_a for i in range(20)]
</code>```

Or your code, fixed:

```<code>a_4th =  6.08
delta_a = 0.052
a = [a_4th]
for i in xrange (1,19):
  a.append(a[i-1] + delta_a)  # or the elegant a.append(a[-1] + delta_a) kudos @Prune
</code>```

Also note that appart from the speed benefits of the list comprehension, it also works for both Python 2.x and Python 3.x distributions making it easier to maintain.

Body:
Given these variables:

a_4th =  6.08
delta_a = 0.052

I would like to create a list that contains:

a = [a_4th, a_5th, a_6th, a_7th ... ]

where:

a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a

This code:

a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a
IndexError: list assignment index out of range

Body:
How about this comprehension?

a_4th =  6.08
delta_a = 0.052
a = [a_4th + i * delta_a for i in range(20)]

Or your code, fixed:

a_4th =  6.08
delta_a = 0.052
a = [a_4th]
for i in xrange (1,19):
  a.append(a[i-1] + delta_a)  # or the elegant a.append(a[-1] + delta_a) kudos @Prune

Also note that appart from the speed benefits of the list comprehension, it also works for both Python 2.x and Python 3.x distributions making it easier to maintain.


问:
How to use a tensorflow model extracted from a trained keras model
I want to build and train a neural network using the keras framework. I configured keras that it will use Tensorflow as a backend. After I trained the model with keras I tried to use Tensorflow only. I can access the session and get the tensorflow graph. But I do not know how to use the tensorflow graph for example to make a prediction.

I build a network with the following tutorial
http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/

in the train() method i build and train a model using keras only and save the keras and tensorflow model

in the eval() method

Here is my Code:

```<code>from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import keras.backend.tensorflow_backend as K
import tensorflow as tf
import numpy

sess = tf.Session()
K.set_session(sess)

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]

def train():
    # create model
    model = Sequential()
    model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
    model.add(Dense(8, init='uniform', activation='relu'))
    model.add(Dense(1, init='uniform', activation='sigmoid'))

    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics['accuracy'])

    # Fit the model
    model.fit(X, Y, nb_epoch=10, batch_size=10)

    # evaluate the model
    scores = model.evaluate(X, Y)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100))

    # serialize model to JSON
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    # serialize weights to HDF5
    model.save_weights("model.h5")

    # save tensorflow modell
    saver = tf.train.Saver()
    save_path = saver.save(sess, "model")

def eval():
    # load json and create model
    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)

    # load weights into new model
    loaded_model.load_weights("model.h5")

    # evaluate loaded model on test data
    loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    score = loaded_model.evaluate(X, Y, verbose=0)
    loaded_model.predict(X)
    print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

    # load tensorflow model
    sess = tf.Session()
    saver = tf.train.import_meta_graph('model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # TODO try to predict with the tensorflow model only
    # without using keras functions
</code>```

I can access the tensorflow graph (sess.graph) which the keras framework built for me but I do not know how I can predict with the tensorflow graph. I know how I can build a tensorflow graph and predict with it in generell but not with the model keras build for me.

答:
You need to get the input and output tensors from the Keras model definition and then the current TensorFlow session. Then you can evaluate it using TensorFlow only. Assuming model is your loaded_model and x is your training data.

```<code>sess = K.get_session()
input_tensor = model.input
output_tensor = model.output

output_tensor.eval(feed_dict={input_tensor: x}, session=sess)
</code>```

Body:
I want to build and train a neural network using the keras framework. I configured keras that it will use Tensorflow as a backend. After I trained the model with keras I tried to use Tensorflow only. I can access the session and get the tensorflow graph. But I do not know how to use the tensorflow graph for example to make a prediction.

I build a network with the following tutorial
http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/

in the train() method i build and train a model using keras only and save the keras and tensorflow model

in the eval() method

Here is my Code:

from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import keras.backend.tensorflow_backend as K
import tensorflow as tf
import numpy

sess = tf.Session()
K.set_session(sess)

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]

def train():
    # create model
    model = Sequential()
    model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
    model.add(Dense(8, init='uniform', activation='relu'))
    model.add(Dense(1, init='uniform', activation='sigmoid'))

    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics['accuracy'])

    # Fit the model
    model.fit(X, Y, nb_epoch=10, batch_size=10)

    # evaluate the model
    scores = model.evaluate(X, Y)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100))

    # serialize model to JSON
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    # serialize weights to HDF5
    model.save_weights("model.h5")

    # save tensorflow modell
    saver = tf.train.Saver()
    save_path = saver.save(sess, "model")

def eval():
    # load json and create model
    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)

    # load weights into new model
    loaded_model.load_weights("model.h5")

    # evaluate loaded model on test data
    loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    score = loaded_model.evaluate(X, Y, verbose=0)
    loaded_model.predict(X)
    print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

    # load tensorflow model
    sess = tf.Session()
    saver = tf.train.import_meta_graph('model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # TODO try to predict with the tensorflow model only
    # without using keras functions

I can access the tensorflow graph (sess.graph) which the keras framework built for me but I do not know how I can predict with the tensorflow graph. I know how I can build a tensorflow graph and predict with it in generell but not with the model keras build for me.

Body:
You need to get the input and output tensors from the Keras model definition and then the current TensorFlow session. Then you can evaluate it using TensorFlow only. Assuming model is your loaded_model and x is your training data.

sess = K.get_session()
input_tensor = model.input
output_tensor = model.output

output_tensor.eval(feed_dict={input_tensor: x}, session=sess)


问:
append' produces '()', not the expected contextual result type 'String
I was making an app that would encode messages using regular ciphers that could be decoded on paper, and I ran into this problem. Picture of error

I'm not sure if you need it, but here is the code it is inside:

```<code>func encodeMessage(input:String) -> String {
    var output:String
    if  cipher == "Ceaser/Shift" {
        for i in 0..<input.characters.count {
            output = output.append(alphabet[seekAlphabet(letter: input[i])])
        }
    return output
    }
}
</code>```

Another piece of code that might help:

```<code>func seekAlphabet(letter:String) -> Int {
    for i in 0..<alphabet.count {
        if alphabet[i] == letter {
            return i
        }
    }
}
</code>```

alphabet is just an array that is the alphabet in a series of strings.

Any ideas of why it is doing this? Thanks!

答:
The problem lies on this line:

```<code>output = output.append(alphabet[seekAlphabet(letter: input[i])])
</code>```

The append instance method mutates the original string, it does not return a value with the result. If you would have looked over the docs, you would have seen that it is declared as:

```<code>mutating func append(_ other: String)
</code>```

Here you have two ways to solve this, by replacing

```<code>output = output.append(alphabet[seekAlphabet(letter: input[i])])
</code>```

with either of the following:

output.append(alphabet[seekAlphabet(letter: input[i])])

output = output + alphabet[seekAlphabet(letter: input[i])]

Why was that assignment illegal?

Now, you know that append(_:) is a mutating function, and

```<code>output.append(alphabet[seekAlphabet(letter: input[i])])
</code>```

is a () (a Void), because it just mutates and does not return anything. Therefore, by trying to assign output to the append(_:) method, you try to assign a string to a Void, which is illegal.

Body:
I was making an app that would encode messages using regular ciphers that could be decoded on paper, and I ran into this problem. Picture of error

I'm not sure if you need it, but here is the code it is inside:

func encodeMessage(input:String) -> String {
    var output:String
    if  cipher == "Ceaser/Shift" {
        for i in 0..<input.characters.count {
            output = output.append(alphabet[seekAlphabet(letter: input[i])])
        }
    return output
    }
}

Another piece of code that might help:

func seekAlphabet(letter:String) -> Int {
    for i in 0..<alphabet.count {
        if alphabet[i] == letter {
            return i
        }
    }
}

alphabet is just an array that is the alphabet in a series of strings.

Any ideas of why it is doing this? Thanks!

Body:
The problem lies on this line:

output = output.append(alphabet[seekAlphabet(letter: input[i])])

The append instance method mutates the original string, it does not return a value with the result. If you would have looked over the docs, you would have seen that it is declared as:

mutating func append(_ other: String)

Here you have two ways to solve this, by replacing

output = output.append(alphabet[seekAlphabet(letter: input[i])])

with either of the following:

output.append(alphabet[seekAlphabet(letter: input[i])])

output = output + alphabet[seekAlphabet(letter: input[i])]

Why was that assignment illegal?

Now, you know that append(_:) is a mutating function, and

output.append(alphabet[seekAlphabet(letter: input[i])])

is a () (a Void), because it just mutates and does not return anything. Therefore, by trying to assign output to the append(_:) method, you try to assign a string to a Void, which is illegal.


问:
How to retrieve multiple inherited types from a collection in C++?
Say you have a std::vector class that holds type Item, and you store inherited types of items: Weapon, Potion, Armor, etc. How do you retrieve the item as the inherited class and not the base?</p>

答:
Your design has a bad smell in it. Storing item* has the unfortunate cost of having to manage them outside the vector. The only good motivation for a vector<item*> would be to use the items polymorphically. By trying to detect the type you're demonstrating that you are not using them polymorphically.

A better solution would be to store these items in separate vectors, rather than a communal vector<item*> items, so vector<weapon> weapons, vector<potion> potions, vector<armor> armors.

So please don't use this code, but given vector<item*> items you can do this:

```<code>for(auto i : items) {
    if(dynamic_cast<weapon*>(i) != nullptr) {
        auto iWeapon = static_cast<weapon*>(i);
        // work with weapon here
    } else if(dynamic_cast<potion*>(i) != nullptr) {
        auto iPotion = static_cast<potion*>(i);
        // work with potion here
    } else {
        assert(dynamic_cast<armor*>(i) != nullptr);
        auto iArmor = static_cast<armor*>(i);
        // work with armor here
    }
}
</code>```

Body:
Your design has a bad smell in it. Storing item* has the unfortunate cost of having to manage them outside the vector. The only good motivation for a vector<item*> would be to use the items polymorphically. By trying to detect the type you're demonstrating that you are not using them polymorphically.

A better solution would be to store these items in separate vectors, rather than a communal vector<item*> items, so vector<weapon> weapons, vector<potion> potions, vector<armor> armors.

So please don't use this code, but given vector<item*> items you can do this:

for(auto i : items) {
    if(dynamic_cast<weapon*>(i) != nullptr) {
        auto iWeapon = static_cast<weapon*>(i);
        // work with weapon here
    } else if(dynamic_cast<potion*>(i) != nullptr) {
        auto iPotion = static_cast<potion*>(i);
        // work with potion here
    } else {
        assert(dynamic_cast<armor*>(i) != nullptr);
        auto iArmor = static_cast<armor*>(i);
        // work with armor here
    }
}


问:
User information with Application Insights
I am new to Microsoft Azure Application Insights and need some help on getting user information (Login ID, number of times user logged into application, etc).
I went through another similar stack overflow post Getting User Information in App Insights , but it did not helped me.

I have already setup Application Insights and getting the default data presented by Azure itself.

Request your help on the same.

Thanks in advance.

答:
We did something similar to this using custom properties in our platform - this will be available for grouping in Azure portal as well.

Achievable by TrackPageViews in client side using AI script. With a small tweak:

```<code>appInsights.trackPageView("module_name", "serverUrl", {User: "UserName", DomainName: "Alias" });
</code>```

Reference-Blog post written here: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-sample-mscrm

Body:
We did something similar to this using custom properties in our platform - this will be available for grouping in Azure portal as well.

Achievable by TrackPageViews in client side using AI script. With a small tweak:

appInsights.trackPageView("module_name", "serverUrl", {User: "UserName", DomainName: "Alias" });

Reference-Blog post written here: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-sample-mscrm


答: GetCheck returns an integer and you're comparing it to a boolean. Try comparing GetCheck to BST_UNCHECKED or BST_CHECKED depending on your boolean value, or just cast it to boolean since the 2 values match true and false numerically.

Title: warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) in MFC(VC++)


问:
HTML block stored as var javascript
I am trying to store a block of HTML in javascript variable like this,

```<code>var element = <div class="MMinfoboxRoot">
  <div class="MMinfoboxaddress">
    <div>
      <span class="MMrecordName">leicester
      </span>
      <br>
      <span class="MMdaySpan MMdaySpanTitle">Opening Times
      </span>
      <br>
      <br>
      <span class="MMdaysRoot MMdaysmonday">
        <span class="MMdaySpan">Monday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaystuesday">
        <span class="MMdaySpan">Tuesday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayswednesday">
        <span class="MMdaySpan">Wednesday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaysthursday">
        <span class="MMdaySpan">Thursday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaysfriday">
        <span class="MMdaySpan">Friday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayssaturday">
        <span class="MMdaySpan">Saturday:
        </span>
        <span class="MMdayHoursSpan">9am - 6pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayssunday">
        <span class="MMdaySpan">Sunday:
        </span>
        <span class="MMdayHoursSpan">11am - 5pm
        </span>
      </span>
      <br>
      <br>
      <br>
      <div class="links">
        <strong style="color: rgb(0, 0, 102);">Get directions
        </strong>
        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          <label for="infoboxDir1">From
            <input type="text" id="infoboxDir1" value="birstall" class="text">
          </label>
          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        <a class="go-to-location" onclick="ZoomToLocation( 0 ); return false;" href="#">Zoom to this location
        </a>
      </div>
    </div>
  </div>
</div>
</code>```

However it is throwing js errors saying unecapuslated strings. How can I do this please?

答:
First of you need to use either ' or " to encapsulate strings literals.

Also, you need to add a \ add the end of each line, otherwise JavaScript won't recognize multi line strings.

Something like this will work:

```<code>var element = '<div class="MMinfoboxRoot">\
  <div class="MMinfoboxaddress">\
    <div>\
      <span class="MMrecordName">leicester\
      </span>'
</code>```

Make sure to escape any ' inside that string, and if you want to have line breaks you need to add a \n in front of the trailing \.

Title: HTML block stored as var javascript

Body:
I am trying to store a block of HTML in javascript variable like this,

var element =

      leicester

      Opening Times

        Monday:

        9am - 8pm

        Tuesday:

        9am - 8pm

        Wednesday:

        9am - 8pm

        Thursday:

        9am - 8pm

        Friday:

        9am - 8pm

        Saturday:

        9am - 6pm

        Sunday:

        11am - 5pm

        Get directions

        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          From
            <input type="text" id="infoboxDir1" value="birstall" class="text">

          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        Zoom to this location

However it is throwing js errors saying unecapuslated strings. How can I do this please?

Body:
First of you need to use either ' or " to encapsulate strings literals.

Also, you need to add a \ add the end of each line, otherwise JavaScript won't recognize multi line strings.

Something like this will work:

var element = '<div class="MMinfoboxRoot">\
  <div class="MMinfoboxaddress">\
    <div>\
      <span class="MMrecordName">leicester\
      </span>'

Make sure to escape any ' inside that string, and if you want to have line breaks you need to add a \n in front of the trailing \.


问:
Calling Node.js from C# .NET
Is it possible to call Node.js functions from a C# ASP.NET server?
I found the Edge.js library, but as I understood, it allows Node.js to call into C#. I need the directly reverse solution.</p>

答:
Microsoft.AspNetCore.NodeServices

This provides a fast and robust way for .NET code to run JavaScript on the server inside a Node.js environment. You can use this to consume arbitrary functionality from NPM packages at runtime in your ASP.NET Core app.

Most applications developers don't need to use this directly, but you can do so if you want to implement your own functionality that involves calling Node.js code from .NET at runtime.

Source: https://github.com/aspnet/JavaScriptServices

ContentLicense: CC BY-SA 4.0

Title: Calling Node.js from C# .NET


问:
How to implement OnScrollistener in a fragment
I can't seem to get to implement/extend OnScrollistener for my recyclerview to know when the recyclerview hits the bottom

```<code>public class UpcomingFragment extends Fragment
</code>```

How do i implement it if:

```<code>implements RecyclerView.OnScrollListener
</code>```

and

```<code>implements OnScrollListener
</code>```

give me an "Interface expected here" error

My build gradle module:

```<code>android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "company.com.movieapp"
    minSdkVersion 15
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
 }
}
</code>```

Build grade project

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.2.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
</code>```

}

答:
```<code>private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
    // code
}

@Override
public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
    // code
}
};
</code>```

then add the onScrollListener to the method addOnScrollListener like this

```<code>recyclerView.addOnScrollListener(onScrollListener);
</code>```

Body:
I can't seem to get to implement/extend OnScrollistener for my recyclerview to know when the recyclerview hits the bottom

public class UpcomingFragment extends Fragment

How do i implement it if:

implements RecyclerView.OnScrollListener

and

implements OnScrollListener

give me an "Interface expected here" error

My build gradle module:

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "company.com.movieapp"
    minSdkVersion 15
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
 }
}

Build grade project

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.2.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

}

Body:
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
    // code
}

@Override
public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
    // code
}
};

then add the onScrollListener to the method addOnScrollListener like this

recyclerView.addOnScrollListener(onScrollListener);


答:
Swift String class append(_:) is mutating function and doesn't return anything. Change this line

```<code>output = output.append(alphabet[seekAlphabet(letter: input[i])])
</code>```

to

```<code>output.append(alphabet[seekAlphabet(letter: input[i])])
</code>```

Title: append' produces '()', not the expected contextual result type 'String

Body:
Swift String class append(_:) is mutating function and doesn't return anything. Change this line

output = output.append(alphabet[seekAlphabet(letter: input[i])])

to

output.append(alphabet[seekAlphabet(letter: input[i])])


问:
SSIS:File System Task 'Could not find file'
I am working on a SSIS project that download a file via web and upload the data in sql server then after that move the downloaded file to another folder. Here is an image for a clearer picture

I have a variable:
Source_Folder with a value:C:\Users\T-Aordiz\Documents\DumpDatas\Outbound Dump\Dump
Success_Folder value: C:\Users\T-Aordiz\Documents\DumpDatas\Outbound Dump\Success

For Each Loop values
    Expressions:@[User::Source_Folder] , Variable Mappings: User::FileName(which is blank string)

and here is my file system task

However I encounter this error message

Error: 0xC002F304 at Success, File System Task: An error occurred with the following error message: "Could not find file 'C:\Users\T-Aordiz\Documents\DumpDatas\Outbound Dump\Dump'.".
   Task failed: Success

I tried changing the expression in File System Task but also encountered an error. Help me guys

答:
Source connection,

Option 1,
When using Foreach File Enumerator - 'Retrieve file name', if you choose Fully Qualified, it will give you a complete path, it means  @[User::Filename] includes folder and file name with extension. you can use this variable as source connection variable.

Option 2,
When using Foreach File Enumerator - 'Retrieve file name', if you choose 'Name and Extension', it means you must create another variable FilenameFullpath, expression specified as @[User::Source_Folder] + "\" + @[User::Filename]. (you can always include "\" at the end of your declared folder.)

Destination connection,

You can just specify a folder, no necessary to include file name and extension.


问:
Foreach Loop to supress duplicate but add values
Hope someone can help.

I have this array (this is a only a snippet as there is loads of lines). I have been trying to do this myself today.

```<code>array(628) {
  [0]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "User 2"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [2]=>
  array(3) {
    [0]=>
    string(9) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "8"
  }
  [3]=>
  array(3) {
    [0]=>
    string(7) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "8"
  }
  [4]=>
  array(3) {
    [0]=>
    string(10) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [5]=>
  array(3) {
    [0]=>
    string(9) "User 4"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [6]=>
  array(3) {
    [0]=>
    string(6) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "9"
  }
  [7]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [8]=>
  array(3) {
    [0]=>
    string(9) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [9]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [10]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(1) "0"
    [2]=>
    string(1) "0"
  }
</code>```

As you can see there is duplicate "Users" they wont be called User #. I would like any duplicates gone but the values of [1] added togather and also values of [2] added together also.

Hope that information helps

Thanks

  [0]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "40"
    [2]=>
    string(2) "37"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "User 2"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [2]=>
  array(3) {
    [0]=>
    string(7) "User 3"
    [1]=>
    string(2) "40"
    [2]=>
    string(1) "38"
   }
  [3]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }```

答:
Try this:

```<code>$arr = array ( 0 => array ('User 1', 10, 10),
                1 => array ('User 2', 10, 10),
                2 => array ('User 1', 10, 10),
                3 => array ('User 2', 10, 10),
                4 => array ('User 1', 10, 10),
                5 => array ('User 3', 10, 10),
);
$result = array();

foreach($arr as $val){
    $key = array_search($val[0], array_column($result, 0));
    if($key !== false){
        $result[$key][1] = $result[$key][1] + $val[1];
        $result[$key][2] = $result[$key][2] + $val[2];
    }else{
        $result[] = $val;
    }
}
echo "```";print_r($result);
```

Code Snippet

Body:
Hope someone can help.

I have this array (this is a only a snippet as there is loads of lines). I have been trying to do this myself today.

array(628) {
  [0]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "User 2"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [2]=>
  array(3) {
    [0]=>
    string(9) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "8"
  }
  [3]=>
  array(3) {
    [0]=>
    string(7) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "8"
  }
  [4]=>
  array(3) {
    [0]=>
    string(10) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [5]=>
  array(3) {
    [0]=>
    string(9) "User 4"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [6]=>
  array(3) {
    [0]=>
    string(6) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "9"
  }
  [7]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [8]=>
  array(3) {
    [0]=>
    string(9) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [9]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [10]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(1) "0"
    [2]=>
    string(1) "0"
  }

As you can see there is duplicate "Users" they wont be called User #. I would like any duplicates gone but the values of [1] added togather and also values of [2] added together also.

Hope that information helps

Thanks

  [0]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "40"
    [2]=>
    string(2) "37"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "User 2"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [2]=>
  array(3) {
    [0]=>
    string(7) "User 3"
    [1]=>
    string(2) "40"
    [2]=>
    string(1) "38"
   }
  [3]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }

Body:
Try this:

$arr = array ( 0 => array ('User 1', 10, 10),
                1 => array ('User 2', 10, 10),
                2 => array ('User 1', 10, 10),
                3 => array ('User 2', 10, 10),
                4 => array ('User 1', 10, 10),
                5 => array ('User 3', 10, 10),
);
$result = array();

foreach($arr as $val){
    $key = array_search($val[0], array_column($result, 0));
    if($key !== false){
        $result[$key][1] = $result[$key][1] + $val[1];
        $result[$key][2] = $result[$key][2] + $val[2];
    }else{
        $result[] = $val;
    }
}
echo "<pre>";print_r($result);

Code Snippet


问:
How can I reuse a Dense layer?
I have a network in Tensorflow, and I want to define a function that passes it's input through a tf.layers.dense layer (obviously, the same one). I see the reuse argument, but in order to use it properly it seems I need to keep a global variable just to remember if my function was called already. Is there a cleaner way?

答:
As far as I know, there's no cleaner way. The best we can do is wrap tf.layers.dense into our abstraction and use it as an object, hiding variable scope's backbone:

```<code>def my_dense(*args, **kwargs):
  scope = tf.variable_scope(None, default_name='dense').__enter__()
  def f(input):
    r = tf.layers.dense(input, *args, name=scope, **kwargs)
    scope.reuse_variables()
    return r
  return f

a = [[1,2,3], [4,5,6]]
a = tf.constant(a, dtype=tf.float32)
layer = my_dense(3)
a = layer(a)
a = layer(a)

print(*[[int(a) for a in v.get_shape()] for v in tf.trainable_variables()])
# Prints: "[3, 3] [3]" (one pair of (weights and biases))
</code>```

Title: How can I reuse a Dense layer?

Body:
As far as I know, there's no cleaner way. The best we can do is wrap tf.layers.dense into our abstraction and use it as an object, hiding variable scope's backbone:

def my_dense(*args, **kwargs):
  scope = tf.variable_scope(None, default_name='dense').__enter__()
  def f(input):
    r = tf.layers.dense(input, *args, name=scope, **kwargs)
    scope.reuse_variables()
    return r
  return f

a = [[1,2,3], [4,5,6]]
a = tf.constant(a, dtype=tf.float32)
layer = my_dense(3)
a = layer(a)
a = layer(a)

print(*[[int(a) for a in v.get_shape()] for v in tf.trainable_variables()])
# Prints: "[3, 3] [3]" (one pair of (weights and biases))


问:
TinyMCE editor in Ajax form using jQuery plugin
I have ajax form (http://jquery.malsup.com/form/) and I use jQuery plugin to install my TinyMCE editor. But I cannot get textarea content in ajax request. This is because its in TinyMCE editor iframe. I tried several tutorials from google, but all failed to work for me. Editor shows up, but when I send ajax request, it fails to get edited textarea content.

Here is how I install TinyMCE editor, but this fails

```<code>$("textarea.tinymce").tinymce({
    script_url : tinymceUrl,
    mode : "none",
    theme : "simple",
    setup : function(ed) {
        ed.onChange.add(function() {
            tinyMCE.triggerSave(true,true);
        });
    }
});
</code>```

答:
The onChange event is "iffy" at best.  I recently went through this with a project that I'm on and had to bind the focus & blur events ... it was not pretty. In my setup handler I did the following.  I've removed the code that is specific to my project and put a comment in where to do the save.

```<code>ed.onPostRender.add(function(editor, cm) {
    // Register focus and blur events on BOTH the window and the doc, this way it works properly in
    // IE, Firefox & Chrome
    tinymce.dom.Event.add(editor.getWin(), 'focus', function(e) { });
    tinymce.dom.Event.add(editor.getWin(), 'blur', function(e) { /* save on blur */ });
    tinymce.dom.Event.add(editor.getDoc(), 'focus', function(e) { });
    tinymce.dom.Event.add(editor.getDoc(), 'blur', function(e) { /* save on blur */ });
});
</code>```

On a side note, I noticed that you're calling the editor manager (tinyMCE) with triggerSave(true, true).  I don't see that in the 3.3.9.2 API so I don't know what is attempting to be done there.  In the above code, a handle to the editor (e) is being passed and the method e.save() can be called to perform the save and store it in the textarea field that is being decorated by tinyMCE.

Hope that helps.

Body:
I have ajax form (http://jquery.malsup.com/form/) and I use jQuery plugin to install my TinyMCE editor. But I cannot get textarea content in ajax request. This is because its in TinyMCE editor iframe. I tried several tutorials from google, but all failed to work for me. Editor shows up, but when I send ajax request, it fails to get edited textarea content.

Here is how I install TinyMCE editor, but this fails

$("textarea.tinymce").tinymce({
    script_url : tinymceUrl,
    mode : "none",
    theme : "simple",
    setup : function(ed) {
        ed.onChange.add(function() {
            tinyMCE.triggerSave(true,true);
        });
    }
});

Body:
The onChange event is "iffy" at best.  I recently went through this with a project that I'm on and had to bind the focus & blur events ... it was not pretty. In my setup handler I did the following.  I've removed the code that is specific to my project and put a comment in where to do the save.

ed.onPostRender.add(function(editor, cm) {
    // Register focus and blur events on BOTH the window and the doc, this way it works properly in
    // IE, Firefox & Chrome
    tinymce.dom.Event.add(editor.getWin(), 'focus', function(e) { });
    tinymce.dom.Event.add(editor.getWin(), 'blur', function(e) { /* save on blur */ });
    tinymce.dom.Event.add(editor.getDoc(), 'focus', function(e) { });
    tinymce.dom.Event.add(editor.getDoc(), 'blur', function(e) { /* save on blur */ });
});

On a side note, I noticed that you're calling the editor manager (tinyMCE) with triggerSave(true, true).  I don't see that in the 3.3.9.2 API so I don't know what is attempting to be done there.  In the above code, a handle to the editor (e) is being passed and the method e.save() can be called to perform the save and store it in the textarea field that is being decorated by tinyMCE.

Hope that helps.


问:
Which code is read first when I start my program?
Which part of my C# code is first read when I start my program?

I would like to instantly close the application if a debugger is attached, so where do I put my if (Debugger.IsAttached) code? I've tried putting it inside Program.cs (Main) and I've also tried putting it right after "InitializerComponent();" in "public Form1()" Screenshot: http://prntscr.com/fgl6ql

Screenshot of Program.cs: http://prntscr.com/fgl6zu

答:
LB2 made a good point, so I will add a bunch of

```<code>if (Debugger.IsAttached){
Application.Exit();}
</code>```

in my code at various locations.
Thanks @LB2

Body:
LB2 made a good point, so I will add a bunch of

if (Debugger.IsAttached){
Application.Exit();}

in my code at various locations.
Thanks @LB2