问:
rails rake db:migrate sqllite3 error
```<code>StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: near "ENGINE": syntax error: CREATE TABLE "adv_bgs" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "adv_bg_type" varchar, "adv_bg_id" integer, "uploaded_file_file_name" varchar, "uploaded_file_content_type" varchar, "uploaded_file_file_size" integer, "uploaded_file_updated_at" datetime, "head" boolean DEFAULT 'f', "imageable_id" integer, "imageable_type" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) ENGINE=MyISAM  DEFAULT CHARSET=utf8
/mnt/c/Users/direwolf/Documents/web/rails_projects/okar/db/migrate/20170425144835_init_schema.rb:4:in `up'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `<main>'
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "ENGINE": syntax error: CREATE TABLE "adv_bgs" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "adv_bg_type" varchar, "adv_bg_id" integer, "uploaded_file_file_name" varchar, "uploaded_file_content_type" varchar, "uploaded_file_file_size" integer, "uploaded_file_updated_at" datetime, "head" boolean DEFAULT 'f', "imageable_id" integer, "imageable_type" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) ENGINE=MyISAM  DEFAULT CHARSET=utf8
/mnt/c/Users/direwolf/Documents/web/rails_projects/okar/db/migrate/20170425144835_init_schema.rb:4:in `up'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `<main>'
SQLite3::SQLException: near "ENGINE": syntax error
/mnt/c/Users/direwolf/Documents/web/rails_projects/okar/db/migrate/20170425144835_init_schema.rb:4:in `up'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code>```

What Do I do?
20170425144835_init_schema.rb

```<code>class InitSchema < ActiveRecord::Migration
  def up

    create_table "adv_bgs", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_bg_type"
      t.integer  "adv_bg_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_bg_type", "adv_bg_id"], name: "index_adv_bgs_on_adv_bg_type_and_adv_bg_id", using: :btree
      t.index ["head"], name: "index_adv_bgs_on_head", using: :btree
    end

    create_table "adv_logos", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_logo_type"
      t.integer  "adv_logo_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_logo_type", "adv_logo_id"], name: "index_adv_logos_on_adv_logo_type_and_adv_logo_id", using: :btree
      t.index ["head"], name: "index_adv_logos_on_head", using: :btree
    end

    create_table "adv_pic1s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic1_type"
      t.integer  "adv_pic1_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic1_type", "adv_pic1_id"], name: "index_adv_pic1s_on_adv_pic1_type_and_adv_pic1_id", using: :btree
      t.index ["head"], name: "index_adv_pic1s_on_head", using: :btree
    end

    create_table "adv_pic2s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic2_type"
      t.integer  "adv_pic2_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic2_type", "adv_pic2_id"], name: "index_adv_pic2s_on_adv_pic2_type_and_adv_pic2_id", using: :btree
      t.index ["head"], name: "index_adv_pic2s_on_head", using: :btree
    end

    create_table "adv_pic3s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic3_type"
      t.integer  "adv_pic3_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic3_type", "adv_pic3_id"], name: "index_adv_pic3s_on_adv_pic3_type_and_adv_pic3_id", using: :btree
      t.index ["head"], name: "index_adv_pic3s_on_head", using: :btree
    end

    create_table "adv_pic4s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic4_type"
      t.integer  "adv_pic4_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic4_type", "adv_pic4_id"], name: "index_adv_pic4s_on_adv_pic4_type_and_adv_pic4_id", using: :btree
      t.index ["head"], name: "index_adv_pic4s_on_head", using: :btree
    end

    create_table "adv_pic5s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic5_type"
      t.integer  "adv_pic5_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic5_type", "adv_pic5_id"], name: "index_adv_pic5s_on_adv_pic5_type_and_adv_pic5_id", using: :btree
      t.index ["head"], name: "index_adv_pic5s_on_head", using: :btree
    end

    create_table "adv_pic6s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic6_type"
      t.integer  "adv_pic6_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic6_type", "adv_pic6_id"], name: "index_adv_pic6s_on_adv_pic6_type_and_adv_pic6_id", using: :btree
      t.index ["head"], name: "index_adv_pic6s_on_head", using: :btree
    end

    create_table "adv_pic7s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic7_type"
      t.integer  "adv_pic7_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic7_type", "adv_pic7_id"], name: "index_adv_pic7s_on_adv_pic7_type_and_adv_pic7_id", using: :btree
      t.index ["head"], name: "index_adv_pic7s_on_head", using: :btree
    end

    create_table "advertising_applications", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.integer  "user_id"
      t.integer  "anon_user_id"
      t.integer  "televisor_id",                 limit: 1,                                     null: false
      t.integer  "advertising_public_status_id", limit: 1,     default: 1
      t.integer  "advertising_period_id",        limit: 1,     default: 1
      t.integer  "payment_status_id",            limit: 1,     default: 1
      t.integer  "step",                         limit: 1,     default: 1
      t.integer  "spec_id",                      limit: 1,     default: 1
      t.string   "email"
      t.string   "lnk"
      t.string   "redwords"
      t.string   "zkname"
      t.string   "zkdescr"
      t.integer  "price"
      t.integer  "charge",                       limit: 1,     default: 1
      t.datetime "endtime",                                    default: '2017-04-25 17:47:04'
      t.text     "comment",                      limit: 65535
      t.datetime "created_at",                                                                 null: false
      t.datetime "updated_at",                                                                 null: false
      t.index ["advertising_period_id"], name: "index_advertising_applications_on_advertising_period_id", using: :btree
      t.index ["advertising_public_status_id"], name: "index_advertising_applications_on_advertising_public_status_id", using: :btree
      t.index ["anon_user_id"], name: "index_advertising_applications_on_anon_user_id", using: :btree
      t.index ["payment_status_id"], name: "index_advertising_applications_on_payment_status_id", using: :btree
      t.index ["televisor_id"], name: "index_advertising_applications_on_televisor_id", using: :btree
      t.index ["user_id"], name: "index_advertising_applications_on_user_id", using: :btree
    end

    create_table "advertising_periods", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "advertising_public_statuses", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "anon_saved_searches", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "subtype",            limit: 3,     null: false
      t.string   "link_to",            limit: 64,    null: false
      t.string   "name",               limit: 32
      t.string   "category"
      t.string   "square_from",        limit: 24
      t.string   "square_to",          limit: 24
      t.string   "price_from",         limit: 24
      t.string   "price_to",           limit: 24
      t.string   "price_src",          limit: 3
      t.text     "data",               limit: 65535
      t.datetime "created_at",                       null: false
      t.datetime "updated_at",                       null: false
      t.text     "metro_data",         limit: 65535, null: false
      t.integer  "add_params_count",   limit: 1,                  unsigned: true
      t.integer  "main_city",          limit: 1,                  unsigned: true
      t.text     "location_tags_data", limit: 65535, null: false
    end

    create_table "anon_users", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "email"
      t.string   "access_level", limit: 16, default: "anon", null: false
      t.string   "access_code",  limit: 32,                  null: false
      t.datetime "created_at",                               null: false
      t.datetime "updated_at",                               null: false
      t.index ["email"], name: "index_anon_users_on_email", using: :btree
    end

    create_table "area_types", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "avatars", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "imageable_type"
      t.integer  "imageable_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.datetime "created_at",                 null: false
      t.datetime "updated_at",                 null: false
      t.index ["imageable_type", "imageable_id"], name: "index_avatars_on_imageable_type_and_imageable_id", using: :btree
    end

    create_table "bad_room_kinds", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "bad_room_nums", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "bad_room_presents", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "balcons", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "bg_cn_names", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.index ["value"], name: "ivalue", type: :fulltext
    end
</code>```

答: You are using MySQL-specific syntax ENGINE=MyISAM  DEFAULT CHARSET=utf8 in SQLite database: SQLite3::SQLException: near "ENGINE":

Title: rails rake db:migrate sqllite3 error

Body:
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: near "ENGINE": syntax error: CREATE TABLE "adv_bgs" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "adv_bg_type" varchar, "adv_bg_id" integer, "uploaded_file_file_name" varchar, "uploaded_file_content_type" varchar, "uploaded_file_file_size" integer, "uploaded_file_updated_at" datetime, "head" boolean DEFAULT 'f', "imageable_id" integer, "imageable_type" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) ENGINE=MyISAM  DEFAULT CHARSET=utf8
/mnt/c/Users/direwolf/Documents/web/rails_projects/okar/db/migrate/20170425144835_init_schema.rb:4:in `up'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `'
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "ENGINE": syntax error: CREATE TABLE "adv_bgs" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "adv_bg_type" varchar, "adv_bg_id" integer, "uploaded_file_file_name" varchar, "uploaded_file_content_type" varchar, "uploaded_file_file_size" integer, "uploaded_file_updated_at" datetime, "head" boolean DEFAULT 'f', "imageable_id" integer, "imageable_type" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) ENGINE=MyISAM  DEFAULT CHARSET=utf8
/mnt/c/Users/direwolf/Documents/web/rails_projects/okar/db/migrate/20170425144835_init_schema.rb:4:in `up'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `'
SQLite3::SQLException: near "ENGINE": syntax error
/mnt/c/Users/direwolf/Documents/web/rails_projects/okar/db/migrate/20170425144835_init_schema.rb:4:in `up'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/jonsdirewolf/.rbenv/versions/2.4.0/bin/bundle:22:in `'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

What Do I do?
20170425144835_init_schema.rb

class InitSchema < ActiveRecord::Migration
  def up

    create_table "adv_bgs", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_bg_type"
      t.integer  "adv_bg_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_bg_type", "adv_bg_id"], name: "index_adv_bgs_on_adv_bg_type_and_adv_bg_id", using: :btree
      t.index ["head"], name: "index_adv_bgs_on_head", using: :btree
    end

    create_table "adv_logos", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_logo_type"
      t.integer  "adv_logo_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_logo_type", "adv_logo_id"], name: "index_adv_logos_on_adv_logo_type_and_adv_logo_id", using: :btree
      t.index ["head"], name: "index_adv_logos_on_head", using: :btree
    end

    create_table "adv_pic1s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic1_type"
      t.integer  "adv_pic1_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic1_type", "adv_pic1_id"], name: "index_adv_pic1s_on_adv_pic1_type_and_adv_pic1_id", using: :btree
      t.index ["head"], name: "index_adv_pic1s_on_head", using: :btree
    end

    create_table "adv_pic2s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic2_type"
      t.integer  "adv_pic2_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic2_type", "adv_pic2_id"], name: "index_adv_pic2s_on_adv_pic2_type_and_adv_pic2_id", using: :btree
      t.index ["head"], name: "index_adv_pic2s_on_head", using: :btree
    end

    create_table "adv_pic3s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic3_type"
      t.integer  "adv_pic3_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic3_type", "adv_pic3_id"], name: "index_adv_pic3s_on_adv_pic3_type_and_adv_pic3_id", using: :btree
      t.index ["head"], name: "index_adv_pic3s_on_head", using: :btree
    end

    create_table "adv_pic4s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic4_type"
      t.integer  "adv_pic4_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic4_type", "adv_pic4_id"], name: "index_adv_pic4s_on_adv_pic4_type_and_adv_pic4_id", using: :btree
      t.index ["head"], name: "index_adv_pic4s_on_head", using: :btree
    end

    create_table "adv_pic5s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic5_type"
      t.integer  "adv_pic5_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic5_type", "adv_pic5_id"], name: "index_adv_pic5s_on_adv_pic5_type_and_adv_pic5_id", using: :btree
      t.index ["head"], name: "index_adv_pic5s_on_head", using: :btree
    end

    create_table "adv_pic6s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic6_type"
      t.integer  "adv_pic6_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic6_type", "adv_pic6_id"], name: "index_adv_pic6s_on_adv_pic6_type_and_adv_pic6_id", using: :btree
      t.index ["head"], name: "index_adv_pic6s_on_head", using: :btree
    end

    create_table "adv_pic7s", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "adv_pic7_type"
      t.integer  "adv_pic7_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.boolean  "head",                       default: false
      t.integer  "imageable_id"
      t.string   "imageable_type"
      t.datetime "created_at",                                 null: false
      t.datetime "updated_at",                                 null: false
      t.index ["adv_pic7_type", "adv_pic7_id"], name: "index_adv_pic7s_on_adv_pic7_type_and_adv_pic7_id", using: :btree
      t.index ["head"], name: "index_adv_pic7s_on_head", using: :btree
    end

    create_table "advertising_applications", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.integer  "user_id"
      t.integer  "anon_user_id"
      t.integer  "televisor_id",                 limit: 1,                                     null: false
      t.integer  "advertising_public_status_id", limit: 1,     default: 1
      t.integer  "advertising_period_id",        limit: 1,     default: 1
      t.integer  "payment_status_id",            limit: 1,     default: 1
      t.integer  "step",                         limit: 1,     default: 1
      t.integer  "spec_id",                      limit: 1,     default: 1
      t.string   "email"
      t.string   "lnk"
      t.string   "redwords"
      t.string   "zkname"
      t.string   "zkdescr"
      t.integer  "price"
      t.integer  "charge",                       limit: 1,     default: 1
      t.datetime "endtime",                                    default: '2017-04-25 17:47:04'
      t.text     "comment",                      limit: 65535
      t.datetime "created_at",                                                                 null: false
      t.datetime "updated_at",                                                                 null: false
      t.index ["advertising_period_id"], name: "index_advertising_applications_on_advertising_period_id", using: :btree
      t.index ["advertising_public_status_id"], name: "index_advertising_applications_on_advertising_public_status_id", using: :btree
      t.index ["anon_user_id"], name: "index_advertising_applications_on_anon_user_id", using: :btree
      t.index ["payment_status_id"], name: "index_advertising_applications_on_payment_status_id", using: :btree
      t.index ["televisor_id"], name: "index_advertising_applications_on_televisor_id", using: :btree
      t.index ["user_id"], name: "index_advertising_applications_on_user_id", using: :btree
    end

    create_table "advertising_periods", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "advertising_public_statuses", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "anon_saved_searches", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "subtype",            limit: 3,     null: false
      t.string   "link_to",            limit: 64,    null: false
      t.string   "name",               limit: 32
      t.string   "category"
      t.string   "square_from",        limit: 24
      t.string   "square_to",          limit: 24
      t.string   "price_from",         limit: 24
      t.string   "price_to",           limit: 24
      t.string   "price_src",          limit: 3
      t.text     "data",               limit: 65535
      t.datetime "created_at",                       null: false
      t.datetime "updated_at",                       null: false
      t.text     "metro_data",         limit: 65535, null: false
      t.integer  "add_params_count",   limit: 1,                  unsigned: true
      t.integer  "main_city",          limit: 1,                  unsigned: true
      t.text     "location_tags_data", limit: 65535, null: false
    end

    create_table "anon_users", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "email"
      t.string   "access_level", limit: 16, default: "anon", null: false
      t.string   "access_code",  limit: 32,                  null: false
      t.datetime "created_at",                               null: false
      t.datetime "updated_at",                               null: false
      t.index ["email"], name: "index_anon_users_on_email", using: :btree
    end

    create_table "area_types", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "avatars", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "imageable_type"
      t.integer  "imageable_id"
      t.string   "uploaded_file_file_name"
      t.string   "uploaded_file_content_type"
      t.integer  "uploaded_file_file_size"
      t.datetime "uploaded_file_updated_at"
      t.datetime "created_at",                 null: false
      t.datetime "updated_at",                 null: false
      t.index ["imageable_type", "imageable_id"], name: "index_avatars_on_imageable_type_and_imageable_id", using: :btree
    end

    create_table "bad_room_kinds", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "bad_room_nums", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "bad_room_presents", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "balcons", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end

    create_table "bg_cn_names", force: :cascade, options: "ENGINE=MyISAM  DEFAULT CHARSET=utf8" do |t|
      t.string   "value"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.index ["value"], name: "ivalue", type: :fulltext
    end


来源: stackexchange

问:
Work around for jQuery draggable and resizeable on image
Trying to apply both draggable and resizeable with jQuery to an image does not work correctly. It will resize but not drag. Are there any known solutions to this?</p>

答:
This seems to work fine if I wrap the img in a div:

And then call resizeable and draggable on that div:

$("#drag_resize").resizable().draggable();

Here's a working example: http://jsfiddle.net/andrewwhitaker/HNYVk/

ContentLicense: CC BY-SA 2.5

Body:
This seems to work fine if I wrap the img in a div:

<div id="drag_resize"><img src="img.jpg"/></div>

And then call resizeable and draggable on that div:

$("#drag_resize").resizable().draggable();

Here's a working example: http://jsfiddle.net/andrewwhitaker/HNYVk/


问:
Custom UIView without Storyboard
Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

```<code>import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}

class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}
</code>```

答:
You must have to initialised the self.background = UIView() and self.title = UILabel() first.

You can initalised them in setupSubviews() function before the set/assign values to them.

ContentLicense: CC BY-SA 3.0

Title: Custom UIView without Storyboard

Body:
Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}

class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}


问:
Angular - Copy array to modeled array
I need to make a custom array from an array receiving from an API Rest. I receive this model :

```<code>export interface AreaEstadistica {
  id_area_estadistica: String;
  nombre: String;
  id_distrito: String;
  calculos_estadisticos_pt: Array<CalculoEstadistico>;
}

export interface CalculoEstadistico {
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}
</code>```

And i want to make an array with the same fields, because in the object CalculoEstadistico I can receive so much information, and i need the 'header' for any register in CalculoEstadistico, something like this:

```<code>export interface AreaEstadistica2 {
  id_area_estadistica: String; //Header from this
  nombre: String;
  id_distrito: String;// To this
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}
</code>```

The service in Angular 5 :

```<code>getAreasEstadisticas(): Observable<AreaEstadistica[]> {
    let url: string = this.urlEstadisticas;
    console.log('URL' + url);
    return this._http.get<AreaEstadistica[]>(url);
  }
</code>```

I tried it by using a map in the component:

```<code>    areas: AreaEstadistica[] = [];
    areas2: AreaEstadistica2[] = [];
//...

getAreas() {
    this._EstadisticasService
      .getAreasEstadisticas()
      .subscribe(
        res => {
          this.areas = res;
          this.transformArray();
        },
        err => {
          console.log(err);
          alert('error');
        }
      );
  }
transformArray(){
    this.areas.map(item => {
            return {
               id_area_estadistica: item.id_area_estadistica,
               nombre: item.nombre,
               id_distrito: item.id_distrito,
               aa_ponencia_total: item.aa_ponencia_total,
               uso: item.calculos_estadisticos_pt[i].uso,
               valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
               valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
            };
        }).forEach(item => this.areas2.push(item));
}
</code>```

But this code don't work. One of the errors:

src/app/estadisticas/estadisticas.component.ts(129,57): error TS2304:
  Cannot find name 'i'.

Any ideas? I don't know how to access to the fields in the object CalculoEstadistico to map them:

```<code>uso: item.calculos_estadisticos_pt[i].uso,
valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
</code>```

Is there a way to copy a nested model array to another model array? Thanks!

答:
You use index i that does not exists:

```<code>valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
</code>```

Title: Angular - Copy array to modeled array

Body:
I need to make a custom array from an array receiving from an API Rest. I receive this model :

export interface AreaEstadistica {
  id_area_estadistica: String;
  nombre: String;
  id_distrito: String;
  calculos_estadisticos_pt: Array<CalculoEstadistico>;
}

export interface CalculoEstadistico {
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}

And i want to make an array with the same fields, because in the object CalculoEstadistico I can receive so much information, and i need the 'header' for any register in CalculoEstadistico, something like this:

export interface AreaEstadistica2 {
  id_area_estadistica: String; //Header from this
  nombre: String;
  id_distrito: String;// To this
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}

The service in Angular 5 :

getAreasEstadisticas(): Observable<AreaEstadistica[]> {
    let url: string = this.urlEstadisticas;
    console.log('URL' + url);
    return this._http.get<AreaEstadistica[]>(url);
  }

I tried it by using a map in the component:

    areas: AreaEstadistica[] = [];
    areas2: AreaEstadistica2[] = [];
//...

getAreas() {
    this._EstadisticasService
      .getAreasEstadisticas()
      .subscribe(
        res => {
          this.areas = res;
          this.transformArray();
        },
        err => {
          console.log(err);
          alert('error');
        }
      );
  }
transformArray(){
    this.areas.map(item => {
            return {
               id_area_estadistica: item.id_area_estadistica,
               nombre: item.nombre,
               id_distrito: item.id_distrito,
               aa_ponencia_total: item.aa_ponencia_total,
               uso: item.calculos_estadisticos_pt[i].uso,
               valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
               valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
            };
        }).forEach(item => this.areas2.push(item));
}

But this code don't work. One of the errors:

src/app/estadisticas/estadisticas.component.ts(129,57): error TS2304:
  Cannot find name 'i'.

Any ideas? I don't know how to access to the fields in the object CalculoEstadistico to map them:

uso: item.calculos_estadisticos_pt[i].uso,
valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo

Is there a way to copy a nested model array to another model array? Thanks!

Body:
You use index i that does not exists:

valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo


问:
From FBSDKGraphRequest to Storyboard
i'm total beginner in coding, but i have a big question :)

I dont know how to get information to display on Main Storyboard form FBSDKGraphRequest.

What i should do next to get picture to Storyboard? I hope someone can help me :)

Using Swift 3, Xcode 8

Facebook login is working and code is:

```<code>    func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                self.dict = result as? [String : AnyObject]
                print(result!)
                print(self.dict)
            }
        })
    }
</code>```

答:
In Swift 3

```<code>@IBAction func btnFacebookTapped(_ sender: UIButton)
    {

        let loginManager = FBSDKLoginManager()
        loginManager.logIn(withReadPermissions: ["user_about_me", "email" , "user_birthday","user_hometown"], from: self) { (loginResult, error) in
            if error != nil
            {
                self.showalert(strMessage: (error?.localizedDescription)!)
            }
            else
            {

                if loginResult?.grantedPermissions == nil
                {
                    self.showalert(strMessage: "Login Permissions not granted")
                    return
                }

                if (loginResult?.grantedPermissions.contains("email"))!
                {

                        self.getFBUserData()

                }
            }
        }
    }
    func getFBUserData()
    {
        FBSDKGraphRequest.init(graphPath: "me?fields=id,name,email,first_name,last_name,cover,picture.type(large),gender,birthday,hometown", parameters: nil).start(completionHandler: { (connection , result , error ) in

            if(error == nil){

                DispatchQueue.main.async {
                    let dictionary = result as! NSDictionary

                    print(dictionary)
                    print("Name : \(dictionary.value(forKey: "name")!)")
                    print("FB ID : \(dictionary.value(forKey: "id")!)")
}

            }else{

                self.showalert(strMessage: "Somthig Went Wrong..!")
            }
        })

    }
</code>```

Title: From FBSDKGraphRequest to Storyboard

Body:
i'm total beginner in coding, but i have a big question :)

I dont know how to get information to display on Main Storyboard form FBSDKGraphRequest.

What i should do next to get picture to Storyboard? I hope someone can help me :)

Using Swift 3, Xcode 8

Facebook login is working and code is:

    func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                self.dict = result as? [String : AnyObject]
                print(result!)
                print(self.dict)
            }
        })
    }

Body:
In Swift 3

@IBAction func btnFacebookTapped(_ sender: UIButton)
    {

        let loginManager = FBSDKLoginManager()
        loginManager.logIn(withReadPermissions: ["user_about_me", "email" , "user_birthday","user_hometown"], from: self) { (loginResult, error) in
            if error != nil
            {
                self.showalert(strMessage: (error?.localizedDescription)!)
            }
            else
            {

                if loginResult?.grantedPermissions == nil
                {
                    self.showalert(strMessage: "Login Permissions not granted")
                    return
                }

                if (loginResult?.grantedPermissions.contains("email"))!
                {

                        self.getFBUserData()

                }
            }
        }
    }
    func getFBUserData()
    {
        FBSDKGraphRequest.init(graphPath: "me?fields=id,name,email,first_name,last_name,cover,picture.type(large),gender,birthday,hometown", parameters: nil).start(completionHandler: { (connection , result , error ) in

            if(error == nil){

                DispatchQueue.main.async {
                    let dictionary = result as! NSDictionary

                    print(dictionary)
                    print("Name : \(dictionary.value(forKey: "name")!)")
                    print("FB ID : \(dictionary.value(forKey: "id")!)")
}

            }else{

                self.showalert(strMessage: "Somthig Went Wrong..!")
            }
        })

    }


问:
Generate tr on click of Image button jquery
I have a scenario where I want to duplicate the existing
 whenever I click on  + button which is:

Below is my
. how to generate this using jquery or javascript

```<code> <tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName">
                    <label>SP Vender Name</label><span>Shri Kamalkanth Co.</span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true"></i>
            </div>
            <i class="max">(Maximum 5 Vendors)</i>

        </div>
    </td>
</tr>
</code>```

答:
You'd first clone() the parent
 by finding it through closest() and insert it as a sibling via insertAfter().  Make sure to also pass true as arguments so that all descendants are passed along with their events and data.

```<code>$('.add').on('click', function() {
  var $tr = $(this).closest('tr');

  $tr.clone(true, true).insertAfter($tr)
});
</code>```

Body:
I have a scenario where I want to duplicate the existing
 whenever I click on  + button which is:

Below is my
. how to generate this using jquery or javascript

                    SP Vender NameShri Kamalkanth Co.

                    From Date<input type="text" id="spFromDate1" />

                    To Date<input type="text" id="spToDate1" />

            (Maximum 5 Vendors)

Body:
You'd first clone() the parent <tr/> by finding it through closest() and insert it as a sibling via insertAfter().  Make sure to also pass true as arguments so that all descendants are passed along with their events and data.

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');

  $tr.clone(true, true).insertAfter($tr)
});


问:
Python: Grouping values of different columns into time buckets
Say you have this DataFrame:

```<code>Name    Item    Date    value1  value2
Marc    bike    21-Dec-17   7   1000
Marc    bike    05-Jan-18   9   2000
Marc    bike    27-Jul-18   4   500
John    house   14-Dec-17   4   500
John    house   02-Feb-18   6   500
John    house   07-Feb-18   8   1000
John    house   16-Feb-18   2   1000
John    house   05-Dec-21   7   1000
John    house   27-Aug-25   8   500
John    car     17-Apr-18   4   500
</code>```

I would like to bin value1 and value2 into monthly buckets (each 3rd wednesday for the next 48 months) for each name-item-combination.

So there are 49 time buckets for each combination with the sum of value1 and value2 for each month: Marc/bike, John/house, John/car, ...

The solution for John/house would look like:

```<code>Name    Item    TimeBucket  value1  value2
John    house   20-Dec-17   4   500
John    house   17-Jan-18   0   0
John    house   21-Feb-18   16  2500
John    house   21-Mar-18   0   0
John    house   18-Apr-18   0   0
John    house   …           0   0
John    house   17-Nov-21   0   0
John    house   15-Dec-21   7   1000
John    house   rest        8   500
</code>```

i cant get to a result with pandas. The only solution I can think of is a row-by-row iteration through the dataframe, but I'd really like to avoid having to do this. Is there an elegant way to do it?

答:
The question really boils down to three steps:

1. How to find the third Wednesday of every month?

This may not be the most elegant solution, but you can filter out the third Wednesday of every month by masking a pandas DatetimeIndex which contains every day in the time frame.

```<code># generate a DatetimeIndex for all days in the relevant time frame
from datetime import datetime
start = datetime(2017, 12, 1)
end = datetime(2022, 1, 31)
days = pd.date_range(start, end, freq='D')

# filter out only the third wednesday of each month
import itertools
third_wednesdays = []
for year, month in itertools.product(range(2017, 2023), range(1,13)):
    mask = (days.weekday == 2) & \
        (days.year == year) & \
        (days.month == month)
    if len(days[mask]) > 0:
        third_wednesdays.append(days[mask][2])
bucket_lower_bounds = pd.DatetimeIndex(third_wednesdays)
</code>```

Convert the resulting list to a DatetimeIndex so you can use it as the lower bounds of the bins in step 2.

2. How to bin values of a DataFrame?

Then, once you have the list of buckets as a DatetimeIndex, you can simply use panda's cut function to assign each date to a bucket.  Convert date columns to integers before passing them into cut, and then convert the result back to dates:

```<code>time_buckets = pd.to_datetime(
    pd.cut(
        x = pd.to_numeric(df['Date']),
        bins = pd.to_numeric(bucket_lower_bounds),
        labels = bucket_lower_bounds[:-1]
    )
)
</code>```

The series time_buckets assigns each index value of your original data frame to a bucket's lower bound. We can simply add it to the original data frame now:

```<code>df['TimeBucket'] = time_buckets
</code>```

The result should look somewhat like this (not that NaT stands for the "rest" bucket):

```<code>    Name    Item    Date    value1  value2  TimeBucket
0   Marc    bike    2017-12-21  7   1000    2017-12-20
1   Marc    bike    2018-01-05  9   2000    2017-12-20
2   Marc    bike    2018-07-27  4   500     2018-07-18
3   John    house   2017-12-14  4   500     NaT
4   John    house   2018-02-02  6   500     2018-01-17
5   John    house   2018-02-07  8   1000    2018-01-17
6   John    house   2018-02-16  2   1000    2018-01-17
7   John    house   2021-12-05  7   1000    2021-11-17
8   John    house   2025-08-27  8   500     NaT
9   John    car     2018-04-17  4   500     2018-03-21
</code>```

3. How to aggregate a binned DataFrame?

Now it's as simple as using groupby to get the sums for each combination of name, item and bucket:

```<code>df.groupby(['Name','Item','TimeBucket']).sum()
</code>```

Result:

```<code>Name    Item    TimeBucket  value1  value2
John    car     2018-03-21  4       500
        house   2018-01-17  16      2500
                2021-11-17  7       1000
Marc    bike    2017-12-20  16      3000
                2018-07-18  4       500
</code>```

Unfortunately, NaT values are excluded from groupby. If you need to sum those as well, perhaps it would be easiest to make sure that your list of buckets has at least one bucket for every date in your input range.

Edit: Step 2 requires pandas version >= 0.18.1.

Body:
Say you have this DataFrame:

Name    Item    Date    value1  value2
Marc    bike    21-Dec-17   7   1000
Marc    bike    05-Jan-18   9   2000
Marc    bike    27-Jul-18   4   500
John    house   14-Dec-17   4   500
John    house   02-Feb-18   6   500
John    house   07-Feb-18   8   1000
John    house   16-Feb-18   2   1000
John    house   05-Dec-21   7   1000
John    house   27-Aug-25   8   500
John    car     17-Apr-18   4   500

I would like to bin value1 and value2 into monthly buckets (each 3rd wednesday for the next 48 months) for each name-item-combination.

So there are 49 time buckets for each combination with the sum of value1 and value2 for each month: Marc/bike, John/house, John/car, ...

The solution for John/house would look like:

Name    Item    TimeBucket  value1  value2
John    house   20-Dec-17   4   500
John    house   17-Jan-18   0   0
John    house   21-Feb-18   16  2500
John    house   21-Mar-18   0   0
John    house   18-Apr-18   0   0
John    house   …           0   0
John    house   17-Nov-21   0   0
John    house   15-Dec-21   7   1000
John    house   rest        8   500

i cant get to a result with pandas. The only solution I can think of is a row-by-row iteration through the dataframe, but I'd really like to avoid having to do this. Is there an elegant way to do it?

Body:
The question really boils down to three steps:

1. How to find the third Wednesday of every month?

This may not be the most elegant solution, but you can filter out the third Wednesday of every month by masking a pandas DatetimeIndex which contains every day in the time frame.

# generate a DatetimeIndex for all days in the relevant time frame
from datetime import datetime
start = datetime(2017, 12, 1)
end = datetime(2022, 1, 31)
days = pd.date_range(start, end, freq='D')

# filter out only the third wednesday of each month
import itertools
third_wednesdays = []
for year, month in itertools.product(range(2017, 2023), range(1,13)):
    mask = (days.weekday == 2) & \
        (days.year == year) & \
        (days.month == month)
    if len(days[mask]) > 0:
        third_wednesdays.append(days[mask][2])
bucket_lower_bounds = pd.DatetimeIndex(third_wednesdays)

Convert the resulting list to a DatetimeIndex so you can use it as the lower bounds of the bins in step 2.

2. How to bin values of a DataFrame?

Then, once you have the list of buckets as a DatetimeIndex, you can simply use panda's cut function to assign each date to a bucket.  Convert date columns to integers before passing them into cut, and then convert the result back to dates:

time_buckets = pd.to_datetime(
    pd.cut(
        x = pd.to_numeric(df['Date']),
        bins = pd.to_numeric(bucket_lower_bounds),
        labels = bucket_lower_bounds[:-1]
    )
)

The series time_buckets assigns each index value of your original data frame to a bucket's lower bound. We can simply add it to the original data frame now:

df['TimeBucket'] = time_buckets

The result should look somewhat like this (not that NaT stands for the "rest" bucket):

    Name    Item    Date    value1  value2  TimeBucket
0   Marc    bike    2017-12-21  7   1000    2017-12-20
1   Marc    bike    2018-01-05  9   2000    2017-12-20
2   Marc    bike    2018-07-27  4   500     2018-07-18
3   John    house   2017-12-14  4   500     NaT
4   John    house   2018-02-02  6   500     2018-01-17
5   John    house   2018-02-07  8   1000    2018-01-17
6   John    house   2018-02-16  2   1000    2018-01-17
7   John    house   2021-12-05  7   1000    2021-11-17
8   John    house   2025-08-27  8   500     NaT
9   John    car     2018-04-17  4   500     2018-03-21

3. How to aggregate a binned DataFrame?

Now it's as simple as using groupby to get the sums for each combination of name, item and bucket:

df.groupby(['Name','Item','TimeBucket']).sum()

Result:

Name    Item    TimeBucket  value1  value2
John    car     2018-03-21  4       500
        house   2018-01-17  16      2500
                2021-11-17  7       1000
Marc    bike    2017-12-20  16      3000
                2018-07-18  4       500

Unfortunately, NaT values are excluded from groupby. If you need to sum those as well, perhaps it would be easiest to make sure that your list of buckets has at least one bucket for every date in your input range.

Edit: Step 2 requires pandas version >= 0.18.1.


问:
Installation of Rtools. Can't fnd C++ compiler
I want to use a program called Stan within R. To do so I need to install Rtools to get the C++ compiler. According to the Stan website, I am to check the box for editing path upon installation of Rtools.

For some reason R can't seem to find the compiler.

Sys.getenv("PATH")
  [1] "c:\Rtools\bin;c:\Rtools\mingw_64\bin;c:\Rtools\bin;c:\MiKTeX\miktex\bin;c:\R\R-3.2\bin\i386;c:\windows;c:\windows\system32;C:\Users\a3988\AppData\Local\Microsoft\WindowsApps;"

system('g++ -v')
  Warning message:
  running command 'g++ -v' had status 127

Sys.which("g++")
                                     g++
  "c:\Rtools\mingw_64\bin\G__~1.EXE"

Can anybody help? I am using
R-version: 3.4.2
Rtools34
Windows10

答: You first need to install the gcc compilers and then you can install Rtools: https://github.com/stan-dev/rstan/wiki/Install-Rtools-for-Windows.


问:
Default Option not selected dropdown in angularjs
I am struggling with dropdown list, Please refer bellow code

My Controller

```<code>(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);
</code>```

My UI

```<code><body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</code>```

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

答:
```<code><select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option.name for option in  data.availableOptions track by option.id" ></select>
</code>```

More info: https://docs.angularjs.org/api/ng/directive/ngOptions

If you want to select an option:

```<code>$scope.data.model= $scope.data.availableOptions[1]; // 1 ==> index of the option you want to select
</code>```

or select using a property of the object

```<code>  angular.forEach($scope.data.availableOptions, function (option, index) {
                        if (option.id === 1) { // 1 ==> id of the option
                            $scope.data.model= option;
                        }
                    });
</code>```

Body:
I am struggling with dropdown list, Please refer bellow code

My Controller

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);

My UI

  <form name="myForm">
     Repeat select:
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>

  <tt>model = {{data.model}}</tt>

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

Body:
<select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option.name for option in  data.availableOptions track by option.id" ></select>

More info: https://docs.angularjs.org/api/ng/directive/ngOptions

If you want to select an option:

$scope.data.model= $scope.data.availableOptions[1]; // 1 ==> index of the option you want to select

or select using a property of the object

  angular.forEach($scope.data.availableOptions, function (option, index) {
                        if (option.id === 1) { // 1 ==> id of the option
                            $scope.data.model= option;
                        }
                    });


问:
serialization of class into XML C#
I'm Having Below Class i.e ReconciliationRequest.cs

```<code>using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("ReconciliationRequest")]
[Serializable]
public class ReconciliationRequest
{

    public List<Patient> PatientDetails;
}
[Serializable]

public class Patient
{
    [XmlElement("NHSNumber")]
    public string NHSNumber { get; set; }

    [XmlElement("PDSChangeSerialNumber")]
    public string PDSChangeSerialNumber { get; set; }

}
</code>```

I want to serialize it into XML In Below Format

```<code><ReconciliationRequest xmlns="http://schemas.capita.co.uk/pcse/crm">
        <Patient>
            <NHSNumber>1234567890</NHSNumber>
            <PDSChangeSerialNumber>1234</PDSChangeSerialNumber>
        </Patient>

</ReconciliationRequest>
</code>```

But I'm Getting It into below format,i dont want PatientDetails tag in xml,
iwant it in above mentioned result.

```<code> <ReconciliationRequest>
      <PatientDetails>
        <Patient>
          <NHSNumber>9411992455</NHSNumber>
          <PDSChangeSerialNumber>5</PDSChangeSerialNumber>
        </Patient>
        <Patient>
          <NHSNumber>9801153512</NHSNumber>
          <PDSChangeSerialNumber>20</PDSChangeSerialNumber>
        </Patient>

      </PatientDetails>
    </ReconciliationRequest>
</code>```

I don't want PatientDetails Node .
Below is the code i used to serialize this class object into XML

```<code>ReconciliationRequest obj = new ReconciliationRequest();
                Patient obj1;
                List<Patient> PatientDetails = new List<Patient>();
                if (results.Entities.Count > 0)
                {
                    var PatientData = results.Entities[0].ToEntity<Contact>();

                    foreach (var item in results.Entities)
                    {
                        obj1 = new Patient();
                        if (item.Attributes.Keys.Contains("scr_nhs_number") && item.Attributes.Keys.Contains("csr_pdsserialchangenumber"))
                        {
                            if (!string.IsNullOrEmpty(item.Attributes["scr_nhs_number"].ToString()))
                            {
                                obj1.NHSNumber = item.Attributes["scr_nhs_number"].ToString();
                            }
                            if (!string.IsNullOrEmpty(item.Attributes["csr_pdsserialchangenumber"].ToString()))
                            {
                                obj1.PDSChangeSerialNumber = item.Attributes["csr_pdsserialchangenumber"].ToString();
                            }

                            PatientDetails.Add(obj1);
                        }
                    }
                    obj.PatientDetails = PatientDetails;

                    XmlSerializer serializer =
       new XmlSerializer(typeof(ReconciliationRequest));
                    TextWriter writer = new StreamWriter("D:\\CS\\data3.xml");
                    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                    nameSpace.Add(string.Empty, "http://schemas.capita.co.uk/pcse/crm");

                    serializer.Serialize(writer, obj, nameSpace);
                    writer.Close();
                }

            }
</code>```

Please guide me how can resolve this.

答:
Try this make your class inherit by List

```<code>    public class ReconciliationRequest<T> : List<T>
    {

    }
</code>```

and use it like this.

```<code>    ReconciliationRequest<Patient> obj = new ReconciliationRequest<Patient>();
    obj.Add(new Patient());
</code>```

This will Eliminate your details tag.

Title: serialization of class into XML C#

Body:
I'm Having Below Class i.e ReconciliationRequest.cs

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("ReconciliationRequest")]
[Serializable]
public class ReconciliationRequest
{

    public List<Patient> PatientDetails;
}
[Serializable]

public class Patient
{
    [XmlElement("NHSNumber")]
    public string NHSNumber { get; set; }

    [XmlElement("PDSChangeSerialNumber")]
    public string PDSChangeSerialNumber { get; set; }

}

I want to serialize it into XML In Below Format

<ReconciliationRequest xmlns="http://schemas.capita.co.uk/pcse/crm">
        <Patient>
            <NHSNumber>1234567890</NHSNumber>
            <PDSChangeSerialNumber>1234</PDSChangeSerialNumber>
        </Patient>

</ReconciliationRequest>

But I'm Getting It into below format,i dont want PatientDetails tag in xml,
iwant it in above mentioned result.

 <ReconciliationRequest>
      <PatientDetails>
        <Patient>
          <NHSNumber>9411992455</NHSNumber>
          <PDSChangeSerialNumber>5</PDSChangeSerialNumber>
        </Patient>
        <Patient>
          <NHSNumber>9801153512</NHSNumber>
          <PDSChangeSerialNumber>20</PDSChangeSerialNumber>
        </Patient>

      </PatientDetails>
    </ReconciliationRequest>

I don't want PatientDetails Node .
Below is the code i used to serialize this class object into XML

ReconciliationRequest obj = new ReconciliationRequest();
                Patient obj1;
                List<Patient> PatientDetails = new List<Patient>();
                if (results.Entities.Count > 0)
                {
                    var PatientData = results.Entities[0].ToEntity<Contact>();

                    foreach (var item in results.Entities)
                    {
                        obj1 = new Patient();
                        if (item.Attributes.Keys.Contains("scr_nhs_number") && item.Attributes.Keys.Contains("csr_pdsserialchangenumber"))
                        {
                            if (!string.IsNullOrEmpty(item.Attributes["scr_nhs_number"].ToString()))
                            {
                                obj1.NHSNumber = item.Attributes["scr_nhs_number"].ToString();
                            }
                            if (!string.IsNullOrEmpty(item.Attributes["csr_pdsserialchangenumber"].ToString()))
                            {
                                obj1.PDSChangeSerialNumber = item.Attributes["csr_pdsserialchangenumber"].ToString();
                            }

                            PatientDetails.Add(obj1);
                        }
                    }
                    obj.PatientDetails = PatientDetails;

                    XmlSerializer serializer =
       new XmlSerializer(typeof(ReconciliationRequest));
                    TextWriter writer = new StreamWriter("D:\\CS\\data3.xml");
                    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                    nameSpace.Add(string.Empty, "http://schemas.capita.co.uk/pcse/crm");

                    serializer.Serialize(writer, obj, nameSpace);
                    writer.Close();
                }

            }

Please guide me how can resolve this.

Body:
Try this make your class inherit by List

    public class ReconciliationRequest<T> : List<T>
    {

    }

and use it like this.

    ReconciliationRequest<Patient> obj = new ReconciliationRequest<Patient>();
    obj.Add(new Patient());

This will Eliminate your details tag.


问:
Nested relationships in blade in laravel
I am building my app. I have model user, review and reviewAnswer. I want to display reviewAnswers in blade, but I do not know how to get it from nested relationships, because it looks like:

```<code>User -> has many -> Review
Review -> Belongs to -> user

Review->hasMany->ReviewAnswer
ReviewAnswer->belongs to -> review
</code>```

Now what can I do to display reviewAnswer in blade using something like this - $user->review->reviewAnswer->table from db

Can you help me?

答:
If I got this correctly, you want to use eager loading.
Basically:</p>

```<code>User extends Model {
    public function reviews() {
        return $this->hasMany('App\Review');
    }
}

Review extends Model {
    public function reviewAnswers() {
        return $this->hasMany('App\ReviewAnswers');
    }
}

$usersReviewAnswers = App\User::with('reviews.reviewAnswers')->get();
</code>```

Body:
I am building my app. I have model user, review and reviewAnswer. I want to display reviewAnswers in blade, but I do not know how to get it from nested relationships, because it looks like:

User -> has many -> Review
Review -> Belongs to -> user

Review->hasMany->ReviewAnswer
ReviewAnswer->belongs to -> review

Now what can I do to display reviewAnswer in blade using something like this - $user->review->reviewAnswer->table from db

Can you help me?

Body:
If I got this correctly, you want to use eager loading.
Basically:

User extends Model {
    public function reviews() {
        return $this->hasMany('App\Review');
    }
}

Review extends Model {
    public function reviewAnswers() {
        return $this->hasMany('App\ReviewAnswers');
    }
}

$usersReviewAnswers = App\User::with('reviews.reviewAnswers')->get();


问:
HP UFT operation retrieve DataTable.Value failed. The column <module> does not exist
I am trying to get data from an imported Excel file. This file contains only one sheet with some values.

Somehow I can not select a specific value, no matter what i try I always get an error:

HP UFT ERROR

This is my Code so far:

```<code>Datatable.Importsheet "C:\Temp\test.xlsx",1,Global
row = Datatable.GetSheet(1).GetRowCount

MsgBox row

DataTable.SetCurrentRow(1)
ID_Number = Datatable.Value("Module", 1)

MsgBox("Erstes Feld ist: " & ID_Number)
</code>```

I am sure that the Field exists in the Excel and that it is written right.

Thank you in advance

答: Change Datatable.Importsheet "C:\Temp\test.xlsx",1,Global to Datatable.Importsheet "C:\Temp\test.xlsx",1,1 to actually import the excel sheet into Global sheet on data table. If you debug, you will notice that the existing data is being pasted in the Action sheet.

Body:
I am trying to get data from an imported Excel file. This file contains only one sheet with some values.

Somehow I can not select a specific value, no matter what i try I always get an error:

HP UFT ERROR

This is my Code so far:

Datatable.Importsheet "C:\Temp\test.xlsx",1,Global
row = Datatable.GetSheet(1).GetRowCount

MsgBox row

DataTable.SetCurrentRow(1)
ID_Number = Datatable.Value("Module", 1)

MsgBox("Erstes Feld ist: " & ID_Number)

I am sure that the Field exists in the Excel and that it is written right.

Thank you in advance


问:
How to restrict serialization for the property type Guid?
```<code>    public class Pet
    {
      // The default value for the Animal field is "Dog".
      [DefaultValue(0)]
      public int testinteger { get; set; }

      [DefaultValue (00000000 - 0000 - 0000 - 0000 - 000000000000)]
      public Guid testbool { get; set; }
    }

    public class Run
   {
    public static void Main()
    {
        Run test = new Run();

        test.SerializeObject("OverrideDefaultValue.xml");
    }

    public void SerializeObject(string filename)
    {
        XmlSerializer mySerializer = new XmlSerializer(typeof(Pet));
        TextWriter writer = new StreamWriter(filename);
        Pet myPet = new Pet();
        myPet.testinteger = 10;
        mySerializer.Serialize(writer, myPet);
        writer.Close();
    }
  }
</code>```

Here i have used Id property for serialization. I have used the attribute default value. But serialization is not restricted for Id property.

答:
This varies per serializer. Since you're using XmlSerializer, adding [XmlIgnore] is the attribute-based way to do it.

But you can also add:

```<code>public bool ShouldSerializetestbool() => false;
</code>```

(this is intended for conditional serialization, where you sometimes want to include a value; the pattern is public bool ShouldSerialize{PropertyName}())

A more interesting example might be:

```<code>public bool ShouldSerializetestbool() => testbool != Guid.Empty;
</code>```

Body:
    public class Pet
    {
      // The default value for the Animal field is "Dog".
      [DefaultValue(0)]
      public int testinteger { get; set; }

      [DefaultValue (00000000 - 0000 - 0000 - 0000 - 000000000000)]
      public Guid testbool { get; set; }
    }

    public class Run
   {
    public static void Main()
    {
        Run test = new Run();

        test.SerializeObject("OverrideDefaultValue.xml");
    }

    public void SerializeObject(string filename)
    {
        XmlSerializer mySerializer = new XmlSerializer(typeof(Pet));
        TextWriter writer = new StreamWriter(filename);
        Pet myPet = new Pet();
        myPet.testinteger = 10;
        mySerializer.Serialize(writer, myPet);
        writer.Close();
    }
  }

Here i have used Id property for serialization. I have used the attribute default value. But serialization is not restricted for Id property.

Body:
This varies per serializer. Since you're using XmlSerializer, adding [XmlIgnore] is the attribute-based way to do it.

But you can also add:

public bool ShouldSerializetestbool() => false;

(this is intended for conditional serialization, where you sometimes want to include a value; the pattern is public bool ShouldSerialize{PropertyName}())

A more interesting example might be:

public bool ShouldSerializetestbool() => testbool != Guid.Empty;


问:
find_if with lambda and capturing variables
I am trying to solve the knight problem ( in chess ) and I have the following code for all the possible moves that the knight can make:

```<code>typedef vector<pair<int,int> > Path;

Path moves(const pair<int,int> & pos)
{

    Path allMoves =
    {
        { (get<0>(pos))+1, (get<1>(pos))+2},
        { (get<0>(pos))+2, (get<1>(pos))+1},
        { (get<0>(pos))+2, (get<1>(pos))-1},
        { (get<0>(pos))+1, (get<1>(pos))-2},

        { (get<0>(pos))-1, (get<1>(pos))-2},
        { (get<0>(pos))-2, (get<1>(pos))-1},
        { (get<0>(pos))-2, (get<1>(pos))+1},
        { (get<0>(pos))-1, (get<1>(pos))+2}
    };

    return allMoves;
}
</code>```

and I want to filter it using the following conditions:

The square is inside the board (no negative positions, does not equal or exceed the board size)

The square is not in the given Path

I have tried to do the following:

```<code>Path legal_moves( const int size, Path visitedSquares, const pair<int,int> pos )
{

    Path possible_moves = moves(pos);

    auto legalMoves = find_if(  possible_moves.begin(),
                                possible_moves.end(),
                                []()
                                {

                                });

}
</code>```

But I am not sure how to get the first element of the pair( x on the chess board ) and the second element of the pair( y on the chess board ) inside the lambda and check the condition.

Please if something is not clear, comment it out.

Thanks for your time

答:
You simply have to take a std::pair (a move) as à parameter inside your lambda:

```<code>auto legalMoves = find_if(possible_moves.begin(),
                          possible_moves.end(),
                          [](std::pair<int, int> const& a_move)
                          {
                              int x, y;
                              std::tie(x, y) = a_move;
                              // do whatever you want
                          });
</code>```

You could also use auto:

```<code>auto legalMoves = find_if(std::begin(possible_moves), std::end(possible_moves),
                          [](auto const& a_move) {
                              int x, y;
                              std::tie(x, y) = a_move;
                              // do whatever you want
                          });
</code>```

Body:
I am trying to solve the knight problem ( in chess ) and I have the following code for all the possible moves that the knight can make:

typedef vector<pair<int,int> > Path;

Path moves(const pair<int,int> & pos)
{

    Path allMoves =
    {
        { (get<0>(pos))+1, (get<1>(pos))+2},
        { (get<0>(pos))+2, (get<1>(pos))+1},
        { (get<0>(pos))+2, (get<1>(pos))-1},
        { (get<0>(pos))+1, (get<1>(pos))-2},

        { (get<0>(pos))-1, (get<1>(pos))-2},
        { (get<0>(pos))-2, (get<1>(pos))-1},
        { (get<0>(pos))-2, (get<1>(pos))+1},
        { (get<0>(pos))-1, (get<1>(pos))+2}
    };

    return allMoves;
}

and I want to filter it using the following conditions:

The square is inside the board (no negative positions, does not equal or exceed the board size)

The square is not in the given Path

I have tried to do the following:

Path legal_moves( const int size, Path visitedSquares, const pair<int,int> pos )
{

    Path possible_moves = moves(pos);

    auto legalMoves = find_if(  possible_moves.begin(),
                                possible_moves.end(),
                                []()
                                {

                                });

}

But I am not sure how to get the first element of the pair( x on the chess board ) and the second element of the pair( y on the chess board ) inside the lambda and check the condition.

Please if something is not clear, comment it out.

Thanks for your time

Body:
You simply have to take a std::pair (a move) as à parameter inside your lambda:

auto legalMoves = find_if(possible_moves.begin(),
                          possible_moves.end(),
                          [](std::pair<int, int> const& a_move)
                          {
                              int x, y;
                              std::tie(x, y) = a_move;
                              // do whatever you want
                          });

You could also use auto:

auto legalMoves = find_if(std::begin(possible_moves), std::end(possible_moves),
                          [](auto const& a_move) {
                              int x, y;
                              std::tie(x, y) = a_move;
                              // do whatever you want
                          });


问:
Running mongodb forever using forever in windows
I am trying to run MongoDB server forever locally on Windows 10. And for that I'm using forever server.js which throws an error i.e, Forever is not installed.

I did npm install. But then too showing the same error.
I have followed this guide, but it's for Ubuntu. I am using Windows 10.

I need something like if I close the server cmd also, it should keep running.

答:
In Windows, you can use the mongod command to register Mongo as a service

mongod --directoryperdb --dbpath "C:\Program Files\MongoDB\Server\3.4\data\db" --logpath "C:\Program Files\MongoDB\Server\3.4\log\mongo.log" --logappend --rest --install

Open the cmd(command prompt) as administrator

run the above command

open services and search for mongo service

If it is not running already, click start to start the service


问:
How to set up a cron job via PHP (not CPanel)?
How to set up a cron job via PHP (not CPanel)?</p>

答:
Most Linux systems with crond installed provides a few directories you can set up jobs with:

```<code>/etc/cron.d/
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/
...
</code>```

The idea here is to create a file in one of these directories. You will need to set the proper permissions/ownership to those (or one of those) directories so that the user launching the PHP script can write to it (Apache user if it's a web script, or whatever CLI user if CLI is used).

The easiest thing is to create an empty file, assign proper permission/ownership to it, and have the PHP script append/modify it.

Per example:

```<code>$ touch /etc/cron.d/php-crons
$ chown www-data /etc/cron.d/php-crons
</code>```

Then in PHP:

```<code>$fp = fopen('/etc/cron.d/php-crons', 'a');
fwrite($fp, '* 23 * * * echo foobar'.PHP_EOL);
fclose($fp);
</code>```

Body:
Most Linux systems with crond installed provides a few directories you can set up jobs with:

/etc/cron.d/
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/
...

The idea here is to create a file in one of these directories. You will need to set the proper permissions/ownership to those (or one of those) directories so that the user launching the PHP script can write to it (Apache user if it's a web script, or whatever CLI user if CLI is used).

The easiest thing is to create an empty file, assign proper permission/ownership to it, and have the PHP script append/modify it.

Per example:

$ touch /etc/cron.d/php-crons
$ chown www-data /etc/cron.d/php-crons

Then in PHP:

$fp = fopen('/etc/cron.d/php-crons', 'a');
fwrite($fp, '* 23 * * * echo foobar'.PHP_EOL);
fclose($fp);


问:
How to capture soap error response for an Invalid data in request?
I am able to successfully log request and response for a valid soap request(class generated through wsimport) but couldn't capture the xml content when an exception is thrown(when a node in the request is filled with invalid data). I could get the details of response but I want to capture only the xml part of the raw response. I have tried SOAPFaultException but that gives only the exception message rather than the full envelope with body of the response.How do I capture the exception with only the xml content in the exception/error thrown.

Note: I know I can parse the error(raw response) and pull the xml content but I am wondering if there is simple way/method to get the xml content like below. The content should look like(response captured from Soap UI tool)

```<code><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
   <env:Header xmlns:env="http://www.w3.org/2003/05/soap-envelope">
      <wsa:Action>http://schemas.xmlsoap.org/ws/2004/08/addressing/fault</wsa:Action>
      <wsa:MessageID>urn:uuid:xyz</wsa:MessageID>
      <wsa:RelatesTo>urn:uuid:xyz</wsa:RelatesTo>
      <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
   </env:Header>
   <soap:Body>
      <soap:Fault>
         <soap:Code>
            <soap:Value>soap:Sender</soap:Value>
         </soap:Code>
         <soap:Reason>
            <soap:Text xml:lang="en">The 'http://www.fakexyz.com/schemas/xyz:xyz' element is invalid - The value '123' is invalid according to its datatype 'String' - The Pattern constraint failed.
 Please revise your data fields and make sure that message is correctly formatted.</soap:Text>
         </soap:Reason>
         <detail>
            <faulttype>Schema</faulttype>
         </detail>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>
</code>```

答:
After exploring more and trying, I found that we need to have a class which should implement SoapHandler interface, this gives you pretty much what was needed.
I overrode handleFault method as below.

```<code>public boolean handleFault(SOAPMessageContext context) {
        System.out.println("==============================================RESPONSE(ERROR)=======================================\r\n");

        String[] abc= context.get(MessageContext.HTTP_RESPONSE_HEADERS).toString().split("],");

        for(String httpheader:abc) {
            System.out.println(httpheader+"],");
        }

        System.out.println("\r\n");

        SOAPMessage message= context.getMessage();
        try {
            Source source = message.getSOAPPart().getContent();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
            transformer.transform(source, new StreamResult(System.out));

        } catch (Exception e) {
                System.out.println("Response has errors!!");
            }
        return false;
    }
</code>```

This gave me error info in formatted xml as well as with http headers.

Body:
I am able to successfully log request and response for a valid soap request(class generated through wsimport) but couldn't capture the xml content when an exception is thrown(when a node in the request is filled with invalid data). I could get the details of response but I want to capture only the xml part of the raw response. I have tried SOAPFaultException but that gives only the exception message rather than the full envelope with body of the response.How do I capture the exception with only the xml content in the exception/error thrown.

Note: I know I can parse the error(raw response) and pull the xml content but I am wondering if there is simple way/method to get the xml content like below. The content should look like(response captured from Soap UI tool)

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
   <env:Header xmlns:env="http://www.w3.org/2003/05/soap-envelope">
      <wsa:Action>http://schemas.xmlsoap.org/ws/2004/08/addressing/fault</wsa:Action>
      <wsa:MessageID>urn:uuid:xyz</wsa:MessageID>
      <wsa:RelatesTo>urn:uuid:xyz</wsa:RelatesTo>
      <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
   </env:Header>
   <soap:Body>
      <soap:Fault>
         <soap:Code>
            <soap:Value>soap:Sender</soap:Value>
         </soap:Code>
         <soap:Reason>
            <soap:Text xml:lang="en">The 'http://www.fakexyz.com/schemas/xyz:xyz' element is invalid - The value '123' is invalid according to its datatype 'String' - The Pattern constraint failed.
 Please revise your data fields and make sure that message is correctly formatted.</soap:Text>
         </soap:Reason>
         <detail>
            <faulttype>Schema</faulttype>
         </detail>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

Body:
After exploring more and trying, I found that we need to have a class which should implement SoapHandler interface, this gives you pretty much what was needed.
I overrode handleFault method as below.

public boolean handleFault(SOAPMessageContext context) {
        System.out.println("==============================================RESPONSE(ERROR)=======================================\r\n");

        String[] abc= context.get(MessageContext.HTTP_RESPONSE_HEADERS).toString().split("],");

        for(String httpheader:abc) {
            System.out.println(httpheader+"],");
        }

        System.out.println("\r\n");

        SOAPMessage message= context.getMessage();
        try {
            Source source = message.getSOAPPart().getContent();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
            transformer.transform(source, new StreamResult(System.out));

        } catch (Exception e) {
                System.out.println("Response has errors!!");
            }
        return false;
    }

This gave me error info in formatted xml as well as with http headers.


问:
Excel read text file removing quotations
I am trying to read a text file into Excel that presents along the lines of:

"DVXX = 2.37"

"DVID = 1.967"

"WLXX = 1906"

I created a loop that looks for specific key words, say DVXX, offsets and reports the value:

```<code>Open strFile For Input As #intFile
For i = 1 To 23
Do While Not EOF(intFile)
    Line Input #intFile, strIn
    Key_len = Len(Keywords(i))
    If Left(strIn, Key_len) = Keywords(i) Then
        strOut = Mid(strIn, Key_len + 3)
        Cells(25 + i, 1).Value = Keywords(i)
        Cells(25 + i, 2).Value = strOut
        Exit Do
    End If
    On Error Resume Next
Loop
Next i
Close #intFile
</code>```

This code works fine when I go through and delete all of the quotations, however the text files as generated will have quotes. Is there a way of reading this information in without manually removing the quotes?

答:
Add this right after you read the line:</p>

```<code>strIn = Replace(strIn, chr$(34), "")
</code>```

Body:
I am trying to read a text file into Excel that presents along the lines of:

"DVXX = 2.37"

"DVID = 1.967"

"WLXX = 1906"

I created a loop that looks for specific key words, say DVXX, offsets and reports the value:

Open strFile For Input As #intFile
For i = 1 To 23
Do While Not EOF(intFile)
    Line Input #intFile, strIn
    Key_len = Len(Keywords(i))
    If Left(strIn, Key_len) = Keywords(i) Then
        strOut = Mid(strIn, Key_len + 3)
        Cells(25 + i, 1).Value = Keywords(i)
        Cells(25 + i, 2).Value = strOut
        Exit Do
    End If
    On Error Resume Next
Loop
Next i
Close #intFile

This code works fine when I go through and delete all of the quotations, however the text files as generated will have quotes. Is there a way of reading this information in without manually removing the quotes?

Body:
Add this right after you read the line:

strIn = Replace(strIn, chr$(34), "")


问:
google marker open activity when marker is clicked
I have created an app that shows the list of bar locations by a marker on a map taken from a database on firebase.

each bar has a list of beverages.

what I wish to happen is that when a marker is clicked a new activity will open with the name of the bar selected at the top of the new activity

What i wish to happen is that when the marker is clicked it will open a new activity

//Declaration list of venues

```<code>List<Venue> venueList;
</code>```

//onCreate method

```<code>    venueList = new ArrayList<>();
    mVenues.push().setValue(marker);
</code>```

//onMapsReady method, gets the venues into the map

```<code>  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);

                venueList.add(venue);
                for (int i = 0; i < venueList.size(); i++)
                {
                    LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
                    if (mMap != null) {
                        marker = mMap.addMarker(new MarkerOptions()
                                .position(latLng).title(venue.venueName));
                                           }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });
</code>```

//Marker Click Event

```<code>  //CMarker click event to take user to purchase beverage
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            {
                for (int i = 0; i < venueList.size();) {
                    //getting the selected venue
                    Venue venue = venueList.get(i);
                    //creating an intent

                    Intent intent = new Intent(getApplicationContext(), viewbeverageActivity.class);

                    //putting venue name and id to intent
                    intent.putExtra(VENUE_ID, venue.getVenueId());
                    intent.putExtra(VENUE_NAME, venue.getVenueName());

                    //starting the activity with intent
                    startActivity(intent);

                }
                return false;
            }
        }
    });
</code>```

//Venue Class

```<code>package uk.ac.ferry_j2ulster.beerapp;

import com.google.firebase.database.IgnoreExtraProperties;

public class Venue {
    private String venueId;
    public String venueName;
    private String venueType;
    public double venueLat;
    public double venueLong;

    public Venue(){

    }

    public Venue(String venueId, String venueName, String venueType,double venueLat, double venueLong) {
        this.venueId = venueId;
        this.venueName = venueName;
        this.venueType = venueType;
        this.venueLat =  venueLat;
        this.venueLong =  venueLong;

    }

    public String getVenueId() {
        return venueId;
    }

    public String getVenueName() {
        return venueName;
    }

    public String getVenueType() {
        return venueType;
    }

    public double getVenueLong() { return venueLong;
    }

    public double getVenueLat() {return venueLat;
    }
}
</code>```

I hope to open a new activity with the bar that was selected as a title at the top

no errors, not sure how to start with this one

答:
You need to pass venue information also to the activity :

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

//...........

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker marker) {
        String title = marker.getTitle();
        Venue venue = NULL;
        for(int i=0;i<venueList.size();i++)
        {
          if(venueList.get(i).getTitle().equal(title))
             venue = venueList.get(i);
        }
        Intent intent = new Intent(MapActivity.this, NewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("venue",venue.toJSON());
        startActivity(intent);

        return false;
    }
});
</code>```

}

Make a toJSON() function in your venue class and also fromJSON() which will help you in sending venue data as well.

Body:
I have created an app that shows the list of bar locations by a marker on a map taken from a database on firebase.

each bar has a list of beverages.

what I wish to happen is that when a marker is clicked a new activity will open with the name of the bar selected at the top of the new activity

What i wish to happen is that when the marker is clicked it will open a new activity

//Declaration list of venues

List<Venue> venueList;

//onCreate method

    venueList = new ArrayList<>();
    mVenues.push().setValue(marker);

//onMapsReady method, gets the venues into the map

  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);

                venueList.add(venue);
                for (int i = 0; i < venueList.size(); i++)
                {
                    LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
                    if (mMap != null) {
                        marker = mMap.addMarker(new MarkerOptions()
                                .position(latLng).title(venue.venueName));
                                           }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

//Marker Click Event

  //CMarker click event to take user to purchase beverage
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            {
                for (int i = 0; i < venueList.size();) {
                    //getting the selected venue
                    Venue venue = venueList.get(i);
                    //creating an intent

                    Intent intent = new Intent(getApplicationContext(), viewbeverageActivity.class);

                    //putting venue name and id to intent
                    intent.putExtra(VENUE_ID, venue.getVenueId());
                    intent.putExtra(VENUE_NAME, venue.getVenueName());

                    //starting the activity with intent
                    startActivity(intent);

                }
                return false;
            }
        }
    });

//Venue Class

package uk.ac.ferry_j2ulster.beerapp;

import com.google.firebase.database.IgnoreExtraProperties;

public class Venue {
    private String venueId;
    public String venueName;
    private String venueType;
    public double venueLat;
    public double venueLong;

    public Venue(){

    }

    public Venue(String venueId, String venueName, String venueType,double venueLat, double venueLong) {
        this.venueId = venueId;
        this.venueName = venueName;
        this.venueType = venueType;
        this.venueLat =  venueLat;
        this.venueLong =  venueLong;

    }

    public String getVenueId() {
        return venueId;
    }

    public String getVenueName() {
        return venueName;
    }

    public String getVenueType() {
        return venueType;
    }

    public double getVenueLong() { return venueLong;
    }

    public double getVenueLat() {return venueLat;
    }
}

I hope to open a new activity with the bar that was selected as a title at the top

no errors, not sure how to start with this one

Body:
You need to pass venue information also to the activity :

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

//...........

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker marker) {
        String title = marker.getTitle();
        Venue venue = NULL;
        for(int i=0;i<venueList.size();i++)
        {
          if(venueList.get(i).getTitle().equal(title))
             venue = venueList.get(i);
        }
        Intent intent = new Intent(MapActivity.this, NewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("venue",venue.toJSON());
        startActivity(intent);

        return false;
    }
});

}

Make a toJSON() function in your venue class and also fromJSON() which will help you in sending venue data as well.


问:
How to use mapGetters when Vue CDN is used?
I'm trying to use mapGetters from Vue.js but instead use NPM to install I used Vue CDN like this:

```<code><script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
</code>```

I can't do the import as usual:

```<code>import {mapGetters} from 'vuex';
</code>```

And neither use mapGetters without import.

```<code>export default {
computed: mapGetters([
  'doubleCounter',
  'realCounter'
])}
</code>```

How can I use mapGetters using Vue CDN?

答:
```<code>export default {
  computed: Vuex.mapGetters([
    'doubleCounter',
    'realCounter'
  ])
}

export default {
  computed: {
    ...Vuex.mapGetters([
      'doubleCounter',
      'realCounter'
    ]),
    otherComputedProperty () {
      // implementation
    }
  }
}
</code>```

Body:
I'm trying to use mapGetters from Vue.js but instead use NPM to install I used Vue CDN like this:

I can't do the import as usual:

import {mapGetters} from 'vuex';

And neither use mapGetters without import.

export default {
computed: mapGetters([
  'doubleCounter',
  'realCounter'
])}

How can I use mapGetters using Vue CDN?