问:
popover on empty inputs after clicking submit using javascript
I want to display error when the user doesn't enter in the input field after he clicks on the submit button. This display should be displayed at right of the input field. But i can't seem to figure out how is that possible using php and javascript. Here is my code:</p>

```<code><?php include "head.php";?>
<div class="container">
<?php

    if(isset($_SESSION["error"]) && $_SESSION["error"] != ""){
            echo $_SESSION["error"];
        }unset($_SESSION["error"]);
    if(isset($_SESSION["error1"]) && $_SESSION["error1"] != ""){
            echo $_SESSION["error1"];
        }unset($_SESSION["error1"]);

    if(isset($_SESSION["warning"]) && $_SESSION["warning"] != ""){
            echo $_SESSION["warning"];
        }unset($_SESSION["warning"]);
    if(isset($_SESSION["warning1"]) && $_SESSION["warning1"] != ""){
            echo $_SESSION["warning1"];
        }unset($_SESSION["warning1"]);
    if(isset($_SESSION["success"]) && $_SESSION["success"] != ""){
            echo $_SESSION["success"];
        }unset($_SESSION["success"]);
?>
<form class="form-horizontal" action="loginprocess.php" method="post">

<!--username input--->
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-3 control-label">username</label>
    <div class="col-sm-6">
      <input type="text" class="form-control" id="inputEmail3" placeholder="Email" name="username">
    </div>
  </div>
<!--password input --->
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-3 control-
       label">Password</label>
    <div class="col-sm-6">
      <input type="password" class="form-control" id="inputPassword3"
              placeholder="Password" name="password">
    </div>
  </div>
<!-- input file --->
<div class="form-group">
    <label for="exampleInputFile" class="col-sm-3 control-label">File
            input</label>
    <div class="col-sm-6">
    <input type="file" id="exampleInputFile" name="file">
    <!--<p class="help-block">Example block-level help text here.</p>-->
    </div>
  </div>

<!-- selecting country --->
<div class="form-group">
 <label for="country" class="col-sm-3 control-label">Select Country</label>
<div class="col-sm-6">
  <select class="form-control" id="country" name="country[]">
    Nepal
    <span class="caret"></span>
        <option><a href="#">Nepal</a></option>
        <option><a href="#">USA</a></option>
        <option><a href="#">Dubai</a></option>
    <option><a href="#">Nepal</a></option>
    <option><a href="#">USA</a></option>
        <option><a href="#">Dubai</a></option>
    <option><a href="#">Nepal</a></option>
        <option><a href="#">USA</a></option>
        <option><a href="#">Dubai</a></option>
 </select>
</div>
</div>
<!-- checkbox--->
  <div class="form-group">
    <div class="col-sm-offset-3 col-sm-6">
      <div class="checkbox">
        <label>
          <input type="checkbox" name="remember me"> Remember me
        </label>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9">
      <button type="submit" class="btn btn-default">Sign in</button>
    </div>
  </div>
</form>
</div>
<script>
$(function () {
  $("[data-toggle="tooltip"]").tooltip()
})
</script>
<?php
print_r ($_POST);
?>
<?php include "foot.php";?>
</code>```

答:
https://www.w3schools.com/js/js_validation.asp
Check this. Alternatively you could work with php only and show the message after the form has been submitted (in form handler).

Here you have some more examples using bootstrap:
http://1000hz.github.io/bootstrap-validator/

$(document).ready(function() {
  $('#contact_form').bootstrapValidator({
      // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        first_name: {
          validators: {
            stringLength: {
              min: 2,
            },
            notEmpty: {
              message: 'Please supply your first name'
            }
          }
        },
        last_name: {
          validators: {
            stringLength: {
              min: 2,
            },
            notEmpty: {
              message: 'Please supply your last name'
            }
          }
        },
        email: {
          validators: {
            notEmpty: {
              message: 'Please supply your email address'
            },
            emailAddress: {
              message: 'Please supply a valid email address'
            }
          }
        },
        phone: {
          validators: {
            notEmpty: {
              message: 'Please supply your phone number'
            },
            phone: {
              country: 'US',
              message: 'Please supply a vaild phone number with area code'
            }
          }
        },
        address: {
          validators: {
            stringLength: {
              min: 8,
            },
            notEmpty: {
              message: 'Please supply your street address'
            }
          }
        },
        city: {
          validators: {
            stringLength: {
              min: 4,
            },
            notEmpty: {
              message: 'Please supply your city'
            }
          }
        },
        state: {
          validators: {
            notEmpty: {
              message: 'Please select your state'
            }
          }
        },
        zip: {
          validators: {
            notEmpty: {
              message: 'Please supply your zip code'
            },
            zipCode: {
              country: 'US',
              message: 'Please supply a vaild zip code'
            }
          }
        },
        comment: {
          validators: {
            stringLength: {
              min: 10,
              max: 200,
              message: 'Please enter at least 10 characters and no more than 200'
            },
            notEmpty: {
              message: 'Please supply a description of your project'
            }
          }
        }
      }
    })
    .on('success.form.bv', function(e) {
      $('#success_message').slideDown({
        opacity: "show"
      }, "slow") // Do something ...
      $('#contact_form').data('bootstrapValidator').resetForm();

      // Prevent form submission
      e.preventDefault();

      // Get the form instance
      var $form = $(e.target);

      // Get the BootstrapValidator instance
      var bv = $form.data('bootstrapValidator');

      // Use Ajax to submit form data
      $.post($form.attr('action'), $form.serialize(), function(result) {
        console.log(result);
      }, 'json');
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#success_message {
  display: none;
}</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />

  <form class="well form-horizontal" action=" " method="post" id="contact_form">
    <fieldset>

      <legend>Contact Us Today!</legend>

        First Name

            <input name="first_name" placeholder="First Name" class="form-control" type="text">

        Last Name

            <input name="last_name" placeholder="Last Name" class="form-control" type="text">

        E-Mail

            <input name="email" placeholder="E-Mail Address" class="form-control" type="text">

        Phone #

            <input name="phone" placeholder="(845)555-1212" class="form-control" type="text">

        Address

            <input name="address" placeholder="Address" class="form-control" type="text">

        City

            <input name="city" placeholder="city" class="form-control" type="text">

        State

            <select name="state" class="form-control selectpicker">
      <option value=" " >Please select your state</option>
      <option>Alabama</option>
      <option>Alaska</option>
      <option >Arizona</option>
      <option >Arkansas</option>
      <option >California</option>
      <option >Colorado</option>
      <option >Connecticut</option>
      <option >Delaware</option>
      <option >District of Columbia</option>
      <option> Florida</option>
      <option >Georgia</option>
      <option >Hawaii</option>
      <option >daho</option>
      <option >Illinois</option>
      <option >Indiana</option>
      <option >Iowa</option>
      <option> Kansas</option>
      <option >Kentucky</option>
      <option >Louisiana</option>
      <option>Maine</option>
      <option >Maryland</option>
      <option> Mass</option>
      <option >Michigan</option>
      <option >Minnesota</option>
      <option>Mississippi</option>
      <option>Missouri</option>
      <option>Montana</option>
      <option>Nebraska</option>
      <option>Nevada</option>
      <option>New Hampshire</option>
      <option>New Jersey</option>
      <option>New Mexico</option>
      <option>New York</option>
      <option>North Carolina</option>
      <option>North Dakota</option>
      <option>Ohio</option>
      <option>Oklahoma</option>
      <option>Oregon</option>
      <option>Pennsylvania</option>
      <option>Rhode Island</option>
      <option>South Carolina</option>
      <option>South Dakota</option>
      <option>Tennessee</option>
      <option>Texas</option>
      <option> Uttah</option>
      <option>Vermont</option>
      <option>Virginia</option>
      <option >Washington</option>
      <option >West Virginia</option>
      <option>Wisconsin</option>
      <option >Wyoming</option>
    </select>

        Zip Code

            <input name="zip" placeholder="Zip Code" class="form-control" type="text">

        Website or domain name

            <input name="website" placeholder="Website or domain name" class="form-control" type="text">

        Do you have hosting?

                                    <input type="radio" name="hosting" value="yes" /> Yes

                                    <input type="radio" name="hosting" value="no" /> No

        Project Description

            <textarea class="form-control" name="comment" placeholder="Project Description"></textarea>

Success  Thanks for contacting us, we will get back to you shortly.

          <button type="submit" class="btn btn-warning">Send </button>

    </fieldset>
  </form>

```

https://codepen.io/jaycbrf/pen/iBszr

Body:
I want to display error when the user doesn't enter in the input field after he clicks on the submit button. This display should be displayed at right of the input field. But i can't seem to figure out how is that possible using php and javascript. Here is my code:

<?php include "head.php";?>

<?php

    if(isset($_SESSION["error"]) && $_SESSION["error"] != ""){
            echo $_SESSION["error"];
        }unset($_SESSION["error"]);
    if(isset($_SESSION["error1"]) && $_SESSION["error1"] != ""){
            echo $_SESSION["error1"];
        }unset($_SESSION["error1"]);

    if(isset($_SESSION["warning"]) && $_SESSION["warning"] != ""){
            echo $_SESSION["warning"];
        }unset($_SESSION["warning"]);
    if(isset($_SESSION["warning1"]) && $_SESSION["warning1"] != ""){
            echo $_SESSION["warning1"];
        }unset($_SESSION["warning1"]);
    if(isset($_SESSION["success"]) && $_SESSION["success"] != ""){
            echo $_SESSION["success"];
        }unset($_SESSION["success"]);
?>
<form class="form-horizontal" action="loginprocess.php" method="post">

    username

      <input type="text" class="form-control" id="inputEmail3" placeholder="Email" name="username">

    Password

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

    File
            input

    <input type="file" id="exampleInputFile" name="file">

 Select Country

  <select class="form-control" id="country" name="country[]">
    Nepal

        <option>Nepal</option>
        <option>USA</option>
        <option>Dubai</option>
    <option>Nepal</option>
    <option>USA</option>
        <option>Dubai</option>
    <option>Nepal</option>
        <option>USA</option>
        <option>Dubai</option>
 </select>

          <input type="checkbox" name="remember me"> Remember me

      <button type="submit" class="btn btn-default">Sign in</button>

</form>

<?php
print_r ($_POST);
?>
<?php include "foot.php";?>

Body:
https://www.w3schools.com/js/js_validation.asp
Check this. Alternatively you could work with php only and show the message after the form has been submitted (in form handler).

Here you have some more examples using bootstrap:
http://1000hz.github.io/bootstrap-validator/

$(document).ready(function() {
  $('#contact_form').bootstrapValidator({
      // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        first_name: {
          validators: {
            stringLength: {
              min: 2,
            },
            notEmpty: {
              message: 'Please supply your first name'
            }
          }
        },
        last_name: {
          validators: {
            stringLength: {
              min: 2,
            },
            notEmpty: {
              message: 'Please supply your last name'
            }
          }
        },
        email: {
          validators: {
            notEmpty: {
              message: 'Please supply your email address'
            },
            emailAddress: {
              message: 'Please supply a valid email address'
            }
          }
        },
        phone: {
          validators: {
            notEmpty: {
              message: 'Please supply your phone number'
            },
            phone: {
              country: 'US',
              message: 'Please supply a vaild phone number with area code'
            }
          }
        },
        address: {
          validators: {
            stringLength: {
              min: 8,
            },
            notEmpty: {
              message: 'Please supply your street address'
            }
          }
        },
        city: {
          validators: {
            stringLength: {
              min: 4,
            },
            notEmpty: {
              message: 'Please supply your city'
            }
          }
        },
        state: {
          validators: {
            notEmpty: {
              message: 'Please select your state'
            }
          }
        },
        zip: {
          validators: {
            notEmpty: {
              message: 'Please supply your zip code'
            },
            zipCode: {
              country: 'US',
              message: 'Please supply a vaild zip code'
            }
          }
        },
        comment: {
          validators: {
            stringLength: {
              min: 10,
              max: 200,
              message: 'Please enter at least 10 characters and no more than 200'
            },
            notEmpty: {
              message: 'Please supply a description of your project'
            }
          }
        }
      }
    })
    .on('success.form.bv', function(e) {
      $('#success_message').slideDown({
        opacity: "show"
      }, "slow") // Do something ...
      $('#contact_form').data('bootstrapValidator').resetForm();

      // Prevent form submission
      e.preventDefault();

      // Get the form instance
      var $form = $(e.target);

      // Get the BootstrapValidator instance
      var bv = $form.data('bootstrapValidator');

      // Use Ajax to submit form data
      $.post($form.attr('action'), $form.serialize(), function(result) {
        console.log(result);
      }, 'json');
    });
});

#success_message {
  display: none;
}

<head>
  <script src="https://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
</head>

<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">

  <form class="well form-horizontal" action=" " method="post" id="contact_form">
    <fieldset>

      <!-- Form Name -->
      <legend>Contact Us Today!</legend>

      <!-- Text input-->

      <div class="form-group">
        <label class="col-md-4 control-label">First Name</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="first_name" placeholder="First Name" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Text input-->

      <div class="form-group">
        <label class="col-md-4 control-label">Last Name</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="last_name" placeholder="Last Name" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">E-Mail</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
            <input name="email" placeholder="E-Mail Address" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Text input-->

      <div class="form-group">
        <label class="col-md-4 control-label">Phone #</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
            <input name="phone" placeholder="(845)555-1212" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Text input-->

      <div class="form-group">
        <label class="col-md-4 control-label">Address</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
            <input name="address" placeholder="Address" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Text input-->

      <div class="form-group">
        <label class="col-md-4 control-label">City</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
            <input name="city" placeholder="city" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Select Basic -->

      <div class="form-group">
        <label class="col-md-4 control-label">State</label>
        <div class="col-md-4 selectContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
            <select name="state" class="form-control selectpicker">
      <option value=" " >Please select your state</option>
      <option>Alabama</option>
      <option>Alaska</option>
      <option >Arizona</option>
      <option >Arkansas</option>
      <option >California</option>
      <option >Colorado</option>
      <option >Connecticut</option>
      <option >Delaware</option>
      <option >District of Columbia</option>
      <option> Florida</option>
      <option >Georgia</option>
      <option >Hawaii</option>
      <option >daho</option>
      <option >Illinois</option>
      <option >Indiana</option>
      <option >Iowa</option>
      <option> Kansas</option>
      <option >Kentucky</option>
      <option >Louisiana</option>
      <option>Maine</option>
      <option >Maryland</option>
      <option> Mass</option>
      <option >Michigan</option>
      <option >Minnesota</option>
      <option>Mississippi</option>
      <option>Missouri</option>
      <option>Montana</option>
      <option>Nebraska</option>
      <option>Nevada</option>
      <option>New Hampshire</option>
      <option>New Jersey</option>
      <option>New Mexico</option>
      <option>New York</option>
      <option>North Carolina</option>
      <option>North Dakota</option>
      <option>Ohio</option>
      <option>Oklahoma</option>
      <option>Oregon</option>
      <option>Pennsylvania</option>
      <option>Rhode Island</option>
      <option>South Carolina</option>
      <option>South Dakota</option>
      <option>Tennessee</option>
      <option>Texas</option>
      <option> Uttah</option>
      <option>Vermont</option>
      <option>Virginia</option>
      <option >Washington</option>
      <option >West Virginia</option>
      <option>Wisconsin</option>
      <option >Wyoming</option>
    </select>
          </div>
        </div>
      </div>

      <!-- Text input-->

      <div class="form-group">
        <label class="col-md-4 control-label">Zip Code</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
            <input name="zip" placeholder="Zip Code" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">Website or domain name</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span>
            <input name="website" placeholder="Website or domain name" class="form-control" type="text">
          </div>
        </div>
      </div>

      <!-- radio checks -->
      <div class="form-group">
        <label class="col-md-4 control-label">Do you have hosting?</label>
        <div class="col-md-4">
          <div class="radio">
            <label>
                                    <input type="radio" name="hosting" value="yes" /> Yes
                                </label>
          </div>
          <div class="radio">
            <label>
                                    <input type="radio" name="hosting" value="no" /> No
                                </label>
          </div>
        </div>
      </div>

      <!-- Text area -->

      <div class="form-group">
        <label class="col-md-4 control-label">Project Description</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
            <textarea class="form-control" name="comment" placeholder="Project Description"></textarea>
          </div>
        </div>
      </div>

      <!-- Success message -->
      <div class="alert alert-success" role="alert" id="success_message">Success <i class="glyphicon glyphicon-thumbs-up"></i> Thanks for contacting us, we will get back to you shortly.</div>

      <!-- Button -->
      <div class="form-group">
        <label class="col-md-4 control-label"></label>
        <div class="col-md-4">
          <button type="submit" class="btn btn-warning">Send <span class="glyphicon glyphicon-send"></span></button>
        </div>
      </div>

    </fieldset>
  </form>
</div>
</div>
<!-- /.container -->

https://codepen.io/jaycbrf/pen/iBszr


来源: stackexchange

问:
How to read resource file from unit test?
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.

How I'm reading:

```<code>String json = Files.lines(Paths.get("file.json"))
                .parallel()
                .collect(Collectors.joining());
</code>```

folder structure:

```<code>+project
  +app (android)
  +module (java only)
    +src
      +main
        +java
          +package
            -the java file
        +resources
            -file.json
</code>```

My question is how can I read the file?

updated below

```<code>URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");
</code>```

All these are null.
I've copied the json file to resources/same.package.structure too, but to no success.

答:
you should using Paths.get(URI) instead, for example:

```<code>ClassLoader loader = ClassLoader.getSystemClassLoader();

String json = Files.lines(Paths.get(loader.getResource("file.json").toURI()))
                   .parallel()
                   .collect(Collectors.joining());
</code>```

this is because you run your tests in android platform, and the resoruces were packaged in a jar, please using BufferedReader.lines instead, for example:

```<code>ClassLoader  loader = activity.getClassLoader();

BufferedReader in = new BufferedReader(new InputStreamReader(
   loader.getResourceAsStream("file.json"),"UTF-8"
));

String json = in.lines()
                .parallel()
                .collect(Collectors.joining());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.

How I'm reading:

String json = Files.lines(Paths.get("file.json"))
                .parallel()
                .collect(Collectors.joining());

folder structure:

+project
  +app (android)
  +module (java only)
    +src
      +main
        +java
          +package
            -the java file
        +resources
            -file.json

My question is how can I read the file?

updated below

URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");

All these are null.
I've copied the json file to resources/same.package.structure too, but to no success.

Body:
you should using Paths.get(URI) instead, for example:

ClassLoader loader = ClassLoader.getSystemClassLoader();

String json = Files.lines(Paths.get(loader.getResource("file.json").toURI()))
                   .parallel()
                   .collect(Collectors.joining());

this is because you run your tests in android platform, and the resoruces were packaged in a jar, please using BufferedReader.lines instead, for example:

ClassLoader  loader = activity.getClassLoader();

BufferedReader in = new BufferedReader(new InputStreamReader(
   loader.getResourceAsStream("file.json"),"UTF-8"
));

String json = in.lines()
                .parallel()
                .collect(Collectors.joining());


问:
Python glob, os, relative path, making filenames into a list
I am trying to make a list of all files in a directory with filenames in a that end in .root.

After reading some writings in the forum I tried to basic strategies using glob and os.listdir but I got into trouble for both of them

First, when I use

```<code>import glob
filelist = glob.glob('/home/usr/dir/*.root')
</code>```

It does make a list of string with all filenames that end in .root but I still face a problem.

I would like to be the list of string to have filenames as '/dir/.root' but the string has full path '/home/usr/dir/.root'

Second, if I use os.listdir, I get into the trouble that

```<code>  path = '/home/usr/'
  filelist = os.listdir(path + 'dir/*.root')
  syntax error
</code>```

which tells me that I can not only get the list of files for .root.

In summary, I would like to make a list of filenames, that end in .root and are in my /home/usr/dir, while cutting off the '/home/usr' part. If I use globe, I get into the trouble of having /home/usr/. If I use os.listdir, I can't specify ".root" endling.

答:
glob will return paths in a format matching your query, so that

```<code>glob.glob("/home/usr/dir/*.root")
# ['home/usr/dir/foo.root', 'home/usr/dir/bar.root', ...]

glob.glob("*.root")
# ['foo.root', 'bar.root', ...]

glob.glob("./*.root")
# ['./foo.root', './bar.root', ...]
</code>```

...and so forth.

To get only the filename, you can use path.basename of the os module, something like this:

```<code>from glob import glob
from os import path

pattern = "/home/usr/dir/*.root"
files = [path.basename(x) for x in glob(pattern)]
# ['foo.root', 'bar.root', ...]
</code>```

...or, if you want to prepend the dir part:

```<code>pattern = "/home/usr/dir/*.root"
files = [path.join('dir', path.basename(x)) for x in glob(pattern)]
# ['dir/foo.root', 'dir/bar.root', ...]
</code>```

...or, if you really want the path separator at the start:

```<code>from glob import glob
import os

pattern = "/home/usr/dir/*.root"
files = [os.sep + os.path.join('dir', os.path.basename(x)) for x in glob(pattern)]
# ['/dir/foo.root', '/dir/bar.root', ...]
</code>```

Using path.join and path.sep will make sure that the correct path syntax is used, depending on your OS (i.e. / or \ as a separator).

Depending on what you are really trying to do here, you might want to look at os.path.relpath, for the relative path. The title of your question indicates that relative paths might be what you are actually after:

```<code>pattern = "/home/usr/dir/*.root"
files = [os.path.relpath(x) for x in glob(pattern)]
# files will now contain the relative path to each file, from the current working directory
</code>```

Body:
I am trying to make a list of all files in a directory with filenames in a that end in .root.

After reading some writings in the forum I tried to basic strategies using glob and os.listdir but I got into trouble for both of them

First, when I use

import glob
filelist = glob.glob('/home/usr/dir/*.root')

It does make a list of string with all filenames that end in .root but I still face a problem.

I would like to be the list of string to have filenames as '/dir/.root' but the string has full path '/home/usr/dir/.root'

Second, if I use os.listdir, I get into the trouble that

  path = '/home/usr/'
  filelist = os.listdir(path + 'dir/*.root')
  syntax error

which tells me that I can not only get the list of files for .root.

In summary, I would like to make a list of filenames, that end in .root and are in my /home/usr/dir, while cutting off the '/home/usr' part. If I use globe, I get into the trouble of having /home/usr/. If I use os.listdir, I can't specify ".root" endling.

Body:
glob will return paths in a format matching your query, so that

glob.glob("/home/usr/dir/*.root")
# ['home/usr/dir/foo.root', 'home/usr/dir/bar.root', ...]

glob.glob("*.root")
# ['foo.root', 'bar.root', ...]

glob.glob("./*.root")
# ['./foo.root', './bar.root', ...]

...and so forth.

To get only the filename, you can use path.basename of the os module, something like this:

from glob import glob
from os import path

pattern = "/home/usr/dir/*.root"
files = [path.basename(x) for x in glob(pattern)]
# ['foo.root', 'bar.root', ...]

...or, if you want to prepend the dir part:

pattern = "/home/usr/dir/*.root"
files = [path.join('dir', path.basename(x)) for x in glob(pattern)]
# ['dir/foo.root', 'dir/bar.root', ...]

...or, if you really want the path separator at the start:

from glob import glob
import os

pattern = "/home/usr/dir/*.root"
files = [os.sep + os.path.join('dir', os.path.basename(x)) for x in glob(pattern)]
# ['/dir/foo.root', '/dir/bar.root', ...]

Using path.join and path.sep will make sure that the correct path syntax is used, depending on your OS (i.e. / or \ as a separator).

Depending on what you are really trying to do here, you might want to look at os.path.relpath, for the relative path. The title of your question indicates that relative paths might be what you are actually after:

pattern = "/home/usr/dir/*.root"
files = [os.path.relpath(x) for x in glob(pattern)]
# files will now contain the relative path to each file, from the current working directory


问:
Mock an XML response using Phoenix the Elixir framework
The response body of my HTTP request is XML.  The XML is quite complex and contains may double quotes.
I'd like to mock the response by providing an example of a typical XML response in my code.  I can't seem to find a way to provide the XML as a simple string.
Here's an example from the start of the XML that cause Elixir lots of pain:

```<code><Title xmlns="http://website/namespaces/thing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .... >
</code>```

The body response of HTTPoison is body: { ... }.  So I need to provide the XML string inside the tuple without Elixir blowing up. I've tried sigils w/o success.

thanks!

答:
If you would like to mock an XML response, you could use a library: https://github.com/parroty/exvcr

When you do test for the first time, it will record a request. After that you will use a saved response in a json file.

Body:
The response body of my HTTP request is XML.  The XML is quite complex and contains may double quotes.
I'd like to mock the response by providing an example of a typical XML response in my code.  I can't seem to find a way to provide the XML as a simple string.
Here's an example from the start of the XML that cause Elixir lots of pain:

<Title xmlns="http://website/namespaces/thing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .... >

The body response of HTTPoison is body: { ... }.  So I need to provide the XML string inside the tuple without Elixir blowing up. I've tried sigils w/o success.

thanks!


问:
Python: Accessing List of Dict. Typeerror: Column name can't be str
I have a question about accessing a list of dict in Python. I'm trying to access all value in a column of a CSV file. I've isolated and simplified the problem into the code below.

I'm trying to define a function which

inputs:
1) data set (list of dict)
2) column name

outputs: 1) printed list of all value in column

Instead i receive a "TypeError: list indices must be integers or slices, not str"

```<code>dict_1 = {'a':1, 'b':2, 'c':3}
dict_2 = {'a':4, 'b':5, 'c':6}
list_1 = [dict_1, dict_2]

def len_unique_element(data_set,column_name):

    data = ([data_set[column_name] for row in data_set])

    return print (data)

len_unique_element (list_1, 'a')
</code>```

Thanks!

答:
You are looking for column_name in data_set when you should be looking in row.</p>

```<code>def len_unique_element(data_set, column_name):
    return [row[column_name] for row in data_set]
</code>```

Body:
I have a question about accessing a list of dict in Python. I'm trying to access all value in a column of a CSV file. I've isolated and simplified the problem into the code below.

I'm trying to define a function which

inputs:
1) data set (list of dict)
2) column name

outputs: 1) printed list of all value in column

Instead i receive a "TypeError: list indices must be integers or slices, not str"

dict_1 = {'a':1, 'b':2, 'c':3}
dict_2 = {'a':4, 'b':5, 'c':6}
list_1 = [dict_1, dict_2]

def len_unique_element(data_set,column_name):

    data = ([data_set[column_name] for row in data_set])

    return print (data)

len_unique_element (list_1, 'a')

Thanks!

Body:
You are looking for column_name in data_set when you should be looking in row.

def len_unique_element(data_set, column_name):
    return [row[column_name] for row in data_set]


问:
How do I swap column values in sql server 2008?
I have a table called Employee

```<code> Eno     ename     AttributeValue      AttributeName
 1       aa           a123             abc
 2       bbb          b123             dcf
 3       cc           c7sd             wew3
</code>```

I want to swap the data from column AttributeValue to AttributeName and AttributeName to AttributeValue

For Example:

```<code>Eno     ename     AttributeValue   AttributeName
1       aa        abc              a123
2       bbb       dcf              b123
3       cc        wew3             c7sd
</code>```

答:
Just swap both columns in a single update:</p>

```<code>Update registration
Set AttributeName = AttributeValue ,
    AttributeValue = AttributeName where id in (1,2,3)
</code>```

Body:
I have a table called Employee

 Eno     ename     AttributeValue      AttributeName
 1       aa           a123             abc
 2       bbb          b123             dcf
 3       cc           c7sd             wew3

I want to swap the data from column AttributeValue to AttributeName and AttributeName to AttributeValue

For Example:

Eno     ename     AttributeValue   AttributeName
1       aa        abc              a123
2       bbb       dcf              b123
3       cc        wew3             c7sd

Body:
Just swap both columns in a single update:

Update registration
Set AttributeName = AttributeValue ,
    AttributeValue = AttributeName where id in (1,2,3)


问:
Execute external program from Java (with cmd, Windows)
I've done many research for executing an external program (e.g. iTunes) by some simple code, however the suggestions did never work. Sometimes nothing happend, sometimes I got this error message:
English: Unable to find "Discord". Be sure the name is written correctly and try again.

My Code is the following:

```<code>try {
    String name = (String) "start " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
    ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd /D %HOMEDRIVE%%HOMEPATH%/Desktop", "/c", name);
    p.start();
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

In my example I get the name of the external program from a JTable, this part is working fine. The ProcessBuilder is changing the directory to the desktop first. Then the external program should be executed by the start <program name> command. With this code I get the mentioned error message.

If you have a solution with cmd, please include changing the directory to the desktop.

答:
You should pass each argument as a single entry to ProcessBuilder. In your current code, you sometimes take multiple arguments together (like cd /D %HOME...). Try passing every argument as it's own parameter, including the command to start and its argument:

```<code>String name = (String) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd", "/D", "%HOMEDRIVE%%HOMEPATH%/Desktop", "/c", "start", name);
</code>```

Body:
I've done many research for executing an external program (e.g. iTunes) by some simple code, however the suggestions did never work. Sometimes nothing happend, sometimes I got this error message:
English: Unable to find "Discord". Be sure the name is written correctly and try again.

My Code is the following:

try {
    String name = (String) "start " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
    ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd /D %HOMEDRIVE%%HOMEPATH%/Desktop", "/c", name);
    p.start();
} catch (Exception e) {
    e.printStackTrace();
}

In my example I get the name of the external program from a JTable, this part is working fine. The ProcessBuilder is changing the directory to the desktop first. Then the external program should be executed by the start <program name> command. With this code I get the mentioned error message.

If you have a solution with cmd, please include changing the directory to the desktop.

Body:
You should pass each argument as a single entry to ProcessBuilder. In your current code, you sometimes take multiple arguments together (like cd /D %HOME...). Try passing every argument as it's own parameter, including the command to start and its argument:

String name = (String) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd", "/D", "%HOMEDRIVE%%HOMEPATH%/Desktop", "/c", "start", name);


问:
ASP C# Website Error Handling
Using  error handling in Web.config and in Index.aspx i am using try and catch error handling. How do i catch error in Index.aspx catch { } based on  in Web.config.

Web.config

```<code><customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="500.aspx" />
</customErrors>
</code>```

Index.aspx

```<code>try {

}
catch {
How to trigger error handling in custom error?
}
</code>```

答:
defaultRedirect = "Error.aspx" means that when you have an unhandled exception, ASP.NET will call your Error.aspx page instead of the standard one (called "Yellow Screen Of Death").

In my case I behave like this: first in Global.asax I store the unhandled exception in Application:

```<code>Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when an unhandled error occurs
    Try
        Application("errore") = Server.GetLastError
    Catch ex As Exception
    end try
End Sub
</code>```

Then in the Handling page (in your case, Error.aspx) I do the Handling:

```<code>Partial Class Error
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then

            If Session("userid") <> "" Then
                'Ho avuto una eccezione vera !
                Dim ex As Exception = Application("errore")
                Application("errore") = Nothing
                If IsNothing(ex) Then
                    ex = Server.GetLastError()
                End If
                If Not IsNothing(ex) Then
                    Dim bex As Exception = ex.GetBaseException
                    If IsNothing(bex) Then
                        bex = ex
                    End If

                    'Show details of exception bex on page or store in DB

                    Catch exall As Exception

                    End Try
                End If
            End If
        End If
    End If
End Sub
End Class
</code>```

Title: ASP C# Website Error Handling

Body:
Using  error handling in Web.config and in Index.aspx i am using try and catch error handling. How do i catch error in Index.aspx catch { } based on  in Web.config.

Web.config

<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="500.aspx" />
</customErrors>

Index.aspx

try {

}
catch {
How to trigger error handling in custom error?
}

Body:
defaultRedirect = "Error.aspx" means that when you have an unhandled exception, ASP.NET will call your Error.aspx page instead of the standard one (called "Yellow Screen Of Death").

In my case I behave like this: first in Global.asax I store the unhandled exception in Application:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when an unhandled error occurs
    Try
        Application("errore") = Server.GetLastError
    Catch ex As Exception
    end try
End Sub

Then in the Handling page (in your case, Error.aspx) I do the Handling:

Partial Class Error
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then

            If Session("userid") <> "" Then
                'Ho avuto una eccezione vera !
                Dim ex As Exception = Application("errore")
                Application("errore") = Nothing
                If IsNothing(ex) Then
                    ex = Server.GetLastError()
                End If
                If Not IsNothing(ex) Then
                    Dim bex As Exception = ex.GetBaseException
                    If IsNothing(bex) Then
                        bex = ex
                    End If

                    'Show details of exception bex on page or store in DB

                    Catch exall As Exception

                    End Try
                End If
            End If
        End If
    End If
End Sub
End Class


问:
cin loses first few characters of each line
I've seen other people reporting this problem with cin.ignore() and getline(). I understand it's some problem involving newlines, but I'm not entirely sure how to debug this with >>. I'm trying to implement a gradebook that takes in a student name and test grades and outputs their name (and eventually, course grade) [from Chapter 4 of Accelerated C++]. I'm having trouble even outputting the names properly, though.

```<code>// Student.cpp
#include "Student.h"
#include <iostream>
#include <vector>

istream& read(istream& in, Student& s) {
   in >> s.name >> s.midterm;
   read_hw(in, s.homework);
   return in;
}

istream& read_hw(istream& in, vector<double>& hw) {
    if (in) {
       hw.clear();

       double x;
       while (in >> x)
           hw.push_back(x);

       in.clear();
    }
    return in;
}
</code>```

And here I try to test it with my main function:

```<code>int main() {
    vector<Student> students;
    Student curr_student;

    while (read(cin, curr_student)) {
        cout << curr_student.name;
        students.push_back(curr_student);
        cout << students.size() << endl;
    }

    cout << students.size() << endl;
    for (int i = 0; i < students.size(); i++) {
        cout << students[i].name << endl;
    }
    return 0;
}
</code>```

When I input something into the command line, though, the output of the student names after the first one are cut off:

Input in terminal:

```<code> Alice 50 50 50 50 (<enter>)
 Bob 100 100 100 100 (<enter>)
 Carl 50 50 50 50 (<enter>)
 (<Ctrl-D>)
</code>```

And then it outputs:

```<code> Alice
 ob
 rl
</code>```

答:
From the look of the result the grades are read using hex format: B, C, and a are vaild hex digits. That shouldn't be happen according to your cide, though.

In any case note that formatted reading will normally skip all leading white space, including newlines. There are a few approaches to deal with line ends. The usual one is to resd lines into a std::string and use the string to initialize an std::istringstream.

An alternative approach would be the use of a custom definition of line ends by specializing the std::ctype<char> facet to not consider newline a space character. Another approach is using a manipulator which consumes whitespace but sets std::ios_base::failbit upon encountering a newline. For example:

```<code>std::istream& skip(std::istream& in) {
    if (std::istream::sentry kerberos{in, true}) {
        std::istreambuf_iterator<char> it(in), end;
        if (end != (it = std::find_if(it, end, [](unsigned char c){
                return !std::isspace(c) || char(c) == '\n'; }))
            && *it == '\n') {
            ++it;
            in.setstate(std::ios_base::failbit);
         }
    }
    return in;
}
// ...
if (in) {
    while (in >> skip >> x) {
        hw.push_back(x);
    }
    if (!hw.empty()) {
        in.clear();
    }
}
</code>```

While I don't think I'd be able that the original code actually reproduces the problem I'm fairly sure that the above approach does fix it!

Body:
I've seen other people reporting this problem with cin.ignore() and getline(). I understand it's some problem involving newlines, but I'm not entirely sure how to debug this with >>. I'm trying to implement a gradebook that takes in a student name and test grades and outputs their name (and eventually, course grade) [from Chapter 4 of Accelerated C++]. I'm having trouble even outputting the names properly, though.

// Student.cpp
#include "Student.h"
#include <iostream>
#include <vector>

istream& read(istream& in, Student& s) {
   in >> s.name >> s.midterm;
   read_hw(in, s.homework);
   return in;
}

istream& read_hw(istream& in, vector<double>& hw) {
    if (in) {
       hw.clear();

       double x;
       while (in >> x)
           hw.push_back(x);

       in.clear();
    }
    return in;
}

And here I try to test it with my main function:

int main() {
    vector<Student> students;
    Student curr_student;

    while (read(cin, curr_student)) {
        cout << curr_student.name;
        students.push_back(curr_student);
        cout << students.size() << endl;
    }

    cout << students.size() << endl;
    for (int i = 0; i < students.size(); i++) {
        cout << students[i].name << endl;
    }
    return 0;
}

When I input something into the command line, though, the output of the student names after the first one are cut off:

Input in terminal:

 Alice 50 50 50 50 (<enter>)
 Bob 100 100 100 100 (<enter>)
 Carl 50 50 50 50 (<enter>)
 (<Ctrl-D>)

And then it outputs:

 Alice
 ob
 rl

Body:
From the look of the result the grades are read using hex format: B, C, and a are vaild hex digits. That shouldn't be happen according to your cide, though.

In any case note that formatted reading will normally skip all leading white space, including newlines. There are a few approaches to deal with line ends. The usual one is to resd lines into a std::string and use the string to initialize an std::istringstream.

An alternative approach would be the use of a custom definition of line ends by specializing the std::ctype<char> facet to not consider newline a space character. Another approach is using a manipulator which consumes whitespace but sets std::ios_base::failbit upon encountering a newline. For example:

std::istream& skip(std::istream& in) {
    if (std::istream::sentry kerberos{in, true}) {
        std::istreambuf_iterator<char> it(in), end;
        if (end != (it = std::find_if(it, end, [](unsigned char c){
                return !std::isspace(c) || char(c) == '\n'; }))
            && *it == '\n') {
            ++it;
            in.setstate(std::ios_base::failbit);
         }
    }
    return in;
}
// ...
if (in) {
    while (in >> skip >> x) {
        hw.push_back(x);
    }
    if (!hw.empty()) {
        in.clear();
    }
}

While I don't think I'd be able that the original code actually reproduces the problem I'm fairly sure that the above approach does fix it!


问:
Unable to open file alpha.apk You do not have an app installed on this device
I am trying to build android apk file via cordova build android. It gives me an apk at the location of

D:/wamp/www/templateproject/platforms/android/build/outputs/apk/android-debug.apk

When I try to open that app in my mobile i get this alert message.

Unable to open file android-debug.apk. You do not have an app installed on this device to open this type of file.

Note: I have already check the installation from unknown sources.

How do I open such file ?

Note: It seems working with my friend device Redmi note 3 but not working with my device Redmi note 4 and moto g2 not sure what is the issue.

答:
The problem is with the updated skype. I was trying to share the apk file via desktop skype to android skype. With the latest update on skype it was not allowing me to open apk file. Bug with the skype. However the file is working fine if I try to access it from file manager.

The reason Redmi note 3 was working because it had skype of older version and other two mobile like redmi note 4 and moto g2 had updated one.


问:
How to show "read more" link after 3 buttons
In this code, I want to display show more link, after 3 buttons:
I know, how to display show more button after x words, but how to display show more link after buttons?

This is my code to display show more link after x words, if it helps:

jQuery(function(){

    var minimized_elements = $('span.showmore');

    minimized_elements.each(function(){
        var t = $(this).text();
        if(t.length < 410) return;

        $(this).html(
            t.slice(0,410)+'... Show More'+
            ''+ t.slice(410,t.length)+' Less'
        );

    });

    $('a.more', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).hide().prev().hide();
        $(this).next().show();
    });

    $('a.less', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).parent().hide().prev().show().prev().show();
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button></code>```

答:
You can use jquery eq() and after() function for the task.

```<code>$(document).ready(function() {
  $( "button.playtrailer" ).eq(2).after('<a>Read More</a>');
});
</code>```

Here is an example

Body:
In this code, I want to display show more link, after 3 buttons:
I know, how to display show more button after x words, but how to display show more link after buttons?

This is my code to display show more link after x words, if it helps:

jQuery(function(){

    var minimized_elements = $('span.showmore');

    minimized_elements.each(function(){
        var t = $(this).text();
        if(t.length < 410) return;

        $(this).html(
            t.slice(0,410)+'... Show More'+
            ''+ t.slice(410,t.length)+' Less'
        );

    });

    $('a.more', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).hide().prev().hide();
        $(this).next().show();
    });

    $('a.less', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).parent().hide().prev().show().prev().show();
    });

});

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button>

Body:
You can use jquery eq() and after() function for the task.

$(document).ready(function() {
  $( "button.playtrailer" ).eq(2).after('<a>Read More</a>');
});

Here is an example


问:
What is the point of PHP's stripslashes function?
Suppose you have the following:

```<code><?php

    $connection = mysqli_connect("host", "root", "passwd", "dbname");

    $habits = mysqli_real_escape_string($connection, $_POST['habits']);

?>
</code>```

Lets say you entered, for a field called 'habits', the value 'tug o' war'. Therefore, the mysqli_real_escape_string function will escape the second quote symbol and the database engine won't be fooled into thinking that the value is 'tug o'. Instead, it will know that the value is actually 'tug o' war'. My question is, why then do you need a stripslashes function? A stripslashes function will simply strip away the good work that was done by the mysqli_real_escape_string function. Stripping away a backslash will simply return you to where you were, and the database will be fooled again. Am I to assume that the stripslashes function is NOT used for database purposes? That is, would this piece of code be completely nonsensical?:

```<code><?php

    $connection = mysqli_connect("host", "root", "passwd", "dbname");

    $habits = mysqli_real_escape_string($connection, $_POST['habits']);

    $undosomething = stripslashes($habits);

    echo '$undosomething';

?>
</code>```

If stripslashes is NOT used for database purposes, what exactly is it used for?

答:
addslashes():

w3schools.com - function returns a string with backslashes in front of predefined characters.

php.net - Quote string with slashes

stripslashes():

w3schools.com - function removes backslashes added by the addslashes() function.

php.net - Un-quotes a quoted string

```<code><?php

  $str = "Who's Peter Griffin?";

  echo $str . " This is original string." . PHP_EOL;

  echo addslashes($str) . " This is addslashes string." . PHP_EOL;

  echo stripslashes(addslashes($str)) . " This is stripslashes string."  . PHP_EOL;

?>
</code>```

Embed PHP online:

body, html, iframe {
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe src="https://ideone.com/2DNzNJ"></iframe></code>```

Body:
Suppose you have the following:

<?php

    $connection = mysqli_connect("host", "root", "passwd", "dbname");

    $habits = mysqli_real_escape_string($connection, $_POST['habits']);

?>

Lets say you entered, for a field called 'habits', the value 'tug o' war'. Therefore, the mysqli_real_escape_string function will escape the second quote symbol and the database engine won't be fooled into thinking that the value is 'tug o'. Instead, it will know that the value is actually 'tug o' war'. My question is, why then do you need a stripslashes function? A stripslashes function will simply strip away the good work that was done by the mysqli_real_escape_string function. Stripping away a backslash will simply return you to where you were, and the database will be fooled again. Am I to assume that the stripslashes function is NOT used for database purposes? That is, would this piece of code be completely nonsensical?:

<?php

    $connection = mysqli_connect("host", "root", "passwd", "dbname");

    $habits = mysqli_real_escape_string($connection, $_POST['habits']);

    $undosomething = stripslashes($habits);

    echo '$undosomething';

?>

If stripslashes is NOT used for database purposes, what exactly is it used for?

Body:
addslashes():

w3schools.com - function returns a string with backslashes in front of predefined characters.

php.net - Quote string with slashes

stripslashes():

w3schools.com - function removes backslashes added by the addslashes() function.

php.net - Un-quotes a quoted string

<?php

  $str = "Who's Peter Griffin?";

  echo $str . " This is original string." . PHP_EOL;

  echo addslashes($str) . " This is addslashes string." . PHP_EOL;

  echo stripslashes(addslashes($str)) . " This is stripslashes string."  . PHP_EOL;

?>

Embed PHP online:

body, html, iframe {
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}

<iframe src="https://ideone.com/2DNzNJ"></iframe>

ContentLicense: CC BY-SA 4.0


问:
I am getting an error in my android application
The App is working fine in Android Jelly Bean, but it not working on Android M. It says InvocationTargetException.

MainActivity.java

```<code>     @Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.enableWifiHotSpotId:
            try {
                if (!((editText.getText().toString()).equals(""))) {
                    OnOfHotspot.hotspotName = editText.getText().toString();
                    OnOfHotspot.getApConfiguration(this);
                    OnOfHotspot.configApState(this, true);
                }else {
                    Toast.makeText(getApplicationContext(),"Please Specify Hotspot name!",Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case R.id.disableWifiHotspotId:
            try {
                OnOfHotspot.getApConfiguration(this);
                OnOfHotspot.configApState(this, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
      }
 }
</code>```

Permissions

```<code><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

Logcat

```<code>07-09 14:04:23.869 29724-29724/com.juggernaut.hotspot W/System.err:java.lang.reflect.InvocationTargetException
07-09 14:04:23.874 432-3097/? D/APM-AudioPolicyManager: startOutput()--
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.juggernaut.hotspot.OnOfHotspot.configApState(OnOfHotspot.java:47)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.juggernaut.hotspot.MainActivity.onClick(MainActivity.java:48)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.view.View.performClick(View.java:5233)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.view.View$PerformClick.run(View.java:21209)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Looper.loop(Looper.java:152)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5497)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err: Caused by: java.lang.SecurityException: com.juggernaut.hotspot was not granted  this
permission: android.permission.WRITE_SETTINGS.
07-9 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Parcel.readException(Parcel.java:1620)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Parcel.readException(Parcel.java:1573)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.net.wifi.IWifiManager$Stub$Proxy.setWifiApEnabled(IWifiManager.java:1511)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.net.wifi.WifiManager.setWifiApEnabled(WifiManager.java:1590)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     ... 12 more
</code>```

Github link

Solution : I just have to add this method for getting WRITE_SETTING
  permission.

```<code> public void writePermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.System.canWrite(getApplicationContext())) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 200);

        }
    }
}
</code>```

And call writePermission() within onClick

答:
In android version 23 and above you have to request permissions at runtime. ie; even if you have declared the permission in the manifest, you should ask for the permission at runtime in version 23 and above. That is why the app worked in Jellybean and crashed in Marshmallow. See the line Caused by: java.lang.SecurityException: com.juggernaut.hotspot was not granted  this
permission: android.permission.WRITE_SETTINGS. it clearly says that the permission is not granted. Request and get the permission granted before creating the hotspot. Please see This link for more information managing permissions at runtime

Body:
The App is working fine in Android Jelly Bean, but it not working on Android M. It says InvocationTargetException.

MainActivity.java

     @Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.enableWifiHotSpotId:
            try {
                if (!((editText.getText().toString()).equals(""))) {
                    OnOfHotspot.hotspotName = editText.getText().toString();
                    OnOfHotspot.getApConfiguration(this);
                    OnOfHotspot.configApState(this, true);
                }else {
                    Toast.makeText(getApplicationContext(),"Please Specify Hotspot name!",Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case R.id.disableWifiHotspotId:
            try {
                OnOfHotspot.getApConfiguration(this);
                OnOfHotspot.configApState(this, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
      }
 }

Permissions

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

Logcat

07-09 14:04:23.869 29724-29724/com.juggernaut.hotspot W/System.err:java.lang.reflect.InvocationTargetException
07-09 14:04:23.874 432-3097/? D/APM-AudioPolicyManager: startOutput()--
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.juggernaut.hotspot.OnOfHotspot.configApState(OnOfHotspot.java:47)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.juggernaut.hotspot.MainActivity.onClick(MainActivity.java:48)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.view.View.performClick(View.java:5233)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.view.View$PerformClick.run(View.java:21209)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Looper.loop(Looper.java:152)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5497)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-09 14:04:23.879 29724-29724/com.juggernaut.hotspot W/System.err: Caused by: java.lang.SecurityException: com.juggernaut.hotspot was not granted  this
permission: android.permission.WRITE_SETTINGS.
07-9 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Parcel.readException(Parcel.java:1620)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.os.Parcel.readException(Parcel.java:1573)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.net.wifi.IWifiManager$Stub$Proxy.setWifiApEnabled(IWifiManager.java:1511)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     at android.net.wifi.WifiManager.setWifiApEnabled(WifiManager.java:1590)
07-09 14:04:23.883 29724-29724/com.juggernaut.hotspot W/System.err:     ... 12 more

Github link

Solution : I just have to add this method for getting WRITE_SETTING
  permission.

 public void writePermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.System.canWrite(getApplicationContext())) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 200);

        }
    }
}

And call writePermission() within onClick


问:
Strip all non-numeric characters from string in JavaScript
Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.

```<code>var myString = 'abc123.8<blah>';

//desired output is 1238
</code>```

How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.

答:
we are in 2017 now you can also use ES2016

```<code>var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
</code>```

or

```<code>console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
</code>```

The result is

```<code>1238
</code>```

Body:
Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.

var myString = 'abc123.8<blah>';

//desired output is 1238

How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.

Body:
we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));

The result is

1238


答:
you can add a show more link after first three buttons using jquery and move the rest of buttons to a div with a class and hide it. Attach an eventlistener to the link which shows hidden buttons.

jQuery(function(){
        var playButtons = $('.playtrailer');
        $(playButtons[2]).after('Show more');
        $(playButtons[2]).after('

');
        for (var i=3; i<playButtons.length; i++){
            $(playButtons[i]).detach();
            $(playButtons[i]).appendTo('.more-buttons');
        }
        $('.more-buttons').hide();
        $("#show-more").click(function(){
            $('.more-buttons').toggle();
            $(this).toggle();
        });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button></code>```

Title: How to show "read more" link after 3 buttons

Body:
you can add a show more link after first three buttons using jquery and move the rest of buttons to a div with a class and hide it. Attach an eventlistener to the link which shows hidden buttons.

jQuery(function(){
        var playButtons = $('.playtrailer');
        $(playButtons[2]).after('<a id="show-more" href="#">Show more</a>');
        $(playButtons[2]).after('<div class="more-buttons"></div>');
        for (var i=3; i<playButtons.length; i++){
            $(playButtons[i]).detach();
            $(playButtons[i]).appendTo('.more-buttons');
        }
        $('.more-buttons').hide();
        $("#show-more").click(function(){
            $('.more-buttons').toggle();
            $(this).toggle();
        });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="playtrailer">Trailer 1</button>
<button class="playtrailer">Trailer 2</button>
<button class="playtrailer">Trailer 3 HD</button>
<button class="playtrailer">Trailer 4 SD</button>
<button class="playtrailer">Trailer 5</button>
<button class="playtrailer">Trailer 6</button>
<button class="playtrailer">Video</button>


问:
What is the difference between a Linux platform driver and normal device driver?
Earlier I had assumed that :

Platform driver is for those devices that are on chip.

Normal device driver are for those that are interfaced to the processor chip.

Before coming across one i2c driver...
But here, I am reading through multi function i2c driver defined as platform driver. I had gone through https://www.kernel.org/doc/Documentation/driver-model/platform.txt. But still could not get clear idea to come to an conclusion on how to define drivers, like for both onchip as well interfaced devices.

Please somebody explain.

答:
Minimal module code examples

Maybe the difference will also become clearer with some concrete examples.

Platform device example

Code:

driver upstream

minimal QEMU virtual device driven.

DTS entry modifications on Linux kernel

Further integration notes at: https://stackoverflow.com/a/44612957/895245

See how:

register and interrupt addresses are hardcoded in the device tree and match the QEMU -M versatilepb machine description, which represents the SoC

there is no way to remove the device hardware (since it is part of the SoC)

the correct driver is selected by the compatible device tree property which matches platform_driver.name in the driver

platform_driver_register is the main register interface

```<code>#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>

MODULE_LICENSE("GPL");

static struct resource res;
static unsigned int irq;
static void __iomem *map;

static irqreturn_t lkmc_irq_handler(int irq, void *dev)
{
    /* TODO this 34 and not 18 as in the DTS, likely the interrupt controller moves it around.
     * Understand precisely. 34 = 18 + 16. */
    pr_info("lkmc_irq_handler irq = %d dev = %llx\n", irq, *(unsigned long long *)dev);
    /* ACK the IRQ. */
    iowrite32(0x9ABCDEF0, map + 4);
    return IRQ_HANDLED;
}

static int lkmc_platform_device_probe(struct platform_device *pdev)
{
    int asdf;
    struct device *dev = &pdev->dev;
    struct device_node *np = dev->of_node;

    dev_info(dev, "probe\n");

    /* Play with our custom poperty. */
    if (of_property_read_u32(np, "lkmc-asdf", &asdf) ) {
        dev_err(dev, "of_property_read_u32\n");
        return -EINVAL;
    }
    if (asdf != 0x12345678) {
        dev_err(dev, "asdf = %llx\n", (unsigned long long)asdf);
        return -EINVAL;
    }

    /* IRQ. */
    irq = irq_of_parse_and_map(dev->of_node, 0);
    if (request_irq(irq, lkmc_irq_handler, 0, "lkmc_platform_device", dev) < 0) {
        dev_err(dev, "request_irq");
        return -EINVAL;
    }
    dev_info(dev, "irq = %u\n", irq);

    /* MMIO. */
    if (of_address_to_resource(pdev->dev.of_node, 0, &res)) {
        dev_err(dev, "of_address_to_resource");
        return -EINVAL;
    }
    if  (!request_mem_region(res.start, resource_size(&res), "lkmc_platform_device")) {
        dev_err(dev, "request_mem_region");
        return -EINVAL;
    }
    map = of_iomap(pdev->dev.of_node, 0);
    if (!map) {
        dev_err(dev, "of_iomap");
        return -EINVAL;
    }
    dev_info(dev, "res.start = %llx resource_size = %llx\n",
            (unsigned long long)res.start, (unsigned long long)resource_size(&res));

    /* Test MMIO and IRQ. */
    iowrite32(0x12345678, map);

    return 0;
}

static int lkmc_platform_device_remove(struct platform_device *pdev)
{
    dev_info(&pdev->dev, "remove\n");
    free_irq(irq, &pdev->dev);
    iounmap(map);
    release_mem_region(res.start, resource_size(&res));
    return 0;
}

static const struct of_device_id of_lkmc_platform_device_match[] = {
    { .compatible = "lkmc_platform_device", },
    {},
};

MODULE_DEVICE_TABLE(of, of_lkmc_platform_device_match);

static struct platform_driver lkmc_plaform_driver = {
    .probe      = lkmc_platform_device_probe,
    .remove     = lkmc_platform_device_remove,
    .driver     = {
        .name   = "lkmc_platform_device",
        .of_match_table = of_lkmc_platform_device_match,
        .owner = THIS_MODULE,
    },
};

static int lkmc_platform_device_init(void)
{
    pr_info("lkmc_platform_device_init\n");
    return platform_driver_register(&lkmc_plaform_driver);
}

static void lkmc_platform_device_exit(void)
{
    pr_info("lkmc_platform_device_exit\n");
    platform_driver_unregister(&lkmc_plaform_driver);
}

module_init(lkmc_platform_device_init)
module_exit(lkmc_platform_device_exit)
</code>```

PCI non-platform device example

driver upstream

minimal QEMU virtual device driven

See how:

register and interrupt addresses are dynamically allocated by the PCI system, no device tree is used

the correct driver is selected by the PCI vendor:device ID (QEMU_VENDOR_ID, EDU_DEVICE_ID on example). This is baked into every device, and vendors must ensure uniqueness.

we can insert and remove the PCI device with device_add edu and device_del edu as we can in real life. Probing is not automatic, but can be done after boot with echo 1 > /sys/bus/pci/rescan. See also: Why is the probe method needed in Linux device drivers in addition to init?

```<code>#include <asm/uaccess.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>

#define BAR 0
#define CDEV_NAME "lkmc_hw_pci_min"
#define EDU_DEVICE_ID 0x11e9
#define QEMU_VENDOR_ID 0x1234

MODULE_LICENSE("GPL");

static struct pci_device_id id_table[] = {
    { PCI_DEVICE(QEMU_VENDOR_ID, EDU_DEVICE_ID), },
    { 0, }
};
MODULE_DEVICE_TABLE(pci, id_table);
static int major;
static struct pci_dev *pdev;
static void __iomem *mmio;
static struct file_operations fops = {
    .owner   = THIS_MODULE,
};

static irqreturn_t irq_handler(int irq, void *dev)
{
    pr_info("irq_handler irq = %d dev = %d\n", irq, *(int *)dev);
    iowrite32(0, mmio + 4);
    return IRQ_HANDLED;
}

static int probe(struct pci_dev *dev, const struct pci_device_id *id)
{
    pr_info("probe\n");
    major = register_chrdev(0, CDEV_NAME, &fops);
    pdev = dev;
    if (pci_enable_device(dev) < 0) {
        dev_err(&(pdev->dev), "pci_enable_device\n");
        goto error;
    }
    if (pci_request_region(dev, BAR, "myregion0")) {
        dev_err(&(pdev->dev), "pci_request_region\n");
        goto error;
    }
    mmio = pci_iomap(pdev, BAR, pci_resource_len(pdev, BAR));
    pr_info("dev->irq = %u\n", dev->irq);
    if (request_irq(dev->irq, irq_handler, IRQF_SHARED, "pci_irq_handler0", &major) < 0) {
        dev_err(&(dev->dev), "request_irq\n");
        goto error;
    }
    iowrite32(0x12345678, mmio);
    return 0;
error:
    return 1;
}

static void remove(struct pci_dev *dev)
{
    pr_info("remove\n");
    free_irq(dev->irq, &major);
    pci_release_region(dev, BAR);
    unregister_chrdev(major, CDEV_NAME);
}

static struct pci_driver pci_driver = {
    .name     = CDEV_NAME,
    .id_table = id_table,
    .probe    = probe,
    .remove   = remove,
};

static int myinit(void)
{
    if (pci_register_driver(&pci_driver) < 0) {
        return 1;
    }
    return 0;
}

static void myexit(void)
{
    pci_unregister_driver(&pci_driver);
}

module_init(myinit);
module_exit(myexit);
</code>```

Body:
Minimal module code examples

Maybe the difference will also become clearer with some concrete examples.

Platform device example

Code:

driver upstream

minimal QEMU virtual device driven.

DTS entry modifications on Linux kernel

Further integration notes at: https://stackoverflow.com/a/44612957/895245

See how:

register and interrupt addresses are hardcoded in the device tree and match the QEMU -M versatilepb machine description, which represents the SoC

there is no way to remove the device hardware (since it is part of the SoC)

the correct driver is selected by the compatible device tree property which matches platform_driver.name in the driver

platform_driver_register is the main register interface

#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>

MODULE_LICENSE("GPL");

static struct resource res;
static unsigned int irq;
static void __iomem *map;

static irqreturn_t lkmc_irq_handler(int irq, void *dev)
{
    /* TODO this 34 and not 18 as in the DTS, likely the interrupt controller moves it around.
     * Understand precisely. 34 = 18 + 16. */
    pr_info("lkmc_irq_handler irq = %d dev = %llx\n", irq, *(unsigned long long *)dev);
    /* ACK the IRQ. */
    iowrite32(0x9ABCDEF0, map + 4);
    return IRQ_HANDLED;
}

static int lkmc_platform_device_probe(struct platform_device *pdev)
{
    int asdf;
    struct device *dev = &pdev->dev;
    struct device_node *np = dev->of_node;

    dev_info(dev, "probe\n");

    /* Play with our custom poperty. */
    if (of_property_read_u32(np, "lkmc-asdf", &asdf) ) {
        dev_err(dev, "of_property_read_u32\n");
        return -EINVAL;
    }
    if (asdf != 0x12345678) {
        dev_err(dev, "asdf = %llx\n", (unsigned long long)asdf);
        return -EINVAL;
    }

    /* IRQ. */
    irq = irq_of_parse_and_map(dev->of_node, 0);
    if (request_irq(irq, lkmc_irq_handler, 0, "lkmc_platform_device", dev) < 0) {
        dev_err(dev, "request_irq");
        return -EINVAL;
    }
    dev_info(dev, "irq = %u\n", irq);

    /* MMIO. */
    if (of_address_to_resource(pdev->dev.of_node, 0, &res)) {
        dev_err(dev, "of_address_to_resource");
        return -EINVAL;
    }
    if  (!request_mem_region(res.start, resource_size(&res), "lkmc_platform_device")) {
        dev_err(dev, "request_mem_region");
        return -EINVAL;
    }
    map = of_iomap(pdev->dev.of_node, 0);
    if (!map) {
        dev_err(dev, "of_iomap");
        return -EINVAL;
    }
    dev_info(dev, "res.start = %llx resource_size = %llx\n",
            (unsigned long long)res.start, (unsigned long long)resource_size(&res));

    /* Test MMIO and IRQ. */
    iowrite32(0x12345678, map);

    return 0;
}

static int lkmc_platform_device_remove(struct platform_device *pdev)
{
    dev_info(&pdev->dev, "remove\n");
    free_irq(irq, &pdev->dev);
    iounmap(map);
    release_mem_region(res.start, resource_size(&res));
    return 0;
}

static const struct of_device_id of_lkmc_platform_device_match[] = {
    { .compatible = "lkmc_platform_device", },
    {},
};

MODULE_DEVICE_TABLE(of, of_lkmc_platform_device_match);

static struct platform_driver lkmc_plaform_driver = {
    .probe      = lkmc_platform_device_probe,
    .remove     = lkmc_platform_device_remove,
    .driver     = {
        .name   = "lkmc_platform_device",
        .of_match_table = of_lkmc_platform_device_match,
        .owner = THIS_MODULE,
    },
};

static int lkmc_platform_device_init(void)
{
    pr_info("lkmc_platform_device_init\n");
    return platform_driver_register(&lkmc_plaform_driver);
}

static void lkmc_platform_device_exit(void)
{
    pr_info("lkmc_platform_device_exit\n");
    platform_driver_unregister(&lkmc_plaform_driver);
}

module_init(lkmc_platform_device_init)
module_exit(lkmc_platform_device_exit)

PCI non-platform device example

driver upstream

minimal QEMU virtual device driven

See how:

register and interrupt addresses are dynamically allocated by the PCI system, no device tree is used

the correct driver is selected by the PCI vendor:device ID (QEMU_VENDOR_ID, EDU_DEVICE_ID on example). This is baked into every device, and vendors must ensure uniqueness.

we can insert and remove the PCI device with device_add edu and device_del edu as we can in real life. Probing is not automatic, but can be done after boot with echo 1 > /sys/bus/pci/rescan. See also: Why is the probe method needed in Linux device drivers in addition to init?

#include <asm/uaccess.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>

#define BAR 0
#define CDEV_NAME "lkmc_hw_pci_min"
#define EDU_DEVICE_ID 0x11e9
#define QEMU_VENDOR_ID 0x1234

MODULE_LICENSE("GPL");

static struct pci_device_id id_table[] = {
    { PCI_DEVICE(QEMU_VENDOR_ID, EDU_DEVICE_ID), },
    { 0, }
};
MODULE_DEVICE_TABLE(pci, id_table);
static int major;
static struct pci_dev *pdev;
static void __iomem *mmio;
static struct file_operations fops = {
    .owner   = THIS_MODULE,
};

static irqreturn_t irq_handler(int irq, void *dev)
{
    pr_info("irq_handler irq = %d dev = %d\n", irq, *(int *)dev);
    iowrite32(0, mmio + 4);
    return IRQ_HANDLED;
}

static int probe(struct pci_dev *dev, const struct pci_device_id *id)
{
    pr_info("probe\n");
    major = register_chrdev(0, CDEV_NAME, &fops);
    pdev = dev;
    if (pci_enable_device(dev) < 0) {
        dev_err(&(pdev->dev), "pci_enable_device\n");
        goto error;
    }
    if (pci_request_region(dev, BAR, "myregion0")) {
        dev_err(&(pdev->dev), "pci_request_region\n");
        goto error;
    }
    mmio = pci_iomap(pdev, BAR, pci_resource_len(pdev, BAR));
    pr_info("dev->irq = %u\n", dev->irq);
    if (request_irq(dev->irq, irq_handler, IRQF_SHARED, "pci_irq_handler0", &major) < 0) {
        dev_err(&(dev->dev), "request_irq\n");
        goto error;
    }
    iowrite32(0x12345678, mmio);
    return 0;
error:
    return 1;
}

static void remove(struct pci_dev *dev)
{
    pr_info("remove\n");
    free_irq(dev->irq, &major);
    pci_release_region(dev, BAR);
    unregister_chrdev(major, CDEV_NAME);
}

static struct pci_driver pci_driver = {
    .name     = CDEV_NAME,
    .id_table = id_table,
    .probe    = probe,
    .remove   = remove,
};

static int myinit(void)
{
    if (pci_register_driver(&pci_driver) < 0) {
        return 1;
    }
    return 0;
}

static void myexit(void)
{
    pci_unregister_driver(&pci_driver);
}

module_init(myinit);
module_exit(myexit);


问:
How to cut corner of an image

I make this view with a swift file

```<code>import UIKit

@IBDesignable class DesignView: UIView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}
</code>```

But when i set a image background the image overflow of the view like this :

I tried to apply the same swift file to my image view like this

```<code>import UIKit

@IBDesignable class DesignImageView: UIImageView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}
</code>```

But nothing append so how can i cut the corner without edit my image ?

答:
Try

```<code>view.clipsToBound = true
</code>```

Your Image is showing out of its bounds because of its size

From Apple Developer Docs:

Setting this value to true causes subviews to be clipped to the bounds of the receiver. If set to false, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is false.

Title: How to cut corner of an image

Body:
I make this view with a swift file

import UIKit

@IBDesignable class DesignView: UIView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}

But when i set a image background the image overflow of the view like this :

I tried to apply the same swift file to my image view like this

import UIKit

@IBDesignable class DesignImageView: UIImageView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}

But nothing append so how can i cut the corner without edit my image ?

Body:
Try

view.clipsToBound = true

Your Image is showing out of its bounds because of its size

From Apple Developer Docs:

Setting this value to true causes subviews to be clipped to the bounds of the receiver. If set to false, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is false.


问:
Finding repeat rate using sql
I have a table mentioned below:
If X customers had made the purchase in the month of Jan, how many of them made them in Feb too i.e Y. (Repeat Rate: Y/X*100)

```<code>customer_no month
---------------------
1           jan
2           jan
3           jan
4           jan
11          jan
1           feb
2           feb
3           feb
9           feb
10          feb
</code>```

Output:

```<code> Repeat_Rate
 60%
</code>```

答:
i would do it like:

```<code>   SELECT CAST(COUNT(yourtable_feb.customer_no) as FLOAT)
          / CAST(COUNT(yourtable_jan.customer_no) AS FLOAT) AS Repeating_Rate
     FROM yourtable yourtable_jan
LEFT JOIN yourtable yourtable_feb
       ON yourtable_jan.customer_no = yourtable_feb.customer_no
      AND yourtable_feb.mymonth = 'feb'
    WHERE yourtable_jan.mymonth = 'jan'
</code>```

here a rextester, if you'd like to retest my query:
http://rextester.com/ESO11614

Title: Finding repeat rate using sql

Body:
I have a table mentioned below:
If X customers had made the purchase in the month of Jan, how many of them made them in Feb too i.e Y. (Repeat Rate: Y/X*100)

customer_no month
---------------------
1           jan
2           jan
3           jan
4           jan
11          jan
1           feb
2           feb
3           feb
9           feb
10          feb

Output:

 Repeat_Rate
 60%

Body:
i would do it like:

   SELECT CAST(COUNT(yourtable_feb.customer_no) as FLOAT)
          / CAST(COUNT(yourtable_jan.customer_no) AS FLOAT) AS Repeating_Rate
     FROM yourtable yourtable_jan
LEFT JOIN yourtable yourtable_feb
       ON yourtable_jan.customer_no = yourtable_feb.customer_no
      AND yourtable_feb.mymonth = 'feb'
    WHERE yourtable_jan.mymonth = 'jan'

here a rextester, if you'd like to retest my query:
http://rextester.com/ESO11614


问:
"source" attribute of the package resource in chef
I am a beginner with the chef and slowly diving deep into it. I have a doubt regarding the "source" attribute of the resource "Package". The documentation says the "source" attribute uses local file system stored files and not HTTP or FTP. I have a 'TOMCAT tar' file and 'Java RPM' package to be installed on nodes.

Just like how the resource "cookbook_file" has files saved in "file" Directory in the cookbooks directory:
tree structure of apache cookbook

on which local file system does the "source" attribute of the resource "package" take files from? Does it grab files from the same 'files' directory? or in any other folders? I have written a simple cookbook assuming that the "source" attribute would take files from the "file" dir by default. but that is not working out:

package 'Installing JAVA' do
  source 'jdk-8u131-linux-x64'
  action :install
end

package 'Installing tomcat version 9' do
    source 'apache-tomcat-9.0.0.M22.tar'
    action :install
end

Kindly help me out!

答:
The source on a package is a plain ol' local filesystem path. If you want to use something from a cookbook you need to use it alongside a cookbook_file resource.

However we really don't recommend this. Chef is not a very good file distribution system. It will work, and on small scales it's okay-ish but it's really not going to be pleasant over the long term. For packages, you could host an internal Yum repository somewhere on your network and use Chef to configure it via the yum_repository resource.


问:
Why does an inline function have lower efficiency than an in-built function?
I was trying a question on arrays in InterviewBit. In this question I made an inline function returning the absolute value of an integer. But I was told that my algorithm was not efficient on submitting it. But when I changed to using abs() from C++ library it gave a correct answer verdict.

Here is my function that got an inefficient verdict -

```<code>inline int abs(int x){return x>0 ? x : -x;}

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}
</code>```

Here's the one that got the correct answer -

```<code>int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}
</code>```

Why did this happened, as I thought that inline functions are fastest as no calling is done? Or is the site having an error? And if the site is correct, what does C++ abs() use that is faster than inline abs()?

答:
Your abs performs branching based on a condition. While the built-in variant just removes the sign bit from the integer, most likely using just a couple of instructions. Possible assembly example (taken from here):

```<code>cdq
xor eax, edx
sub eax, edx
</code>```

The cdq copies the sign of the register eax to register edx. For example, if it is a positive number, edx will be zero, otherwise, edx will be 0xFFFFFF which denotes -1. The xor operation with the origin number will change nothing if it is a positive number (any number xor 0 will not change). However, when eax is negative, eax xor 0xFFFFFF yields (not eax). The final step is to subtract edx from eax. Again, if eax is positive, edx is zero, and the final value is still the same. For negative values, (~ eax) – (-1) = –eax which is the value wanted.

As you can see this approach uses only three simple arithmetic instructions and no conditional branching at all.

Edit: After some research it turned out that many built-in implementations of abs use the same approach, return __x >= 0 ? __x : -__x;, and such a pattern is an obvious target for compiler optimization to avoid unnecessary branching.

However, that does not justify the use of custom abs implementation as it violates the DRY principle and no one can guarantee that your implementation is going to be just as good for more sophisticated scenarios and/or unusual platforms. Typically one should think about rewriting some of the library functions only when there is a definite performance problem or some other defect detected in existing implementation.

Edit2: Just switching from int to float shows considerable performance degradation:

```<code>float libfoo(float x)
{
    return ::std::fabs(x);
}

andps   xmm0, xmmword ptr [rip + .LCPI0_0]
</code>```

And a custom version:

```<code>inline float my_fabs(float x)
{
    return x>0.0f?x:-x;
}

float myfoo(float x)
{
    return my_fabs(x);
}

movaps  xmm1, xmmword ptr [rip + .LCPI1_0] # xmm1 = [-0.000000e+00,-0.000000e+00,-0.000000e+00,-0.000000e+00]
xorps   xmm1, xmm0
xorps   xmm2, xmm2
cmpltss xmm2, xmm0
andps   xmm0, xmm2
andnps  xmm2, xmm1
orps    xmm0, xmm2
</code>```

online compiler

Body:
I was trying a question on arrays in InterviewBit. In this question I made an inline function returning the absolute value of an integer. But I was told that my algorithm was not efficient on submitting it. But when I changed to using abs() from C++ library it gave a correct answer verdict.

Here is my function that got an inefficient verdict -

inline int abs(int x){return x>0 ? x : -x;}

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}

Here's the one that got the correct answer -

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}

Why did this happened, as I thought that inline functions are fastest as no calling is done? Or is the site having an error? And if the site is correct, what does C++ abs() use that is faster than inline abs()?

Body:
Your abs performs branching based on a condition. While the built-in variant just removes the sign bit from the integer, most likely using just a couple of instructions. Possible assembly example (taken from here):

cdq
xor eax, edx
sub eax, edx

The cdq copies the sign of the register eax to register edx. For example, if it is a positive number, edx will be zero, otherwise, edx will be 0xFFFFFF which denotes -1. The xor operation with the origin number will change nothing if it is a positive number (any number xor 0 will not change). However, when eax is negative, eax xor 0xFFFFFF yields (not eax). The final step is to subtract edx from eax. Again, if eax is positive, edx is zero, and the final value is still the same. For negative values, (~ eax) – (-1) = –eax which is the value wanted.

As you can see this approach uses only three simple arithmetic instructions and no conditional branching at all.

Edit: After some research it turned out that many built-in implementations of abs use the same approach, return __x >= 0 ? __x : -__x;, and such a pattern is an obvious target for compiler optimization to avoid unnecessary branching.

However, that does not justify the use of custom abs implementation as it violates the DRY principle and no one can guarantee that your implementation is going to be just as good for more sophisticated scenarios and/or unusual platforms. Typically one should think about rewriting some of the library functions only when there is a definite performance problem or some other defect detected in existing implementation.

Edit2: Just switching from int to float shows considerable performance degradation:

float libfoo(float x)
{
    return ::std::fabs(x);
}

andps   xmm0, xmmword ptr [rip + .LCPI0_0]

And a custom version:

inline float my_fabs(float x)
{
    return x>0.0f?x:-x;
}

float myfoo(float x)
{
    return my_fabs(x);
}

movaps  xmm1, xmmword ptr [rip + .LCPI1_0] # xmm1 = [-0.000000e+00,-0.000000e+00,-0.000000e+00,-0.000000e+00]
xorps   xmm1, xmm0
xorps   xmm2, xmm2
cmpltss xmm2, xmm0
andps   xmm0, xmm2
andnps  xmm2, xmm1
orps    xmm0, xmm2

online compiler