问:
Bootstrap show datepicker on modal
I am trying to use datepicker that show on modal. But my code isn't work. I already use .datepicker{z-index:1151;} and it's not working too, can someone help me to show datepicker on bootstrap modal ? Thanks

And this is my code,

Button (in edit.php) :

```<code><a href="#detail" id="custId" data-toggle="modal" data-id="'.$row["id"].'" class="btn btn-success btn-sm" role="button" title="Detail"><i class="glyphicon glyphicon-eye-open"></i></a>
</code>```

Modal (in index.php) :

```<code><div class="modal fade" id="edit" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Edit Costumer</h4>
            </div>
            <div class="modal-body">
                <div class="fetched-data"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Keluar</button>
            </div>
        </div>
    </div>
</div>
</code>```

JS for modal (in index.php) :

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('#edit').on('show.bs.modal', function (e) {
            var rowid = $(e.relatedTarget).data('id');
            //menggunakan fungsi ajax untuk pengambilan data
            $.ajax({
                type : 'post',
                url : 'edit.php',
                data :  'rowid='+ rowid,
                success : function(data){
                $('.fetched-data').html(data);//menampilkan data ke dalam modal
                }
            });
         });
    });
</script>
</code>```

JS for Datepicker (in index.php) :

```<code><script type='text/javascript'>
    $(function(){
        $('.input-group.date').datepicker({
            calendarWeeks: true,
            todayHighlight: true,
            autoclose: true
        });
    });
</script>
</code>```

答:
Use datepicker method on jQuery object that refers to existing input element. See example below.

$(function() {
  $('.fetched-date input').datepicker({
    calendarWeeks: true,
    todayHighlight: true,
    autoclose: true
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.0/css/bootstrap-datepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.0/js/bootstrap-datepicker.min.js"></script>

<!-- body -->
<div class="modal fade" id="edit" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Edit Costumer</h4>
      </div>
      <div class="modal-body">
        <div class="input-group fetched-date">
          <input type="text" class="form-control" value="07/07/2017">
          <div class="input-group-addon">
            <span class="glyphicon glyphicon-th"></span>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Keluar</button>
      </div>
    </div>
  </div>
</div>

<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#edit" title="Detail">
  <i class="glyphicon glyphicon-eye-open"></i>
</button></code>```

Title: Bootstrap show datepicker on modal

Body:
I am trying to use datepicker that show on modal. But my code isn't work. I already use .datepicker{z-index:1151;} and it's not working too, can someone help me to show datepicker on bootstrap modal ? Thanks

And this is my code,

Button (in edit.php) :

Modal (in index.php) :

                <button type="button" class="close" data-dismiss="modal">×</button>

Edit Costumer

                <button type="button" class="btn btn-danger" data-dismiss="modal">Keluar</button>

JS for modal (in index.php) :

JS for Datepicker (in index.php) :

Body:
Use datepicker method on jQuery object that refers to existing input element. See example below.

$(function() {
  $('.fetched-date input').datepicker({
    calendarWeeks: true,
    todayHighlight: true,
    autoclose: true
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.0/css/bootstrap-datepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.0/js/bootstrap-datepicker.min.js"></script>

<!-- body -->
<div class="modal fade" id="edit" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Edit Costumer</h4>
      </div>
      <div class="modal-body">
        <div class="input-group fetched-date">
          <input type="text" class="form-control" value="07/07/2017">
          <div class="input-group-addon">
            <span class="glyphicon glyphicon-th"></span>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Keluar</button>
      </div>
    </div>
  </div>
</div>

<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#edit" title="Detail">
  <i class="glyphicon glyphicon-eye-open"></i>
</button>


来源: stackexchange

问:
How to back up my.cnf file from /etc/mysql
I encountered same problem here https://askubuntu.com/questions/760724/16-04-upgrade-broke-mysql-server

I am trying to follow the answers but I am not sure how to back up my.cnf file in /etc/mysql. Can anyone help me?

答: You can do sudo cp /etc/mysql/my.cnf /etc/mysql/my.cnf.bak This basically copies the file and renames it.

ContentLicense: CC BY-SA 3.0


问:
What could cause performance issue(s) when using roadie-rails for our case?
Originally posted as
https://github.com/Mange/roadie-rails/issues/75

We are seeing performance issue for our daily email jobs

By using NewRelic custom instrumentation,

we found out that most time is spent in calling Roadies

Screenshot of our NewRelic data for an example worker:

The integration code:

```<code># frozen_string_literal: true

require "rails"
require "action_controller"
require "contracts"
require "memoist"
require "roadie"
require "roadie-rails"

require "new_relic/agent/method_tracer"

module Shared::MailerMixins
  module WithRoadieIntegration
    # I don't want to include the constants into the class as well
    module Concern
      def self.included(base)
        base.extend ClassMethods
      end

      include ::NewRelic::Agent::MethodTracer

      def mail(*args, &block)
        super.tap do |m|
          options = roadie_options
          next unless options

          trace_execution_scoped(
            [
              [
                "WithRoadieIntegration",
                "Roadie::Rails::MailInliner.new(m, options).execute",
              ].join("/"),
            ],
          ) do
            Roadie::Rails::MailInliner.new(m, options).execute
          end
        end
      end

      private

      def roadie_options
        ::Rails.application.config.roadie.tap do |options|
          options.asset_providers = [UserAssetsProvider.new]
          options.external_asset_providers = [UserAssetsProvider.new]
          options.keep_uninlinable_css = false
          options.url_options = url_options.slice(*[
            :host,
            :port,
            :path,
            :protocol,
            :scheme,
          ])
        end
      end
      add_method_tracer(
        :roadie_options,
        "WithRoadieIntegration/roadie_options",
      )
    end

    class UserAssetsProvider
      extend(
        ::Memoist,
      )
      include(
        ::Contracts::Core,
        ::Contracts::Builtin,
      )

      include ::NewRelic::Agent::MethodTracer

      ABSOLUTE_ASSET_PATH_REGEXP = /\A#{Regexp.escape("//")}.+#{Regexp.escape("/assets/")}/i

      Contract String => Maybe[Roadie::Stylesheet]
      def find_stylesheet(name)
        return nil unless file_exists?(name)

        Roadie::Stylesheet.new("whatever", stylesheet_content(name))
      end
      add_method_tracer(
        :find_stylesheet,
        "UserAssetsProvider/find_stylesheet",
      )

      Contract String => Roadie::Stylesheet
      def find_stylesheet!(name)
        stylesheet = find_stylesheet(name)

        if stylesheet.nil?
          raise Roadie::CssNotFound.new(
            name,
            "does not exists",
            self,
          )
        end

        stylesheet
      end
      add_method_tracer(
        :find_stylesheet!,
        "UserAssetsProvider/find_stylesheet!",
      )

      private

      def file_exists?(name)
        if assets_precompiled?
          File.exists?(local_file_path(name))
        else
          sprockets_asset(name)
        end
      end
      memoize :file_exists?

      # If on-the-fly asset compilation is disabled, we must be precompiling assets.
      def assets_precompiled?
        !Rails.configuration.assets.compile
      rescue
        false
      end

      def local_file_path(name)
        asset_path = asset_path(name)
        if asset_path.match(ABSOLUTE_ASSET_PATH_REGEXP)
          asset_path.gsub!(ABSOLUTE_ASSET_PATH_REGEXP, "assets/")
        end

        File.join(Rails.public_path, asset_path)
      end
      memoize :local_file_path
      add_method_tracer(
        :local_file_path,
        "UserAssetsProvider/local_file_path",
      )

      def sprockets_asset(name)
        asset_path = asset_path(name)
        if asset_path.match(ABSOLUTE_ASSET_PATH_REGEXP)
          asset_path.gsub!(ABSOLUTE_ASSET_PATH_REGEXP, "")
        end

        # Strange thing is since rails 4.2
        # name is passed in like
        # `/assets/mailer-a9c96bd713d0b091297b82053ccd9155b933c00a53595812d755825d1747f42d.css`
        # Before any processing
        # And since `sprockets_asset` is used for preview
        # We just "fix" the name by removing the
        #
        # Regexp taken from gem `asset_sync`
        # https://github.com/AssetSync/asset_sync/blob/v1.2.1/lib/asset_sync/storage.rb#L142
        #
        # Modified to match what we need here (we need `.css` suffix)
        if asset_path =~ /-[0-9a-fA-F]{32,}\.css$/
          asset_path.gsub!(/-[0-9a-fA-F]{32,}\.css$/, ".css")
        end

        Rails.application.assets.find_asset(asset_path)
      end
      add_method_tracer(
        :sprockets_asset,
        "UserAssetsProvider/sprockets_asset",
      )

      def asset_path(name)
        name.gsub(%r{^[/]?assets/}, "")
      end

      Contract String => String
      def stylesheet_content(name)
        if assets_precompiled?
          File.read(local_file_path(name))
        else
          # This will compile and return the asset
          sprockets_asset(name).to_s
        end.strip
      end
      memoize :stylesheet_content
      add_method_tracer(
        :stylesheet_content,
        "UserAssetsProvider/stylesheet_content",
      )
    end
  end
end
</code>```

答:
I would like to report my own findings

With NewRelic data, we think most of the time is spent on

Roadies::Inliner/selector_elements => Roadie::Inliner/elements_matching_selector

And it seems a stylesheet with more style rules will make the style inlining takes longer

Benchmark code will be something like:

```<code># frozen_string_literal: true

require "benchmark/ips"

class TestMailer < ::ActionMailer::Base
  def show(benchmark_file_path:)
    return mail(
      from: "somewhere@test.com",
      to: ["somewhere@test.com"],
      subject: "some subject",
      # This is trying to workaround a strange bug in `mail` gem
      # https://github.com/mikel/mail/issues/912#issuecomment-156186383
      content_type: "text/html",
    ) do |format|
      format.html do
        render(
          file: benchmark_file_path,
          layout: false,
        )
      end
    end
  end
end

Benchmark.ips do |x|
  x.warmup  = 5
  x.time    = 60

  options = Roadie::Rails::Options.new(
    # Use your own provider or use built-in providers
    # I use a custom provider which can be used inside a rails app,
    # See https://github.com/Mange/roadie for built-in providers
    #
    # options.asset_providers = [UserAssetsProvider.new]
    # options.external_asset_providers = [UserAssetsProvider.new]
    options.keep_uninlinable_css = false
  )

  # Need to prepare html_file yourself with
  # different stylesheet tag pointing to two different stylesheet files

  x.report("fat") do
    message = ::TestMailer.
      show(
        benchmark_file_path: "benchmark-fat-stylesheet.html",
      ).message.tap do |m|

        Roadie::Rails::MailInliner.new(m, options).execute
    end

    if message.body.to_s =~ /stylesheet/
      raise "stylesheet not processed"
    end
  end

  x.report("slim") do
    message = ::TestMailer.
      show(
        benchmark_file_path: "benchmark-slim-stylesheet.html",
      ).message

    if message.body.to_s =~ /stylesheet/
      raise "stylesheet not processed"
    end
  end

  # Compare the iterations per second of the various reports!
  x.compare!
end
</code>```

Body:
Originally posted as
https://github.com/Mange/roadie-rails/issues/75

We are seeing performance issue for our daily email jobs

By using NewRelic custom instrumentation,

we found out that most time is spent in calling Roadies

Screenshot of our NewRelic data for an example worker:

The integration code:

# frozen_string_literal: true

require "rails"
require "action_controller"
require "contracts"
require "memoist"
require "roadie"
require "roadie-rails"

require "new_relic/agent/method_tracer"

module Shared::MailerMixins
  module WithRoadieIntegration
    # I don't want to include the constants into the class as well
    module Concern
      def self.included(base)
        base.extend ClassMethods
      end

      include ::NewRelic::Agent::MethodTracer

      def mail(*args, &block)
        super.tap do |m|
          options = roadie_options
          next unless options

          trace_execution_scoped(
            [
              [
                "WithRoadieIntegration",
                "Roadie::Rails::MailInliner.new(m, options).execute",
              ].join("/"),
            ],
          ) do
            Roadie::Rails::MailInliner.new(m, options).execute
          end
        end
      end

      private

      def roadie_options
        ::Rails.application.config.roadie.tap do |options|
          options.asset_providers = [UserAssetsProvider.new]
          options.external_asset_providers = [UserAssetsProvider.new]
          options.keep_uninlinable_css = false
          options.url_options = url_options.slice(*[
            :host,
            :port,
            :path,
            :protocol,
            :scheme,
          ])
        end
      end
      add_method_tracer(
        :roadie_options,
        "WithRoadieIntegration/roadie_options",
      )
    end

    class UserAssetsProvider
      extend(
        ::Memoist,
      )
      include(
        ::Contracts::Core,
        ::Contracts::Builtin,
      )

      include ::NewRelic::Agent::MethodTracer

      ABSOLUTE_ASSET_PATH_REGEXP = /\A#{Regexp.escape("//")}.+#{Regexp.escape("/assets/")}/i

      Contract String => Maybe[Roadie::Stylesheet]
      def find_stylesheet(name)
        return nil unless file_exists?(name)

        Roadie::Stylesheet.new("whatever", stylesheet_content(name))
      end
      add_method_tracer(
        :find_stylesheet,
        "UserAssetsProvider/find_stylesheet",
      )

      Contract String => Roadie::Stylesheet
      def find_stylesheet!(name)
        stylesheet = find_stylesheet(name)

        if stylesheet.nil?
          raise Roadie::CssNotFound.new(
            name,
            "does not exists",
            self,
          )
        end

        stylesheet
      end
      add_method_tracer(
        :find_stylesheet!,
        "UserAssetsProvider/find_stylesheet!",
      )

      private

      def file_exists?(name)
        if assets_precompiled?
          File.exists?(local_file_path(name))
        else
          sprockets_asset(name)
        end
      end
      memoize :file_exists?

      # If on-the-fly asset compilation is disabled, we must be precompiling assets.
      def assets_precompiled?
        !Rails.configuration.assets.compile
      rescue
        false
      end

      def local_file_path(name)
        asset_path = asset_path(name)
        if asset_path.match(ABSOLUTE_ASSET_PATH_REGEXP)
          asset_path.gsub!(ABSOLUTE_ASSET_PATH_REGEXP, "assets/")
        end

        File.join(Rails.public_path, asset_path)
      end
      memoize :local_file_path
      add_method_tracer(
        :local_file_path,
        "UserAssetsProvider/local_file_path",
      )

      def sprockets_asset(name)
        asset_path = asset_path(name)
        if asset_path.match(ABSOLUTE_ASSET_PATH_REGEXP)
          asset_path.gsub!(ABSOLUTE_ASSET_PATH_REGEXP, "")
        end

        # Strange thing is since rails 4.2
        # name is passed in like
        # `/assets/mailer-a9c96bd713d0b091297b82053ccd9155b933c00a53595812d755825d1747f42d.css`
        # Before any processing
        # And since `sprockets_asset` is used for preview
        # We just "fix" the name by removing the
        #
        # Regexp taken from gem `asset_sync`
        # https://github.com/AssetSync/asset_sync/blob/v1.2.1/lib/asset_sync/storage.rb#L142
        #
        # Modified to match what we need here (we need `.css` suffix)
        if asset_path =~ /-[0-9a-fA-F]{32,}\.css$/
          asset_path.gsub!(/-[0-9a-fA-F]{32,}\.css$/, ".css")
        end

        Rails.application.assets.find_asset(asset_path)
      end
      add_method_tracer(
        :sprockets_asset,
        "UserAssetsProvider/sprockets_asset",
      )

      def asset_path(name)
        name.gsub(%r{^[/]?assets/}, "")
      end

      Contract String => String
      def stylesheet_content(name)
        if assets_precompiled?
          File.read(local_file_path(name))
        else
          # This will compile and return the asset
          sprockets_asset(name).to_s
        end.strip
      end
      memoize :stylesheet_content
      add_method_tracer(
        :stylesheet_content,
        "UserAssetsProvider/stylesheet_content",
      )
    end
  end
end

Body:
I would like to report my own findings

With NewRelic data, we think most of the time is spent on

Roadies::Inliner/selector_elements => Roadie::Inliner/elements_matching_selector

And it seems a stylesheet with more style rules will make the style inlining takes longer

Benchmark code will be something like:

# frozen_string_literal: true

require "benchmark/ips"

class TestMailer < ::ActionMailer::Base
  def show(benchmark_file_path:)
    return mail(
      from: "somewhere@test.com",
      to: ["somewhere@test.com"],
      subject: "some subject",
      # This is trying to workaround a strange bug in `mail` gem
      # https://github.com/mikel/mail/issues/912#issuecomment-156186383
      content_type: "text/html",
    ) do |format|
      format.html do
        render(
          file: benchmark_file_path,
          layout: false,
        )
      end
    end
  end
end

Benchmark.ips do |x|
  x.warmup  = 5
  x.time    = 60

  options = Roadie::Rails::Options.new(
    # Use your own provider or use built-in providers
    # I use a custom provider which can be used inside a rails app,
    # See https://github.com/Mange/roadie for built-in providers
    #
    # options.asset_providers = [UserAssetsProvider.new]
    # options.external_asset_providers = [UserAssetsProvider.new]
    options.keep_uninlinable_css = false
  )

  # Need to prepare html_file yourself with
  # different stylesheet tag pointing to two different stylesheet files

  x.report("fat") do
    message = ::TestMailer.
      show(
        benchmark_file_path: "benchmark-fat-stylesheet.html",
      ).message.tap do |m|

        Roadie::Rails::MailInliner.new(m, options).execute
    end

    if message.body.to_s =~ /stylesheet/
      raise "stylesheet not processed"
    end
  end

  x.report("slim") do
    message = ::TestMailer.
      show(
        benchmark_file_path: "benchmark-slim-stylesheet.html",
      ).message

    if message.body.to_s =~ /stylesheet/
      raise "stylesheet not processed"
    end
  end

  # Compare the iterations per second of the various reports!
  x.compare!
end


问:
Write Int16 Into AVAudioPCMBuffer swift
I have a Data object in swift that is an array of Int16 objects. For some reason using ".pcmFormatInt16" did not work for the format of my AVAudioPCMBuffer and yielded no sound, or a memory error.  Eventually, I was able to get white noise/static to play from the speakers by converting the Int16 to a float and putting that onto both channels of my AVAudioPCMBuffer.  I have a feeling that I am getting close to the answer, because whenever I speak into the microphone I hear a different frequency of static. I think the issue is that I am not converting the converted Int16 into the buffer floatChannelData.

Here is my code:

```<code> for ch in 0..<2 {
  for i in 0..<audio.count {

       var val = Float( Int16(audio[i]) ) / Float(Int16.max)

       if( val > 1 ){
          val = 1;
       }
       if( val < -1 ){
          val = -1;
       }

       self.buffer.floatChannelData![ch][i+self.bufferCount] = val
       self.bufferCount+=1
     }
  }
  self.audioFilePlayer.scheduleBuffer(self.buffer, at:nil, options: .interruptsAtLoop, completionHandler: {
                print("played sum")
                 self.bufferCount=0
  })
</code>```

答:
a typical multi-channel PCM buffer has the channels interleaving on a per sample basis although, not being familiar with swift audio,  I find it refreshing to see here channels given a dimension on the buffer datastructure

... a flag goes up when I see your guard checks clamping val > 1 set to val = 1 etc. ... elsewhere that is not needed as those boundary checks are moot as the data nicely falls into place as is

... my guess is your input audio[] is signed int 16 because of your val > 1 and val < -1 ?  if true then dividing by max int float is wrong as you would be loosing half your dynamic range ...

I suggest you look closely at your

```<code>var val = Float( Int16(audio[i]) ) / Float(Int16.max)
</code>```

lets examine range of your ints in audio[]

2^16 == 65536  //  if unsigned then values range from 0 to (2^16 - 1) which is 0 to 65535

2^15 == 32768  //  if signed then values would range from -32768 to (2^15 - 1) which is -32768 to 32767

Please tell is whether input buffer audio[]  is signed or not ... sometimes its helpful to identify the max_seen and min_seen values of your input data ... do this and tell us the value of max and min of your input audio[]

Now lets focus on your desired output buffer self.buffer.floatChannelData ... since you are saying its 16 bit float ... what is the valid range here ?  -1 < valid_value < 1   ?

We can continue once you tell us answers to these basic questions

Title: Write Int16 Into AVAudioPCMBuffer swift

Body:
I have a Data object in swift that is an array of Int16 objects. For some reason using ".pcmFormatInt16" did not work for the format of my AVAudioPCMBuffer and yielded no sound, or a memory error.  Eventually, I was able to get white noise/static to play from the speakers by converting the Int16 to a float and putting that onto both channels of my AVAudioPCMBuffer.  I have a feeling that I am getting close to the answer, because whenever I speak into the microphone I hear a different frequency of static. I think the issue is that I am not converting the converted Int16 into the buffer floatChannelData.

Here is my code:

 for ch in 0..<2 {
  for i in 0..<audio.count {

       var val = Float( Int16(audio[i]) ) / Float(Int16.max)

       if( val > 1 ){
          val = 1;
       }
       if( val < -1 ){
          val = -1;
       }

       self.buffer.floatChannelData![ch][i+self.bufferCount] = val
       self.bufferCount+=1
     }
  }
  self.audioFilePlayer.scheduleBuffer(self.buffer, at:nil, options: .interruptsAtLoop, completionHandler: {
                print("played sum")
                 self.bufferCount=0
  })

Body:
a typical multi-channel PCM buffer has the channels interleaving on a per sample basis although, not being familiar with swift audio,  I find it refreshing to see here channels given a dimension on the buffer datastructure

... a flag goes up when I see your guard checks clamping val > 1 set to val = 1 etc. ... elsewhere that is not needed as those boundary checks are moot as the data nicely falls into place as is

... my guess is your input audio[] is signed int 16 because of your val > 1 and val < -1 ?  if true then dividing by max int float is wrong as you would be loosing half your dynamic range ...

I suggest you look closely at your

var val = Float( Int16(audio[i]) ) / Float(Int16.max)

lets examine range of your ints in audio[]

2^16 == 65536  //  if unsigned then values range from 0 to (2^16 - 1) which is 0 to 65535

2^15 == 32768  //  if signed then values would range from -32768 to (2^15 - 1) which is -32768 to 32767

Please tell is whether input buffer audio[]  is signed or not ... sometimes its helpful to identify the max_seen and min_seen values of your input data ... do this and tell us the value of max and min of your input audio[]

Now lets focus on your desired output buffer self.buffer.floatChannelData ... since you are saying its 16 bit float ... what is the valid range here ?  -1 < valid_value < 1   ?

We can continue once you tell us answers to these basic questions


问:
How to find correct value in mysql
I have a question about finding the correct value from my scenario.
I have two table like this:

shift table

```<code>shift_id | shift_user | gate
-------- | ---------- | ------
   1     |     1001   |   1
   1     |     1001   |   2
   1     |     1001   |   3
   2     |     1002   |   1
   2     |     1002   |   2
   2     |     1002   |   3
   3     |     1003   |   1
   3     |     1003   |   3
</code>```

Transaction Table

```<code>id   |  shift_id  |  sale   |   gate
-----|------------|---------|----------
  1  |     1      |  2000   |     1
  2  |     1      |  30000  |     2
  3  |     1      |  40000  |     3
  4  |     2      |  300    |     1
  5  |     2      |  4000   |     2
  6  |     2      |  3200   |     3
  7  |     3      |  5500   |     1
  8  |     3      |  100000 |     3
</code>```

How to calculate sum of the sales for each shift_id?

Please provide me a good way with query.

Thanks a lot.

:)

EDIT

From the comment section of an answer it became clear that we need to get the sum of sales of a specific shift.

答:
I found a solution for my question.
I have used following query:

```<code>select sum(sale) from transaction inner join shift on shift.shift_id=transaction.shift_id and shift.gate=transaction.gate;
</code>```

This returns the correct result.
Thank for your reply, dear friends.

Title: How to find correct value in mysql

Body:
I have a question about finding the correct value from my scenario.
I have two table like this:

shift table

shift_id | shift_user | gate
-------- | ---------- | ------
   1     |     1001   |   1
   1     |     1001   |   2
   1     |     1001   |   3
   2     |     1002   |   1
   2     |     1002   |   2
   2     |     1002   |   3
   3     |     1003   |   1
   3     |     1003   |   3

Transaction Table

id   |  shift_id  |  sale   |   gate
-----|------------|---------|----------
  1  |     1      |  2000   |     1
  2  |     1      |  30000  |     2
  3  |     1      |  40000  |     3
  4  |     2      |  300    |     1
  5  |     2      |  4000   |     2
  6  |     2      |  3200   |     3
  7  |     3      |  5500   |     1
  8  |     3      |  100000 |     3

How to calculate sum of the sales for each shift_id?

Please provide me a good way with query.

Thanks a lot.

:)

EDIT

From the comment section of an answer it became clear that we need to get the sum of sales of a specific shift.

Body:
I found a solution for my question.
I have used following query:

select sum(sale) from transaction inner join shift on shift.shift_id=transaction.shift_id and shift.gate=transaction.gate;

This returns the correct result.
Thank for your reply, dear friends.


问:
How to stop Firebase from logging status updates when app is launched
Whenever I launch the FireBase app, it logs the status of various Firebase features. Right now this is what is being logged:

```<code>Configuring the default app.

<FIRAnalytics/INFO> Firebase Analytics v.3200000 started

<FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see ...)

<FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist

<FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO

<FIRAnalytics/INFO> Firebase Analytics enabled
</code>```

I looked through the pods and didn't find any print statements so how else would I go about stopping these from being logged overtime I run the app?

答:
Add FirebaseConfiguration.shared.setLoggerLevel(.min) before FirebaseApp.configure() to achieve the minimum amount of logging.

```<code>func setupFirebase() {
  FirebaseConfiguration.shared.setLoggerLevel(.min)
  FirebaseApp.configure()
}
</code>```

Body:
Whenever I launch the FireBase app, it logs the status of various Firebase features. Right now this is what is being logged:

Configuring the default app.

<FIRAnalytics/INFO> Firebase Analytics v.3200000 started

<FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see ...)

<FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist

<FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO

<FIRAnalytics/INFO> Firebase Analytics enabled

I looked through the pods and didn't find any print statements so how else would I go about stopping these from being logged overtime I run the app?

Body:
Add FirebaseConfiguration.shared.setLoggerLevel(.min) before FirebaseApp.configure() to achieve the minimum amount of logging.

func setupFirebase() {
  FirebaseConfiguration.shared.setLoggerLevel(.min)
  FirebaseApp.configure()
}


问:
ionic2 background image not showing
I want set background image in pages of ionic2,

```<code>  <style type="text/css">
    ion-content {
      background: url(../../img/background.jpg) no-repeat center center fixed;
    }
  </style>
  <ion-content  padding>
      <h2>Welcome to Ionic!</h2>
  </ion-content>
</code>```

but it not showing in the device.
why?

答:
Try this</p>

```<code>.content-md {
  background: url("../../img/background.jpg") no-repeat;
}
</code>```

Title: ionic2 background image not showing

Body:
I want set background image in pages of ionic2,

  <ion-content  padding>

Welcome to Ionic!

  </ion-content>

but it not showing in the device.
why?

Body:
Try this

.content-md {
  background: url("../../img/background.jpg") no-repeat;
}


问:
Booting Linux on iPhone
I tried searching and searching and can't find a reason why one can't boot Linux from iPhone. I am not asking if there are drivers available for Linux or anything like that, I am just wondering why one can't boot Linux on a standard ARM processor ? </p>

答:
There isn't any such thing as a "standard ARM processor". Every ARM-based SoC is a little bit different, and Apple doesn't publish any information about how their SoCs work. (They aren't even standard Cortex-A designs; the Apple A6 and later all use CPU cores which were customized by Apple.)

Additionally, all of Apple's SoCs contain a bootloader in ROM which verifies a cryptographic signature before running any software from flash memory. This makes it impossible to run an operating system which was not signed by Apple.

Title: Booting Linux on iPhone


问:
Swift: How to refresh tableview without lag (UIRefreshControl)
Filling my table view with objects from a MYSQL database using PHP and JSON to Swift 3. I have a pull down to refresh function but when I'm pulling down to refresh it lags mid way for a second and then continues (like the wheel won't spin for a second).

How can I update my tableview smoother because I'm guessing as I add more content to the database in the future the bigger the lag. I currently have 12 objects in my database so imagine with 100+ objects.

In viewDidLoad

```<code>// Pull to Refresh
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
    if #available(iOS 10.0, *) {
        myTableView.refreshControl = refreshControl
        print("iOS 10")
    } else {
        myTableView.addSubview(refreshControl)
        print("iOS 9 or iOS 8")
    }
</code>```

Then pull to refresh function

```<code>// Pull to Refresh
func handleRefresh(refreshControl: UIRefreshControl) {

    // Fetching Data for TableView
    retrieveDataFromServer()

    // Stop Refreshing
    refreshControl.endRefreshing()
}

// Retrieving Data from Server
func retrieveDataFromServer() {

    // Loading Data from File Manager
    loadData()

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Clear the arrays
        self.followedArray = [Blog]()
        self.mainArray = [Blog]()

        // Looping through jsonArray
        for jsonObject in jsonArray {

            if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                // Check if Identifiers Match
                if followedIdentifiers.contains(blog.blogID) {
                    self.followedArray.append(blog)
                } else {
                    self.mainArray.append(blog)
                }
            }
        }
    } catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}
</code>```

答:
Refer to the apple sample code at the following location:

http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html

Couple of suggestion :

Don’t  show the data at cellForRowAtIndexPath: method ‘cause at this time cell is not displayed yet. Try to use tableView:willDisplayCell:forRowAtIndexPath: method in the delegate of UITableView.

Re-Use single instance of cell/header/footer even if you need to show more.

Let me know if anything specific is needed.

Body:
Filling my table view with objects from a MYSQL database using PHP and JSON to Swift 3. I have a pull down to refresh function but when I'm pulling down to refresh it lags mid way for a second and then continues (like the wheel won't spin for a second).

How can I update my tableview smoother because I'm guessing as I add more content to the database in the future the bigger the lag. I currently have 12 objects in my database so imagine with 100+ objects.

In viewDidLoad

// Pull to Refresh
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
    if #available(iOS 10.0, *) {
        myTableView.refreshControl = refreshControl
        print("iOS 10")
    } else {
        myTableView.addSubview(refreshControl)
        print("iOS 9 or iOS 8")
    }

Then pull to refresh function

// Pull to Refresh
func handleRefresh(refreshControl: UIRefreshControl) {

    // Fetching Data for TableView
    retrieveDataFromServer()

    // Stop Refreshing
    refreshControl.endRefreshing()
}

// Retrieving Data from Server
func retrieveDataFromServer() {

    // Loading Data from File Manager
    loadData()

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Clear the arrays
        self.followedArray = [Blog]()
        self.mainArray = [Blog]()

        // Looping through jsonArray
        for jsonObject in jsonArray {

            if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                // Check if Identifiers Match
                if followedIdentifiers.contains(blog.blogID) {
                    self.followedArray.append(blog)
                } else {
                    self.mainArray.append(blog)
                }
            }
        }
    } catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}


问:
r - dedupe the rows with value in dataframe
How to subset only the rows with values in a particular column among the duplicates based on another column.

Example:

```<code>df

A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5
</code>```

So in the above dataset, first 4 rows are duplicate based on column A and C, so among them, I want to choose only the rows which has value in column B.

Desired output,

```<code>A B C D
1 5 8 9
2 6 5 8
3 NA 8 5
</code>```

Thanks.

答:
Here is one option with data.table

```<code>library(data.table)
setDT(df)[df[, .I[.N==1 | complete.cases(B)] , .(A, C)]$V1]
#    A  B C D
#1: 1  5 8 9
#2: 2  6 5 8
#3: 3 NA 8 5
</code>```

Body:
How to subset only the rows with values in a particular column among the duplicates based on another column.

Example:

df

A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5

So in the above dataset, first 4 rows are duplicate based on column A and C, so among them, I want to choose only the rows which has value in column B.

Desired output,

A B C D
1 5 8 9
2 6 5 8
3 NA 8 5

Thanks.

Body:
Here is one option with data.table

library(data.table)
setDT(df)[df[, .I[.N==1 | complete.cases(B)] , .(A, C)]$V1]
#    A  B C D
#1: 1  5 8 9
#2: 2  6 5 8
#3: 3 NA 8 5


问:
SQL query for finding records where dont have certain value
I have

table A

```<code>a_id
a001
a002
a003
a004
a005
</code>```

table B

```<code>a_id | status | user_id
a001 | 0      | u001
a001 | 1      | u002
a001 | 2      | u003
a002 | 1      | u001
a002 | 0      | u002
a002 | 0      | u003
a003 | 0      | u002
a003 | 0      | u003
a004 | 0      | u001
</code>```

I want to get
a003 and a004 and a005

because a003,a004,and a005 dont have status 1 and 2

how can i do this?

答:
I would probably do this using aggregation:</p>

```<code>SELECT a_id
FROM tableB
GROUP BY a_id
HAVING SUM(CASE WHEN status <> 0 THEN 1 ELSE 0 END) = 0
</code>```

Body:
I have

table A

a_id
a001
a002
a003
a004
a005

table B

a_id | status | user_id
a001 | 0      | u001
a001 | 1      | u002
a001 | 2      | u003
a002 | 1      | u001
a002 | 0      | u002
a002 | 0      | u003
a003 | 0      | u002
a003 | 0      | u003
a004 | 0      | u001

I want to get
a003 and a004 and a005

because a003,a004,and a005 dont have status 1 and 2

how can i do this?

Body:
I would probably do this using aggregation:

SELECT a_id
FROM tableB
GROUP BY a_id
HAVING SUM(CASE WHEN status <> 0 THEN 1 ELSE 0 END) = 0


问:
htaccess redirection of multiple URLs
I usually use this site to solve my problems, but for the first time I couldn't find a proper question, so forgive me if it actually exists!

Currently, I have valid URLs in such format:

```<code>http://www.example.com/index/modules/news/article.php?storyid=15807
</code>```

That the number at the end is generated dynamically by CMS and therefore changes for any new content published.

In order to use shorter URLs, I want these pages to be accessible by subdomain in such format:

```<code>http://news.example.com/n15807
</code>```

Please help me and let me know if there is a better option rather than using htaccess.

答:
Sure!  You can use mod_rewrite in apache's virtual host config file.

Sarcasm aside, the way to reroute a url is to use the tool that accepts the url and does something with it, which in the case of the typical php installation is apache. If PHP were able to accept connections without the use of an http server, then PHP could do it.  I suppose one could build a server out of php and run it as a singleton, but I've never heard of such a thing.

So here's the thing, using .htaccess and mod_rewrite isn't so hard, if you understand what you're trying to do.  In your case, you want to be able to translate news.example.com/n15807 into that really long uri.  That really long uri is what the server will actually load.

mod_rewrite in effect matches against a regular expression and replaces it with another uri.  So you would attempt to match something like ^([^w]{3}).example.com/([a-z])([0-9]+)$ and use it to replace values in /index/modules/$1/article.php?storyid=$3  (I have no idea what the n in front of the number is supposed to mean.)

The regex I gave is intended only to point you in the right direction; I haven't tested it. [EDIT - It definitely won't work as written; it's been a while since I worked on mod_rewrite.  But the idea is still valid.  FWIW, I wouldn't try to use subdomains, though]

Summary:  Use the tool that works with the urls.  The most accessible way is with .htaccess.  Once you figure it out, you're done.  You can reuse it over and over in future websites.

Title: htaccess redirection of multiple URLs

Body:
I usually use this site to solve my problems, but for the first time I couldn't find a proper question, so forgive me if it actually exists!

Currently, I have valid URLs in such format:

http://www.example.com/index/modules/news/article.php?storyid=15807

That the number at the end is generated dynamically by CMS and therefore changes for any new content published.

In order to use shorter URLs, I want these pages to be accessible by subdomain in such format:

http://news.example.com/n15807

Please help me and let me know if there is a better option rather than using htaccess.


问:
Weblogic, Filebeat Logstash : How to handle multilines
I'm trying to integrate the ELK stack in my JAVA application.
I'm deploying my application to Weblogic and I'm using Filebeat to prospect the log files.

I'm trying to use a grok filter to collect some informations about my logs.
The logs are multilines as you see and I did succeed to collect each line separately by using this pattern in pipeline.conf :

```<code>filter {
    grok {
        match => { "message" => "%{COMBINEDAPACHELOG}"}
    }
}
</code>```

I can't collect every block of log using the multilines (https://www.elastic.co/guide/en/logstash/current/plugins-codecs-multiline.html) attribute
Here are my logs :

```<code>Fri May 19 10:13:28 2017 <519214951816081>
================New Request: [GET /capella/login HTTP/1.1] =================
Fri May 19 10:13:28 2017 <519214951816081> INFO: SSL is not configured
Fri May 19 10:13:28 2017 <519214951816081> Using Uri /capella/login
Fri May 19 10:13:28 2017 <519214951816081> After trimming path: '/capella/login'
Fri May 19 10:13:28 2017 <519214951816082>
================New Request: [GET /capella/login HTTP/1.1] =================
Fri May 19 10:13:28 2017 <519214951816082> INFO: SSL is not configured
Fri May 19 10:13:28 2017 <519214951816082> Using Uri /capella/login
</code>```

Could someone give me a hand or an idea to solve this ?

Thanks

答:
This is a complex problem, and will come in multiple steps.

Step 1: Multiline your inputs

This will cram all the log-lines for a single event into a single... event.

```<code>input {
  file {
    path => "/var/log/app/pipeline.log"
    codec => multiline {
      pattern => "\<\d+\>$"
      negate  => true
      what    => previous
    }
  }
}
</code>```

This will set every line following the <number> line as belonging to the 'number' line. When a new 'number' line is encountered, it will begin a new event. This will yield an event with:

```<code>message => "Fri May 19 10:13:28 2017 <519214951816081>\n================New Request: [GET /capella/login HTTP/1.1] =================\nFri May 19 10:13:28 2017 <519214951816081> INFO: SSL is not configured\nFri May 19 10:13:28 2017 <519214951816081> Using Uri /capella/login\nFri May 19 10:13:28 2017 <519214951816081> After trimming path: '/capella/login'\nFri May 19 10:13:28 2017 <519214951816082>"
</code>```

All of your data is now in one event.

Step 2: Process those events.

This can get rather complicated. If you can trust the order in which the items on the lines following the '==' line arrive, you can construct a gnarly grok statement to capture it all. I'm afraid you'll have to build your grok-statement carefully. Here is an incomplete example:

```<code>^%{DATA:date} <%{NUMBER:transaction_id}>%{DATA}New Request: \[%{WORD:verb} %{DATA:path} HTTP/1.1]%{DATA}<%{NUMBER}> %{WORD:log_level}: %{DATA:log_message}\\n
</code>```

This will populate the following fields:

```<code>date: "Fri May 19 10:13:28 2017"
transaction_id: "519214951816081"
verb: GET
path:  "/capella/login"
log_level: INFO
log_message: "SSL is not configured"
</code>```

Figuring out the rest of the grok config is up to you. I hope I've demonstrated the method. http://grokdebug.herokuapp.com/ will be very handy in constructing your string.

Body:
I'm trying to integrate the ELK stack in my JAVA application.
I'm deploying my application to Weblogic and I'm using Filebeat to prospect the log files.

I'm trying to use a grok filter to collect some informations about my logs.
The logs are multilines as you see and I did succeed to collect each line separately by using this pattern in pipeline.conf :

filter {
    grok {
        match => { "message" => "%{COMBINEDAPACHELOG}"}
    }
}

I can't collect every block of log using the multilines (https://www.elastic.co/guide/en/logstash/current/plugins-codecs-multiline.html) attribute
Here are my logs :

Fri May 19 10:13:28 2017 <519214951816081>
================New Request: [GET /capella/login HTTP/1.1] =================
Fri May 19 10:13:28 2017 <519214951816081> INFO: SSL is not configured
Fri May 19 10:13:28 2017 <519214951816081> Using Uri /capella/login
Fri May 19 10:13:28 2017 <519214951816081> After trimming path: '/capella/login'
Fri May 19 10:13:28 2017 <519214951816082>
================New Request: [GET /capella/login HTTP/1.1] =================
Fri May 19 10:13:28 2017 <519214951816082> INFO: SSL is not configured
Fri May 19 10:13:28 2017 <519214951816082> Using Uri /capella/login

Could someone give me a hand or an idea to solve this ?

Thanks

Body:
This is a complex problem, and will come in multiple steps.

Step 1: Multiline your inputs

This will cram all the log-lines for a single event into a single... event.

input {
  file {
    path => "/var/log/app/pipeline.log"
    codec => multiline {
      pattern => "\<\d+\>$"
      negate  => true
      what    => previous
    }
  }
}

This will set every line following the <number> line as belonging to the 'number' line. When a new 'number' line is encountered, it will begin a new event. This will yield an event with:

message => "Fri May 19 10:13:28 2017 <519214951816081>\n================New Request: [GET /capella/login HTTP/1.1] =================\nFri May 19 10:13:28 2017 <519214951816081> INFO: SSL is not configured\nFri May 19 10:13:28 2017 <519214951816081> Using Uri /capella/login\nFri May 19 10:13:28 2017 <519214951816081> After trimming path: '/capella/login'\nFri May 19 10:13:28 2017 <519214951816082>"

All of your data is now in one event.

Step 2: Process those events.

This can get rather complicated. If you can trust the order in which the items on the lines following the '==' line arrive, you can construct a gnarly grok statement to capture it all. I'm afraid you'll have to build your grok-statement carefully. Here is an incomplete example:

^%{DATA:date} <%{NUMBER:transaction_id}>%{DATA}New Request: \[%{WORD:verb} %{DATA:path} HTTP/1.1]%{DATA}<%{NUMBER}> %{WORD:log_level}: %{DATA:log_message}\\n

This will populate the following fields:

date: "Fri May 19 10:13:28 2017"
transaction_id: "519214951816081"
verb: GET
path:  "/capella/login"
log_level: INFO
log_message: "SSL is not configured"

Figuring out the rest of the grok config is up to you. I hope I've demonstrated the method. http://grokdebug.herokuapp.com/ will be very handy in constructing your string.


问:
PHP files not working when using Bootstrap
I am new to Programming hence need some help. Below is the code I am using for a Contact Form using Bootstrap but my PHP code doesn't seem to work.
I have been keeping "index.php" file with other files of Bootstrap. But when I run this it shows an error and doesn't run.
And when I save this file as "index.html", the HTML part of the code runs but PHP files don't.
In order to run PHP file in wamp server where should I save the files in Bootstrap or in Wamp?</p>

```<code><?php

if ($_POST['submit']) {

    if(!$_POST['name']) {
        $error="<br/>-Please enter your name";
    }

    if(!$_POST['email']) {
        $error.="<br/>- Please enter your email";
    }

    if(!$_POST['subject']) {
        $error.="<br/>- Please enter a subject";
    }

    if(!$_POST['message']) {
        $error.="<br/>- Please enter a message";
    }

    if(!$_POST['check']) {
        $error.="<br/>- Please confirm you are human";
    }

    if($error) {
        $result="Whoops, there is an error; Please correct the following: $error";
    } else {
        mail("namitajamwal19@gmail.com", "Contact message", "Name: ".$_POST['name']."
        Email: ".$_POST['name']."
        Subject: ".$_POST['subject']."
        Message: ".$_POST['message']);"

        {
        $result="Thank you, I'll be in touch shortly";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Contact Us</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <section id="contact">
        <div class="container">

            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <h1>Contact Us</h1>

                    <?php echo $result;?>

                    <p>Send a message via the form below</p>

                    <form method="post" role="form">

                        <div class="form-group">
                            <input type="text" name="name" class="form-control" placeholder="Your Name" value="<?php echo $_POST['name']; ?>">
                        </div>

                        <div class="form-group">
                            <input type="email" name="email" class="form-control" placeholder="Your email" value="<?php echo $_POST['email']; ?>">
                        </div>

                        <div class="form-group">
                            <textarea name="subject" rows="5" class="form-control" placeholder="Subject"><?php echo $_POST['subject']; ?></textarea>
                        </div>

                        <div class="form-group">
                            <textarea name="message" rows="5" class="form-control" placeholder="Message..."><?php echo $_POST['message']; ?></textarea>
                        </div>

                        <div class="checkbox">
                            <label>
                                <input type="checkbox" name="check">I am Human
                            </label>
                        </div>

                        <div align="center">
                        <input type="submit" name="submit" class="btn btn-secondary" value="send message"/>
                        </div>
                    </form>

                </div>
            </div>

        </div>
    </section>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>
</code>```

答:
You must save your file with ".php" extension (like "test.php") and save it in your wamp server folder : "c:\wamp\www".

Run your php file in browser : localhost/test.php.
Hope this help you bro.

Body:
I am new to Programming hence need some help. Below is the code I am using for a Contact Form using Bootstrap but my PHP code doesn't seem to work.
I have been keeping "index.php" file with other files of Bootstrap. But when I run this it shows an error and doesn't run.
And when I save this file as "index.html", the HTML part of the code runs but PHP files don't.
In order to run PHP file in wamp server where should I save the files in Bootstrap or in Wamp?

<?php

if ($_POST['submit']) {

    if(!$_POST['name']) {
        $error="
-Please enter your name";
    }

    if(!$_POST['email']) {
        $error.="
- Please enter your email";
    }

    if(!$_POST['subject']) {
        $error.="
- Please enter a subject";
    }

    if(!$_POST['message']) {
        $error.="
- Please enter a message";
    }

    if(!$_POST['check']) {
        $error.="
- Please confirm you are human";
    }

    if($error) {
        $result="Whoops, there is an error; Please correct the following: $error";
    } else {
        mail("namitajamwal19@gmail.com", "Contact message", "Name: ".$_POST['name']."
        Email: ".$_POST['name']."
        Subject: ".$_POST['subject']."
        Message: ".$_POST['message']);"

        {
        $result="Thank you, I'll be in touch shortly";
        }
    }
}
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Contact Us</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

Contact Us

                    <?php echo $result;?>

Send a message via the form below

                    <form method="post" role="form">

                            <input type="text" name="name" class="form-control" placeholder="Your Name" value="<?php echo $_POST['name']; ?>">

                            <input type="email" name="email" class="form-control" placeholder="Your email" value="<?php echo $_POST['email']; ?>">

                            <textarea name="subject" rows="5" class="form-control" placeholder="Subject"><?php echo $_POST['subject']; ?></textarea>

                            <textarea name="message" rows="5" class="form-control" placeholder="Message..."><?php echo $_POST['message']; ?></textarea>

                                <input type="checkbox" name="check">I am Human

                        <input type="submit" name="submit" class="btn btn-secondary" value="send message"/>

                    </form>


问:
how to redirect on a if loop html
I'm a kind of noob in HTML
here's my code
the problem:
the if loop needs to redirect to a HTML containing links to all the levels
`

<!DOCTYPE html>

    <title>title game beta</title>

```

答:
Use </p>

<p>// Sets the new href (URL) for the current window.</p>

```<code>window.location.href = "https://www.example.com";
</code>```

Title: how to redirect on a if loop html

Body:
Use

// Sets the new href (URL) for the current window.

window.location.href = "https://www.example.com";


问:
How to customize/style woocommerce account page
As you can see here: https://wildlatina.com/my-account/

the white body is not inside the page and there is not margin padding for the login form? what did I do to mess this up? I'm a beginner when it comes to editing with css so please go easy on me. Just would like the account page to look nice.

答:
You have used the Wordpress theme GeneratePress.  In that theme, if you have the class container and grid-container on an element, the width of that element is reset from 1080px to auto - which, in your case, means it fills the width of the page.  So, your DIV with id "page" is changed from 1080px to the width of the page.

You should remove the container class from this DIV.  You may then have to add some styles back to get the final effect you desire.

ContentLicense: CC BY-SA 4.0


问:
How to make something like iPhone Folders?
I'm wanting to know if there's a way I can transform my view to look something like iPhone folders.  In other words, I want my view to split somewhere in the middle and reveal a view underneath it.  Is this possible?

EDIT:
Per the suggestion below, I could take a screenshot of my application by doing this:

```<code>UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

Not sure what to do with this, however.

EDIT:2
I've figured out how to add some shadows to my view, and here's what I've achieved (cropped to show relevant part):

EDIT:3

http://github.com/jwilling/JWFolders

答:
the basic thought will be to take a picture of your current state and split it somewhere. Then animate both parts by setting a new frame. I don't know how to take a screenshot programmatically so I can't provide sample code…

EDIT: hey hey it's not looking great but it works ^^

```<code>// wouldn't be sharp on retina displays, instead use "withOptions" and set scale to 0.0
// UIGraphicsBeginImageContext(self.view.bounds.size);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *f = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGRect fstRect = CGRectMake(0, 0, 320, 200);
CGRect sndRect = CGRectMake(0, 200, 320, 260); // was 0,200,320,280

CGImageRef fImageRef = CGImageCreateWithImageInRect([f CGImage], fstRect);
UIImage *fCroppedImage = [UIImage imageWithCGImage:fImageRef];
CGImageRelease(fImageRef);

CGImageRef sImageRef = CGImageCreateWithImageInRect([f CGImage], sndRect);
UIImage *sCroppedImage = [UIImage imageWithCGImage:sImageRef];
CGImageRelease(sImageRef);

UIImageView *first = [[UIImageView alloc]initWithFrame:fstRect];
first.image = fCroppedImage;
//first.contentMode = UIViewContentModeTop;
UIImageView *second = [[UIImageView alloc]initWithFrame:sndRect];
second.image = sCroppedImage;
//second.contentMode = UIViewContentModeBottom;

UIView *blank = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
blank.backgroundColor = [UIColor darkGrayColor];

[self.view addSubview:blank];
[self.view addSubview:first];
[self.view addSubview:second];

[UIView animateWithDuration:2.0 animations:^{
    second.center = CGPointMake(second.center.x, second.center.y+75);
}];
</code>```

You can uncomment the two .contentMode lines and the quality will improve but in my case the subview has an offset of 10px or so (you can see it by setting a background color to both subviews)

//EDIT 2: ok found that bug. Had used the whole 320x480 screen, but had to cut off the status bar so it should be 320x460 and all is working great ;)

Body:
I'm wanting to know if there's a way I can transform my view to look something like iPhone folders.  In other words, I want my view to split somewhere in the middle and reveal a view underneath it.  Is this possible?

EDIT:
Per the suggestion below, I could take a screenshot of my application by doing this:

UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Not sure what to do with this, however.

EDIT:2
I've figured out how to add some shadows to my view, and here's what I've achieved (cropped to show relevant part):

EDIT:3

http://github.com/jwilling/JWFolders

Body:
the basic thought will be to take a picture of your current state and split it somewhere. Then animate both parts by setting a new frame. I don't know how to take a screenshot programmatically so I can't provide sample code…

EDIT: hey hey it's not looking great but it works ^^

// wouldn't be sharp on retina displays, instead use "withOptions" and set scale to 0.0
// UIGraphicsBeginImageContext(self.view.bounds.size);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *f = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGRect fstRect = CGRectMake(0, 0, 320, 200);
CGRect sndRect = CGRectMake(0, 200, 320, 260); // was 0,200,320,280

CGImageRef fImageRef = CGImageCreateWithImageInRect([f CGImage], fstRect);
UIImage *fCroppedImage = [UIImage imageWithCGImage:fImageRef];
CGImageRelease(fImageRef);

CGImageRef sImageRef = CGImageCreateWithImageInRect([f CGImage], sndRect);
UIImage *sCroppedImage = [UIImage imageWithCGImage:sImageRef];
CGImageRelease(sImageRef);

UIImageView *first = [[UIImageView alloc]initWithFrame:fstRect];
first.image = fCroppedImage;
//first.contentMode = UIViewContentModeTop;
UIImageView *second = [[UIImageView alloc]initWithFrame:sndRect];
second.image = sCroppedImage;
//second.contentMode = UIViewContentModeBottom;

UIView *blank = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
blank.backgroundColor = [UIColor darkGrayColor];

[self.view addSubview:blank];
[self.view addSubview:first];
[self.view addSubview:second];

[UIView animateWithDuration:2.0 animations:^{
    second.center = CGPointMake(second.center.x, second.center.y+75);
}];

You can uncomment the two .contentMode lines and the quality will improve but in my case the subview has an offset of 10px or so (you can see it by setting a background color to both subviews)

//EDIT 2: ok found that bug. Had used the whole 320x480 screen, but had to cut off the status bar so it should be 320x460 and all is working great ;)

ContentLicense: CC BY-SA 2.5


问:
unable to receive the push notification in foreground using FCM
I have been trying to get firebase push-notification in my app. I have tried everything on the internet but couldn't find solution. I have been receiving notification in background, but when App is in foreground I am unable to get the notification. But when I print the userInfo in "didReceiveRemoteNotification" I get the message in console
Any help would be appreciated.</p>

```<code>import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    //FirebaseApp.configure()

    self.initializeFCM(application)
    let token = InstanceID.instanceID().token()
    debugPrint("GCM TOKEN = \(String(describing: token))")

    return true
}

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
    debugPrint("didFailToRegisterForRemoteNotificationsWithError: \(error)")
}

func application(received remoteMessage: MessagingRemoteMessage)
{
    debugPrint("remoteMessage:\(remoteMessage.appData)")
}

func initializeFCM(_ application: UIApplication)
{
    print("initializeFCM")

    if #available(iOS 10.0, *) // enable new way for notifications on iOS 10
    {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.badge, .alert , .sound]) { (accepted, error) in
            if !accepted
            {
                print("Notification access denied.")
            }
            else
            {
                print("Notification access accepted.")
                UIApplication.shared.registerForRemoteNotifications();
            }
        }
    }
    else
    {
        let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound];
        let setting = UIUserNotificationSettings(types: type, categories: nil);
        UIApplication.shared.registerUserNotificationSettings(setting);
        UIApplication.shared.registerForRemoteNotifications();
    }

    FirebaseApp.configure()
    Messaging.messaging().delegate = self
    Messaging.messaging().shouldEstablishDirectChannel = true

}

// enable new way for notifications on iOS 10

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings)
{
    debugPrint("didRegister notificationSettings")
    if (notificationSettings.types == .alert || notificationSettings.types == .badge || notificationSettings.types == .sound)
    {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: NSDATA")

    let token = String(format: "%@", deviceToken as CVarArg)
    debugPrint("*** deviceToken: \(token)")

    Messaging.messaging().apnsToken = deviceToken as Data
    debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
    let token = String(format: "%@", deviceToken as CVarArg)
    debugPrint("*** deviceToken: \(token)")

    Messaging.messaging().apnsToken = deviceToken
    debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}
//-------------------------------------------------------------------------//

// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]

}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    completionHandler()
 }
}
 // [END ios_10_message_handling]

 extension AppDelegate : MessagingDelegate {
// [START refresh_token]
 func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
</code>```

答:
Since iOS 14, .alert is deprecated, you might use .banner instead:

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let content = notification.request.content
    // Process notification content
    print("\(content.userInfo)")
    completionHandler([.banner, .list, .sound]) // Display notification Banner
}
</code>```

From iOS 10, You can display Apple's default notification banner using below function.
Notification behaviour will depend on properties which you return within completionHandler.

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let content = notification.request.content
    // Process notification content
    print("\(content.userInfo)")
    completionHandler([.alert, .sound]) // Display notification Banner
}
</code>```

As per details in your question, you have already implemented above function, but with blank completionHandler(). Because of that notification banner doesn't display while app is in foreground state.

Earlier iOS 10:

You need to handle this by yourself. Like if you want to display banner when you received a notification, while app is in foreground state. You need to do this by yourself. You have to design your custom notification banner to display within app.

Hope it helps you.

Body:
I have been trying to get firebase push-notification in my app. I have tried everything on the internet but couldn't find solution. I have been receiving notification in background, but when App is in foreground I am unable to get the notification. But when I print the userInfo in "didReceiveRemoteNotification" I get the message in console
Any help would be appreciated.

import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    //FirebaseApp.configure()

    self.initializeFCM(application)
    let token = InstanceID.instanceID().token()
    debugPrint("GCM TOKEN = \(String(describing: token))")

    return true
}

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
    debugPrint("didFailToRegisterForRemoteNotificationsWithError: \(error)")
}

func application(received remoteMessage: MessagingRemoteMessage)
{
    debugPrint("remoteMessage:\(remoteMessage.appData)")
}

func initializeFCM(_ application: UIApplication)
{
    print("initializeFCM")

    if #available(iOS 10.0, *) // enable new way for notifications on iOS 10
    {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.badge, .alert , .sound]) { (accepted, error) in
            if !accepted
            {
                print("Notification access denied.")
            }
            else
            {
                print("Notification access accepted.")
                UIApplication.shared.registerForRemoteNotifications();
            }
        }
    }
    else
    {
        let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound];
        let setting = UIUserNotificationSettings(types: type, categories: nil);
        UIApplication.shared.registerUserNotificationSettings(setting);
        UIApplication.shared.registerForRemoteNotifications();
    }

    FirebaseApp.configure()
    Messaging.messaging().delegate = self
    Messaging.messaging().shouldEstablishDirectChannel = true

}

// enable new way for notifications on iOS 10

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings)
{
    debugPrint("didRegister notificationSettings")
    if (notificationSettings.types == .alert || notificationSettings.types == .badge || notificationSettings.types == .sound)
    {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: NSDATA")

    let token = String(format: "%@", deviceToken as CVarArg)
    debugPrint("*** deviceToken: \(token)")

    Messaging.messaging().apnsToken = deviceToken as Data
    debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
    let token = String(format: "%@", deviceToken as CVarArg)
    debugPrint("*** deviceToken: \(token)")

    Messaging.messaging().apnsToken = deviceToken
    debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}
//-------------------------------------------------------------------------//

// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]

}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    completionHandler()
 }
}
 // [END ios_10_message_handling]

 extension AppDelegate : MessagingDelegate {
// [START refresh_token]
 func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}

Body:
Since iOS 14, .alert is deprecated, you might use .banner instead:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let content = notification.request.content
    // Process notification content
    print("\(content.userInfo)")
    completionHandler([.banner, .list, .sound]) // Display notification Banner
}

From iOS 10, You can display Apple's default notification banner using below function.
Notification behaviour will depend on properties which you return within completionHandler.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let content = notification.request.content
    // Process notification content
    print("\(content.userInfo)")
    completionHandler([.alert, .sound]) // Display notification Banner
}

As per details in your question, you have already implemented above function, but with blank completionHandler(). Because of that notification banner doesn't display while app is in foreground state.

Earlier iOS 10:

You need to handle this by yourself. Like if you want to display banner when you received a notification, while app is in foreground state. You need to do this by yourself. You have to design your custom notification banner to display within app.

Hope it helps you.


问:
building multiple models per group
I'd like to group my data, then build two linear models per group, gather the results, and use broom to summarize the model parameters, but I'm having an infinite recursion error that I cant seem to understand. Here's the code:

```<code>library(dplyr)
library(tidyr)
library(broom)

mtcars %>%
group_by(am) %>%
dplyr::do(simple_fit =  lm(mpg ~ disp, data = .),
          complex_fit = lm(mpg ~ disp + hp, data = .)) %>%
ungroup()
gather(model_type, model, -am) %>%
broom::tidy(model)
</code>```

which results in this error:

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

There are only 4 models in this example, so I don't understand why I'm hitting such a deep nested loop?

答:
I found  a comment on the github that fixed my issue here

Fixed version of the code is as follows:

```<code>mtcars %>%
group_by(am) %>%
dplyr::do(simple_fit = lm(mpg~disp, data = .),
          complex_fit = lm(mpg ~ disp + hp, data = .)) %>%
ungroup() %>%
gather(model_type, model, -am) %>%
rowwise() %>%
broom::tidy(model)
</code>```

Title: building multiple models per group

Body:
I'd like to group my data, then build two linear models per group, gather the results, and use broom to summarize the model parameters, but I'm having an infinite recursion error that I cant seem to understand. Here's the code:

library(dplyr)
library(tidyr)
library(broom)

mtcars %>%
group_by(am) %>%
dplyr::do(simple_fit =  lm(mpg ~ disp, data = .),
          complex_fit = lm(mpg ~ disp + hp, data = .)) %>%
ungroup()
gather(model_type, model, -am) %>%
broom::tidy(model)

which results in this error:

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

There are only 4 models in this example, so I don't understand why I'm hitting such a deep nested loop?

Body:
I found  a comment on the github that fixed my issue here

Fixed version of the code is as follows:

mtcars %>%
group_by(am) %>%
dplyr::do(simple_fit = lm(mpg~disp, data = .),
          complex_fit = lm(mpg ~ disp + hp, data = .)) %>%
ungroup() %>%
gather(model_type, model, -am) %>%
rowwise() %>%
broom::tidy(model)


问:
Is it possible to have more than one canvas on an HTML5 page?
I was wondering if it is possible to have more than one canvas fully functioning on and HTML5 page. I have tried this a little while ago and it didn't work but I really didn't take time to think about how to do this and it ultimately failed. So is it possible to have more than one canvas fully functioning on an HTML5 page?</p>

答:
var cnv1 = document.getElementById("1");
var ctx1 = cnv1.getContext("2d");
var cnv2 = document.getElementById("2");
var ctx2 = cnv2.getContext("2d");

ctx1.fillStyle = "#FF0000";
ctx1.fillRect(0, 0, 50, 75);

ctx2.fillStyle = "#0000FF";
ctx2.fillRect(0, 0, 50, 75);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  border: 2px solid black;
}</code>```

<canvas id="1" width="100px" height="100px">
Canvas doesn't work.
</canvas>
<canvas id="2" width="100px" height="100px">
Canvas doesn't work.
</canvas>```

Body:
var cnv1 = document.getElementById("1");
var ctx1 = cnv1.getContext("2d");
var cnv2 = document.getElementById("2");
var ctx2 = cnv2.getContext("2d");

ctx1.fillStyle = "#FF0000";
ctx1.fillRect(0, 0, 50, 75);

ctx2.fillStyle = "#0000FF";
ctx2.fillRect(0, 0, 50, 75);

canvas {
  border: 2px solid black;
}

<canvas id="1" width="100px" height="100px"><p>Canvas doesn't work.</p></canvas>
<canvas id="2" width="100px" height="100px"><p>Canvas doesn't work.</p></canvas>


问:
pinch and zoom on apple mapkit swift
I have been able to implement MapKit into my app, but it currently looks the map in one static position.

I have been struggling to add the pinch and zoom functionality as well as the ability to allow users to explore other regions on the map.

Here is what my current code looks like:

```<code>import UIKit
import MapKit
import CoreLocation

class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()
let newPin = MKPointAnnotation()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    // Setup the location services delegate in this class.
    locationManager.delegate = self

    // This little method requests the users permission for location services whilst in this view controller.
    if CLLocationManager.authorizationStatus() == .notDetermined {
        self.locationManager.requestAlwaysAuthorization()
    let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. ",
                                  preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
    }

    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

}

// Drops the pin on the users current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    mapView.removeAnnotation(newPin)

    let location = locations.last! as CLLocation
    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    // Set the region on the map.
    mapView.setRegion(region, animated: true)

    newPin.coordinate = location.coordinate
    mapView.addAnnotation(newPin)

}
</code>```

}

答:
I think that you problem is related to this method func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]), because over and over again when the position is updated you are adjusting the region in the map that is why you see only the region where the position is updated and can't move any other region in the map, you must make a flag for first time and adjust the region only once or don't adjust the region at all

EDITED

```<code>    import UIKit
    import MapKit
    import CoreLocation

    class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    var isFirstTime = true

    var locationManager = CLLocationManager()
    let newPin = MKPointAnnotation()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // Setup the location services delegate in this class.
        locationManager.delegate = self

        // This little method requests the users permission for location services whilst in this view controller.
        if CLLocationManager.authorizationStatus() == .notDetermined {
            self.locationManager.requestAlwaysAuthorization()
        let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. ",
                                      preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

            self.present(alert, animated: true, completion: nil)
        }

        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

    }

    // Drops the pin on the users current location.
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        mapView.removeAnnotation(newPin)

        let location = locations.last! as CLLocation
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        if(self.isFirstTime){
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

        // Set the region on the map.
        mapView.setRegion(region, animated: true)
        self.isFirstTime = false
        }

        newPin.coordinate = location.coordinate
        mapView.addAnnotation(newPin)

    }
}
</code>```

Hope this helps, and let me know if I misunderstood your question

Title: pinch and zoom on apple mapkit swift

Body:
I have been able to implement MapKit into my app, but it currently looks the map in one static position.

I have been struggling to add the pinch and zoom functionality as well as the ability to allow users to explore other regions on the map.

Here is what my current code looks like:

import UIKit
import MapKit
import CoreLocation

class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()
let newPin = MKPointAnnotation()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    // Setup the location services delegate in this class.
    locationManager.delegate = self

    // This little method requests the users permission for location services whilst in this view controller.
    if CLLocationManager.authorizationStatus() == .notDetermined {
        self.locationManager.requestAlwaysAuthorization()
    let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. ",
                                  preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
    }

    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

}

// Drops the pin on the users current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    mapView.removeAnnotation(newPin)

    let location = locations.last! as CLLocation
    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    // Set the region on the map.
    mapView.setRegion(region, animated: true)

    newPin.coordinate = location.coordinate
    mapView.addAnnotation(newPin)

}

}

Body:
I think that you problem is related to this method func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]), because over and over again when the position is updated you are adjusting the region in the map that is why you see only the region where the position is updated and can't move any other region in the map, you must make a flag for first time and adjust the region only once or don't adjust the region at all

EDITED

    import UIKit
    import MapKit
    import CoreLocation

    class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    var isFirstTime = true

    var locationManager = CLLocationManager()
    let newPin = MKPointAnnotation()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // Setup the location services delegate in this class.
        locationManager.delegate = self

        // This little method requests the users permission for location services whilst in this view controller.
        if CLLocationManager.authorizationStatus() == .notDetermined {
            self.locationManager.requestAlwaysAuthorization()
        let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. ",
                                      preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

            self.present(alert, animated: true, completion: nil)
        }

        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

    }

    // Drops the pin on the users current location.
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        mapView.removeAnnotation(newPin)

        let location = locations.last! as CLLocation
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        if(self.isFirstTime){
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

        // Set the region on the map.
        mapView.setRegion(region, animated: true)
        self.isFirstTime = false
        }

        newPin.coordinate = location.coordinate
        mapView.addAnnotation(newPin)

    }
}

Hope this helps, and let me know if I misunderstood your question


问:
answer repeating in the foor-loop
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

```<code>        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7
</code>```

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

```<code>MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime
</code>```

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

答:
You can use groupby() by month and day.

Your data is in df.

```<code>>>> df
         Date  Temp   Time
0  31/05/2006   9.3  09:00
1  31/05/2006  10.1  09:10
2  31/05/2006  10.7  09:20
3  31/05/2006  10.5  09:30
4  31/05/2006  10.9  09:40
5  01/06/2006   9.0  09:00
6  01/06/2006   9.3  09:10
7  01/06/2006   9.2  09:20
8  01/06/2006   9.7  09:30
9  01/06/2006   9.5  09:40
</code>```

Create month and day column.

```<code>>>> df2 = df.assign(Date = pd.to_datetime(df.Date, dayfirst=True))
>>> df2 = df2.assign(mon = df2.Date.dt.month, day = df2.Date.dt.day)
</code>```

groupby() by month and day, get the indices of max Temp.

```<code>>>> df2.groupby(['mon', 'day'])['Temp'].idxmax()

mon  day
5    31     4
6    1      8
Name: Temp, dtype: int64
</code>```

Select the indices from df2

```<code>>>> df2.loc[df2.groupby(['mon', 'day'])['Temp'].idxmax()]

        Date  Temp   Time  day  mon
4 2006-05-31  10.9  09:40   31    5
8 2006-06-01   9.7  09:30    1    6
</code>```

Keep other columns when using min() with groupby

Title: answer repeating in the foor-loop

Body:
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

Body:
You can use groupby() by month and day.

Your data is in df.

>>> df
         Date  Temp   Time
0  31/05/2006   9.3  09:00
1  31/05/2006  10.1  09:10
2  31/05/2006  10.7  09:20
3  31/05/2006  10.5  09:30
4  31/05/2006  10.9  09:40
5  01/06/2006   9.0  09:00
6  01/06/2006   9.3  09:10
7  01/06/2006   9.2  09:20
8  01/06/2006   9.7  09:30
9  01/06/2006   9.5  09:40

Create month and day column.

>>> df2 = df.assign(Date = pd.to_datetime(df.Date, dayfirst=True))
>>> df2 = df2.assign(mon = df2.Date.dt.month, day = df2.Date.dt.day)

groupby() by month and day, get the indices of max Temp.

>>> df2.groupby(['mon', 'day'])['Temp'].idxmax()

mon  day
5    31     4
6    1      8
Name: Temp, dtype: int64

Select the indices from df2

>>> df2.loc[df2.groupby(['mon', 'day'])['Temp'].idxmax()]

        Date  Temp   Time  day  mon
4 2006-05-31  10.9  09:40   31    5
8 2006-06-01   9.7  09:30    1    6

Keep other columns when using min() with groupby