问:
Radio Buttons with Individual Labels for Enum using MVC6 Tag Helpers
My model contains an enum which I'm trying to bind to a list of radio buttons, so that only one value can be selected when the form is submitted.

```<code>public enum Options
{
    [Display(Name="Option A")
    OptionA,
    [Display(Name="Option B")
    OptionB
}

public class MyModel
{
     public Options SelectedOption {get; set;}
     public string TextA{get; set;}
     public string TextB{get; set;}
}
</code>```

In MVC 5, I would render a radio button input for each enum value, and the user would be able to select just one. So the code in the view for each radio button would probably look like this:

```<code>@Html.RadioButtonFor(m => m.SelectedOption, Options.OptionA)
</code>```

The problem with MVC6 seems to be that the input tag helper does not support an enum property out of the box. So if I try to add <input asp-for="SelectedOption"/>, all I get is a textbox.

So my question is, is there a way to do this using an MVC6 tag helper (out of the box or custom) or is there another way to do this? Maybe something like using the old razor syntax or just adding an input tag and populating its attributes?

Please note that ideally there have to be labels for both radio buttons showing the text specified in the enum's [Display] attributes. Also, only one of the TextA or TextB textboxes can appear at the same time and this should be based on the selected radio button, but this is out of the scope of the question. So here's how the rendered markup should look like (more or less):

```<code><div>
    <div>
        <input id="OptionA" type="radio" name="SelectedOption"/>
        <label for="OptionA">Option A</label>
    </div>
    <div>
        <label for="TextA">Text A</label>
        <input type="text" id="TextA" name="TextA">
    </div>
<div>

<div>
<div>
    <input id="OptionB" type="radio" name="SelectedOption"/>
    <label for="OptionB">Option B</label>
</div>

    <div>
        <label for="TextB">Text A</label>
        <input type="text" id="TextB" name="TextB">
    </div>
<div>
</code>```

答:
```<code><enum-radio-button asp-for="ThisEnum"></enum-radio-button>
<enum-radio-button asp-for="ThisEnum" value="ThisEnum.Value001"></enum-radio-button>
</code>```

ThisEnum.Value001 = Auto Checked radio input..

Asp.Net Core TagHelper for enum radio button list

```<code>/// <summary>
/// <see cref="ITagHelper"/> implementation targeting <enum-radio-button> elements with an <c>asp-for</c> attribute, <c>value</c> attribute.
/// </summary>
[HtmlTargetElement("enum-radio-button", Attributes = RadioButtonEnumForAttributeName)]
public class RadioButtonEnumTagHelper : TagHelper
{
    private const string RadioButtonEnumForAttributeName = "asp-for";
    private const string RadioButtonEnumValueAttributeName = "value";

    /// <summary>
    /// Creates a new <see cref="RadioButtonEnumTagHelper"/>.
    /// </summary>
    /// <param name="generator">The <see cref="IHtmlGenerator"/>.</param>
    public RadioButtonEnumTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    /// <inheritdoc />
    public override int Order => -1000;

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    protected IHtmlGenerator Generator { get; }

    /// <summary>
    /// An expression to be evaluated against the current model.
    /// </summary>
    [HtmlAttributeName(RadioButtonEnumForAttributeName)]
    public ModelExpression For { get; set; }

    [HtmlAttributeName(RadioButtonEnumValueAttributeName)]
    public Enum value { get; set; }

    /// <inheritdoc />
    /// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks>
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {

        var childContent = await output.GetChildContentAsync();
        string innerContent = childContent.GetContent();
        output.Content.AppendHtml(innerContent);

        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;
        output.Attributes.Add("class", "btn-group btn-group-radio");

        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (output == null)
        {
            throw new ArgumentNullException(nameof(output));
        }

        var modelExplorer = For.ModelExplorer;
        var metaData = For.Metadata;

        if (metaData.EnumNamesAndValues != null)
        {
            foreach (var item in metaData.EnumNamesAndValues)
            {
                string enum_id = $"{metaData.ContainerType.Name}_{metaData.PropertyName}_{item.Key}";

                bool enum_ischecked = false;
                if (value != null)
                {
                    if (value != null && item.Key.ToString() == value.ToString())
                    {
                        enum_ischecked = true;
                    }
                }
                else
                {
                    if (For.Model != null && item.Key.ToString() == For.Model.ToString())
                    {
                        enum_ischecked = true;
                    }
                }

                string enum_input_label_name = item.Key;
                var enum_resourced_name = metaData.EnumGroupedDisplayNamesAndValues.Where(x => x.Value == item.Value).FirstOrDefault();
                if (enum_resourced_name.Value != null)
                {
                    enum_input_label_name = enum_resourced_name.Key.Name;
                }

                var enum_radio = Generator.GenerateRadioButton(
                    ViewContext,
                    For.ModelExplorer,
                    metaData.PropertyName,
                    item.Key,
                    false,
                    htmlAttributes: new { @id = enum_id });
                enum_radio.Attributes.Remove("checked");
                if (enum_ischecked)
                {
                    enum_radio.MergeAttribute("checked", "checked");
                }
                output.Content.AppendHtml(enum_radio);

                var enum_label = Generator.GenerateLabel(
                    ViewContext,
                    For.ModelExplorer,
                    For.Name,
                    enum_input_label_name,
                    htmlAttributes: new { @for = enum_id, @Class = "btn btn-default" });
                output.Content.AppendHtml(enum_label);
            }
        }
    }
}
</code>```

I'm using this style

Html result

Body:
My model contains an enum which I'm trying to bind to a list of radio buttons, so that only one value can be selected when the form is submitted.

public enum Options
{
    [Display(Name="Option A")
    OptionA,
    [Display(Name="Option B")
    OptionB
}

public class MyModel
{
     public Options SelectedOption {get; set;}
     public string TextA{get; set;}
     public string TextB{get; set;}
}

In MVC 5, I would render a radio button input for each enum value, and the user would be able to select just one. So the code in the view for each radio button would probably look like this:

@Html.RadioButtonFor(m => m.SelectedOption, Options.OptionA)

The problem with MVC6 seems to be that the input tag helper does not support an enum property out of the box. So if I try to add <input asp-for="SelectedOption"/>, all I get is a textbox.

So my question is, is there a way to do this using an MVC6 tag helper (out of the box or custom) or is there another way to do this? Maybe something like using the old razor syntax or just adding an input tag and populating its attributes?

Please note that ideally there have to be labels for both radio buttons showing the text specified in the enum's [Display] attributes. Also, only one of the TextA or TextB textboxes can appear at the same time and this should be based on the selected radio button, but this is out of the scope of the question. So here's how the rendered markup should look like (more or less):

        <input id="OptionA" type="radio" name="SelectedOption"/>
        Option A

        Text A
        <input type="text" id="TextA" name="TextA">

    <input id="OptionB" type="radio" name="SelectedOption"/>
    Option B

        Text A
        <input type="text" id="TextB" name="TextB">

Body:
<enum-radio-button asp-for="ThisEnum"></enum-radio-button>
<enum-radio-button asp-for="ThisEnum" value="ThisEnum.Value001"></enum-radio-button>

ThisEnum.Value001 = Auto Checked radio input..

Asp.Net Core TagHelper for enum radio button list

/// <summary>
/// <see cref="ITagHelper"/> implementation targeting &lt;enum-radio-button&gt; elements with an <c>asp-for</c> attribute, <c>value</c> attribute.
/// </summary>
[HtmlTargetElement("enum-radio-button", Attributes = RadioButtonEnumForAttributeName)]
public class RadioButtonEnumTagHelper : TagHelper
{
    private const string RadioButtonEnumForAttributeName = "asp-for";
    private const string RadioButtonEnumValueAttributeName = "value";

    /// <summary>
    /// Creates a new <see cref="RadioButtonEnumTagHelper"/>.
    /// </summary>
    /// <param name="generator">The <see cref="IHtmlGenerator"/>.</param>
    public RadioButtonEnumTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    /// <inheritdoc />
    public override int Order => -1000;

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    protected IHtmlGenerator Generator { get; }

    /// <summary>
    /// An expression to be evaluated against the current model.
    /// </summary>
    [HtmlAttributeName(RadioButtonEnumForAttributeName)]
    public ModelExpression For { get; set; }

    [HtmlAttributeName(RadioButtonEnumValueAttributeName)]
    public Enum value { get; set; }

    /// <inheritdoc />
    /// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks>
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {

        var childContent = await output.GetChildContentAsync();
        string innerContent = childContent.GetContent();
        output.Content.AppendHtml(innerContent);

        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;
        output.Attributes.Add("class", "btn-group btn-group-radio");

        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (output == null)
        {
            throw new ArgumentNullException(nameof(output));
        }

        var modelExplorer = For.ModelExplorer;
        var metaData = For.Metadata;

        if (metaData.EnumNamesAndValues != null)
        {
            foreach (var item in metaData.EnumNamesAndValues)
            {
                string enum_id = $"{metaData.ContainerType.Name}_{metaData.PropertyName}_{item.Key}";

                bool enum_ischecked = false;
                if (value != null)
                {
                    if (value != null && item.Key.ToString() == value.ToString())
                    {
                        enum_ischecked = true;
                    }
                }
                else
                {
                    if (For.Model != null && item.Key.ToString() == For.Model.ToString())
                    {
                        enum_ischecked = true;
                    }
                }

                string enum_input_label_name = item.Key;
                var enum_resourced_name = metaData.EnumGroupedDisplayNamesAndValues.Where(x => x.Value == item.Value).FirstOrDefault();
                if (enum_resourced_name.Value != null)
                {
                    enum_input_label_name = enum_resourced_name.Key.Name;
                }

                var enum_radio = Generator.GenerateRadioButton(
                    ViewContext,
                    For.ModelExplorer,
                    metaData.PropertyName,
                    item.Key,
                    false,
                    htmlAttributes: new { @id = enum_id });
                enum_radio.Attributes.Remove("checked");
                if (enum_ischecked)
                {
                    enum_radio.MergeAttribute("checked", "checked");
                }
                output.Content.AppendHtml(enum_radio);

                var enum_label = Generator.GenerateLabel(
                    ViewContext,
                    For.ModelExplorer,
                    For.Name,
                    enum_input_label_name,
                    htmlAttributes: new { @for = enum_id, @Class = "btn btn-default" });
                output.Content.AppendHtml(enum_label);
            }
        }
    }
}

I'm using this style

Html result


来源: stackexchange

问:
POST form not working with PHP, working with Postman
This is login code with session. Iam using bootstrap.The code is not redirecting to index.html, when I test it in Postman it works but it is not working in this bootstrap template. I didnt get the reason? Please Help

```<code><?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    $email=$_POST["email"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login where email='$email' and password='$password'";

    $result = mysqli_query($conn,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);

    if ($count>0) {

        // output data of each row
        if($row['admin_role']==1) {
            //$_SESSION["email"]=$email;
            //$_SESSION["id"]=$row['user_id'];

            //echo "Login successfull";

            header('Location: index.html');
            exit;
        }
    } else {
        echo "0 results";
    }
}

?>

<div class="row">
    <div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
        <div class="login-panel panel panel-default">
            <div class="panel-heading"> Admin Log in</div>
            <div class="panel-body">
                <form role="form">
                    <fieldset>
                        <div class="form-group">
                            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">
                        </div>
                        <div class="form-group">
                            <input class="form-control" placeholder="Password" name="password" type="password" value="">
                        </div>
                        <div class="checkbox">
                            <label>
                                <input name="remember" type="checkbox" value="Remember Me">Remember Me
                            </label>
                        </div>
                        <a href="" class="btn btn-primary">Login</a>
                    </fieldset>
                </form>
            </div>
        </div>
    </div><!-- /.col-->
</div><!-- /.row -->
</code>```

答:
OverCoder was right, and by the way, you should check isset for two POST variables before assign value:
if (isset($_POST["email"]) && isset($_POST["password"])) {
 //bla bla
}

ContentLicense: CC BY-SA 3.0

Body:
This is login code with session. Iam using bootstrap.The code is not redirecting to index.html, when I test it in Postman it works but it is not working in this bootstrap template. I didnt get the reason? Please Help

<?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    $email=$_POST["email"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login where email='$email' and password='$password'";

    $result = mysqli_query($conn,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);

    if ($count>0) {

        // output data of each row
        if($row['admin_role']==1) {
            //$_SESSION["email"]=$email;
            //$_SESSION["id"]=$row['user_id'];

            //echo "Login successfull";

            header('Location: index.html');
            exit;
        }
    } else {
        echo "0 results";
    }
}

?>

 Admin Log in

                <form role="form">
                    <fieldset>

                            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">

                            <input class="form-control" placeholder="Password" name="password" type="password" value="">

                                <input name="remember" type="checkbox" value="Remember Me">Remember Me

                        Login
                    </fieldset>
                </form>


问:
collection.save() not persisting data to mongodb
I'm totally new to Nodejs, and I've been trying to update a field in my collection to no avail. Here's my code for pushing into an array on the model.
update array field in model

Then here's my schema.
course schema

Any reason why the changes are not saved to my database ? Thanks .

NB: I've tried using markModified('enrolled_courses.completed_lesson'), but it didn't make any difference.

答:
```<code>router.route('/yourRoute').post((req, res) => {

  Schema.findOneAndUpdate({
    username: newName
  }, {
    $set: {
      enrolled_courses: [
        {
          key: newValue

        }
      ]
    }
  }, {
    upsert: true
  }, function(err, user) {
    if (err) {
      res.json(err);
    } else {
      res.send({message: "Successfully updated"});

    }
  })

});
</code>```


问:
How to write the code recursively?
I want to convert these pieces of code into smaller one via recursion, but I stuck in place where I'm using for loop.

I have the next dictionary: var structure = []; with the structure:

```<code>"path": path,
"children": []
</code>```

I'm filling it by parsing my JSON file. One of the paths from the JSON looks like: "path": "Assignment_1/src/com",, so I'm parsing path by / and trying to rebuild this structure inside of my structure dictionary. The first part, "path": "Assignment_1/", I'm putting inside of my structure. The second part "path": "Assignment_1/src/", I'm putting inside of the children dictionary and so on.

Without recursion I'm doing this:

```<code>if(path.split("/").length == 2) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    structure[j]["children"].push({
                        "path": path1,
                        "children": []
                    })
                }
            }
        }
    }

    if(path.split("/").length == 3) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];
            var path2 = path.split("/")[2];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    for(var k = 0; k < structure[j]["children"].length; k++) {
                        var foundPath = structure[j]["children"][k]["path"];

                        if(foundPath == path1) {
                            structure[j]["children"][k]["children"].push({
                                "path": path2,
                                "children": []
                            })
                        }
                    }
                }

                print(structure);
            }
        }
    }
</code>```

Now I want to unify it, so it will automatically go through all folders and fill my structure dictionary. I started with while loops, but this parts:

```<code>structure[j]["children"].push({ })
structure[j]["children"][k]["children"].push({ })
</code>```

are too difficult to program. Any help or advice will help me a lot!

UPDATE

Input is(one part):

```<code>{
  "path": "Folder_1/src/com",
  "mode": "040000",
  "type": "tree"
},
</code>```

Output:

答:
```<code>var inputs = [
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_2/docs/files",
      "mode": "040000",
      "type":"tree"
    }
],
output = [];

inputs.forEach( function( input ) {
    parse( input.path.split('/'), output );
} );

function parse( input, into ){
    var split = input,
      first = split.shift(),
      newItem = { 'src': first, 'children': [] };

    if( split.length ){
        parse( split, newItem.children );
    }
  if( ! into.find(function(item){return item.src == first } ) ){
        into.push( newItem );
  }
}

console.log( output );
</code>```

Jfiddle

Although I haven't taken into account type == tree, whatever that is.

Title: How to write the code recursively?

Body:
I want to convert these pieces of code into smaller one via recursion, but I stuck in place where I'm using for loop.

I have the next dictionary: var structure = []; with the structure:

"path": path,
"children": []

I'm filling it by parsing my JSON file. One of the paths from the JSON looks like: "path": "Assignment_1/src/com",, so I'm parsing path by / and trying to rebuild this structure inside of my structure dictionary. The first part, "path": "Assignment_1/", I'm putting inside of my structure. The second part "path": "Assignment_1/src/", I'm putting inside of the children dictionary and so on.

Without recursion I'm doing this:

if(path.split("/").length == 2) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    structure[j]["children"].push({
                        "path": path1,
                        "children": []
                    })
                }
            }
        }
    }

    if(path.split("/").length == 3) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];
            var path2 = path.split("/")[2];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    for(var k = 0; k < structure[j]["children"].length; k++) {
                        var foundPath = structure[j]["children"][k]["path"];

                        if(foundPath == path1) {
                            structure[j]["children"][k]["children"].push({
                                "path": path2,
                                "children": []
                            })
                        }
                    }
                }

                print(structure);
            }
        }
    }

Now I want to unify it, so it will automatically go through all folders and fill my structure dictionary. I started with while loops, but this parts:

structure[j]["children"].push({ })
structure[j]["children"][k]["children"].push({ })

are too difficult to program. Any help or advice will help me a lot!

UPDATE

Input is(one part):

{
  "path": "Folder_1/src/com",
  "mode": "040000",
  "type": "tree"
},

Output:

Body:
var inputs = [
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_2/docs/files",
      "mode": "040000",
      "type":"tree"
    }
],
output = [];

inputs.forEach( function( input ) {
    parse( input.path.split('/'), output );
} );

function parse( input, into ){
    var split = input,
      first = split.shift(),
      newItem = { 'src': first, 'children': [] };

    if( split.length ){
        parse( split, newItem.children );
    }
  if( ! into.find(function(item){return item.src == first } ) ){
        into.push( newItem );
  }
}

console.log( output );

Jfiddle

Although I haven't taken into account type == tree, whatever that is.


问:
How do I get this page to redirect? (.htaccess)
when I go to https://www.safepub.com it redirects to https://www.safepub.com/home. How do I get that to stop? I found this in the .htaccess file:

```<code>RewriteCond %{SERVER_PORT} 80
  RewriteRule ^(.*)$ https://www.safepub.com/$1 [R,L]

   RewriteCond %{REQUEST_URI} ^/$
   RewriteRule ^(.*)$ https://www.safepub.com/home [r=301,nc,L]

   RewriteCond ${REQUEST_URI} ^/store/(.*)$
   RewriteRule ^/store/(.*)$ https://www.safepub.com/$1 [r=301,nc,L]
</code>```

I'm not very familiar with that language, so I'm not sure what it's saying. Any help will be greatly appreciated. Thanks.

答:
```<code>RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ https://www.safepub.com/home [r=301,nc,L]
</code>```

In Above lines RewriteCond check if there is no string after / then it will redirect REQUEST_URI to https://www.safepub.com/home.

Flag R (default R=301) takes you to redirected url. If you don't want to rewrite your url to /home then remove flag R.

Body:
when I go to https://www.safepub.com it redirects to https://www.safepub.com/home. How do I get that to stop? I found this in the .htaccess file:

RewriteCond %{SERVER_PORT} 80
  RewriteRule ^(.*)$ https://www.safepub.com/$1 [R,L]

   RewriteCond %{REQUEST_URI} ^/$
   RewriteRule ^(.*)$ https://www.safepub.com/home [r=301,nc,L]

   RewriteCond ${REQUEST_URI} ^/store/(.*)$
   RewriteRule ^/store/(.*)$ https://www.safepub.com/$1 [r=301,nc,L]

I'm not very familiar with that language, so I'm not sure what it's saying. Any help will be greatly appreciated. Thanks.

Body:
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ https://www.safepub.com/home [r=301,nc,L]

In Above lines RewriteCond check if there is no string after / then it will redirect REQUEST_URI to https://www.safepub.com/home.

Flag R (default R=301) takes you to redirected url. If you don't want to rewrite your url to /home then remove flag R.


问:
Android and   in TextView
is it possible to add   in TextView? Has anyone achieved similar functionality?

I want to have non-breakable space in TextView.

答:
This worked for me:</p>

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    textview.setText(Html.fromHtml(your string, Html.FROM_HTML_MODE_LEGACY));
} else {
    textview.setText(Html.fromHtml(your string);
}
</code>```

Title: Android and   in TextView

Body:
This worked for me:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    textview.setText(Html.fromHtml(your string, Html.FROM_HTML_MODE_LEGACY));
} else {
    textview.setText(Html.fromHtml(your string);
}


问:
CMake with flex/bison in CLion
I'm trying to translate a Makefile into CMakeLists.txt.

Makefile which works

```<code>fb1-5:  fb1-5.l fb1-5.y
    bison -d fb1-5.y
    flex fb1-5.l
    cc -o $@ fb1-5.tab.c lex.yy.c -lfl
</code>```

CMakeLists.txt attempt

```<code>cmake_minimum_required(VERSION 3.7)
project(calc)

set(CMAKE_C_STANDARD 99)

FIND_PACKAGE(BISON REQUIRED)
SET(BisonOutput ${CMAKE_SOURCE_DIR}/parser.c)
IF(BISON_FOUND)
    ADD_CUSTOM_COMMAND(
            OUTPUT ${BisonOutput}
            COMMAND ${BISON_EXECUTABLE}
            -d
            ${CMAKE_SOURCE_DIR}/fb1-5.y
            COMMENT "Generating parser.c"
    )
ENDIF()

FIND_PACKAGE(FLEX REQUIRED)
SET(FlexOutput ${CMAKE_SOURCE_DIR}/scanner.c)
IF(FLEX_FOUND)
    ADD_CUSTOM_COMMAND(
            OUTPUT ${FlexOutput}
            COMMAND ${FLEX_EXECUTABLE}
            ${CMAKE_SOURCE_DIR}/fb1-5.l
            COMMENT "Generating fb1-5.l"
    )
ENDIF()

ADD_LIBRARY(calc ${BisonOutput} ${FlexOutput})
</code>```

It says it finds bison and flex in clion

```<code>-- Found BISON: /usr/bin/bison (found version "3.0.4")
-- Found FLEX: /usr/bin/flex (found version "2.6.0")
</code>```

But my CMake script won't generate an executable. How should I define "executable" and how can I make the CMake build script work in CLion?

答:
But my CMake script won't generate an executable. How should I define "executable" and how can I make the CMake build script work in CLion?

I think you should at least do something like this:

```<code>add_executable(fb1-5
  ${BisonOutput}
  ${FlexOutput}
)
</code>```

See add_executable.

Title: CMake with flex/bison in CLion

Body:
I'm trying to translate a Makefile into CMakeLists.txt.

Makefile which works

fb1-5:  fb1-5.l fb1-5.y
    bison -d fb1-5.y
    flex fb1-5.l
    cc -o $@ fb1-5.tab.c lex.yy.c -lfl

CMakeLists.txt attempt

cmake_minimum_required(VERSION 3.7)
project(calc)

set(CMAKE_C_STANDARD 99)

FIND_PACKAGE(BISON REQUIRED)
SET(BisonOutput ${CMAKE_SOURCE_DIR}/parser.c)
IF(BISON_FOUND)
    ADD_CUSTOM_COMMAND(
            OUTPUT ${BisonOutput}
            COMMAND ${BISON_EXECUTABLE}
            -d
            ${CMAKE_SOURCE_DIR}/fb1-5.y
            COMMENT "Generating parser.c"
    )
ENDIF()

FIND_PACKAGE(FLEX REQUIRED)
SET(FlexOutput ${CMAKE_SOURCE_DIR}/scanner.c)
IF(FLEX_FOUND)
    ADD_CUSTOM_COMMAND(
            OUTPUT ${FlexOutput}
            COMMAND ${FLEX_EXECUTABLE}
            ${CMAKE_SOURCE_DIR}/fb1-5.l
            COMMENT "Generating fb1-5.l"
    )
ENDIF()

ADD_LIBRARY(calc ${BisonOutput} ${FlexOutput})

It says it finds bison and flex in clion

-- Found BISON: /usr/bin/bison (found version "3.0.4")
-- Found FLEX: /usr/bin/flex (found version "2.6.0")

But my CMake script won't generate an executable. How should I define "executable" and how can I make the CMake build script work in CLion?

Body:
But my CMake script won't generate an executable. How should I define "executable" and how can I make the CMake build script work in CLion?

I think you should at least do something like this:

add_executable(fb1-5
  ${BisonOutput}
  ${FlexOutput}
)

See add_executable.


问:
Return from list the double value that has the highest absolute value, without making the return value absolute
Short of iterating the collection, is there a way to return the double in a set that has the highest absolute value without making the values in the set actually absolute?</p>

```<code>double[] vals = new double[] { 2.3, 1.7, -3.8};

vals.Max(v => Math.Abs(v)); // This returns 3.8 instead of -3.8
</code>```

答:
Here are two ways of doing this:

First with LINQ:

```<code>double[] vals = new double[] { 2.3, 1.7, -3.8};
var max = vals.Max(x => Math.Abs(x));
Console.WriteLine(vals.Where(z => Math.Abs(z) == max).First());
</code>```

Second with For loop:

```<code>int index =0;
for(int i=0;i<vals.Length;i++)
{
    if(Math.Abs(vals[i])>=Math.Abs(vals[index]))
        index=i;
}
Console.WriteLine(vals[index]);
</code>```

Body:
Short of iterating the collection, is there a way to return the double in a set that has the highest absolute value without making the values in the set actually absolute?

double[] vals = new double[] { 2.3, 1.7, -3.8};

vals.Max(v => Math.Abs(v)); // This returns 3.8 instead of -3.8

Body:
Here are two ways of doing this:

First with LINQ:

double[] vals = new double[] { 2.3, 1.7, -3.8};
var max = vals.Max(x => Math.Abs(x));
Console.WriteLine(vals.Where(z => Math.Abs(z) == max).First());

Second with For loop:

int index =0;
for(int i=0;i<vals.Length;i++)
{
    if(Math.Abs(vals[i])>=Math.Abs(vals[index]))
        index=i;
}
Console.WriteLine(vals[index]);


问:
How to upload arules package in R
I am not able to upload arules package
Below is the following command I am using

```<code>library(arules)
</code>```

I have downloaded the file from http://cran.r-project.org/web/packages/arules/index.html still it is not able to upload it.
Can anyone help me out

答:
If you want to install "arules" package, you may not be able to install it just using the code below.
<<  install.packages("arules")  >>

follow the steps in order to solve problem:

go to the package's address and download it manually.you will find it in the link below:
https://cran.r-project.org/web/packages/arules/index.html

If you are using R-Studio just install that package you have got, by "tools" menu in your IDE (R-studio)
Tools->Install packages->...

brows the file in your computer and install it.

go to the command line and using library(arules) function test the package. If there is still an error it could belong to incompatibility of the package with the version of R (Not R-Studio or any other IDE that you are using), just upgrade R and try installation period again.

Title: How to upload arules package in R

Body:
I am not able to upload arules package
Below is the following command I am using

library(arules)

I have downloaded the file from http://cran.r-project.org/web/packages/arules/index.html still it is not able to upload it.
Can anyone help me out

ContentLicense: CC BY-SA 4.0


问:
Ionic Sqlite : insert dynamic array into table
I am trying to insert an array into my sqlite database. But all the data is getting inserted into the first column. Please help. I already checked these :

https://github.com/litehelpers/Cordova-sqlite-storage/issues/392

sqlite3 insert into dynamic table

But not able to solve my problem.

my code is

```<code> let insertarr:Array;

for(var i=0;i<this.fullData.length;i++)

{
insertarr = [];
for(var j=0;j<this.fullData[i].length;j++)
{

        insertarr.push(this.fullData[i][j].val);

      }
     alert(insertarr);
      db.executeSql('insert into mytable (col1, col2, col3) values(?,?,?)', [insertarr]);
  }
</code>```

When I run the above code col1 is getting populated with the full array. col2 and col3 are populated with null.

答:
Solved this issue. Posting if it helps someone in future.

I changed the arguments of db.executeSql like below:

```<code> db.executeSql('insert into mytable (col1, col2, col3) values('+insertarr+')', {});
</code>```

Body:
I am trying to insert an array into my sqlite database. But all the data is getting inserted into the first column. Please help. I already checked these :

https://github.com/litehelpers/Cordova-sqlite-storage/issues/392

sqlite3 insert into dynamic table

But not able to solve my problem.

my code is

 let insertarr:Array;

for(var i=0;i<this.fullData.length;i++)

{
insertarr = [];
for(var j=0;j<this.fullData[i].length;j++)
{

        insertarr.push(this.fullData[i][j].val);

      }
     alert(insertarr);
      db.executeSql('insert into mytable (col1, col2, col3) values(?,?,?)', [insertarr]);
  }

When I run the above code col1 is getting populated with the full array. col2 and col3 are populated with null.

Body:
Solved this issue. Posting if it helps someone in future.

I changed the arguments of db.executeSql like below:

 db.executeSql('insert into mytable (col1, col2, col3) values('+insertarr+')', {});


问:
How do I fix "Port 80 requires elevated privileges" on Windows Azure with node.js?
I created the simple Node.js express tutorial and it runs locally. I setup my Azure Web App to pull the repo from BitBucket, which it does, but I'm getting the following error in LogFiles/Application:

Port 80 requires elevated privileges

Why would this be happening? Isn't node running at elevated privileges? If not, how do I configure it so it is?

UPDATE: IMPORTANT!!!

This is never clearly explained in any documentation that I saw...

Azure appears to be doing port forwarding for node.js applications. So when you hit your Azure URL on port 80/443 it gets forwarded to another port that your node.js application is running on. YOU DO NOT SET THAT PORT!! It is an environment variable managed by Azure so you simple listen at process.env.PORT. Done, that's it.

答: I just fixed this. In my case it was due to set PORT = 80 in env variables (Application Settings). Once I removed PORT from there and let Azure automatically handle the port the error was gone.</p>


问:
Bootstrap - Adding a pixel border to the active link on a menu
I'm styling my navigation menu but I'm having some trouble. On mobile mode, I have home selected, and gallery is hovered, as per the image below.

However, I want there to be a 1 pixel border running between them. I have the following CSS:

```<code>/* Small Devices, Tablets */
@media only screen and (max-width: 766px) {
.collapsing, .in {background-color: #transparent;  border: 1px; border-color: #7A292A;}
.collapsing .in ul li a {color: #DEE0A3!important;}
.collapsing ul li a:hover, .in ul li a:hover {color: #9D343D!important; border: 1px; border-color: #7A292A;}
.collapsing ul li a:focus, .in ul li a:focus {background-color: #000 !important;}
}
</code>```

But it's not working. Any ideas? I think I want a 1px border at the bottom of the current active navigation link, which I thought was the focus link.

答:
In your HTML markup apply id on the active li and in css media rules target the li#id and apply border-bottom: 1px solid #7A292A;

HTML:

```<code><ul>
    <li id="active">Home</li>
    <li>Gallery</li>
</ul>
</code>```

CSS:

```<code>li#active{ border-bottom: 1px solid #7A292A;}
</code>```

Note: Make sure you are viewing at resolution according to your css media rule.

Body:
I'm styling my navigation menu but I'm having some trouble. On mobile mode, I have home selected, and gallery is hovered, as per the image below.

However, I want there to be a 1 pixel border running between them. I have the following CSS:

/* Small Devices, Tablets */
@media only screen and (max-width: 766px) {
.collapsing, .in {background-color: #transparent;  border: 1px; border-color: #7A292A;}
.collapsing .in ul li a {color: #DEE0A3!important;}
.collapsing ul li a:hover, .in ul li a:hover {color: #9D343D!important; border: 1px; border-color: #7A292A;}
.collapsing ul li a:focus, .in ul li a:focus {background-color: #000 !important;}
}

But it's not working. Any ideas? I think I want a 1px border at the bottom of the current active navigation link, which I thought was the focus link.

Body:
In your HTML markup apply id on the active li and in css media rules target the li#id and apply border-bottom: 1px solid #7A292A;

HTML:

<ul>
    <li id="active">Home</li>
    <li>Gallery</li>
</ul>

CSS:

li#active{ border-bottom: 1px solid #7A292A;}

Note: Make sure you are viewing at resolution according to your css media rule.


问:
ssl connection using python 2.7.13 requests
I tried to use python requests package to connect over SSL and i used below code.

```<code>resp = requests.get(addr , auth=HttpNtlmAuth(userFile[unum],passFile[pnum]) , headers = {'User-Agent':'Mozilla/4.01 (compatible; MSIE 6.0; Windows NT 5.1)'} , verify = False)
</code>```

but every time i got below error.

```<code>("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
</code>```

UPDATE 1:

I dump host certificate and save that to c.cert and used below code.

```<code>resp = requests.get(addr , auth=HttpNtlmAuth(userFile[unum],passFile[pnum]) , headers = {'User-Agent':'Mozilla/4.01 (compatible; MSIE 6.0; Windows NT 5.1)'} , cert = '/home/user/Desktop/c.cert' , verify = '/home/user/Desktop/c.cert')
</code>```

and new error.

```<code>[('PEM routines', 'PEM_read_bio', 'no start line'), ('SSL routines', 'SSL_CTX_use_PrivateKey_file', 'PEM lib')]
</code>```

UPDATE 2 :

Here is what Burp Suite captured.

(First , session creation):

```<code>GET /PATH HTTP/1.1
Host: HOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: ASPSESSIONIDCQCTCTCQ=EPEHGDDAKOINODAJJKCELEOK
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
</code>```

(Second , when use credentials):

```<code>GET /PATH HTTP/1.1
Host: HOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: ASPSESSIONIDCQCTCTCQ=EPEHGDDAKOINODAJJKCELEOK
DNT: 1
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Authorization: NTLM TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=
Connection: close
</code>```

(Third , credentials was wrong)

```<code>GET /PATH HTTP/1.1
Host: HOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: ASPSESSIONIDCQCTCTCQ=EPEHGDDAKOINODAJJKCELEOK
DNT: 1
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGAAAACIAIgAeAAAAAAAAABAAAAACgAKAEAAAAAWABYASgAAAAAAAAAAAAAABYIIAGEAZABtAGkAbgBXAE8AUgBLAFMAVABBAFQASQBPAE4Ao8+kG6lMZcLmQys5IUkpayq+W1VFZPkjUQjxBhzugt88vU6RR3wahQEBAAAAAAAAgPonWPz30gGr58MfeUgvgQAAAAACABIAVwBFAEIAUwBFAFIAVgBFAFIAAQASAFcARQBCAFMARQBSAFYARQBSAAQAEgBXAEUAQgBTAEUAUgBWAEUAUgADABIAVwBFAEIAUwBFAFIAVgBFAFIAAAAAAA==
Connection: close
</code>```

when using URL without HTTPS it gives me page with below custom error

Bad Request (Invalid Hostname)

答:
Maybe you need to create a SSL context, and pass it to requests.

```<code>import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) #if you need TLS v1.2
</code>```

and then, pass this context var to the requests method. If an optional keyword argument, name context. So, the call will be like this:

resp = requests.get(addr, ...., context=context)

Body:
I tried to use python requests package to connect over SSL and i used below code.

resp = requests.get(addr , auth=HttpNtlmAuth(userFile[unum],passFile[pnum]) , headers = {'User-Agent':'Mozilla/4.01 (compatible; MSIE 6.0; Windows NT 5.1)'} , verify = False)

but every time i got below error.

("bad handshake: SysCallError(-1, 'Unexpected EOF')",)

UPDATE 1:

I dump host certificate and save that to c.cert and used below code.

resp = requests.get(addr , auth=HttpNtlmAuth(userFile[unum],passFile[pnum]) , headers = {'User-Agent':'Mozilla/4.01 (compatible; MSIE 6.0; Windows NT 5.1)'} , cert = '/home/user/Desktop/c.cert' , verify = '/home/user/Desktop/c.cert')

and new error.

[('PEM routines', 'PEM_read_bio', 'no start line'), ('SSL routines', 'SSL_CTX_use_PrivateKey_file', 'PEM lib')]

UPDATE 2 :

Here is what Burp Suite captured.

(First , session creation):

GET /PATH HTTP/1.1
Host: HOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: ASPSESSIONIDCQCTCTCQ=EPEHGDDAKOINODAJJKCELEOK
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

(Second , when use credentials):

GET /PATH HTTP/1.1
Host: HOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: ASPSESSIONIDCQCTCTCQ=EPEHGDDAKOINODAJJKCELEOK
DNT: 1
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Authorization: NTLM TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=
Connection: close

(Third , credentials was wrong)

GET /PATH HTTP/1.1
Host: HOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Cookie: ASPSESSIONIDCQCTCTCQ=EPEHGDDAKOINODAJJKCELEOK
DNT: 1
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGAAAACIAIgAeAAAAAAAAABAAAAACgAKAEAAAAAWABYASgAAAAAAAAAAAAAABYIIAGEAZABtAGkAbgBXAE8AUgBLAFMAVABBAFQASQBPAE4Ao8+kG6lMZcLmQys5IUkpayq+W1VFZPkjUQjxBhzugt88vU6RR3wahQEBAAAAAAAAgPonWPz30gGr58MfeUgvgQAAAAACABIAVwBFAEIAUwBFAFIAVgBFAFIAAQASAFcARQBCAFMARQBSAFYARQBSAAQAEgBXAEUAQgBTAEUAUgBWAEUAUgADABIAVwBFAEIAUwBFAFIAVgBFAFIAAAAAAA==
Connection: close

when using URL without HTTPS it gives me page with below custom error

Bad Request (Invalid Hostname)

Body:
Maybe you need to create a SSL context, and pass it to requests.

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) #if you need TLS v1.2

and then, pass this context var to the requests method. If an optional keyword argument, name context. So, the call will be like this:

resp = requests.get(addr, ...., context=context)


问:
Using Bootstrap with Webpack
I have an app that uses Webpack. I'm new to Webpack and trying to learn how to use it effectively. Specifically, I'm trying to import Bootstrap with Font Awesome into my project. I found this SO post, however, I am still unable to use Bootstrap. I'm not sure if it's out-of-date, or if I'm misunderstanding something.

I tried loading Bootstrap and Font Awesome via the url-loader. I was referencing the following URLs:

```<code>https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css
https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css
</code>```

I also tried using loading Bootstrap and Font Awesome via NPM and then referencing it in my entry file like this:

```<code>require('bootstrap');
require('font-awesome');
</code>```

It seems like this should be part of a commonly used template. However, I'm not finding one. How do I use Bootstrap and Font Awesome with Webpack?

However, I've come up short with that approach as well.

答:
if you are not generating your base HTML file dynamically then you can symply include a <link> tag in your base html's head section (means same base html file everywhere)

and if you want to use it using webpack then along with url-loader you need to use either style-loader and css-loader (if you want to insert the style as style tag in head witch is probabbly not the case)

or you can use webpack's extract to text plugin to load as a different file and insert it using html link tag

for reference you can use this open source project's configration file

webpack production config

and

webpack developement config

edit: link update

Title: Using Bootstrap with Webpack

Body:
I have an app that uses Webpack. I'm new to Webpack and trying to learn how to use it effectively. Specifically, I'm trying to import Bootstrap with Font Awesome into my project. I found this SO post, however, I am still unable to use Bootstrap. I'm not sure if it's out-of-date, or if I'm misunderstanding something.

I tried loading Bootstrap and Font Awesome via the url-loader. I was referencing the following URLs:

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css
https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css

I also tried using loading Bootstrap and Font Awesome via NPM and then referencing it in my entry file like this:

require('bootstrap');
require('font-awesome');

It seems like this should be part of a commonly used template. However, I'm not finding one. How do I use Bootstrap and Font Awesome with Webpack?

However, I've come up short with that approach as well.


问:
iPhone mapview will only update when in wifi
I have a little application in progress.
One of my current problems is: it seems that the MapView will only load map data when I am in wifi range (when e.g. zooming in). When only 3G/2G is available, it displays the tiles already cached but will not load new ones. It seems to be no problem with the general setup of my iPhone: the Maps application works nicley.

Any ideas?

答: ... well, looks like I was indeed too impatient. Sometimes, it takes a lot of time until the maps starts loading.</p>

ContentLicense: CC BY-SA 2.5


问:
How to use row_number() to filter duplicates with multiple joins?
I need to filter duplicates in base of other column. This is the code I am trying. Unfortunately, it doesn't work as the query never finish.

```<code>Select r1, r2, r3...,rb1,..., rc1,...
From (
  Select *, ROW_NUMBER() OVER (PARTITION BY r1 order by r6 DESC) AS rownbr
  From
    table1
    join table2 ON r2=rb1
    Join table3 ON r6=rc1
    Join table4 ON rx=rdx
) source
Where
  rownbr=1
</code>```

Any ideas?

答:
Sorry can't add a comment yet...

Assuming your joins are correct, why not just use group by?

```<code>    Select r1, r2, r3...,rb1,..., rc1,...
From (
  Select *
  From
    table1
    join table2 ON r2=rb1
    Join table3 ON r6=rc1
    Join table 4 ON rx=rdx
) source
group by r1, r2, r3...,rb1,..., rc1,...
</code>```

Body:
I need to filter duplicates in base of other column. This is the code I am trying. Unfortunately, it doesn't work as the query never finish.

Select r1, r2, r3...,rb1,..., rc1,...
From (
  Select *, ROW_NUMBER() OVER (PARTITION BY r1 order by r6 DESC) AS rownbr
  From
    table1
    join table2 ON r2=rb1
    Join table3 ON r6=rc1
    Join table4 ON rx=rdx
) source
Where
  rownbr=1

Any ideas?

Body:
Sorry can't add a comment yet...

Assuming your joins are correct, why not just use group by?

    Select r1, r2, r3...,rb1,..., rc1,...
From (
  Select *
  From
    table1
    join table2 ON r2=rb1
    Join table3 ON r6=rc1
    Join table 4 ON rx=rdx
) source
group by r1, r2, r3...,rb1,..., rc1,...


问:
Delete selected gridview row
trying to delete selected gridview row. I read few sites and used code however I am getting error. I think because most of the codes I've seen they using DataGridView, This code is within delete button event

```<code>   For i = 0 To myGridView.Rows.Count - 1 Step i + 1
        Dim delrow As GridViewRow = myGridView.Rows(i)
        If delrow.Selected = True Then
            myGridView.Rows.RemoveAt(i)
        End If
    Next
</code>```

the two errors I am getting are:

1) RemoveAt is not a member of GridViewRowCollection
2) Selected is not a member of GridViewRow

Your help will be highly appreciated!

答:
I usually delete rows on GridViews putting an ImageButton (with a trash bin) on every row with a Template Field, then on RowDataBound event I associate "DeleteRow" event and rowIndex to the CommandName and CommandArgument</p>

```<code>Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim ib As ImageButton = e.Row.FindControl("ibDeleteRow")
        ib.CommandName = "DeleteRow"
        ib.CommandArgument = e.Row.RowIndex
    End if
end sub

Private Sub myGridView_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName = "DeleteRow" Then
        Dim rowToDeleteIndex as integer = e.CommandArgument
        myGridView.DeleteRow(rowToDeleteIndex)
    end if
end sub

Private Sub myGridView_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GridView1.RowDeleting

End Sub
</code>```

Title: Delete selected gridview row

Body:
trying to delete selected gridview row. I read few sites and used code however I am getting error. I think because most of the codes I've seen they using DataGridView, This code is within delete button event

   For i = 0 To myGridView.Rows.Count - 1 Step i + 1
        Dim delrow As GridViewRow = myGridView.Rows(i)
        If delrow.Selected = True Then
            myGridView.Rows.RemoveAt(i)
        End If
    Next

the two errors I am getting are:

1) RemoveAt is not a member of GridViewRowCollection
2) Selected is not a member of GridViewRow

Your help will be highly appreciated!

Body:
I usually delete rows on GridViews putting an ImageButton (with a trash bin) on every row with a Template Field, then on RowDataBound event I associate "DeleteRow" event and rowIndex to the CommandName and CommandArgument

Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim ib As ImageButton = e.Row.FindControl("ibDeleteRow")
        ib.CommandName = "DeleteRow"
        ib.CommandArgument = e.Row.RowIndex
    End if
end sub

Private Sub myGridView_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName = "DeleteRow" Then
        Dim rowToDeleteIndex as integer = e.CommandArgument
        myGridView.DeleteRow(rowToDeleteIndex)
    end if
end sub

Private Sub myGridView_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GridView1.RowDeleting

End Sub


问:
How to create lower density plot using your own density function in GGally
With the following code:

```<code>library(GGally)
library(tidyverse)
library(viridis)

dat <- iris %>% select(-Species)

my_fn <- function(data, mapping, ...){
      # Using default ggplot density function

      p <- ggplot(data = data, mapping = mapping) +
        stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
        scale_fill_gradientn(colours=viridis::viridis(100, option="viridis"))
      p
}

ggpairs(dat, lower=list(continuous=my_fn)) +
  theme_void()
</code>```

I can create this plot:

My question is how can I change the GGally lower density plot with the following scheme:

```<code>library(MASS)
# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}

# Data wrangling method2 --------------------------------------------------
theme_set(theme_bw(base_size = 16))
tbl <- as.tibble(iris) %>%
        select(-Species)

# tbl
dens_wrapper <- function (tbl=NULL, var1=NULL, var2=NULL) {
  tbl_pair <- tbl %>%
                select_(var1, var2)
  x <- tbl_pair %>% pull(var1)
  y <- tbl_pair %>% pull(var2)
  tbl_pair$density <- get_density(x,y)
  tbl_pair
}

feature1 = "Sepal.Length"
feature2 = "Petal.Length"
tbl_pair1 <- dens_wrapper(tbl=tbl, var1=feature1, var2=feature2)
ggplot(tbl_pair1) +
  geom_point(aes_string(feature1, feature2, color = 'density')) +
  scale_color_viridis()
</code>```

Which produce this:

答:
Using a similar idea as from Change colors in ggpairs now that params is deprecated , you can just add the calculations in to your own defined function.

```<code>my_fn <- function(data, mapping, N=100, ...){

      get_density <- function(x, y, n ) {
                  dens <- MASS::kde2d(x = x, y = y, n = n)
                  ix <- findInterval(x, dens$x)
                  iy <- findInterval(y, dens$y)
                  ii <- cbind(ix, iy)
                  return(dens$z[ii])
                }

      X <- eval_data_col(data, mapping$x)
      Y <- eval_data_col(data, mapping$y)

      data$density <- get_density(x=X, y=Y, n=N)

      p <- ggplot(data, mapping) +
               geom_point(aes(colour=density), ...) +
               scale_color_viridis()
      p
}

 ggpairs(dat, lower=list(continuous=my_fn)) +
 theme_bw()
</code>```

Produces:

Body:
With the following code:

library(GGally)
library(tidyverse)
library(viridis)

dat <- iris %>% select(-Species)

my_fn <- function(data, mapping, ...){
      # Using default ggplot density function

      p <- ggplot(data = data, mapping = mapping) +
        stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
        scale_fill_gradientn(colours=viridis::viridis(100, option="viridis"))
      p
}

ggpairs(dat, lower=list(continuous=my_fn)) +
  theme_void()

I can create this plot:

My question is how can I change the GGally lower density plot with the following scheme:

library(MASS)
# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}

# Data wrangling method2 --------------------------------------------------
theme_set(theme_bw(base_size = 16))
tbl <- as.tibble(iris) %>%
        select(-Species)

# tbl
dens_wrapper <- function (tbl=NULL, var1=NULL, var2=NULL) {
  tbl_pair <- tbl %>%
                select_(var1, var2)
  x <- tbl_pair %>% pull(var1)
  y <- tbl_pair %>% pull(var2)
  tbl_pair$density <- get_density(x,y)
  tbl_pair
}

feature1 = "Sepal.Length"
feature2 = "Petal.Length"
tbl_pair1 <- dens_wrapper(tbl=tbl, var1=feature1, var2=feature2)
ggplot(tbl_pair1) +
  geom_point(aes_string(feature1, feature2, color = 'density')) +
  scale_color_viridis()

Which produce this:

Body:
Using a similar idea as from Change colors in ggpairs now that params is deprecated , you can just add the calculations in to your own defined function.

my_fn <- function(data, mapping, N=100, ...){

      get_density <- function(x, y, n ) {
                  dens <- MASS::kde2d(x = x, y = y, n = n)
                  ix <- findInterval(x, dens$x)
                  iy <- findInterval(y, dens$y)
                  ii <- cbind(ix, iy)
                  return(dens$z[ii])
                }

      X <- eval_data_col(data, mapping$x)
      Y <- eval_data_col(data, mapping$y)

      data$density <- get_density(x=X, y=Y, n=N)

      p <- ggplot(data, mapping) +
               geom_point(aes(colour=density), ...) +
               scale_color_viridis()
      p
}

 ggpairs(dat, lower=list(continuous=my_fn)) +
 theme_bw()

Produces:


问:
Enter key is "clicking" the wrong button. asp.net
I have two asp buttons and a asp textbox. One button is to logout and the other to add the content of the textbox (username) to a database table.

All works great except when I type in a username and hit the enter key, it logs me off i.e. clicks logout button.

```<code><asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
<asp:TextBox ID="adduser" runat="server" placeholder="Enter username here"></asp:TextBox>
<asp:Button ID="adduserbtn" runat="server" Text="Add" />
</code>```

I got it to work by wrapping the textbox and adduserbtn button in a panel and setting the adduserbtn button as the default button.

```<code><asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Panel DefaultButton="adduserbtn" runat="server" ID="addUserPanel">
    <asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
    <asp:TextBox ID="adduser" runat="server" placeholder="Enter username here" ></asp:TextBox>
    <asp:Button ID="adduserbtn" runat="server" Text="Add" />
</asp:Panel>
</code>```

But this feels more like a "hack" than a fix.  Does anybody know of a better / cleaner way to do this? Thanks in advance.

答:
The answer from Partha Thakura with the Panel and the DefaultButton is correct and can be used when you want a button pressed. But you can also disable the clicking of the Enter Key with javascript. I use this in large forms because pressing Enter will trigger all the Validators or do the form post with more input fields to go.

```<code><div onkeydown="return (event.keyCode!=13);">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</code>```

Just make sure you don't use it on a MultiLine TextBox (textarea).

Body:
I have two asp buttons and a asp textbox. One button is to logout and the other to add the content of the textbox (username) to a database table.

All works great except when I type in a username and hit the enter key, it logs me off i.e. clicks logout button.

<asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
<asp:TextBox ID="adduser" runat="server" placeholder="Enter username here"></asp:TextBox>
<asp:Button ID="adduserbtn" runat="server" Text="Add" />

I got it to work by wrapping the textbox and adduserbtn button in a panel and setting the adduserbtn button as the default button.

<asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Panel DefaultButton="adduserbtn" runat="server" ID="addUserPanel">
    <asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
    <asp:TextBox ID="adduser" runat="server" placeholder="Enter username here" ></asp:TextBox>
    <asp:Button ID="adduserbtn" runat="server" Text="Add" />
</asp:Panel>

But this feels more like a "hack" than a fix.  Does anybody know of a better / cleaner way to do this? Thanks in advance.

Body:
The answer from Partha Thakura with the Panel and the DefaultButton is correct and can be used when you want a button pressed. But you can also disable the clicking of the Enter Key with javascript. I use this in large forms because pressing Enter will trigger all the Validators or do the form post with more input fields to go.

<div onkeydown="return (event.keyCode!=13);">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" />
</div>

Just make sure you don't use it on a MultiLine TextBox (textarea).


问:
Datetimepicker cancels Textchanged event
Normally I can find an answer to every question here, but this time I just can't.

The problem is when I change my asp textbox to a (bootstrap) datetimepicker the OnTextChanged event of the textbox doesn't fire at all.

I don't know the way the datetimepicker puts the text in the textbox, but somehow it doesn't trigger the textchanged event.

If anyone got an answer or an alternative way to fix this, please let me know.

My code is below:

```<code><div class="col-lg-12 text-center">
    <asp:TextBox runat="server" ID="txtSearch"
    OnTextChanged="txtSearch_TextChanged" AutoPostBack="true"
    PlaceHolder="  Zoeken op Datum..." Height="30"
    Width="25%"></asp:TextBox>
</div>

<script type="text/javascript">
    $('#txtSearch').datetimepicker({
        locale: 'nl',
        format: 'DD-MM-YYYY',
        showClear: true
    });
</script>

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
    ShowData();
}
</code>```

Edit: I solved it by using the dp.change event of the datetimepicker itself.
By using __doPostBack() inside the event, I get kind of the same result of the textchanged event of the asp textbox.

```<code>$('#txtSearch').on("dp.change", function () {
    __doPostBack();
});
</code>```

答:
Programmatical changes do normally not fire onchanged events. And that is a good thing, because you would fire those events when setting values to your controls from your program, something that happens a lot when displaying data.

And your datetimepicker changes your value from your program.

Look to see if you can use the .change or .hide events of the datepicker itself.

Body:
Normally I can find an answer to every question here, but this time I just can't.

The problem is when I change my asp textbox to a (bootstrap) datetimepicker the OnTextChanged event of the textbox doesn't fire at all.

I don't know the way the datetimepicker puts the text in the textbox, but somehow it doesn't trigger the textchanged event.

If anyone got an answer or an alternative way to fix this, please let me know.

My code is below:

    <asp:TextBox runat="server" ID="txtSearch"
    OnTextChanged="txtSearch_TextChanged" AutoPostBack="true"
    PlaceHolder="  Zoeken op Datum..." Height="30"
    Width="25%"></asp:TextBox>

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
    ShowData();
}

Edit: I solved it by using the dp.change event of the datetimepicker itself.
By using __doPostBack() inside the event, I get kind of the same result of the textchanged event of the asp textbox.

$('#txtSearch').on("dp.change", function () {
    __doPostBack();
});


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答:
The performance penalty of using virtual functions can never outweight the advantages you get at the design level. Supposedly a call to a virtual function would be 25% less efficient then a direct call to a static function. This is because there is a level of indirection throught the VMT.  However the time taken to make the call is normally very small compared to the time taken in the actual execution of your function so the total performance cost will be nigligable, especially with current performance of hardware.
Furthermore the compiler can sometimes optimise and see that no virtual call is needed and compile it into a static call. So don't worry use virtual functions and abstract classes as much as you need.</p>

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: Koen


问:
Dependency injection into scala objects (not classes)
I have an import "import play.api.libs.ws.WSClient" which i want to use within my object

```<code>Object X {
...

}
</code>```

But this doesn't seem to be available inside my object. I see that dependency injection is only available for classes. How do i get this to work?

答:
Injecting a dependency into an object is impossible.

You have two options:

Ugly and deprecated: Access the injector via the global application:

```<code>val wsClient = Play.current.injector.instanceOf[WSClient]
</code>```

Way to go if your code needs to live in an object: Pass the dependency in as a parameter. However this just defers the problem to the caller.

```<code>def myMethod(wsClient: WSClient) = // foo
</code>```

If youre working with a legacy application where you have objects and need an injected dependency, I think one way to "improve" the situation and make a step into the right direction is to provide access to an injected class like so:

```<code>object MyObject {
  private def instance = Play.current.injector.instanceOf[MyObject]
  def myMethod(param: String): String =
    instance.myMethod(param)
}

class MyObject @Inject() (wsClient: WSClient) {
  def myMethod(param: String): String =
   // foo
}
</code>```

This allows legacy code to access the methods via object, while new code can inject the dependency. You may also annotate the method on the object as deprecated so that users know.

Body:
I have an import "import play.api.libs.ws.WSClient" which i want to use within my object

Object X {
...

}

But this doesn't seem to be available inside my object. I see that dependency injection is only available for classes. How do i get this to work?

Body:
Injecting a dependency into an object is impossible.

You have two options:

Ugly and deprecated: Access the injector via the global application:

val wsClient = Play.current.injector.instanceOf[WSClient]

Way to go if your code needs to live in an object: Pass the dependency in as a parameter. However this just defers the problem to the caller.

def myMethod(wsClient: WSClient) = // foo

If youre working with a legacy application where you have objects and need an injected dependency, I think one way to "improve" the situation and make a step into the right direction is to provide access to an injected class like so:

object MyObject {
  private def instance = Play.current.injector.instanceOf[MyObject]
  def myMethod(param: String): String =
    instance.myMethod(param)
}

class MyObject @Inject() (wsClient: WSClient) {
  def myMethod(param: String): String =
   // foo
}

This allows legacy code to access the methods via object, while new code can inject the dependency. You may also annotate the method on the object as deprecated so that users know.


问:
Changes in the code or the designer won't update when debugging
I am trying to debug my VB.net app in Visual Studio Express 2010, when I realized my changes will not update on my form-on the designer or in the code. After looking online, I found that you should clear out the "Debug" folder under the bin. That worked-for only one time. Now it went back to the older version and when I delete it again, it doesn't change. When I build the project and run it from the "Release" folder, it works perfectly, but when a error occurs at runtime, it won't show where the error is because it is running independently.

Thanks in advance.

(I have Windows XP SP3)

答:
"Save all" works for me in VS 2010 VB, in Debug and Release mode.
I put the "Save all" icon next to the Run and Build icons.</p>


问:
how to convert Thu Apr 06 14:30:00 IST 2017 for to this format 2017-07-05T16:50:22.490 in N1QL query
how to convert "Thu Apr 06 14:30:00 IST 2017" for to this format
"2017-07-05T16:50:22.490" in N1QL query</p>

答:
thanks kbinstance, it got resolved after converted to millsecond

```<code>String fulfillmenttime1 = "Thu Apr 06 14:30:01 IST 2017";
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date1 = formatter.parse(fulfillmenttime1);
long longfulfillmenttime1 = date1.getTime();
</code>```

After using Collections.sort  it got sorted . no need of using n1ql query.

Body:
thanks kbinstance, it got resolved after converted to millsecond

String fulfillmenttime1 = "Thu Apr 06 14:30:01 IST 2017";
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date1 = formatter.parse(fulfillmenttime1);
long longfulfillmenttime1 = date1.getTime();

After using Collections.sort  it got sorted . no need of using n1ql query.


问:
Adding/updating 'news' to an app without updating the app
I am attempting to create a simple app by using html/css in Cordova. However I am stuck in one area and that is updating the news page content. I don't really know what method I can use to achieve this without having to update the whole app and resubmitting onto the store and I don't really know what I need to google to get the answer so I thought I would ask here and hopefully someone can help me out?

Thank you.

答:
You can make jQuery ajax calls to the web server and fetch news. Update them in news section on successful retrieval. Make these calls when user opts to refresh or after certain time interval.

Something like -

```<code>$.ajax({
    url     :   'fetchNewsFrom.php', //some server page to retrieve news from db and return
    type    :   "POST",
    dataType:   "json",
    data    :   {fromTime : $someTimestamp}, //fetch latest news since some time
    success :   function (result){
          console.log(result);  //has fetched results
          //update your news section with fetched news
    }
});
</code>```

You can also do push notifications using phonegap-plugin-push. There is something called topic messaging. You can subscribe the users to topics and push the updated news to subscribed users.

Body:
You can make jQuery ajax calls to the web server and fetch news. Update them in news section on successful retrieval. Make these calls when user opts to refresh or after certain time interval.

Something like -

$.ajax({
    url     :   'fetchNewsFrom.php', //some server page to retrieve news from db and return
    type    :   "POST",
    dataType:   "json",
    data    :   {fromTime : $someTimestamp}, //fetch latest news since some time
    success :   function (result){
          console.log(result);  //has fetched results
          //update your news section with fetched news
    }
});

You can also do push notifications using phonegap-plugin-push. There is something called topic messaging. You can subscribe the users to topics and push the updated news to subscribed users.


问:
On focus, how to place the caret after the last character in an already populated field in IE?
On focus, how to place the caret after the last character  in an already populated field in IE?</p>

答:
The following will work in all major browsers, including IE 5-9. IE 9 will support the selectionStart and selectionEnd properties of text inputs, bringing it into line with all the other browsers.

```<code>function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}
</code>```

Body:
The following will work in all major browsers, including IE 5-9. IE 9 will support the selectionStart and selectionEnd properties of text inputs, bringing it into line with all the other browsers.

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}


问:
How to find all possible subarrays of an array?
Let's suppose I am given an array; A[] = {1,2,3} and I want to find all the sub-arrays of this array. The answer should be

```<code>{1}
{1,2}
{1,2,3}
{2}
{2,3}
{3}
</code>```

How to find all possible subarrays of an array efficiently?

答:
We can use substr function to find the all possible sub array.

Code Snippet :

```<code>       #include<bits/stdc++.h>
       using namespace std;

       void generateSubstring(string str)
       {
            if(str.size()==0)
            {
                return;
            }
            else
            {
                for(int i=0; i<str.size(); i++)
                {
                    for(int j=1; j<=str.size()-i; j++)
                    {
                        cout<<str.substr(i, i+j)<<endl;
                    }
                }
            }
        }

        int main()
        {
            ios::sync_with_stdio(false);
            string str;
            getline(cin, str);
            generateSubstring(str);
            return 0;
        }
</code>```

Body:
Let's suppose I am given an array; A[] = {1,2,3} and I want to find all the sub-arrays of this array. The answer should be

{1}
{1,2}
{1,2,3}
{2}
{2,3}
{3}

How to find all possible subarrays of an array efficiently?

Body:
We can use substr function to find the all possible sub array.

Code Snippet :

       #include<bits/stdc++.h>
       using namespace std;

       void generateSubstring(string str)
       {
            if(str.size()==0)
            {
                return;
            }
            else
            {
                for(int i=0; i<str.size(); i++)
                {
                    for(int j=1; j<=str.size()-i; j++)
                    {
                        cout<<str.substr(i, i+j)<<endl;
                    }
                }
            }
        }

        int main()
        {
            ios::sync_with_stdio(false);
            string str;
            getline(cin, str);
            generateSubstring(str);
            return 0;
        }


问:
Clustering map markers on zoom out and unclustering on zoom in
I am using the Google Map Android clustering Utitlity With Google Maps v2 play services.

I am not getting the behavior I expected. As you can see in the two images below, when zoomed in I can see a cluster of 20 and a single marker up an to the left, but when i zoom out til they are on top of each other i am not seeing them cluster.. the 20 cluster still says 20 and not 21?

Is that expected behavior?  Is there a way can make the cluster show 21 instead of 20+

答:
For someone who is struggling to do the same..
in your custom renderer override these two function as below
    @Override
    protected int getBucket(Cluster cluster) {
        return cluster.getSize();
    }</p>

```<code>@Override
protected String getClusterText(int bucket) {
    return String.valueOf(bucket);
}
</code>```

Body:
For someone who is struggling to do the same..
in your custom renderer override these two function as below
    @Override
    protected int getBucket(Cluster cluster) {
        return cluster.getSize();
    }

@Override
protected String getClusterText(int bucket) {
    return String.valueOf(bucket);
}


问:
How do i display people who are older than a particular person SQL?
What function shall i use to display all those people who are older than a specific person. DOB in my table is given in the format 19-JAN-88  </p>

```<code>select * from student
where
order by firstname;
</code>```

答:
```<code>select * from student where DOB > ( select DOB from student where student_name='value')
</code>```

I assume DOB datatype is Date or otherwise, you can use following:

```<code>select * from student where CONVERT( VARCHAR(30),DOB,105) > ( select CONVERT( VARCHAR(30),DOB,105) from student where student_name='value')
</code>```

Body:
What function shall i use to display all those people who are older than a specific person. DOB in my table is given in the format 19-JAN-88

select * from student
where
order by firstname;

Body:
select * from student where DOB > ( select DOB from student where student_name='value')

I assume DOB datatype is Date or otherwise, you can use following:

select * from student where CONVERT( VARCHAR(30),DOB,105) > ( select CONVERT( VARCHAR(30),DOB,105) from student where student_name='value')


问:
AngularJS and material icons
Material Icons are working fine in my AngularJS app.

In my template.html :

```<code><i class="material-icons"></i>
</code>```

This works fine, the icon is displayed correctly.

But this code does not :

```<code><div ng-repeat="x in pages">
    current icon : {{x.icon}}
    <br>
    <i class="material-icons">{{x.icon}}</i>
</div>
</code>```

where pages is defined in the controller :

```<code>$scope.pages = [
{icon: ""},
{icon: ""},
{icon: ""}
];
</code>```

I can see the right value of {{x.icon}}.

Why does

```<code><i class="material-icons">{{x.icon}}</i>
</code>```

not work ?

答:
use ng-bind-html and unsafe filter:

templat.html

```<code> <i class="material-icons" ng-bind-html="x.icon | unsafe "></i>
</code>```

JS

```<code>app.filter('unsafe',function($sce){
  return $sce.trustAsHtml
})
</code>```

Title: AngularJS and material icons

Body:
Material Icons are working fine in my AngularJS app.

In my template.html :



This works fine, the icon is displayed correctly.

But this code does not :

    current icon : {{x.icon}}

    {{x.icon}}

where pages is defined in the controller :

$scope.pages = [
{icon: ""},
{icon: ""},
{icon: ""}
];

I can see the right value of {{x.icon}}.

Why does

{{x.icon}}

not work ?

Body:
use ng-bind-html and unsafe filter:

templat.html

 <i class="material-icons" ng-bind-html="x.icon | unsafe "></i>

JS

app.filter('unsafe',function($sce){
  return $sce.trustAsHtml
})


问:
SharePoint permissions for a specific group
I'm trying to establish whether a specific group has Read access to a particular site collection.

I have been trying for a day and a half but feel as if I have found three halves of different solutions!

The code fragments I have so far are:

```<code>using (SPSite site = new SPSite(this.GenerateAbsoluteUri(moduleCode, academicYear)))
{
    using (SPWeb web = site.OpenWeb())
    {
        for (int i = web.SiteGroups.Count - 1; i >= 0; i--)
        {
            SPGroup group = web.SiteGroups[i];

            if (Regex.IsMatch(group.Name, theGroupImLookingFor))
            {
</code>```

but then what?!

Most of my Google results tell me about roles but I don't know how to tie a role to a group.

Please help!

答:
Heres snippets from my own code (Sharepoint 2010).
Creating a role:

```<code>SPRoleDefinition network_role = new SPRoleDefinition();
                network_role.BasePermissions = SPBasePermissions.AddListItems |
                    SPBasePermissions.BrowseDirectories |
                    SPBasePermissions.EditListItems |
                    SPBasePermissions.DeleteListItems;
                network_role.Name = "Network - Project Member";
                network_role.Description = "Provides permissions required for a member of a project.";

                web.RoleDefinitions.Add(network_role);
</code>```

Adding a role to a group:

```<code>var assign = new SPRoleAssignment(oweb.SiteGroups["Network Project - " + item.Code]);
assign.RoleDefinitionBindings.Add(network_role);
</code>```

Body:
I'm trying to establish whether a specific group has Read access to a particular site collection.

I have been trying for a day and a half but feel as if I have found three halves of different solutions!

The code fragments I have so far are:

using (SPSite site = new SPSite(this.GenerateAbsoluteUri(moduleCode, academicYear)))
{
    using (SPWeb web = site.OpenWeb())
    {
        for (int i = web.SiteGroups.Count - 1; i >= 0; i--)
        {
            SPGroup group = web.SiteGroups[i];

            if (Regex.IsMatch(group.Name, theGroupImLookingFor))
            {

but then what?!

Most of my Google results tell me about roles but I don't know how to tie a role to a group.

Please help!

Body:
Heres snippets from my own code (Sharepoint 2010).
Creating a role:

SPRoleDefinition network_role = new SPRoleDefinition();
                network_role.BasePermissions = SPBasePermissions.AddListItems |
                    SPBasePermissions.BrowseDirectories |
                    SPBasePermissions.EditListItems |
                    SPBasePermissions.DeleteListItems;
                network_role.Name = "Network - Project Member";
                network_role.Description = "Provides permissions required for a member of a project.";

                web.RoleDefinitions.Add(network_role);

Adding a role to a group:

var assign = new SPRoleAssignment(oweb.SiteGroups["Network Project - " + item.Code]);
assign.RoleDefinitionBindings.Add(network_role);


问:
POST form not working with PHP, working with Postman
This is login code with session. Iam using bootstrap.The code is not redirecting to index.html, when I test it in Postman it works but it is not working in this bootstrap template. I didnt get the reason? Please Help

```<code><?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    $email=$_POST["email"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login where email='$email' and password='$password'";

    $result = mysqli_query($conn,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);

    if ($count>0) {

        // output data of each row
        if($row['admin_role']==1) {
            //$_SESSION["email"]=$email;
            //$_SESSION["id"]=$row['user_id'];

            //echo "Login successfull";

            header('Location: index.html');
            exit;
        }
    } else {
        echo "0 results";
    }
}

?>

<div class="row">
    <div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
        <div class="login-panel panel panel-default">
            <div class="panel-heading"> Admin Log in</div>
            <div class="panel-body">
                <form role="form">
                    <fieldset>
                        <div class="form-group">
                            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">
                        </div>
                        <div class="form-group">
                            <input class="form-control" placeholder="Password" name="password" type="password" value="">
                        </div>
                        <div class="checkbox">
                            <label>
                                <input name="remember" type="checkbox" value="Remember Me">Remember Me
                            </label>
                        </div>
                        <a href="" class="btn btn-primary">Login</a>
                    </fieldset>
                </form>
            </div>
        </div>
    </div><!-- /.col-->
</div><!-- /.row -->
</code>```

答:
You forgot about submit button, you forgot about form method and type so:
action="#" tell you that come on the same php file.
And very important change this:
$email=$_POST["email"];
on
$email=strip_tags($_POST["email"]);

Read about strip_tags() function :)

```<code><div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
    <div class="login-panel panel panel-default">
        <div class="panel-heading"> Admin Log in</div>
        <div class="panel-body">
            <form role="form" action="#" method="post">
                <fieldset>
                    <div class="form-group">
                        <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">
                    </div>
                    <div class="form-group">
                        <input class="form-control" placeholder="Password" name="password" type="password" value="">
                    </div>
                    <div class="checkbox">
                        <label>
                            <input name="remember" type="checkbox" value="Remember Me">Remember Me
                        </label>
                    </div>
                    <button type="submit" class="btn btn-primary">Login</button>
                </fieldset>
            </form>
        </div>
    </div>
</div><!-- /.col-->
</code>```

Body:
This is login code with session. Iam using bootstrap.The code is not redirecting to index.html, when I test it in Postman it works but it is not working in this bootstrap template. I didnt get the reason? Please Help

<?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    $email=$_POST["email"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login where email='$email' and password='$password'";

    $result = mysqli_query($conn,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);

    if ($count>0) {

        // output data of each row
        if($row['admin_role']==1) {
            //$_SESSION["email"]=$email;
            //$_SESSION["id"]=$row['user_id'];

            //echo "Login successfull";

            header('Location: index.html');
            exit;
        }
    } else {
        echo "0 results";
    }
}

?>

 Admin Log in

                <form role="form">
                    <fieldset>

                            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">

                            <input class="form-control" placeholder="Password" name="password" type="password" value="">

                                <input name="remember" type="checkbox" value="Remember Me">Remember Me

                        Login
                    </fieldset>
                </form>

Body:
You forgot about submit button, you forgot about form method and type so:
action="#" tell you that come on the same php file.
And very important change this:
$email=$_POST["email"];
on
$email=strip_tags($_POST["email"]);

Read about strip_tags() function :)

<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
    <div class="login-panel panel panel-default">
        <div class="panel-heading"> Admin Log in</div>
        <div class="panel-body">
            <form role="form" action="#" method="post">
                <fieldset>
                    <div class="form-group">
                        <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">
                    </div>
                    <div class="form-group">
                        <input class="form-control" placeholder="Password" name="password" type="password" value="">
                    </div>
                    <div class="checkbox">
                        <label>
                            <input name="remember" type="checkbox" value="Remember Me">Remember Me
                        </label>
                    </div>
                    <button type="submit" class="btn btn-primary">Login</button>
                </fieldset>
            </form>
        </div>
    </div>
</div><!-- /.col-->


问:
Google/CloudMessaging' and Firebase/Messaging' fail with erro duplicate symbol
I am using Firebase in my project as well as Google sing-in.
For that I am using pod library.

```<code>pod 'SVProgressHUD'
pod 'SDWebImage'
pod 'AlamofireObjectMapper', '~> 4.0'
pod 'Google/SignIn'
pod 'IQKeyboardManagerSwift'
pod 'FBSDKLoginKit'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Auth'
pod 'Google/CloudMessaging'
</code>```

This are my pod which I am using in project.

Now I am remove pod 'Google/CloudMessaging' then app build successfully but GGLContext.sharedInstance().configureWithError(&configureError)
 giving error like below

You have enabled the CloudMessaging service in Developer Console, but it appears as though your Podfile is missing the line: 'pod "Google/CloudMessaging" or you may need to run pod update in your project directory.

If I am adding pod "Google/CloudMessaging pod and then build project XCode fail with duplicate symbols.

How can I add two and also avoid this error.

答: It seems you cant use GCM and FCM at the same time as FCM is the new improved GCM and you're certainly going to run into those kind of errors. You can see that question addressed in this SO post</p>

Body:
I am using Firebase in my project as well as Google sing-in.
For that I am using pod library.

pod 'SVProgressHUD'
pod 'SDWebImage'
pod 'AlamofireObjectMapper', '~> 4.0'
pod 'Google/SignIn'
pod 'IQKeyboardManagerSwift'
pod 'FBSDKLoginKit'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Auth'
pod 'Google/CloudMessaging'

This are my pod which I am using in project.

Now I am remove pod 'Google/CloudMessaging' then app build successfully but GGLContext.sharedInstance().configureWithError(&configureError)
 giving error like below

You have enabled the CloudMessaging service in Developer Console, but it appears as though your Podfile is missing the line: 'pod "Google/CloudMessaging" or you may need to run pod update in your project directory.

If I am adding pod "Google/CloudMessaging pod and then build project XCode fail with duplicate symbols.

How can I add two and also avoid this error.