问:
jQuery validate, only accept a latex file
I am working with a form in jQuery and using jQuery validate, I'd like the form to only accept a latex file and I went through the documentation and attempted to use the accept method https://jqueryvalidation.org/accept-method/.

From my understanding here https://www.freeformatter.com/mime-types-list.html

Accept needs a mime type, and the mime type for latex is "application/x-latex"

So I have my form set up like the following

$('#adminLatexUpload').validate({
  rules: {
    file: {
      required: true,
      accept: "application/x-latex"
    },
    version: {
      required: true,
      pattern: /^[a-zA-Z0-9_.\/]*$/
    }
  },

  messages: {
    file: {
      accept: "Unsupported file type, you must upload a .latex file"
    },
    version: {
      pattern: "Invalid naming convention, no whitespaces or special characters"
    }
  },

  errorElement: "span", // error tag name

  errorPlacement: function(error, element) { // rules for placement of error tag
    element.parent().parent().addClass('has-error');
    error.addClass('help-block');
    error.appendTo(element.parent());
  },

  success: function(error, element) { // rules for placement of success tag
    error.removeClass('help-block');
    error.parents('.form-group').removeClass('has-error');
    error.remove();
  },

  submitHandler: function(form, e) {
    document.write('Good');
  },

  invalidHandler: function(e, validator) {
    var errorCount = validator.numberOfInvalids();
    if (errorCount) {
      var errMessage = errorCount === 1 ? "You have 1 error." : "You have " + errorCount + " errors."
      window.confirm(errMessage);
    }
  }
});```
<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>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.min.js"></script>

<div class="col-md-4 latex-container">
  <h4>Upload new Latex File</h4>
  <form class="form-vertical" id="adminLatexUpload">
    <div class="form-group">
      <label class="control-label">
                                        Attach Latex File:
                                        <input class="form-control" type="file" name="file" id="adminLatexUpload_File" accept=".tex" required />
                                    </label>
    </div>
    <div class="form-group">
      <label class="control-label">
                                        Version Name:
                                        <input class="form-control" type="text" name="version" id="adminLatexUpload_Version" required />
                                    </label>
    </div>
    <button class="btn btn-success btn-sm" id="adminLatexUpload_Submit" type="submit"><span class="glyphicon glyphicon-share"></span> Upload</button>
  </form>
</div></code>```

Currently the page just refreshes when I click the submit button if I have both fields filled out. The text field validates as expected. But the input field exhibits quite a bit of undefined behavior.

Currently my testing has revealed the following:

 - Adding a non-latex file (.jpg and .gif) don't trigger any validation
   response

Submitting the file with a non-tex file refreshes the

Trying to submit the form without a file trips the requires error,

uploading a wrong file should give me a different error message and

it doesn't, the required error persists

2 of these are pointing to the fact that the accept method is failing, but no scenario should force a page refresh.

What is wrong with my validate method? And what is causing this page refresh?

Edit
After taking the suggestion to add debug:true I get the following console error on submit of invalid file

答:
The basic problem is that the accept validator is in the additional methods file and not in the core. So you need to include the https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/additional-methods.min.js file.

Still, the test i performed has the type of .tex as empty string, while if i pass a .latex file it is correctly identified as application/x-latex which seems to be the correct extension according to the link you posted.

So you might want to change the accept attribute on the input as well to accept=".latex"

$('#adminLatexUpload').validate({
  rules: {
    file: {
      required: true,
      accept: "application/x-latex"
    },
    version: {
      required: true,
      pattern: /^[a-zA-Z0-9_.\/]*$/
    }
  },

  messages: {
    file: {
      accept: "Unsupported file type, you must upload a .latex file"
    },
    version: {
      pattern: "Invalid naming convention, no whitespaces or special characters"
    }
  },

  errorElement: "span", // error tag name

  errorPlacement: function(error, element) { // rules for placement of error tag
    element.parent().parent().addClass('has-error');
    error.addClass('help-block');
    error.appendTo(element.parent());
  },

  success: function(error, element) { // rules for placement of success tag
    error.removeClass('help-block');
    error.parents('.form-group').removeClass('has-error');
    error.remove();
  },

  submitHandler: function(form, e) {
    document.write('Good');
  },

  invalidHandler: function(e, validator) {
    var errorCount = validator.numberOfInvalids();
    if (errorCount) {
      var errMessage = errorCount === 1 ? "You have 1 error." : "You have " + errorCount + " errors."
      window.confirm(errMessage);
    }
  }
});```
<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>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/additional-methods.min.js"></script>

<div class="col-md-4 latex-container">
  <h4>Upload new Latex File</h4>
  <form class="form-vertical" id="adminLatexUpload">
    <div class="form-group">
      <label class="control-label">
                                        Attach Latex File:
                                        <input class="form-control" type="file" name="file" id="adminLatexUpload_File" accept=".latex" required />
                                    </label>
    </div>
    <div class="form-group">
      <label class="control-label">
                                        Version Name:
                                        <input class="form-control" type="text" name="version" id="adminLatexUpload_Version" required />
                                    </label>
    </div>
    <button class="btn btn-success btn-sm" id="adminLatexUpload_Submit" type="submit"><span class="glyphicon glyphicon-share"></span> Upload</button>
  </form>
</div></code>```

Body:
I am working with a form in jQuery and using jQuery validate, I'd like the form to only accept a latex file and I went through the documentation and attempted to use the accept method https://jqueryvalidation.org/accept-method/.

From my understanding here https://www.freeformatter.com/mime-types-list.html

Accept needs a mime type, and the mime type for latex is "application/x-latex"

So I have my form set up like the following

$('#adminLatexUpload').validate({
  rules: {
    file: {
      required: true,
      accept: "application/x-latex"
    },
    version: {
      required: true,
      pattern: /^[a-zA-Z0-9_.\/]*$/
    }
  },

  messages: {
    file: {
      accept: "Unsupported file type, you must upload a .latex file"
    },
    version: {
      pattern: "Invalid naming convention, no whitespaces or special characters"
    }
  },

  errorElement: "span", // error tag name

  errorPlacement: function(error, element) { // rules for placement of error tag
    element.parent().parent().addClass('has-error');
    error.addClass('help-block');
    error.appendTo(element.parent());
  },

  success: function(error, element) { // rules for placement of success tag
    error.removeClass('help-block');
    error.parents('.form-group').removeClass('has-error');
    error.remove();
  },

  submitHandler: function(form, e) {
    document.write('Good');
  },

  invalidHandler: function(e, validator) {
    var errorCount = validator.numberOfInvalids();
    if (errorCount) {
      var errMessage = errorCount === 1 ? "You have 1 error." : "You have " + errorCount + " errors."
      window.confirm(errMessage);
    }
  }
});

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">

Upload new Latex File

  <form class="form-vertical" id="adminLatexUpload">

                                        Attach Latex File:
                                        <input class="form-control" type="file" name="file" id="adminLatexUpload_File" accept=".tex" required />

                                        Version Name:
                                        <input class="form-control" type="text" name="version" id="adminLatexUpload_Version" required />

    <button class="btn btn-success btn-sm" id="adminLatexUpload_Submit" type="submit"> Upload</button>
  </form>

Currently the page just refreshes when I click the submit button if I have both fields filled out. The text field validates as expected. But the input field exhibits quite a bit of undefined behavior.

Currently my testing has revealed the following:

 - Adding a non-latex file (.jpg and .gif) don't trigger any validation
   response

Submitting the file with a non-tex file refreshes the

Trying to submit the form without a file trips the requires error,

uploading a wrong file should give me a different error message and

it doesn't, the required error persists

2 of these are pointing to the fact that the accept method is failing, but no scenario should force a page refresh.

What is wrong with my validate method? And what is causing this page refresh?

Edit
After taking the suggestion to add debug:true I get the following console error on submit of invalid file

Body:
The basic problem is that the accept validator is in the additional methods file and not in the core. So you need to include the https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/additional-methods.min.js file.

Still, the test i performed has the type of .tex as empty string, while if i pass a .latex file it is correctly identified as application/x-latex which seems to be the correct extension according to the link you posted.

So you might want to change the accept attribute on the input as well to accept=".latex"

$('#adminLatexUpload').validate({
  rules: {
    file: {
      required: true,
      accept: "application/x-latex"
    },
    version: {
      required: true,
      pattern: /^[a-zA-Z0-9_.\/]*$/
    }
  },

  messages: {
    file: {
      accept: "Unsupported file type, you must upload a .latex file"
    },
    version: {
      pattern: "Invalid naming convention, no whitespaces or special characters"
    }
  },

  errorElement: "span", // error tag name

  errorPlacement: function(error, element) { // rules for placement of error tag
    element.parent().parent().addClass('has-error');
    error.addClass('help-block');
    error.appendTo(element.parent());
  },

  success: function(error, element) { // rules for placement of success tag
    error.removeClass('help-block');
    error.parents('.form-group').removeClass('has-error');
    error.remove();
  },

  submitHandler: function(form, e) {
    document.write('Good');
  },

  invalidHandler: function(e, validator) {
    var errorCount = validator.numberOfInvalids();
    if (errorCount) {
      var errMessage = errorCount === 1 ? "You have 1 error." : "You have " + errorCount + " errors."
      window.confirm(errMessage);
    }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/additional-methods.min.js"></script>

<div class="col-md-4 latex-container">
  <h4>Upload new Latex File</h4>
  <form class="form-vertical" id="adminLatexUpload">
    <div class="form-group">
      <label class="control-label">
                                        Attach Latex File:
                                        <input class="form-control" type="file" name="file" id="adminLatexUpload_File" accept=".latex" required />
                                    </label>
    </div>
    <div class="form-group">
      <label class="control-label">
                                        Version Name:
                                        <input class="form-control" type="text" name="version" id="adminLatexUpload_Version" required />
                                    </label>
    </div>
    <button class="btn btn-success btn-sm" id="adminLatexUpload_Submit" type="submit"><span class="glyphicon glyphicon-share"></span> Upload</button>
  </form>
</div>


来源: stackexchange

问:
How to solve the UPDATE command denied to user in mysql?
How to solve the UPDATE command denied to user in mysql?
yesterday it is working the update operation but today it is not working.
I am checking in the my privileges but the update is there.
What is the reason this error coming?

答:
Try This </p>

```<code>GRANT UPDATE ON `database_name`.`table_name` TO `username`@`localhost`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try This

GRANT UPDATE ON `database_name`.`table_name` TO `username`@`localhost`


问:
What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone
What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone.

considerations:

+ for country code

() for area code

x + 6 numbers for Extension extension (so make it 8 {space})

spaces between groups (i.e. in American phones +x xxx xxx xxxx = 3 spaces)

here is where I need your help, I want it to be worldwide

Consider that in my particular case now, I don't need cards etc. number begins with country code and ends with the extension, no Fax/Phone etc. comments, nor calling card stuff needed.

答:
Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.

Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.

As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.


问:
Bootstrap 4 Navbar-Brand Vertical Alignment
I have not tried any code yet but wanted to ask if it was possible to have a single navbar with a center navbar brand which is positioned ontop and bottom aligned with the navbar so that if the brand grew the navbar did not?

I would like to align the bottom of the image with the bottom of the navbar:

#hdrContainer {
  background-color: #0a3782;
}

.container {
  background-color: inherit;
}

#tblHeader {
  width: 100%;
  /*font-size: .8125rem;*/
  font-size: 1rem;
  text-align: right;
  color: #ffffff;
  font-weight: bold;
}

#tblHeader tr {
  height: 50px;
}

.breadcrumb {
  background-color: inherit;
  margin-bottom: initial;
  font-weight: bold;
}

.breadcrumb .active {
  color: inherit;
}

#socialbrand {
  text-align: right;
}

#mainNavbar {
  background-color: gray;
}

#mainNavbar .container .navbar {
  position: relative;
  z-index: 0;
  max-height: 40px;
}

.navbar-brand {
  position: relative;
  z-index: 1;
  margin-right: initial;
}

.form-control {
  width: 200px;
}

.btn-outline-navy {
  color: #f6b40e;
  background-color: transparent;
  background-image: none;
  border-color: #f6b40e;
}

body {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <div id="hdrContainer" class="container-fluid">
    <div class="container">
      <table id="tblHeader">
        <tbody>
          <tr>
            <td>
              <nav aria-label="breadcrumb" role="navigation">
                <ol class="breadcrumb">
                  <li class="breadcrumb-item active" aria-current="page">Commander, Naval Surface Force, US Pacific</li>
                </ol>
              </nav>
            </td>
            <td id="socialbrand" style="display: block; padding: .75rem 1rem;">Follow Us |
              <i class="fa fa-facebook-square" aria-hidden="true"></i>
              <i class="fa fa-twitter-square" aria-hidden="true"></i>
              <i class="fa fa-flickr" aria-hidden="true"></i>
              <i class="fa fa-wordpress" aria-hidden="true"></i>
              <i class="fa fa-youtube-square" aria-hidden="true"></i>
            </td>
          </tr>
          <tr>
            <td colspan="2">
              <nav class="navbar navbar-light">
                <form class="form-inline">
                  <input class="form-control form-control-sm ml-auto mr-sm-2 float-right" type="search" placeholder="Search" aria-label="Search">
                  <button class="btn btn-sm btn-outline-navy my-2 my-sm-0" type="submit">Search</button>
                </form>
              </nav>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div id="mainNavbar" class="container-fluid">
    <div class="container">
      <nav class="navbar navbar-expand-lg navbar-light">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav ml-auto mr-auto">
            <li class="nav-item active">
              Home <span class="sr-only">(current)</span>
            </li>
            <li class="nav-item">
              Link
            </li>
            <li class="nav-item dropdown">
              Dropdown

              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                Action
                Another action
                <div class="dropdown-divider"></div>
                Something else here
              </div>
            </li>
            <li class="nav-item">
              Disabled
            </li>
          </ul>
          <!-- Just an image -->

            <img src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" width="75" height="75" alt="">

          <ul class="navbar-nav ml-auto mr-auto">
            <li class="nav-item active">
              Home <span class="sr-only">(current)</span>
            </li>
            <li class="nav-item">
              Link
            </li>
            <li class="nav-item dropdown">
              Dropdown

              <div class="dropdown-menu" aria-labelledby="navbarDropdown1">
                Action
                Another action
                <div class="dropdown-divider"></div>
                Something else here
              </div>
            </li>
            <li class="nav-item">
              Disabled
            </li>
          </ul>
        </div>
      </nav>
    </div>
  </div>
</body></code>```

答:
See W3 Documentation on position: https://www.w3schools.com/css/css_positioning.asp

My guess is you might want to use a div with position sticky and put both the navbar and the brand inside, then change the brand on scroll-y if you were hoping to animate it to shrink.

Body:
I have not tried any code yet but wanted to ask if it was possible to have a single navbar with a center navbar brand which is positioned ontop and bottom aligned with the navbar so that if the brand grew the navbar did not?

I would like to align the bottom of the image with the bottom of the navbar:

#hdrContainer {
  background-color: #0a3782;
}

.container {
  background-color: inherit;
}

#tblHeader {
  width: 100%;
  /*font-size: .8125rem;*/
  font-size: 1rem;
  text-align: right;
  color: #ffffff;
  font-weight: bold;
}

#tblHeader tr {
  height: 50px;
}

.breadcrumb {
  background-color: inherit;
  margin-bottom: initial;
  font-weight: bold;
}

.breadcrumb .active {
  color: inherit;
}

#socialbrand {
  text-align: right;
}

#mainNavbar {
  background-color: gray;
}

#mainNavbar .container .navbar {
  position: relative;
  z-index: 0;
  max-height: 40px;
}

.navbar-brand {
  position: relative;
  z-index: 1;
  margin-right: initial;
}

.form-control {
  width: 200px;
}

.btn-outline-navy {
  color: #f6b40e;
  background-color: transparent;
  background-image: none;
  border-color: #f6b40e;
}

body {}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Commander, Naval Surface Force, US Pacific

            Follow Us |

                <form class="form-inline">
                  <input class="form-control form-control-sm ml-auto mr-sm-2 float-right" type="search" placeholder="Search" aria-label="Search">
                  <button class="btn btn-sm btn-outline-navy my-2 my-sm-0" type="submit">Search</button>
                </form>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                    </button>

              Home (current)

              Link

              Dropdown

                Action
                Another action

                Something else here

              Disabled

              Home (current)

              Link

              Dropdown

                Action
                Another action

                Something else here

              Disabled


问:
Convert Whole Digit to Date Format
I am trying to convert the Day column to a standard date format. 1 for Nov 1 (current month), 2 for Nov 2, and so on. Would be nice if the formula will display the current month. The format for the Day column is in general.

答:
Copy the following formula into cell B2 (if that's your Date column and Day is in the A column) and then copy it down:

```<code>=DATE(YEAR(TODAY()),MONTH(TODAY()),A2)
</code>```

Title: Convert Whole Digit to Date Format

Body:
Copy the following formula into cell B2 (if that's your Date column and Day is in the A column) and then copy it down:

=DATE(YEAR(TODAY()),MONTH(TODAY()),A2)


问:
how can we connect a2billing back to asterisk?
Dears,

the scenario that I am trying to accomplish is to connect a2billing back to asterisk [freepbx ] , since I have configured inboud routes that I want to use for some special numbers [ like toll free ] ,

the question is how can we use the inbound routes that we have configured before on the freepbx side

-- Adding what is done so far

I have defind a trunk from the provider , and from there I added inbound routes based on cid , and so far so good , and from a special did , I mapped to a2billing using custom-destination , and from there ,  I want to reuse the inbound routes after authenticating the card

Regards,

答:
Dears,

I have made a little adjustment to the code to check for special prefix and when I receive that by checking the destination in the code , I do a query to the inbound route to get the mapped phone number

Regards,


问:
Rails / Dalli: expire fragment from another namespace
I have two apps connecting to memcached servers on different namespaces, for example's sake we'll call them "admin" and "users".

Every now and then I want to expire some fragments in the "users" namespace from the admin application.

Note: I am not caching/expiring actions as per the other several questions/answers I found here. I want to expire keys such as "abcde". I cache all sorts of things, AR results, JSON, and so on.

Already tried things like:

```<code>Rails.cache.delete("abcd")
Rails.cache.delete("users/abcd")
Rails.cache.delete("/users/abcd")
</code>```

Digests are off.

How do I do this?

答:
If your rails cache is configured with a namespace, that namespace will be prepended to the cache key automatically. So, when you Rails.cache.write("FOO", "BAR") the key will actually be $NAMESPACE:FOO. Keys are just strings and can't be navigated like a file system or anything fancy (AFAIK).

I think your best option is instantiate a separate instance of a dalli client for your alternative namespace to delete the key.

Body:
I have two apps connecting to memcached servers on different namespaces, for example's sake we'll call them "admin" and "users".

Every now and then I want to expire some fragments in the "users" namespace from the admin application.

Note: I am not caching/expiring actions as per the other several questions/answers I found here. I want to expire keys such as "abcde". I cache all sorts of things, AR results, JSON, and so on.

Already tried things like:

Rails.cache.delete("abcd")
Rails.cache.delete("users/abcd")
Rails.cache.delete("/users/abcd")

Digests are off.

How do I do this?


问:
Determine the $Number of segments of a DASH Media from MPD file
How can I determine the $Number of segments of a DASH media if the MPD file doesn't have any segment URL's lists?
It only has a segment template tag, so I don't know how many segments the media associated to this MPD has.
Hereafter the MPD file:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<MPD profiles="urn:mpeg:dash:profile:isoff-live:2011" type="dynamic" availabilityStartTime="2017-09-24T02:32:58Z" minimumUpdatePeriod="PT2.0S" minBufferTime="PT1S" timeShiftBufferDepth="PT2M" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd">
  <Period start="PT0S">

    <AdaptationSet mimeType="video/mp4" startWithSAP="1" segmentAlignment="true">

      <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" />
      <ContentProtection schemeIdUri="urn:uuid:5E629AF5-38DA-4063-8977-97FFBD9902D4">
        <mas:MarlinContentIds xmlns:mas="marlin:mas:1-0:services:schemas:mpd" >
          <mas:MarlinContentId>urn:marlin:kid:48e495a75aefaa2f22a8c15f8c564afa</mas:MarlinContentId>
        </mas:MarlinContentIds>
      </ContentProtection>

      <SegmentTemplate timescale="10000000" presentationTimeOffset="311133404" duration="20000000" startNumber="1" media="$RepresentationID$_Segment-$Number$.m4v" initialization="$RepresentationID$_init.m4i" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_0_1600000" bandwidth="1600000" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_1_2600000" bandwidth="2600000" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_2_3900000" bandwidth="3900000" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_3_4800000" bandwidth="4800000" />

    </AdaptationSet>

    <AdaptationSet mimeType="audio/mp4" startWithSAP="1" lang="ita" segmentAlignment="true">
      <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" />
      <ContentProtection schemeIdUri="urn:uuid:5E629AF5-38DA-4063-8977-97FFBD9902D4">
        <mas:MarlinContentIds xmlns:mas="marlin:mas:1-0:services:schemas:mpd" >
          <mas:MarlinContentId>urn:marlin:kid:48e495a75aefaa2f22a8c15f8c564afa
          </mas:MarlinContentId>
        </mas:MarlinContentIds>
      </ContentProtection>
      <SegmentTemplate timescale="10000000" presentationTimeOffset="311133404" duration="20000000" startNumber="1" media="$RepresentationID$_Segment-$Number$.m4a" initialization="$RepresentationID$_init.m4i" />
      <Representation audioSamplingRate="48000" codecs="mp4a.40.5" id="Stream_4_96000" bandwidth="96000" />
    </AdaptationSet>
  </Period>
</MPD>
</code>```

I have difficult to understand how the next segment $Number is calculated.

答:
For live manifests, you have to calculate the approximate segment number based on the start time of the event, i.e. calculate the elapsed duration (time since the beginning of the event) till now (wall clock time - start time). Divide that by the fixed duration of each segment.

Because the startNumber=1, we can get the most recent segment number by calculating startNumber + (elapsedDur/segmentDur).

IMHO, this is nice way of keeping small manifest size. But this expects the DASH client to have its clock synchronized. Otherwise you will end up requesting segment numbers that do not exist (either too early or late). You will also run into a lot of 404s if the segments are not advertised yet.

ContentLicense: CC BY-SA 4.0

Body:
How can I determine the $Number of segments of a DASH media if the MPD file doesn't have any segment URL's lists?
It only has a segment template tag, so I don't know how many segments the media associated to this MPD has.
Hereafter the MPD file:

<?xml version="1.0" encoding="UTF-8" ?>
<MPD profiles="urn:mpeg:dash:profile:isoff-live:2011" type="dynamic" availabilityStartTime="2017-09-24T02:32:58Z" minimumUpdatePeriod="PT2.0S" minBufferTime="PT1S" timeShiftBufferDepth="PT2M" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd">
  <Period start="PT0S">

    <AdaptationSet mimeType="video/mp4" startWithSAP="1" segmentAlignment="true">

      <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" />
      <ContentProtection schemeIdUri="urn:uuid:5E629AF5-38DA-4063-8977-97FFBD9902D4">
        <mas:MarlinContentIds xmlns:mas="marlin:mas:1-0:services:schemas:mpd" >
          <mas:MarlinContentId>urn:marlin:kid:48e495a75aefaa2f22a8c15f8c564afa</mas:MarlinContentId>
        </mas:MarlinContentIds>
      </ContentProtection>

      <SegmentTemplate timescale="10000000" presentationTimeOffset="311133404" duration="20000000" startNumber="1" media="$RepresentationID$_Segment-$Number$.m4v" initialization="$RepresentationID$_init.m4i" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_0_1600000" bandwidth="1600000" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_1_2600000" bandwidth="2600000" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_2_3900000" bandwidth="3900000" />
      <Representation width="1920" height="1080" frameRate="25" codecs="avc1.640029" scanType="progressive" id="Stream_3_4800000" bandwidth="4800000" />

    </AdaptationSet>

    <AdaptationSet mimeType="audio/mp4" startWithSAP="1" lang="ita" segmentAlignment="true">
      <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" />
      <ContentProtection schemeIdUri="urn:uuid:5E629AF5-38DA-4063-8977-97FFBD9902D4">
        <mas:MarlinContentIds xmlns:mas="marlin:mas:1-0:services:schemas:mpd" >
          <mas:MarlinContentId>urn:marlin:kid:48e495a75aefaa2f22a8c15f8c564afa
          </mas:MarlinContentId>
        </mas:MarlinContentIds>
      </ContentProtection>
      <SegmentTemplate timescale="10000000" presentationTimeOffset="311133404" duration="20000000" startNumber="1" media="$RepresentationID$_Segment-$Number$.m4a" initialization="$RepresentationID$_init.m4i" />
      <Representation audioSamplingRate="48000" codecs="mp4a.40.5" id="Stream_4_96000" bandwidth="96000" />
    </AdaptationSet>
  </Period>
</MPD>

I have difficult to understand how the next segment $Number is calculated.


问:
Is Swift Pass By Value or Pass By Reference
I'm really new to Swift and I just read that classes are passed by reference and arrays/strings etc. are copied.

Is the pass by reference the same way as in Objective-C or Java wherein you actually pass "a" reference or is it proper pass by reference?

答:
Here is a small code sample for passing by reference.
Avoid doing this, unless you have a strong reason to.

```<code>func ComputeSomeValues(_ value1: inout String, _ value2: inout Int){
    value1 = "my great computation 1";
    value2 = 123456;
}
</code>```

Call it like this

```<code>var val1: String = "";
var val2: Int = -1;
ComputeSomeValues(&val1, &val2);
</code>```

Body:
Here is a small code sample for passing by reference.
Avoid doing this, unless you have a strong reason to.

func ComputeSomeValues(_ value1: inout String, _ value2: inout Int){
    value1 = "my great computation 1";
    value2 = 123456;
}

Call it like this

var val1: String = "";
var val2: Int = -1;
ComputeSomeValues(&val1, &val2);


问:
access count number of records with criteria celebrity
i was looking for a solution for my problem for along time, i wish you help me
i have a table with a two column first is a name and two is a town i need to count Sarah from Egpyt how many it repeated but here is the trick i need the result like table 2 below is it possible</p>

```<code>Name    town
Sarah   Egypt
John    Germany
Mick    France
Sarah   Egypt
Sarah   USA
John    Germany
Mick    France
John    Germany

Name    town    duplicate
Sarah   Egypt      1
John    Germany    1
Mick    France     1
Sarah   Egypt      2
Sarah   USA        1
John    Germany    2
Mick    France     2
John    Germany    3
</code>```

答:
You should use the aggregation function count(*) and group by  </p>

```<code>select name, town, count(*) as duplicated
from my_table
group by  name, town
</code>```

Body:
i was looking for a solution for my problem for along time, i wish you help me
i have a table with a two column first is a name and two is a town i need to count Sarah from Egpyt how many it repeated but here is the trick i need the result like table 2 below is it possible

Name    town
Sarah   Egypt
John    Germany
Mick    France
Sarah   Egypt
Sarah   USA
John    Germany
Mick    France
John    Germany

Name    town    duplicate
Sarah   Egypt      1
John    Germany    1
Mick    France     1
Sarah   Egypt      2
Sarah   USA        1
John    Germany    2
Mick    France     2
John    Germany    3

Body:
You should use the aggregation function count(*) and group by

select name, town, count(*) as duplicated
from my_table
group by  name, town


问:
Dynamically changing UI using merge and include tags depending on click
I'm new to android and programming in general so go easy!

I have created a - probably overcomplicated but it does what I want - main.xml with my layout which goes something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_scrollview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
<LinearLayout
    ...
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/title"
        android:gravity="center"
    />
    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:stretchColumns="0"
        >
        <TableRow>
            <TextView/>
            <Spinner/>
        </TableRow>
        <TableRow>
            <TextView/>
            <Spinner/>
        </TableRow>
    </TableLayout>
    <TableLayout
        android:id="@+id/main_tablelayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:stretchColumns="*"
        >
        <include
            android:id="@+id/include"
            layout="@layout/price0"
        />
        <TableRow>
            <TextView/>
            <EditText/>
        </TableRow>
    </TableLayout>
</LinearLayout>
</ScrollView>
</code>```

This is one of the options that I'm trying to include (price1.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="@string/price1"
        android:gravity="center_vertical"
    />
    <EditText
        android:id="@+id/price1"
    />
</TableRow>
</merge>
</code>```

I am trying to dynamically change the include depending on what value one of the spinners has, but I get a force close on starting the app.

The logcat error is:

```<code>01-18 15:31:42.826: ERROR/AndroidRuntime(719): FATAL EXCEPTION: main
01-18 15:31:42.826: ERROR/AndroidRuntime(719): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addView(ViewGroup.java:1871)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.TableLayout.addView(TableLayout.java:421)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addView(ViewGroup.java:1828)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.TableLayout.addView(TableLayout.java:403)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addView(ViewGroup.java:1808)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.TableLayout.addView(TableLayout.java:394)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at com.kavi.eta.Calculate$1.onItemSelected(Calculate.java:36)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:871)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.AdapterView.access$200(AdapterView.java:42)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.os.Handler.handleCallback(Handler.java:587)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.os.Looper.loop(Looper.java:123)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at java.lang.reflect.Method.invokeNative(Native Method)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at java.lang.reflect.Method.invoke(Method.java:507)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at dalvik.system.NativeStart.main(Native Method)
</code>```

Looks like I'm doing the java code wrong but I can't figure out how to properly remove the default include and replace it with another layout:

```<code>public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            int index = formatSpinner.getSelectedItemPosition();
            if (index == 0) {

                TableLayout tl = (TableLayout)findViewById(R.id.main_tablelayout2);
                tl.removeView(findViewById(R.id.include));

                LayoutInflater inflater = getLayoutInflater();
                tl.addView(inflater.inflate(R.layout.price1, tl, true));
            }
</code>```

Sorry about the long post but I've searched everywhere and can't find a clear answer. Hopefully this'll at least provide a decent-ish example...

答:
I'm also quite new, but maybe it helps:

You could give removing the  a try. I don't think this tag is appropiate in this case because you won't have two layouts of the same kind directly nested either way.
Although I wouldn't expect an IllegalStateException in this case.

Are you adding Views in your onCreate()?

ContentLicense: CC BY-SA 2.5

Body:
I'm new to android and programming in general so go easy!

I have created a - probably overcomplicated but it does what I want - main.xml with my layout which goes something like this:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_scrollview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
<LinearLayout
    ...
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/title"
        android:gravity="center"
    />
    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:stretchColumns="0"
        >
        <TableRow>
            <TextView/>
            <Spinner/>
        </TableRow>
        <TableRow>
            <TextView/>
            <Spinner/>
        </TableRow>
    </TableLayout>
    <TableLayout
        android:id="@+id/main_tablelayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:stretchColumns="*"
        >
        <include
            android:id="@+id/include"
            layout="@layout/price0"
        />
        <TableRow>
            <TextView/>
            <EditText/>
        </TableRow>
    </TableLayout>
</LinearLayout>
</ScrollView>

This is one of the options that I'm trying to include (price1.xml):

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="@string/price1"
        android:gravity="center_vertical"
    />
    <EditText
        android:id="@+id/price1"
    />
</TableRow>
</merge>

I am trying to dynamically change the include depending on what value one of the spinners has, but I get a force close on starting the app.

The logcat error is:

01-18 15:31:42.826: ERROR/AndroidRuntime(719): FATAL EXCEPTION: main
01-18 15:31:42.826: ERROR/AndroidRuntime(719): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addView(ViewGroup.java:1871)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.TableLayout.addView(TableLayout.java:421)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addView(ViewGroup.java:1828)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.TableLayout.addView(TableLayout.java:403)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.view.ViewGroup.addView(ViewGroup.java:1808)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.TableLayout.addView(TableLayout.java:394)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at com.kavi.eta.Calculate$1.onItemSelected(Calculate.java:36)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:871)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.AdapterView.access$200(AdapterView.java:42)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.os.Handler.handleCallback(Handler.java:587)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.os.Looper.loop(Looper.java:123)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at java.lang.reflect.Method.invokeNative(Native Method)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at java.lang.reflect.Method.invoke(Method.java:507)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-18 15:31:42.826: ERROR/AndroidRuntime(719):     at dalvik.system.NativeStart.main(Native Method)

Looks like I'm doing the java code wrong but I can't figure out how to properly remove the default include and replace it with another layout:

public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            int index = formatSpinner.getSelectedItemPosition();
            if (index == 0) {

                TableLayout tl = (TableLayout)findViewById(R.id.main_tablelayout2);
                tl.removeView(findViewById(R.id.include));

                LayoutInflater inflater = getLayoutInflater();
                tl.addView(inflater.inflate(R.layout.price1, tl, true));
            }

Sorry about the long post but I've searched everywhere and can't find a clear answer. Hopefully this'll at least provide a decent-ish example...


问:
Adding values to new Pandas dataframe column based on partial string contents of existing column
I have data stored as a dataframe using Python Pandas. Among the columns, I have a "Product" column which contains the brand name and model (e.g. Nike Air Jordan, Adidas Gazelle). I want to create a new column that just contains the brand (e.g. Nike, Adidas), which I will later use in groupby to summarize the data.
From my research, I believe contains and regex can be used to do this. However, the implementation has not worked. I've also seen different approaches, some using "for i in range" while others do it as a replace in a single line of code.

```<code>import pandas as pd
import numpy as np

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600,
2341, 1345, 4523, 2345, 1634, 3129]})

shoes_df['Brand'] = np.where(shoes_df['Product'].str.contains('Nike.*|Adidas.*').any(), 'Nike|Adidas', np.nan)

print(shoes_df)
</code>```

Here was my attempt at doing the "for i in range" approach, which did not work either. Here, I got the error "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

```<code>shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600, 2341, 1345, 4523,
                                   2345, 1634, 3129]})

for i in shoes_df.iterrows():
    if shoes_df['Product'].str.contains('Nike').any():
        shoes_df.set_value(i, 'Brand', 'Nike')
    elif shoes_df['Product'].str.contains('Adidas').any():
        shoes_df.set_value(i, 'Brand', 'Adidas')
    elif shoes_df['Product'].str.contains('Asics').any():
        shoes_df.set_value(i, 'Brand', 'Asics')
    else:
        shoes_df.set_value(i, 'Brand', np.nan)
</code>```

答:
If you can assume that the brand is always the first word, then the solution gives you flexibility to capture brands beyond a known list, so just adding it for interest:</p>

```<code>shoes_df['Product'].str.extract('^([^\s]+)\s')
</code>```

Body:
I have data stored as a dataframe using Python Pandas. Among the columns, I have a "Product" column which contains the brand name and model (e.g. Nike Air Jordan, Adidas Gazelle). I want to create a new column that just contains the brand (e.g. Nike, Adidas), which I will later use in groupby to summarize the data.
From my research, I believe contains and regex can be used to do this. However, the implementation has not worked. I've also seen different approaches, some using "for i in range" while others do it as a replace in a single line of code.

import pandas as pd
import numpy as np

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600,
2341, 1345, 4523, 2345, 1634, 3129]})

shoes_df['Brand'] = np.where(shoes_df['Product'].str.contains('Nike.*|Adidas.*').any(), 'Nike|Adidas', np.nan)

print(shoes_df)

Here was my attempt at doing the "for i in range" approach, which did not work either. Here, I got the error "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600, 2341, 1345, 4523,
                                   2345, 1634, 3129]})

for i in shoes_df.iterrows():
    if shoes_df['Product'].str.contains('Nike').any():
        shoes_df.set_value(i, 'Brand', 'Nike')
    elif shoes_df['Product'].str.contains('Adidas').any():
        shoes_df.set_value(i, 'Brand', 'Adidas')
    elif shoes_df['Product'].str.contains('Asics').any():
        shoes_df.set_value(i, 'Brand', 'Asics')
    else:
        shoes_df.set_value(i, 'Brand', np.nan)

Body:
If you can assume that the brand is always the first word, then the solution gives you flexibility to capture brands beyond a known list, so just adding it for interest:

shoes_df['Product'].str.extract('^([^\s]+)\s')


问:
What optimization does move semantics provide if we already have RVO?
As far as I understand one of the purposes of adding  move semantics is to optimize code by calling special constructor for copying "temporary" objects. For example, in this answer we see that it can be used to optimize such string a = x + y stuff. Because x+y is an rvalue expression, instead of deep copying we can copy only the pointer to the string and the size of the string. But as we know, modern compilers support return value optimization, so without using move semantics our code will not call the copy constructor at all.

To prove it I write this code:

```<code>#include <iostream>

struct stuff
{
        int x;
        stuff(int x_):x(x_){}
        stuff(const stuff & g):x(g.x)
        {
                std::cout<<"copy"<<std::endl;
        }
};
stuff operator+(const stuff& lhs,const stuff& rhs)
{
        stuff g(lhs.x+rhs.x);
        return g;
}
int main()
{
        stuff a(5),b(7);
        stuff c = a+b;
}
</code>```

And after executing it in VC++2010 and g++ in optimize mode I'm getting empty output.

What kind of optimization is it, if without it my code still works faster? Could you explain what I'm understanding wrong?

答:
Another good example I can think of. Imagine that you're implementing a matrix library and write an algorithm which takes two matrices and outputs another one:

```<code>Matrix MyAlgorithm(Matrix U, Matrix V)
{
    Transform(U); //doesn't matter what this actually does, but it modifies U
    Transform(V);
    return U*V;
}
</code>```

Note that you can't pass U and V by const reference, because the algorithm tweaks them. You could theoretically pass them by reference, but this would look gross and leave U and V in some intermediate state (since you call Transform(U)), which may not make any sense to the caller, or just not make any mathematical sense at all, since it's just one of the internal algorithm transformations. The code looks much cleaner if you just pass them by value and use move semantics if you are not going to use U and V after calling this function:

```<code>Matrix u, v;
...
Matrix w = MyAlgorithm(u, v); //slow, but will preserve u and v
Matrix w = MyAlgorithm(move(u), move(v)); //fast, but will nullify u and v
Matrix w = MyAlgorithm(u, move(v)); //and you can even do this if you need one but not the other
</code>```

Body:
As far as I understand one of the purposes of adding  move semantics is to optimize code by calling special constructor for copying "temporary" objects. For example, in this answer we see that it can be used to optimize such string a = x + y stuff. Because x+y is an rvalue expression, instead of deep copying we can copy only the pointer to the string and the size of the string. But as we know, modern compilers support return value optimization, so without using move semantics our code will not call the copy constructor at all.

To prove it I write this code:

#include <iostream>

struct stuff
{
        int x;
        stuff(int x_):x(x_){}
        stuff(const stuff & g):x(g.x)
        {
                std::cout<<"copy"<<std::endl;
        }
};
stuff operator+(const stuff& lhs,const stuff& rhs)
{
        stuff g(lhs.x+rhs.x);
        return g;
}
int main()
{
        stuff a(5),b(7);
        stuff c = a+b;
}

And after executing it in VC++2010 and g++ in optimize mode I'm getting empty output.

What kind of optimization is it, if without it my code still works faster? Could you explain what I'm understanding wrong?

Body:
Another good example I can think of. Imagine that you're implementing a matrix library and write an algorithm which takes two matrices and outputs another one:

Matrix MyAlgorithm(Matrix U, Matrix V)
{
    Transform(U); //doesn't matter what this actually does, but it modifies U
    Transform(V);
    return U*V;
}

Note that you can't pass U and V by const reference, because the algorithm tweaks them. You could theoretically pass them by reference, but this would look gross and leave U and V in some intermediate state (since you call Transform(U)), which may not make any sense to the caller, or just not make any mathematical sense at all, since it's just one of the internal algorithm transformations. The code looks much cleaner if you just pass them by value and use move semantics if you are not going to use U and V after calling this function:

Matrix u, v;
...
Matrix w = MyAlgorithm(u, v); //slow, but will preserve u and v
Matrix w = MyAlgorithm(move(u), move(v)); //fast, but will nullify u and v
Matrix w = MyAlgorithm(u, move(v)); //and you can even do this if you need one but not the other


问:
Magento 2 on docker generated files' user and permissions Mgt Development Environment
I'm trying out MGT Development Environment 7.0 and installed a fresh copy of Magento 2.

every time after php bin/magento setup:upgrade, and reload the page, generated files in var, pub, generated have different user and group clp:clp.

Instead of running chmod -R 777 . every time.  Can anyone suggest a better solution?

Thank in advance.

答:
After view phpinfo(), found out that php in running by user clp

Simply chown the webroot clp:clp and everytime run php command by sudo -u clp php yourCommand, which solve the problem.


问:
ADFS 2016 OAuth: Compress JWT?
We are using ADFS 2016 as our OAuth authorization server.  It is returning the OAuth access token as a JWT.  ADFS has been configured to return the groups the Active Directory account is a member of.  Everything is working properly from a token issuance standpoint.  However, we have recently run into issue where the Authorization HTTP header that contains the JWT on subsequent RESTful service calls is too large.  The Amazon ALBs that we are using as load balancers have a hard limit on the size of a header value and are rejecting the request.

I know that the contents of the JWT can be customized through some configuration within ADFS.  Is compression also an option?  If we were able to compress the token at issuance time it would reduce the size enough to go through the load balancers.

Has anyone else encountered something like this?  If so, how did you get around it?  I can't imagine we're the only shop that has encountered large header sizes with OAuth/JWTs.

答:
I don't know of a compress option.

Are you using memberOf?

Can you use the Group claim rule to pass just the groups you need?

You can also use claims rules to make smaller claims e.g.

change http://... /claims/givenname to just http://company/gn.

Title: ADFS 2016 OAuth: Compress JWT?


问:
How do I reverse each word in a sentence string like "I love computer science" using c++
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

```<code>#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}
</code>```

答:
It's always good practice to use the standard library. Here's what I could come up with to reverse words inplace while maintaining successive whitespace:

```<code>#include <string>
#include <algorithm>

std::string& reverse_words(std::string& sentence) {
  auto first = sentence.find_first_not_of(' ');
  auto last  = sentence.find_first_of(' ', first);
  while (last < std::string::npos) {
    std::reverse(&sentence[first], &sentence[last]);
    first = sentence.find_first_not_of(' ', last);
    last  = sentence.find_first_of(' ', first);
  }
  std::reverse(&sentence[first], &sentence[sentence.size()]);
  return sentence;
}
</code>```

There is maybe a way to write this more elegantly but I think you will get the idea.

Body:
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}

Body:
It's always good practice to use the standard library. Here's what I could come up with to reverse words inplace while maintaining successive whitespace:

#include <string>
#include <algorithm>

std::string& reverse_words(std::string& sentence) {
  auto first = sentence.find_first_not_of(' ');
  auto last  = sentence.find_first_of(' ', first);
  while (last < std::string::npos) {
    std::reverse(&sentence[first], &sentence[last]);
    first = sentence.find_first_not_of(' ', last);
    last  = sentence.find_first_of(' ', first);
  }
  std::reverse(&sentence[first], &sentence[sentence.size()]);
  return sentence;
}

There is maybe a way to write this more elegantly but I think you will get the idea.


问:
Php inside a javascript function?
I have a feature on my users inbox that allows users to check/uncheck messages in their inbox that they want to make favourite.

I'm currently testing what happens when a user checks the box (clicks on the image and causes it to go from greyed out to colour meaning the box is checked).

Anyway as you can see from the code below when the box ischecked this url is suppose to be loaded: http://mysite.com/messages/favourite_checked

The message_id of the row the user has checked the box on is suppose to be added onto the end of the url this then loads my controller "messages" and method "favourite_checked" which then passes a variable that grabs the message_id from the url, stores it in a variable then sends it the my model and it is used in a mysql query.

Basically I update the favourites column of my messages table and set it to = 1 where the message_id from url matches the one in the messages table in my database. So yea, where the match is found the "favourite" column in that row is updated to 1. 1 = favourite 0 = not favourite.

Any I just thought I would make it clear what was happening..

My problem is nothing happens when I check the box, nothing is updated so I feel I must be doing something wrong where I try to add the id to the url in the javascript function.

I've tried $(post) also.. nothing happens then also.

Maybe someone can spot it because I really don't know what the problem is.

```<code><script type="text/javascript">

// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {

  //query to db from php to update favourite number to 1
  $.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row):  ?><?php $row['id']; ?><?php endforeach; ?>');

    }
//    else (!isChecked)
//        {
//            //query to db from php to update favourite number to 0
//              $.get('http://mysite.com/messages/favourite_unchecked');
//        }
  }
});
</script>
</code>```

答:
About the PHP:

I think you want to replace this:

```<code><?php $row['id']; ?>    // does nothing
</code>```

with this:

```<code><?php echo $row['id']; ?>    // echo's the id
</code>```

Although I´m not sure that that will work as the loop you have there will generate a strange url, just adding all id's...

About the javascript:

I´m not familiar with the simpleImageCheck() function you are calling, but does it have an onClick or onChange event handler? Otherwise I don´t see your code being run at all.

Title: Php inside a javascript function?

Body:
About the PHP:

I think you want to replace this:

<?php $row['id']; ?>    // does nothing

with this:

<?php echo $row['id']; ?>    // echo's the id

Although I´m not sure that that will work as the loop you have there will generate a strange url, just adding all id's...

About the javascript:

I´m not familiar with the simpleImageCheck() function you are calling, but does it have an onClick or onChange event handler? Otherwise I don´t see your code being run at all.


问:
WebDriverWait.until no longer available in Selenium-java-3.2 and Selenium-java-3.3 releases
In Selenium-java-3.0.1, I can use WebDriverWait.until for explicit waits:

```<code>new WebDriverWait(myChromeDriver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
</code>```

Above code was running well in Selenium-java-3.0.1, until we upgraded to Selenium-java-3.2 where class WebDriverWait disappear from client-combined-3.3.0-nodeps.jar all together.

What is the corresponding method call in Selenium 3.2/3.3? Thanks in advance.

Stack trace is as below:

```<code>java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;
    at au.com.testpro.rft2selenium.objects.TestObject.waitForLoad(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at test.ScriptSuperClass_JZ.findTestObject(ScriptSuperClass_JZ.java:65)
    at test.refData_Verify.execute(refData_Verify.java:102)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.execute(Unknown Source)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.executeCsv(Unknown Source)
    at test.refData_Verify.test(refData_Verify.java:486)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

答:
If you are using pom.xml and getting the same error again.Just go to
C/user/yoursystemuser/.m2/repo/com/google/guava/guavaVersions.

Delete all the previous versions of guava and keep latest.
Below is the link to the dependency for guava.You might have to check your selenium version as well.

https://mvnrepository.com/artifact/com.google.guava/guava/23.0

Body:
In Selenium-java-3.0.1, I can use WebDriverWait.until for explicit waits:

new WebDriverWait(myChromeDriver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));

Above code was running well in Selenium-java-3.0.1, until we upgraded to Selenium-java-3.2 where class WebDriverWait disappear from client-combined-3.3.0-nodeps.jar all together.

What is the corresponding method call in Selenium 3.2/3.3? Thanks in advance.

Stack trace is as below:

java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;
    at au.com.testpro.rft2selenium.objects.TestObject.waitForLoad(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at test.ScriptSuperClass_JZ.findTestObject(ScriptSuperClass_JZ.java:65)
    at test.refData_Verify.execute(refData_Verify.java:102)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.execute(Unknown Source)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.executeCsv(Unknown Source)
    at test.refData_Verify.test(refData_Verify.java:486)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)


问:
"OSError: cannot identify image file" opening image with PIL/Image
I am trying to get some code working that has broken but was working before. I have a PNG file on my desktop and I simply want to open it using the Image module from PIL.

```<code>from PIL import Image
img_dir = r'C:\Users\DylanDB\Desktop\square.png'
img = Image.open(img_dir)
</code>```

This is a remake of my more advanced code that it happens in as well. The error is:

Traceback (most recent call last):
  File "C:/Users/DylanDB/Desktop/img_test.py", line 5, in <module>
    img = Image.open(img_dir)
  File "C:\Python34\lib\site-packages\PIL\Image.py", line 2317, in open
    % (filename if filename else fp))
OSError: cannot identify image file 'C:\\Users\\DylanDB\\Desktop\\square.png'
```

答: I had the same error and it was due to the file was recently created and not closed properly before opening with the Image.open(). After closing the file f.close() it werked as expect</p>

Body:
I am trying to get some code working that has broken but was working before. I have a PNG file on my desktop and I simply want to open it using the Image module from PIL.

from PIL import Image
img_dir = r'C:\Users\DylanDB\Desktop\square.png'
img = Image.open(img_dir)

This is a remake of my more advanced code that it happens in as well. The error is:

Traceback (most recent call last):
  File "C:/Users/DylanDB/Desktop/img_test.py", line 5, in <module>
    img = Image.open(img_dir)
  File "C:\Python34\lib\site-packages\PIL\Image.py", line 2317, in open
    % (filename if filename else fp))
OSError: cannot identify image file 'C:\\Users\\DylanDB\\Desktop\\square.png'


问:
Auto scaling docker containers in AWS
We can scale docker containers using service auto scaling feature in AWS with the help of Cloud-watch Alarms -
http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_autoscaling_tutorial.html

Is there any other options are available to scale the docker container if the CPU/Memory utilization reaches 80% without using Cloud-watch?

Note: We can achieve the same in Kubernetes using horizontal pod auto scaling. I want to achieve the same in AWS without Cloudwatch support.

答:
You can use AWS ECS to scale docker containers. It provides a native orchestration platform to AWS as well as support for Kubernetes.

If you decides to use ECS native container orchestration, it involves a learning curve where you need to understand ECS specific terms such as Tasks, Services and etc. The same goes with Kubernetes where you need to understand Pods, Services and etc.

When using ECS, it manages the underlying complexities such as placing containers across multiple EC2s which powers the container cluster, supporting Load Balancer intergration for container level load balancing, Supporting fault tolerance by replacing unhealthy containers and etc.

It is also possible to use AWS Fargate which also comes with ECS, where the underlying nodes in the cluster is entirely managed by AWS without even exposing the number of EC2s powering the cluster. It is more like you can scale up and down to large number of containers without worrying about allocating EC2s to the cluster. However,  it is expensive in comparison which limits its usage for more specific workloads that requires higher levels of scalability with least predictability which justifies the pricing.

Title: Auto scaling docker containers in AWS


问:
ask the user for the maximum number to print out to and then print each multiple of the base number starting from the base to the maximum
```<code>System.out.print("Please enter the max number:");
int max = input.nextInt();

System.out.print("Please enter the base:");
int base = input.nextInt();

for (int i = 0; i <= max; max % base == 0;) {
    System.out.println("Number is " + i);
}
</code>```

How do I get it to print the multiples of a number?

答:
I'm not sure if I have fully understood your question. However, I believe this is the solution you were looking for:

```<code>int currentMultiple = 0;

int step = 1;
do {
    currentMultiple = (base * step);
    System.out.println(currentMultiple);
    step += 1;
} while ( currentMultiple <= max );
</code>```

You're needing a while or do while loop for this problem. Since you are unaware of when the current multiple is going to exceed the input.

Let me know if this is what you needed!

Body:
System.out.print("Please enter the max number:");
int max = input.nextInt();

System.out.print("Please enter the base:");
int base = input.nextInt();

for (int i = 0; i <= max; max % base == 0;) {
    System.out.println("Number is " + i);
}

How do I get it to print the multiples of a number?

Body:
I'm not sure if I have fully understood your question. However, I believe this is the solution you were looking for:

int currentMultiple = 0;

int step = 1;
do {
    currentMultiple = (base * step);
    System.out.println(currentMultiple);
    step += 1;
} while ( currentMultiple <= max );

You're needing a while or do while loop for this problem. Since you are unaware of when the current multiple is going to exceed the input.

Let me know if this is what you needed!


问:
php generate date/ time in the same format appears mysql datatime
I would like to know if there is a function in php to generate data/time format like in mysql : 0000-00-00 00:00:00 .
I know you can generate data/time in the sql query with CURDATE() but I would like to know if it's possible to generate it with php in the same format mysql datatime format .</p>

答:
At the moment PHP only supports RFC 2822 and ISO 8601 conform dates as well as Unix epoch timestamp. Check more here.

The reason for that is probably that they include timezone offset, and the "mysql form"  - its a localized compbound format - doesnt, which would often lead to a mess in when using with application servers.

But you can define your own formats as you like, all the components are available via the datetime functions. Just have a look here and here

Example:

```<code>$mysql_date = date('Y-m-d H:i:s', $unix_timestamp);
</code>```

But be aware of the Y2k38 bug if you are not on a 64 bit system, you may want to use the datetime class

Body:
At the moment PHP only supports RFC 2822 and ISO 8601 conform dates as well as Unix epoch timestamp. Check more here.

The reason for that is probably that they include timezone offset, and the "mysql form"  - its a localized compbound format - doesnt, which would often lead to a mess in when using with application servers.

But you can define your own formats as you like, all the components are available via the datetime functions. Just have a look here and here

Example:

$mysql_date = date('Y-m-d H:i:s', $unix_timestamp);

But be aware of the Y2k38 bug if you are not on a 64 bit system, you may want to use the datetime class


问:
POST Request Not sent on button press
Hello I have the following template, which I'm wanting to send a POST request to activate the ajax to save the selections of the multiple check boxes.  When I view the console it shows a GET request when the user pushes the button, why is this?

```<code>   <form action="">
    <div class = "container">

      <div class="jumbotron">
        <div class="container">
          <h1 class="jumbotron-heading">Available Application List</h1></br>
        </div>
            <div class="container">

              <div class="row">
                  <div class="col">
                    <h3>Financial</h3>

                            <ul>
                            {% for app in fingrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                  </div>
                  <div class="col">

                    <h3>Care Assure</h3>
                    <div class = "row">

                            <ul>
                            {% for app in cagrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                    </div>

                  <div class = "row">
                    <h3>Performance Improvement</h3>

                            <ul>
                            {% for app in pigrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                  </div>

                  <div class = "row">
                    <h3>Supply Chain</h3>

                            <ul>
                            {% for app in scgrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                  </div>

                  <div class = "row">
                    <h3>DSS Monitoring</h3>

                            <ul>
                            {% for app in dssgrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                  </div>

                  <div class = "row">
                    <h3>Other DSS Applications</h3>

                            <ul>
                            {% for app in othgrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                  </div>

                </div>
                  <div class="col">
                    <div class="row">

                    <h3>Behavior Health / Rehab</h3>

                            <ul>
                            {% for app in bhgrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                    </div>
                    <div class="row">
                    <h3>Clinical Excellence</h3>
                            <ul>
                            {% for app in cegrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                    </div>
                    <div class="row">
                    <h3>Perfomance Service Group</h3>

                            <ul>
                            {% for app in psggrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                    </div>
                    <div class="row">
                    <h3>All Applications</h3>

                            <ul>
                            {% for app in allgrouplist %}
                            <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}</li>
                            {% endfor %}
                            </ul>

                    </div>
                  </div>

              </div class="row">

                </br></br>
                <a href="{% url 'requestaccess' %}" />
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                <script>
                $(document).ready(function(){
                    var selected_items = [];
                    $(".checkbox").click(function(){
                        var selected_item = $(this).val();
                        var index = selected_items.indexOf(selected_item);
                        if(index == -1)
                        {
                           selected_items.push(selected_item);
                        }
                        else{
                           selected_items.splice(index, 1);
                        }
                    });
                    $("#submit-button").click(function(){
                        $.ajax({
                            url: '/requestaccess/',
                            data: {'request_reports': selected_items.join(","), 'csrfmiddlewaretoken': {{csrfmiddlewaretoken}} },
                            dataType: 'json',
                            type: 'post',
                            success: function (data) {
                            }
                        });
                    });
                })
                </script>

                <input class="btn btn-primary" type="button" method = "POST" value="Request Access">
              </div>

    </form>
</code>```

This is the view for the profile page where the user selects the check boxes.

```<code>    def profile(request):
        owner = User.objects.get (formattedusername=request.user.formattedusername)
        reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')

        reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
        reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True)
        reportGroups = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_group_id', flat=True)
        reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0)
        allreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 100)
        bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200)
        cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500)
        finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600)
        careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800)
        pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100)
        screportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1200)
        dssreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1300)
        psgreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1400)
        othreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 99999)

#        if request.method == 'POST':
#            reportnamesc = request.POST.get('report_name_sc', '')
#            checked = request.POST.get('request_reports', '')
#            request_reports = #request_reports.objects.get(report_name_sc=reportnamesc)
#            request_reports.request_reports = checked
#            request_reports.save()

        args = {'user':owner, 'applicationaccess':reportaccess, 'applicationlist':reportlist, 'bhgrouplist':bhreportgrouplist, 'cegrouplist':cereportgrouplist, 'fingrouplist':finreportgrouplist
              , 'cagrouplist':careportgrouplist, 'pigrouplist':pireportgrouplist, 'scgrouplist':screportgrouplist, 'dssgrouplist':dssreportgrouplist, 'psggrouplist':psgreportgrouplist
              , 'othgrouplist':othreportgrouplist, 'allgrouplist':allreportgrouplist}

        return render(request, 'accounts/profile.html', args)
</code>```

But, with my post never occurring the ajax doesn't save my values where I can do a request.POST['request_reports'] on my form to only pull in the reports that were checked.

I'm open to suggestions if there is a better way to accomplish the task of reducing the reports to a users selections from one html template to a form.

答:
You don't prevent the default action of the button, which is to submit the form - which in turn uses the default action, GET.

Make your click event handler take an event parameter and call event.preventDefault();.

Title: POST Request Not sent on button press

Body:
Hello I have the following template, which I'm wanting to send a POST request to activate the ajax to save the selections of the multiple check boxes.  When I view the console it shows a GET request when the user pushes the button, why is this?

   <form action="">

Available Application List

Financial

                            {% for app in fingrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Care Assure

                            {% for app in cagrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Performance Improvement

                            {% for app in pigrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Supply Chain

                            {% for app in scgrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

DSS Monitoring

                            {% for app in dssgrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Other DSS Applications

                            {% for app in othgrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Behavior Health / Rehab

                            {% for app in bhgrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Clinical Excellence

                            {% for app in cegrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

Perfomance Service Group

                            {% for app in psggrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

All Applications

                            {% for app in allgrouplist %}

<input type="checkbox" name="request_reports" value ="{{app.report_id}}" >  {{ app.report_name_sc }}

                            {% endfor %}

                <input class="btn btn-primary" type="button" method = "POST" value="Request Access">

    </form>

This is the view for the profile page where the user selects the check boxes.

    def profile(request):
        owner = User.objects.get (formattedusername=request.user.formattedusername)
        reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')

        reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
        reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True)
        reportGroups = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_group_id', flat=True)
        reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0)
        allreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 100)
        bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200)
        cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500)
        finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600)
        careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800)
        pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100)
        screportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1200)
        dssreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1300)
        psgreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1400)
        othreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 99999)

#        if request.method == 'POST':
#            reportnamesc = request.POST.get('report_name_sc', '')
#            checked = request.POST.get('request_reports', '')
#            request_reports = #request_reports.objects.get(report_name_sc=reportnamesc)
#            request_reports.request_reports = checked
#            request_reports.save()

        args = {'user':owner, 'applicationaccess':reportaccess, 'applicationlist':reportlist, 'bhgrouplist':bhreportgrouplist, 'cegrouplist':cereportgrouplist, 'fingrouplist':finreportgrouplist
              , 'cagrouplist':careportgrouplist, 'pigrouplist':pireportgrouplist, 'scgrouplist':screportgrouplist, 'dssgrouplist':dssreportgrouplist, 'psggrouplist':psgreportgrouplist
              , 'othgrouplist':othreportgrouplist, 'allgrouplist':allreportgrouplist}

        return render(request, 'accounts/profile.html', args)

But, with my post never occurring the ajax doesn't save my values where I can do a request.POST['request_reports'] on my form to only pull in the reports that were checked.

I'm open to suggestions if there is a better way to accomplish the task of reducing the reports to a users selections from one html template to a form.


问:
How to upload a mapping file to Firebase Crashlytics?
In the old Crash reporting - there is easy way to upload. i didn't find it in the Crashlytics section</p>

答:
UPDATE: Firebase update their docs: see here

There is no need anymore to manually upload mapping file.

1 - To preserve the info Crashlytics needs for readable crash reports, add the following lines to your config file:

```<code>-keepattributes *Annotation*
-keepattributes SourceFile,LineNumberTable
-keep public class * extends java.lang.Exception
</code>```

2 - To let Crashlytics automatically upload the ProGuard or DexGuard mapping file, remove this line from the config file (app/proguard-rules.pro):

```<code>-printmapping mapping.txt
</code>```

For faster builds with ProGuard, exclude Crashlytics. Add the
  following lines to your config file:

```<code>-keep class com.crashlytics.** { *; }
-dontwarn com.crashlytics.**
</code>```

Body:
UPDATE: Firebase update their docs: see here

There is no need anymore to manually upload mapping file.

1 - To preserve the info Crashlytics needs for readable crash reports, add the following lines to your config file:

-keepattributes *Annotation*
-keepattributes SourceFile,LineNumberTable
-keep public class * extends java.lang.Exception

2 - To let Crashlytics automatically upload the ProGuard or DexGuard mapping file, remove this line from the config file (app/proguard-rules.pro):

-printmapping mapping.txt

For faster builds with ProGuard, exclude Crashlytics. Add the
  following lines to your config file:

-keep class com.crashlytics.** { *; }
-dontwarn com.crashlytics.**