问:
how to get the days and exact minutes,exact hours from two dates in javascript?
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

```<code>var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}
</code>```

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

答:
```<code>var startDateTime = 1497029400000;
var endDateTime = 1497120300000;
var timeDifference = endDateTime - startDateTime
// with the given dates, days equals 1.0520833333333333
// we want to extract the trailing decimal values using modulus to get the other times

function getTimeDifference(timeDifference) {
  var days = timeDifference/1000/60/60/24
  days >= 1
    ? var dayCount = Math.trunc(days); // store the day count
    : var dayCount = 0; // it is less than one day

  // get the remaining hours
  var hours = (days % 1) * 24;
  var hoursCount = Math.trunc((days % 1) * 24);

  // get the remaining minutes
  var minutesCount = Math.ceil((hours % 1) * 60);
}
</code>```

Body:
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance


来源: stackexchange

问:
onCreate() is not called by getWritableDatabase()
I am writing a database in my android app, but my tables aren't being created. I added break points at my onCreate method, and my getWriteableDatabase, and getWritableDatabase is called, but onCreate is not.

```<code>package com.fslade.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "applicationdata";
    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_TABLE = "peopleT";

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
            + "company_name text not null, name text not null, city text not null, vertical text not null, title text not null, email text not null, bio text not null, photo text not null, status text not null);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database, e.g. if you increase
    // the database version
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion,
            int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS todo");
        onCreate(database);
    }
}
</code>```

And in my database helper I call getWriteableDatabse():

```<code>package com.fslade.app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ContentStorageHelper {
    public static final String KEY_ID = "_id";
    public static final String KEY_COMPANY_NAME = "company_name";
    public static final String KEY_PERSON_NAME = "name";
    public static final String KEY_CITY = "city";
    public static final String KEY_VERTICAL = "vertical";
    public static final String KEY_TITLE = "title";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_BIO = "bio";
    public static final String KEY_PHOTO = "photo";
    public static final String KEY_STATUS = "status";

    private static final String[] COLUMNS = { KEY_ID, KEY_COMPANY_NAME,
            KEY_PERSON_NAME, KEY_CITY, KEY_VERTICAL, KEY_TITLE, KEY_EMAIL,
            KEY_BIO, KEY_PHOTO, KEY_STATUS };

    private Context context;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;

    public ContentStorageHelper(Context context) {
        this.context = context;
    }

    public ContentStorageHelper open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        // dbHelper.onCreate(database);
// I added this onCreate() to see if it helped, but when I ran it
// it said that the database had already been created
        return this;
    }

    public void close() {
        dbHelper.close();
    }

/**
 * Create a new person If the person is successfully created return the new
 * rowId for that person, otherwise return a -1 to indicate failure.
 */
public long createPerson(String company_name, String name, String city,
        String vertical, String title, String email, String bio,
        String photo, String status) {
    ContentValues initialValues = createContentValues(company_name, name,
            city, vertical, title, email, bio, photo, status);

    return database.insert(DatabaseHelper.DATABASE_TABLE, null,
            initialValues);
}

/**
 * Return a Cursor over the list of all people in the database
 *
 * @return Cursor over all notes
 */
public Cursor fetchPeopleByVertical(String vertical) {
    String selection = KEY_VERTICAL+"="+vertical;
        Cursor result = database.query(DatabaseHelper.DATABASE_TABLE, COLUMNS,
                selection, null, null, null, null);
        return result;
    }

    private ContentValues createContentValues(String company_name, String name,
            String city, String vertical, String title, String email,
            String bio, String photo, String status) {
        ContentValues values = new ContentValues();
        values.put(KEY_COMPANY_NAME, company_name);
        values.put(KEY_PERSON_NAME, name);
        values.put(KEY_CITY, city);
        values.put(KEY_VERTICAL, vertical);
        values.put(KEY_TITLE, title);
        values.put(KEY_EMAIL, email);
        values.put(KEY_BIO, bio);
        values.put(KEY_PHOTO, photo);
        values.put(KEY_STATUS, status);
        System.out.print("test: " + status);
        return values;
    }
}
</code>```

答: I was having the same problem. I had forgotten a space in between two sql commands in my SQL_Create string and so the column I needed wasn't implemented correctly, but when I found and fixed the error in the String, it didn't fix the issue, because the App already registered that database as having that table. So onCreate was never called. For me, the simplest solution was to update the version number. This created a new db and table (correctly), and fixed the app. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am writing a database in my android app, but my tables aren't being created. I added break points at my onCreate method, and my getWriteableDatabase, and getWritableDatabase is called, but onCreate is not.

package com.fslade.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "applicationdata";
    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_TABLE = "peopleT";

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
            + "company_name text not null, name text not null, city text not null, vertical text not null, title text not null, email text not null, bio text not null, photo text not null, status text not null);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database, e.g. if you increase
    // the database version
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion,
            int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS todo");
        onCreate(database);
    }
}

And in my database helper I call getWriteableDatabse():

package com.fslade.app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ContentStorageHelper {
    public static final String KEY_ID = "_id";
    public static final String KEY_COMPANY_NAME = "company_name";
    public static final String KEY_PERSON_NAME = "name";
    public static final String KEY_CITY = "city";
    public static final String KEY_VERTICAL = "vertical";
    public static final String KEY_TITLE = "title";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_BIO = "bio";
    public static final String KEY_PHOTO = "photo";
    public static final String KEY_STATUS = "status";

    private static final String[] COLUMNS = { KEY_ID, KEY_COMPANY_NAME,
            KEY_PERSON_NAME, KEY_CITY, KEY_VERTICAL, KEY_TITLE, KEY_EMAIL,
            KEY_BIO, KEY_PHOTO, KEY_STATUS };

    private Context context;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;

    public ContentStorageHelper(Context context) {
        this.context = context;
    }

    public ContentStorageHelper open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        // dbHelper.onCreate(database);
// I added this onCreate() to see if it helped, but when I ran it
// it said that the database had already been created
        return this;
    }

    public void close() {
        dbHelper.close();
    }

/**
 * Create a new person If the person is successfully created return the new
 * rowId for that person, otherwise return a -1 to indicate failure.
 */
public long createPerson(String company_name, String name, String city,
        String vertical, String title, String email, String bio,
        String photo, String status) {
    ContentValues initialValues = createContentValues(company_name, name,
            city, vertical, title, email, bio, photo, status);

    return database.insert(DatabaseHelper.DATABASE_TABLE, null,
            initialValues);
}

/**
 * Return a Cursor over the list of all people in the database
 *
 * @return Cursor over all notes
 */
public Cursor fetchPeopleByVertical(String vertical) {
    String selection = KEY_VERTICAL+"="+vertical;
        Cursor result = database.query(DatabaseHelper.DATABASE_TABLE, COLUMNS,
                selection, null, null, null, null);
        return result;
    }

    private ContentValues createContentValues(String company_name, String name,
            String city, String vertical, String title, String email,
            String bio, String photo, String status) {
        ContentValues values = new ContentValues();
        values.put(KEY_COMPANY_NAME, company_name);
        values.put(KEY_PERSON_NAME, name);
        values.put(KEY_CITY, city);
        values.put(KEY_VERTICAL, vertical);
        values.put(KEY_TITLE, title);
        values.put(KEY_EMAIL, email);
        values.put(KEY_BIO, bio);
        values.put(KEY_PHOTO, photo);
        values.put(KEY_STATUS, status);
        System.out.print("test: " + status);
        return values;
    }
}


问:
Ordering menu items when some are excluded in bootstrap 3 navbar
I currently have a navbar which contains some menu items that collapse when in mobile mode and some that do not. I am having trouble getting the collapsing menu item (my log out link) to sit to the right of the non-collapsing menu items (glyphicon links) when in non-mobile mode.

How can I achieve the desired navbar-right layout below?

Current navbar-right layout

Desired navbar-right layout

My HTML:

      <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle">
        Toggle navigation

      </button>

Home

About

Contact

Log out

```

答:
There may be a better way, but this works well too:

```<code><nav role="navigation" class="navbar navbar-default navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header navbar-right pull-right">
      <ul class="nav navbar-nav pull-left visible-xs">
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-bell"></span></a></li>
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-alert"></span></a></li>
      </ul>
      <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <div class="visible-xs-block clearfix"></div>
    <div >
      <ul class="nav navbar-nav navbar-left collapse navbar-collapse">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right collapse navbar-collapse">
        <li  class="pull-left"><a href="#">Log out</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right hidden-xs">
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-bell"></span></a></li>
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-alert"></span></a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

To see it in action, copy and paste it into your Bootply example at
https://www.bootply.com/NBW8RrCTCG

Body:
There may be a better way, but this works well too:

<nav role="navigation" class="navbar navbar-default navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header navbar-right pull-right">
      <ul class="nav navbar-nav pull-left visible-xs">
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-bell"></span></a></li>
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-alert"></span></a></li>
      </ul>
      <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <div class="visible-xs-block clearfix"></div>
    <div >
      <ul class="nav navbar-nav navbar-left collapse navbar-collapse">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right collapse navbar-collapse">
        <li  class="pull-left"><a href="#">Log out</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right hidden-xs">
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-bell"></span></a></li>
        <li class="pull-left"><a href="#"><span class="glyphicon glyphicon-alert"></span></a></li>
      </ul>
    </div>
  </div>
</nav>

To see it in action, copy and paste it into your Bootply example at
https://www.bootply.com/NBW8RrCTCG


问:
How to embed H2 database into jar file delivered to the client?
I use H2 database for a desktop application in embedded mode. When I compress the application into jar file the database file is omitted. So, when I run MyApplication.jar nothing works. What is the correct way to embed/include/connect h2.jar file with MyApplication.jar? Or maybe there is another way to deliver database and application in the bundle?</p>

答:
If you want to put the database itself in your jar file, then this explanation might help:
http://www.h2database.com/html/features.html#database_in_zip

This is also discussed in this thread in the H2 forum.

ContentLicense: CC BY-SA 2.5


问:
Complicated cross module search in SugarCRM (SuiteCRM)
I want search by field phone number in many db fields in at least 2 modules.
I have solution, but it is not have optimization and very slow.

My solution:

custom/modules/Accounts/metadata/searchdefs.php

```<code> 'phone' => array (
    'name' => 'phone',
    'label' => 'LBL_ANY_PHONE',
    'type' => 'name',
    'default' => true,
    'width' => '10%',
  ),
</code>```

custom/modules/Accounts/metadata/SearchFields.php

```<code>'phone' => array(
  'query_type' => 'default',
  'operator' => 'subquery',
  'subquery' => array(
    'SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
     WHERE returnNumericOnly(phone_office_mask_c) LIKE',

    'SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
     WHERE returnNumericOnly(phone_fax_mask_c) LIKE',

    'SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
     WHERE returnNumericOnly(phone_alternate_mask_c) LIKE',

    'SELECT acc.id FROM accounts acc
       LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
       LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
       LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
     WHERE returnNumericOnly(cont_c.phone_mobile_mask_c) LIKE',

    'SELECT acc.id FROM accounts acc
       LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
       LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
       LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
     WHERE returnNumericOnly(cont_c.phone_work_mask_c) LIKE',

    'SELECT acc.id FROM accounts acc
       LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
       LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
       LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
     WHERE returnNumericOnly(cont_c.phone_fax_mask_c) LIKE',

    'OR' => true
  ),
  'db_field' => array('id')
),
</code>```

But result SQL something like:

```<code>    SELECT  *
FROM accounts
 LEFT JOIN accounts_cstm ON accounts.id = accounts_cstm.id_c
 LEFT JOIN ea1_lead_source jt0 ON accounts_cstm.ea1_lead_source_id_c = jt0.id AND jt0.deleted=0
 LEFT JOIN  users jt1 ON accounts.created_by=jt1.id AND jt1.deleted=0 AND jt1.deleted=0
 LEFT JOIN ea1_region jt2 ON accounts_cstm.ea1_region_id_c = jt2.id AND jt2.deleted=0
WHERE
((

accounts.id IN (
  SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
        WHERE phone_office_mask_c LIKE '749577%')

OR  accounts.id IN (
  SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
        WHERE phone_fax_mask_c LIKE '749577%')

OR  accounts.id IN (
  SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
        WHERE phone_alternate_mask_c LIKE '749577%')

OR  accounts.id IN (
  SELECT acc.id FROM accounts acc LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
          LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
          LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
        WHERE returnNumericOnly(cont_c.phone_mobile_mask_c) LIKE '749577%')

OR  accounts.id IN (
  SELECT acc.id FROM accounts acc
          LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
          LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
          LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
        WHERE returnNumericOnly(cont_c.phone_work_mask_c) LIKE '749577%')

OR  accounts.id IN (
  SELECT acc.id FROM accounts acc
          LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
          LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
          LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
        WHERE returnNumericOnly(cont_c.phone_fax_mask_c) LIKE '749577%')

))
AND accounts.deleted=0
ORDER BY accounts.name ASC
</code>```

I want result search SQL without subqueries, something like:

```<code>    SELECT *
FROM accounts acc
  LEFT JOIN accounts_cstm acc_c ON accounts.id = accounts_cstm.id_c
  LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
  LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
  LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
  LEFT JOIN ...
WHERE
  acc_c.phone_office_mask_c LIKE '749577%'
  AND acc_c.phone_fax_mask_c LIKE '749577%'
  AND acc_c.phone_alternate_mask_c LIKE '749577%'
  AND cont_c.phone_mobile_mask_c LIKE '749577%'
  AND cont_c.phone_work_mask_c LIKE '749577%'
  AND cont_c.phone_fax_mask_c LIKE '749577%'
  AND ….
</code>```

Can this be done?

答:
If you are using the subquery operator it will do a subquery.

You can get more information from source code here include/SearchForm/SearchForm2.php#L1164

There is ANY PHONE search on contacts for example, why not use that as a base?

Body:
I want search by field phone number in many db fields in at least 2 modules.
I have solution, but it is not have optimization and very slow.

My solution:

custom/modules/Accounts/metadata/searchdefs.php

 'phone' => array (
    'name' => 'phone',
    'label' => 'LBL_ANY_PHONE',
    'type' => 'name',
    'default' => true,
    'width' => '10%',
  ),

custom/modules/Accounts/metadata/SearchFields.php

'phone' => array(
  'query_type' => 'default',
  'operator' => 'subquery',
  'subquery' => array(
    'SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
     WHERE returnNumericOnly(phone_office_mask_c) LIKE',

    'SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
     WHERE returnNumericOnly(phone_fax_mask_c) LIKE',

    'SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
     WHERE returnNumericOnly(phone_alternate_mask_c) LIKE',

    'SELECT acc.id FROM accounts acc
       LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
       LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
       LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
     WHERE returnNumericOnly(cont_c.phone_mobile_mask_c) LIKE',

    'SELECT acc.id FROM accounts acc
       LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
       LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
       LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
     WHERE returnNumericOnly(cont_c.phone_work_mask_c) LIKE',

    'SELECT acc.id FROM accounts acc
       LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
       LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
       LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
     WHERE returnNumericOnly(cont_c.phone_fax_mask_c) LIKE',

    'OR' => true
  ),
  'db_field' => array('id')
),

But result SQL something like:

    SELECT  *
FROM accounts
 LEFT JOIN accounts_cstm ON accounts.id = accounts_cstm.id_c
 LEFT JOIN ea1_lead_source jt0 ON accounts_cstm.ea1_lead_source_id_c = jt0.id AND jt0.deleted=0
 LEFT JOIN  users jt1 ON accounts.created_by=jt1.id AND jt1.deleted=0 AND jt1.deleted=0
 LEFT JOIN ea1_region jt2 ON accounts_cstm.ea1_region_id_c = jt2.id AND jt2.deleted=0
WHERE
((

accounts.id IN (
  SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
        WHERE phone_office_mask_c LIKE '749577%')

OR  accounts.id IN (
  SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
        WHERE phone_fax_mask_c LIKE '749577%')

OR  accounts.id IN (
  SELECT id FROM accounts a LEFT JOIN accounts_cstm ac ON a.id = ac.id_c
        WHERE phone_alternate_mask_c LIKE '749577%')

OR  accounts.id IN (
  SELECT acc.id FROM accounts acc LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
          LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
          LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
        WHERE returnNumericOnly(cont_c.phone_mobile_mask_c) LIKE '749577%')

OR  accounts.id IN (
  SELECT acc.id FROM accounts acc
          LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
          LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
          LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
        WHERE returnNumericOnly(cont_c.phone_work_mask_c) LIKE '749577%')

OR  accounts.id IN (
  SELECT acc.id FROM accounts acc
          LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
          LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
          LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
        WHERE returnNumericOnly(cont_c.phone_fax_mask_c) LIKE '749577%')

))
AND accounts.deleted=0
ORDER BY accounts.name ASC

I want result search SQL without subqueries, something like:

    SELECT *
FROM accounts acc
  LEFT JOIN accounts_cstm acc_c ON accounts.id = accounts_cstm.id_c
  LEFT JOIN accounts_contacts ac_cont ON acc.id = ac_cont.account_id AND ac_cont.deleted = 0
  LEFT JOIN contacts cont ON ac_cont.contact_id = cont.id AND cont.deleted = 0
  LEFT JOIN contacts_cstm cont_c ON cont.id = cont_c.id_c
  LEFT JOIN ...
WHERE
  acc_c.phone_office_mask_c LIKE '749577%'
  AND acc_c.phone_fax_mask_c LIKE '749577%'
  AND acc_c.phone_alternate_mask_c LIKE '749577%'
  AND cont_c.phone_mobile_mask_c LIKE '749577%'
  AND cont_c.phone_work_mask_c LIKE '749577%'
  AND cont_c.phone_fax_mask_c LIKE '749577%'
  AND ….

Can this be done?


问:
What are the supported return types for Google App Engine Endpoints for Python?
I would like to know whether I could return a pdf as a response to Google App Engine Endpoints for Python.</p>

答: Responses from Google Cloud Endpoints APIs must be of content-type application/json. You could bundle the binary data of the PDF in a JSON value by encoding it with base64.</p>


问:
Change display timezone in Google Cloud Platform logs
How do I change the timezone for the displayed times in Google Cloud Platform logs?  It is currently showing the logs with CEST time, and I would like to see UTC time (which is what the sever it is logging always uses).</p>

答:
There is no support in Stackdriver (the tool used for viewing Google Cloud Platform logs) for directly changing the time zone used for displaying logs. From what I can tell, the time zone displayed is the time zone configured on your Google account.

Having said that, Stackdriver does offer advanced filtering mechanism for filtering logs. One of the criteria you can use for filtering is timestamp and you can configure time zones in this filter.

You can follow these steps:

Open Menu -> Logging -> Logs. This will open the Stackdriver Logging page.

You will see a text box which says Filter by label or text search. This is the simple filter mode.

You need to switch to advanced filter mode by clicking the down arrow on the right of the text box and selecting Convert to advanced filter.

In the textbox you can enter the advanced filter query. For example you can enter timestamp >= "2017-06-05T21:10:00-07:00" to filter and display only logs whose timestamp is at or after 2017-06-05 9:10 PM PDT

If you do not want to specify any time zone offset and just filter based on UTC time, you can use this format 2017-06-05T21:10:00Z.

The format of the Log entry and the fields like timestamp are documented here.

timestamp

string

The time the event occurred: "YYYY-MM-DDTHH:MM:SS.SSSZ".

Some more pointers about searching by time is available here.

You can also combine timestamp with other search criteria, specify both >= and <= to specify a timestamp range, etc. to narrow down your results.

Further reading about using Advanced Log filters here.


问:
Dynamic allocation in ksh
i am newbie on this forum
I am looking for dynamically modifying variable along the code
Ex.

```<code>#!/bin/ksh -f
VAR1=123456
VAR2=$VAR1
echo VAR1 # Will return '123456', good
echo VAR2 # Will return '123456', good
VAR1=azerty
echo VAR2 # Will return 123456, not good, I hope it was 'azerty', the new value of VAR1
</code>```

If anyone has an answer or a hint to this question

Thx in advance,
Antrema

答:
Try nameref, eg:

```<code>$ VAR1=123456
$ nameref VAR2=VAR1
$ echo "$VAR1 : $VAR2"

123456 : 123456

$ VAR1=azerty
$ echo "$VAR1 : $VAR2"

azerty : azerty

# NOTE: this relationship works in both directions, eg:

$ VAR2=xyz123
$ echo "$VAR1 : $VAR2"

xyz123 : xyz123
</code>```

See: O'Reilly: Learning the Korn Shell: 4.4 Indirect Variable References

Title: Dynamic allocation in ksh

Body:
i am newbie on this forum
I am looking for dynamically modifying variable along the code
Ex.

#!/bin/ksh -f
VAR1=123456
VAR2=$VAR1
echo VAR1 # Will return '123456', good
echo VAR2 # Will return '123456', good
VAR1=azerty
echo VAR2 # Will return 123456, not good, I hope it was 'azerty', the new value of VAR1

If anyone has an answer or a hint to this question

Thx in advance,
Antrema

Body:
Try nameref, eg:

$ VAR1=123456
$ nameref VAR2=VAR1
$ echo "$VAR1 : $VAR2"

123456 : 123456

$ VAR1=azerty
$ echo "$VAR1 : $VAR2"

azerty : azerty

# NOTE: this relationship works in both directions, eg:

$ VAR2=xyz123
$ echo "$VAR1 : $VAR2"

xyz123 : xyz123

See: O'Reilly: Learning the Korn Shell: 4.4 Indirect Variable References


问:
How to pass system system properties from jruby to Rails server
I'm running a local Rails server (WEBrick) via JRuby and want to test some code that will eventually be running on Torquebox.  I'm trying to access some custom Java system properties via ENV_JAVA.  These system properties will be available when running on Torquebox so to test my code locally, I'm passing in the system properties on the command line using the "-J" argument.

When I run just JRuby, everything works fine,  I can access my custom property.

```<code>C:\jruby\jruby-1.7.24\bin\jruby.exe -J-Dmy_prop=my_value -e "puts ENV_JAVA['my_prop']"
</code>```

This simply prints "my_value" to output.

My problem is trying access these custom properties when running a local Rails server.  My command line to startup the local Rails server looks something like this:

```<code>C:\jruby\jruby-1.7.24\bin\jruby.exe -J-Dmy_prop=my_value C:\jruby\jruby-1.7.24\bin\rails s
</code>```

When WEBrick starts up, my custom property "my_prop" is no longer in ENV_JAVA.  It looks like this is because inside the railties Rails::AppRailsLoader module, exec_app_rails simply replaces the current process with another one by calling the Kernel exec method and passing in the command arguments.

This does NOT keep the custom properties around.  Does anyone know how I can work around this?  I'm currently running Rails 4.2.6. It looks like in Rails 5 the module name changed to Rails::AppLoader.

答:
So I figured out a better(?) way to handle this.  Instead of:

```<code>exec RUBY, exe, *ARGV
</code>```

I can do this:

```<code>custom_sys_props = {}
current_sys_props = ENV_JAVA.to_hash
default_sys_props = eval(%x(#{RUBY} -e "puts ENV_JAVA"))
current_sys_props.each {|k,v| custom_sys_props[k] = v if default_sys_props[k] != v }
jruby_props = []
custom_sys_props.each{|k,v| jruby_props << "-J-D#{k}=#{v}"}
exec RUBY, *jruby_props, exe, *ARGV
</code>```

Its ugly and really only works for JRuby, but I dont know of a better way to handle it.  Still a shame that this hasn't been addressed before

Body:
I'm running a local Rails server (WEBrick) via JRuby and want to test some code that will eventually be running on Torquebox.  I'm trying to access some custom Java system properties via ENV_JAVA.  These system properties will be available when running on Torquebox so to test my code locally, I'm passing in the system properties on the command line using the "-J" argument.

When I run just JRuby, everything works fine,  I can access my custom property.

C:\jruby\jruby-1.7.24\bin\jruby.exe -J-Dmy_prop=my_value -e "puts ENV_JAVA['my_prop']"

This simply prints "my_value" to output.

My problem is trying access these custom properties when running a local Rails server.  My command line to startup the local Rails server looks something like this:

C:\jruby\jruby-1.7.24\bin\jruby.exe -J-Dmy_prop=my_value C:\jruby\jruby-1.7.24\bin\rails s

When WEBrick starts up, my custom property "my_prop" is no longer in ENV_JAVA.  It looks like this is because inside the railties Rails::AppRailsLoader module, exec_app_rails simply replaces the current process with another one by calling the Kernel exec method and passing in the command arguments.

This does NOT keep the custom properties around.  Does anyone know how I can work around this?  I'm currently running Rails 4.2.6. It looks like in Rails 5 the module name changed to Rails::AppLoader.

Body:
So I figured out a better(?) way to handle this.  Instead of:

exec RUBY, exe, *ARGV

I can do this:

custom_sys_props = {}
current_sys_props = ENV_JAVA.to_hash
default_sys_props = eval(%x(#{RUBY} -e "puts ENV_JAVA"))
current_sys_props.each {|k,v| custom_sys_props[k] = v if default_sys_props[k] != v }
jruby_props = []
custom_sys_props.each{|k,v| jruby_props << "-J-D#{k}=#{v}"}
exec RUBY, *jruby_props, exe, *ARGV

Its ugly and really only works for JRuby, but I dont know of a better way to handle it.  Still a shame that this hasn't been addressed before


问:
Bundle JSON as a plain JSON file with Webpack
I have a web-app that requires a configuration JSON file which contains end-points and other required start-up parameters.

If I use the json-loader, the file is not "real json", it'll look something like this:

```<code>module.exports = {
    "name": "foo",
    "key": true,
};
</code>```

What I would like is plain old JSON which means it can be parsed and changed as part of a deployment process before being sent to the web server where it will be served from.

An alternative is to use the file-loader.  However, that means that (even though it's a trivial task) I have to write the code to download the file myself.  I would like to have webpack handle this and be available.

Is there a way that I can require a JSON file, which is written as a plain-old JSON file and imported at run time?

答:
As ShabbY said above, Webpack is a module bundler and compiles your files ahead of time.

It sounds like you need to add a configuration file (json) after build time to be accessed at runtime. For this, a solution would be to load the file using a normal ajax call rather than attempting to bundle it with Webpack.

Body:
I have a web-app that requires a configuration JSON file which contains end-points and other required start-up parameters.

If I use the json-loader, the file is not "real json", it'll look something like this:

module.exports = {
    "name": "foo",
    "key": true,
};

What I would like is plain old JSON which means it can be parsed and changed as part of a deployment process before being sent to the web server where it will be served from.

An alternative is to use the file-loader.  However, that means that (even though it's a trivial task) I have to write the code to download the file myself.  I would like to have webpack handle this and be available.

Is there a way that I can require a JSON file, which is written as a plain-old JSON file and imported at run time?


Title: pandas dataframe change column value

Body:
I have python dict like this:

keysdict={'date': {20: '201012', 21: '201101', 22: '201102', 23: '201103', 24: '201104', 25: '201105', 26: '201106', 27: '201107', 28: '201108', 29: '201109', 30: '201110', 31: '201111'}}

And I have pandas dataframe like this

A    B
20  0.123
21  2.123
22  4.45
23  3.2
24  3.1
25  3.9
26  4.2

Now I want to add an extra column C which takes the respective value from dict keys that are in Column A . Like below one

A    B      C
20  0.123  201012
21  2.123  201101
22  4.45   201102
23  3.2    201103
24  3.1    201104
25  3.9    201105
26  4.2    201106

I tried this

df.loc[:,'C']=keysdict['date'][df.loc['A']]

But getting below error

KeyError: 'the label [A] is not in the [index]

Body:
df.loc['A'] refers to the row labeled 'A', and you need column, which is accessed as df['A']. Here's the correct code:

df = pd.DataFrame({'A':[20,21,22,23], 'B':[0.123,2.123,4.45,3.2]})
#    A      B
#0  20  0.123
#1  21  2.123
#2  22  4.450
#3  23  3.200

Sample key dictionary:

keysdict = {'date' : {20:0,21:1,22:2,23:3}}

df['C'] = df['A'].apply(lambda x: keysdict['date'][x])
#    A      B  C
#0  20  0.123  0
#1  21  2.123  1
#2  22  4.450  2
#3  23  3.200  3


问:
Chromecast more than one video element
is it possible to play more than one video element at a time on Chromecast? Or at least to have two video elements and just play one of them?

I tried it but I just get a black screen for the second video. But there is no error while debugging.

Thank you.

答: Unfortunately no. Thus we were not able to find good way to integrate ads via Google IMA SDK. It lead to bad user experience when IMA SDK need to "share" player with Video itself - there is always "blackout" at the end of ads playback till main video is loaded.</p>

Title: Chromecast more than one video element


问:
Switching Views/layouts
I have a problem that I can't seem to find the solution to.

I have an app that loads the main.xml file on startup, of course. In it are several buttons, and I want the buttons to take me to a different XML file. I just used setContentView(R.layout.newlayout.xml) method for that, and it works great.

The problem comes in after that. If I reference any of the buttons or other objects in the new layout, the app won't even finish loading before it errors out and closes on the emulator. However, if I take all references to objects out, the app runs fine.

I can navigate TO the new layouts, but their buttons can't do anything. Do I need to create a separate Java file for each layout? Or am I doing it all wrong? I'm trying to be as specific as I can. I suppose you could say I need to have different "pages" in my app as a website would.

答:
I think what you are trying to do is best solved using multiple java files, each one defining it's own android Activity.

While it is possible to have multiple layouts/views in a single activity, this will generally make the code more complex and harder to read/debug in the future. By having each 'screen' in its own file, it will be a bit easier to manage all the different views you need to juggle.

ContentLicense: CC BY-SA 4.0

Title: Switching Views/layouts


问:
DFP advertisements no longer opening in gmail
We have been using DFP (Double Click for Publishers Small Business) to display ads in HTML emails for about a year. We are aware that they are not supported in HTML emails but up until lately, they have been working well.

Recently, the ads only open a blank browser tab when opened in Gmail. Emails that are delivered to other email providers, outlook.com, yahoo, etc... are still working correctly.

We are using the following markup within our HTML emails for the advertisements:

 ```

In the past, the co=1 url variable is what seemed to make these work. The same ads spots delivered to a webpage work fine. It just seems to be an issue in Gmail. Any ideas on what is causing this issue or how I might be able to work around it?

答: As email ads our not supported by DFP we ended up switching to Live Intent and no longer are facing these issues.</p>

Body:
We have been using DFP (Double Click for Publishers Small Business) to display ads in HTML emails for about a year. We are aware that they are not supported in HTML emails but up until lately, they have been working well.

Recently, the ads only open a blank browser tab when opened in Gmail. Emails that are delivered to other email providers, outlook.com, yahoo, etc... are still working correctly.

We are using the following markup within our HTML emails for the advertisements:

In the past, the co=1 url variable is what seemed to make these work. The same ads spots delivered to a webpage work fine. It just seems to be an issue in Gmail. Any ideas on what is causing this issue or how I might be able to work around it?


问:
Can not access nginx container on a local windows machine
I'm running an nginx container on a windows 10 machine. I've stripped it down to a bare minimum - an nginx image provided in the Docker hub. I'm running it using:

docker run --name ng -d -P nginx

This is the output of docker ps:

b5411ff47ca6        nginx               "nginx -g 'daemon off"   22 seconds ago      Up 21 seconds       0.0.0.0:32771->80/tcp, 0.0.0.0:32770->443/tcp   ng

And this is the IP I'm getting when doing docker inspect ng: "IPAddress": "172.17.0.2"

So, the next thing I'm trying to do is access the Nginx server from the host machine by opening http://172.17.0.2:32771 in browser of the host machine. This is not working (host not found etc).

Please advise

答:
Follow this article... https://docs.docker.com/get-started/part2/#run-the-app

And make sure your application is running not just docker.

docker run -d -p 4000:80 friendlyhello

After this on Windows 10 host machine

Worked http://192.168.99.100:4000/

Not working: http://localhost:4000/


问:
How to specifiy Youtube player initialization on Android activity?
I am developing an Android app, and one of my activities contain a Youtube player. Here I want the player to be visible only if the link provided is not equal to "null" I have tried as below, but the youtube player is initialized with an error.  </p>

```<code>package com.example.acer.videoapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

public class FourthActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
    public static final String API_KEY = "key";
    public static String VIDEO_ID = "";
    Toolbar toolbar3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fourth);

        //setting title to toolbar
        toolbar3 = (Toolbar) findViewById(R.id.toolbar3);
        toolbar3.setTitleTextColor(getColor(R.color.white));

        //set back button on toolbar
        toolbar3.setNavigationIcon(R.drawable.back);
        toolbar3.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null) {
            TextView textView = (TextView) findViewById(R.id.text);
            textView.setText(bundle.getString("name"));
            TextView textView1 = (TextView) findViewById(R.id.text1);
            textView1.setText(bundle.getString("engname"));
            TextView textView2 = (TextView) findViewById(R.id.text2);
            textView2.setText(bundle.getString("desc"));
            VIDEO_ID=bundle.getString("link");
            //Log.d("link",VIDEO_ID);
        }

        //initializing youtube player view
        if(VIDEO_ID!="null") {
            YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
            youTubePlayerView.initialize(API_KEY, this);
        }
    }

    @Override
    public void onInitializationFailure(Provider provider, YouTubeInitializationResult result){
        Toast.makeText(this,"Failed to Initialize",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored){
        if(VIDEO_ID!="null") {
            //add listeners to YouTubePlayer instance
            player.setPlayerStateChangeListener(playerStateChangeListener);
            player.setPlaybackEventListener(playbackEventListner);

            //start buffering
            if (!wasRestored) {
                player.cueVideo(VIDEO_ID);
            }
        }
    }

    private PlaybackEventListener playbackEventListner = new PlaybackEventListener() {
        @Override
        public void onPlaying() {

        }

        @Override
        public void onPaused() {

        }

        @Override
        public void onStopped() {

        }

        @Override
        public void onBuffering(boolean arg0) {

        }

        @Override
        public void onSeekTo(int arg0) {

        }
    };

    private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
        @Override
        public void onLoading() {

        }

        @Override
        public void onLoaded(String arg0) {

        }

        @Override
        public void onAdStarted() {

        }

        @Override
        public void onVideoStarted() {

        }

        @Override
        public void onVideoEnded() {

        }

        @Override
        public void onError(ErrorReason arg0) {

        }
    };

}
</code>```

答:
try using,</p>

```<code>if(VIDEO_ID.equals("")){ /* do the initialization */ }
</code>```

Body:
I am developing an Android app, and one of my activities contain a Youtube player. Here I want the player to be visible only if the link provided is not equal to "null" I have tried as below, but the youtube player is initialized with an error.

package com.example.acer.videoapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

public class FourthActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
    public static final String API_KEY = "key";
    public static String VIDEO_ID = "";
    Toolbar toolbar3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fourth);

        //setting title to toolbar
        toolbar3 = (Toolbar) findViewById(R.id.toolbar3);
        toolbar3.setTitleTextColor(getColor(R.color.white));

        //set back button on toolbar
        toolbar3.setNavigationIcon(R.drawable.back);
        toolbar3.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null) {
            TextView textView = (TextView) findViewById(R.id.text);
            textView.setText(bundle.getString("name"));
            TextView textView1 = (TextView) findViewById(R.id.text1);
            textView1.setText(bundle.getString("engname"));
            TextView textView2 = (TextView) findViewById(R.id.text2);
            textView2.setText(bundle.getString("desc"));
            VIDEO_ID=bundle.getString("link");
            //Log.d("link",VIDEO_ID);
        }

        //initializing youtube player view
        if(VIDEO_ID!="null") {
            YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
            youTubePlayerView.initialize(API_KEY, this);
        }
    }

    @Override
    public void onInitializationFailure(Provider provider, YouTubeInitializationResult result){
        Toast.makeText(this,"Failed to Initialize",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored){
        if(VIDEO_ID!="null") {
            //add listeners to YouTubePlayer instance
            player.setPlayerStateChangeListener(playerStateChangeListener);
            player.setPlaybackEventListener(playbackEventListner);

            //start buffering
            if (!wasRestored) {
                player.cueVideo(VIDEO_ID);
            }
        }
    }

    private PlaybackEventListener playbackEventListner = new PlaybackEventListener() {
        @Override
        public void onPlaying() {

        }

        @Override
        public void onPaused() {

        }

        @Override
        public void onStopped() {

        }

        @Override
        public void onBuffering(boolean arg0) {

        }

        @Override
        public void onSeekTo(int arg0) {

        }
    };

    private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
        @Override
        public void onLoading() {

        }

        @Override
        public void onLoaded(String arg0) {

        }

        @Override
        public void onAdStarted() {

        }

        @Override
        public void onVideoStarted() {

        }

        @Override
        public void onVideoEnded() {

        }

        @Override
        public void onError(ErrorReason arg0) {

        }
    };

}

Body:
try using,

if(VIDEO_ID.equals("")){ /* do the initialization */ }


答:
Try map instead:

```<code>df['C'] = df['A'].map(keysdict['date'])
</code>```

If column 'A' is an index:

```<code>df['C'] = df.map(keysdict['date'])
</code>```

Title: pandas dataframe change column value

Body:
Try map instead:

df['C'] = df['A'].map(keysdict['date'])

If column 'A' is an index:

df['C'] = df.map(keysdict['date'])


问:
Calling C function taking bool, not BOOL, from ObjC
Within my ObjC code, I am calling a function which has an argument of type bool (not BOOL).

Should I be passing YES to this argument from my ObjC code, or would passing true should be correct?

This question is about conventions, not functional correctness.

答:
This really depends on your build settings. See the related answer Objective-C : BOOL vs bool

BOOL and bool can refer to the same type but sometimes they don't.

To be safe, always use the correct type, that is, false and true for bool.

The difference can be seen mostly in rare edge cases but if it appears, it's really difficult to find.

For the same reason we use NULL instead of nil when interacting with C APIs, even if they both are usually just a macro for 0. Their types still differ.


问:
How to Use Required Field validator on a check box CHECKED true or false
I  have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check

```<code><asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />

<div class="col-xs-9 form-inline" id="PChange" style="display: none;">
   <asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password"  ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
   <asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
   <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>
</div>
</code>```

gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.

```<code><asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />
</code>```

If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?

Java script function to show/hide div.

```<code><script type="text/javascript">
        function showhidepasswordFields() {
            if (document.getElementById('<%=cbPassword.ClientID%>').checked) {
                document.getElementById('PChange').style.display = 'block';
            }
            else if (!document.getElementById('<%=cbPassword.ClientID%>').checked) {
                document.getElementById('PChange').style.display = 'none';
            }
        }
    </script>
</code>```

答:
You can use a CustomValidator for that. The first function just test wether the CheckBox is checked or not. The other one adds more logic like checking if a TextBox also has a value. Just change the ClientValidationFunction for testing.

```<code><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="testCheckBoxAndTextBox"></asp:CustomValidator>

<script type="text/javascript">
    function testCheckBox(sender, element) {
        element.IsValid = $("#<%= CheckBox1.ClientID %>").prop('checked');
    }

    function testCheckBoxAndTextBox(sender, element) {
        var isValid = false;
        if ($("#<%= CheckBox1.ClientID %>").prop('checked') == true && $("#<%= TextBox1.ClientID %>").val() != "") {
            isValid = true;
        }
        element.IsValid = isValid;
    }
</script>
</code>```

Body:
I  have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check

<asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />

   <asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password"  ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
   <asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
   <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>

gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.

<asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />

If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?

Java script function to show/hide div.

Body:
You can use a CustomValidator for that. The first function just test wether the CheckBox is checked or not. The other one adds more logic like checking if a TextBox also has a value. Just change the ClientValidationFunction for testing.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="testCheckBoxAndTextBox"></asp:CustomValidator>

<script type="text/javascript">
    function testCheckBox(sender, element) {
        element.IsValid = $("#<%= CheckBox1.ClientID %>").prop('checked');
    }

    function testCheckBoxAndTextBox(sender, element) {
        var isValid = false;
        if ($("#<%= CheckBox1.ClientID %>").prop('checked') == true && $("#<%= TextBox1.ClientID %>").val() != "") {
            isValid = true;
        }
        element.IsValid = isValid;
    }
</script>


问:
Ruby - producing a combination from two arrays *produces headache*
What I'm trying to do is take an array of service names and apply a service response of either true of false to each.

Basically I'm getting an xml with a set of booleans for each of the services checked.  So for this example they all came back as true.

I put them into an array using Nokogiri like so:

```<code>doc = Nokogiri::XML.parse(xml)
service_state = doc.css("HeartBeat Status").map(&:text)
</code>```

This results in an array with 3 ["true"] items.

What I need to is apply each of them sequentially with an array I have in the code.

```<code>name = ['svc1', 'svc2', 'svc3']
</code>```

To do this I used the following code:

```<code>status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status.each {|state| print state.to_s + "\n"}
</code>```

This does what I want... sort of...

I do get an output of:

["svc1", "true"]
["svc2", "true"]
["svc3", "true"]

However, it repeats all the possible combinations.
When applying this to the actual array I have a total of 13 services that have a response 17 times so I end up with an array with 221 items.

Question: How do I do what I'm doing now but without repeating for each item in both arrays?

Thanks!

答:
Sounds like you want to use Array#zip</p>

```<code>name = ['svc1', 'svc2', 'svc3']
status = ['true', 'true', 'true']

name.zip(status)
#=> [['svc1','true'], ['svc2','true'], ['svc3','true']]
</code>```

Body:
What I'm trying to do is take an array of service names and apply a service response of either true of false to each.

Basically I'm getting an xml with a set of booleans for each of the services checked.  So for this example they all came back as true.

I put them into an array using Nokogiri like so:

doc = Nokogiri::XML.parse(xml)
service_state = doc.css("HeartBeat Status").map(&:text)

This results in an array with 3 ["true"] items.

What I need to is apply each of them sequentially with an array I have in the code.

name = ['svc1', 'svc2', 'svc3']

To do this I used the following code:

status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status.each {|state| print state.to_s + "\n"}

This does what I want... sort of...

I do get an output of:

["svc1", "true"]
["svc2", "true"]
["svc3", "true"]

However, it repeats all the possible combinations.
When applying this to the actual array I have a total of 13 services that have a response 17 times so I end up with an array with 221 items.

Question: How do I do what I'm doing now but without repeating for each item in both arrays?

Thanks!

Body:
Sounds like you want to use Array#zip

name = ['svc1', 'svc2', 'svc3']
status = ['true', 'true', 'true']

name.zip(status)
#=> [['svc1','true'], ['svc2','true'], ['svc3','true']]


问:
Error when calling h2o.init() in R to connecting to remote cluster
I'm trying to connect to the cluster hosted on EC2 machine from R and getting the same error when trying both on Windows and Mac:

```<code>> h2o.init(ip = "<Public IP>")
 Connection successful!

ERROR: Unexpected HTTP Status code: 404 Not Found (url = http://<Public IP>:54321/3/Cloud?skip_ticks=true)

Error: lexical error: invalid char in json text.
                                       <!DOCTYPE html> <html lang="en"
                     (right here) ------^
</code>```

Cluster is reachable at http://<Public IP>:54321/

Starting a local cluster with h2o.init() also works fine in R, so the problem is only when trying to connect to remote one.

I've seen the following issue marked as resolved, but it doesn't help in my case. Have anybody experienced anything similar?

UPD: The answer was very simple. It turns out that the code example given in their guide for EC2 is outdated and uses the old version of H2O. Using the most recent version (3.9.1.5555 at the moment) on EC2 machines has resolved the issue.

答:
To elaborate on the OP's update, when using a remote cluster:

Make sure you install the most recent version (check the S3 download page for the redirect to the release number).  In the example below, this is 3.13.0.3908:

```<code>wget http://s3.amazonaws.com/h2o-release/h2o/master/3908/h2o-3.13.0.3908.zip
unzip h2o-3.13.0.3908.zip
mv h2o-3.13.0.3908 h2o
cd h2o
java -Xmx4g -jar h2o.jar
</code>```

You then need to install the version of h2o-R that corresponds to this version.  (The correct version is likely not the CRAN version.)  Otherwise you will get an error like:

```<code>Error in h2o.init(ip = "XXX.XX.XX.XXX", startH2O = FALSE) :
  Version mismatch! H2O is running version 3.13.0.3908 but h2o-R package is version 3.10.4.6.
         Install the matching h2o-R version from - http://h2o-release.s3.amazonaws.com/h2o/master/3908/index.html
</code>```

So you need to note the version number H2O is running (in the above example, 3908), make sure you have previously removed any existing h2o-R package (see here for more info), and then do:

```<code>install.packages("h2o", type="source", repos="http://h2o-release.s3.amazonaws.com/h2o/master/3908/R")
</code>```

Now it should work:

```<code>library('h2o')
remoteH2O <- h2o.init(ip='XXX.XX.XX.XXX', startH2O=FALSE) #  Connection successful!
</code>```

Body:
I'm trying to connect to the cluster hosted on EC2 machine from R and getting the same error when trying both on Windows and Mac:

> h2o.init(ip = "<Public IP>")
 Connection successful!

ERROR: Unexpected HTTP Status code: 404 Not Found (url = http://<Public IP>:54321/3/Cloud?skip_ticks=true)

Error: lexical error: invalid char in json text.
                                       <!DOCTYPE html> <html lang="en"
                     (right here) ------^

Cluster is reachable at http://<Public IP>:54321/

Starting a local cluster with h2o.init() also works fine in R, so the problem is only when trying to connect to remote one.

I've seen the following issue marked as resolved, but it doesn't help in my case. Have anybody experienced anything similar?

UPD: The answer was very simple. It turns out that the code example given in their guide for EC2 is outdated and uses the old version of H2O. Using the most recent version (3.9.1.5555 at the moment) on EC2 machines has resolved the issue.

Body:
To elaborate on the OP's update, when using a remote cluster:

Make sure you install the most recent version (check the S3 download page for the redirect to the release number).  In the example below, this is 3.13.0.3908:

wget http://s3.amazonaws.com/h2o-release/h2o/master/3908/h2o-3.13.0.3908.zip
unzip h2o-3.13.0.3908.zip
mv h2o-3.13.0.3908 h2o
cd h2o
java -Xmx4g -jar h2o.jar

You then need to install the version of h2o-R that corresponds to this version.  (The correct version is likely not the CRAN version.)  Otherwise you will get an error like:

Error in h2o.init(ip = "XXX.XX.XX.XXX", startH2O = FALSE) :
  Version mismatch! H2O is running version 3.13.0.3908 but h2o-R package is version 3.10.4.6.
         Install the matching h2o-R version from - http://h2o-release.s3.amazonaws.com/h2o/master/3908/index.html

So you need to note the version number H2O is running (in the above example, 3908), make sure you have previously removed any existing h2o-R package (see here for more info), and then do:

install.packages("h2o", type="source", repos="http://h2o-release.s3.amazonaws.com/h2o/master/3908/R")

Now it should work:

library('h2o')
remoteH2O <- h2o.init(ip='XXX.XX.XX.XXX', startH2O=FALSE) #  Connection successful!


问:
Swift 3 Dismissing from Struct after UIAlert
still new to Swift and trying to get around few issues i keep facing now and then... :)
Now i have created a Struct to manage the user login, sign up and recover passowrd...

So here's the part of the code is driving me crazy...

```<code>struct NetworkingService {

var dataBaseRef: FIRDatabaseReference!{
    return FIRDatabase.database().reference()
}
var storageRef: FIRStorageReference {
    return FIRStorage.storage().reference()
}
--------------------------------------------
// Reset Password
 func resetpassword(email: String){
    FIRAuth.auth()?.sendPasswordReset(withEmail: email, completion: { (error) in
        if error == nil{
            let alertView = UIAlertController(title: "SUCCESS!", message: "We have sent an email to \(email) with the information on how to reset your password. Thank you!", preferredStyle: UIAlertControllerStyle.alert)
            alertView.addAction(UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

            })
            UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil)

        } else{
            let alertView = UIAlertController(title: "Error!", message: "Error:\(error!.localizedDescription)", preferredStyle: UIAlertControllerStyle.alert)
            alertView.addAction(UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

            })
            UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil)
        }
    })
}
</code>```

and in my controller i have a simple button which call this func

```<code>ResetPasswordVC{
@IBOutlet weak var emailTextField: UITextField!

var networkingService = NetworkingService()

override func viewDidLoad() {
    super.viewDidLoad()
}
 @IBAction func resetPasswordPressed(_ sender: Any) {
    networkingService.resetpassword(email: emailTextField.text!)
}
</code>```

What I am trying to do is to dismiss the view and go back to previous viewController once the user has successfully resetted the password (basically if there are no errors and he has clicked ok on the alert.

Issue: cannot use dismiss in the struct. I have tried multiple solution but none of them have worked....
have tried this:

```<code>    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let loginVC = storyBoard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = loginVC
</code>```

but i cannot use any animation (so the effect is really ugly) and the real problem is that LoginVC is a tabbed view and when i get back like this the bottom tabbed bar is just not displayed...
I have lost almost an entire day on it... and i really don't know what else to try...
Hope someone can help me!
P.S. if i have written some stupid things... please forgive me... like i said i'm a newbie... :D

Thx!

答: I ran into a similar problem before, what you need to do is show the Tabbar controller and set the tab of it properly instead of showing just the LoginVC otherwise like you found, the tabbar at the bottom will disappear</p>

Body:
still new to Swift and trying to get around few issues i keep facing now and then... :)
Now i have created a Struct to manage the user login, sign up and recover passowrd...

So here's the part of the code is driving me crazy...

struct NetworkingService {

var dataBaseRef: FIRDatabaseReference!{
    return FIRDatabase.database().reference()
}
var storageRef: FIRStorageReference {
    return FIRStorage.storage().reference()
}
--------------------------------------------
// Reset Password
 func resetpassword(email: String){
    FIRAuth.auth()?.sendPasswordReset(withEmail: email, completion: { (error) in
        if error == nil{
            let alertView = UIAlertController(title: "SUCCESS!", message: "We have sent an email to \(email) with the information on how to reset your password. Thank you!", preferredStyle: UIAlertControllerStyle.alert)
            alertView.addAction(UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

            })
            UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil)

        } else{
            let alertView = UIAlertController(title: "Error!", message: "Error:\(error!.localizedDescription)", preferredStyle: UIAlertControllerStyle.alert)
            alertView.addAction(UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

            })
            UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil)
        }
    })
}

and in my controller i have a simple button which call this func

ResetPasswordVC{
@IBOutlet weak var emailTextField: UITextField!

var networkingService = NetworkingService()

override func viewDidLoad() {
    super.viewDidLoad()
}
 @IBAction func resetPasswordPressed(_ sender: Any) {
    networkingService.resetpassword(email: emailTextField.text!)
}

What I am trying to do is to dismiss the view and go back to previous viewController once the user has successfully resetted the password (basically if there are no errors and he has clicked ok on the alert.

Issue: cannot use dismiss in the struct. I have tried multiple solution but none of them have worked....
have tried this:

    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let loginVC = storyBoard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = loginVC

but i cannot use any animation (so the effect is really ugly) and the real problem is that LoginVC is a tabbed view and when i get back like this the bottom tabbed bar is just not displayed...
I have lost almost an entire day on it... and i really don't know what else to try...
Hope someone can help me!
P.S. if i have written some stupid things... please forgive me... like i said i'm a newbie... :D

Thx!


问:
.pfx files not valid for windows 10 release in phonegap
I have made an application using phonegap now I want to release in windows store but the thing is that since windows 10 has introduced they require .pfx certificate signing we have to create a signed certificate.

now as per this link http://docs.phonegap.com/phonegap-build/signing/windows/#winphone8 it redirect to windows page where mentined technology is (according to windows) deprecated.

I tried to make by openssl but when I build it with it I am getting error that "The certificate specified is not valid for signing. " I am stuck at this point please help me to resolve this.

NOTE:
I have also tried self signed certificate but then it ask for eku is not valid hence I have followed this link Certificate in windows .pfx file has EKU issue but seems it is also not working too.
Please help me out.
Is there any special guied-line for this?

Thanks in advance.

答:
Openssl or powershell won't work as expected. Do it this way.

Install the Microsoft Visual Studio (any), you will have option to choose what packages to install. Make sure you install the "Windows Software Development Kit".

Search for Visual Studio Command prompt (this is different from the usual cmd.exe). Then run the following codes.

Replace the CN value (can be found on MS Developer page > settings ) and replace app_name and password.

```<code>makecert.exe -n "CN=XXXXXX-XXXX-XXXX-XXXX-XXXXXX" -r -eku "1.3.6.1.5.5.7.3.3,1.3.6.1.4.1.311.10.3.13" -e "01/01/2020" -h 0 -sv app_name.pvk app_name.cer

pvk2pfx -pvk app_name.pvk -pi password -spc app_name.cer -pfx app_name.pfx -po password
</code>```

Now set phonegap version on your config.xml to cli-6.5.0

Tested and works perfectly.

Body:
Openssl or powershell won't work as expected. Do it this way.

Install the Microsoft Visual Studio (any), you will have option to choose what packages to install. Make sure you install the "Windows Software Development Kit".

Search for Visual Studio Command prompt (this is different from the usual cmd.exe). Then run the following codes.

Replace the CN value (can be found on MS Developer page > settings ) and replace app_name and password.

makecert.exe -n "CN=XXXXXX-XXXX-XXXX-XXXX-XXXXXX" -r -eku "1.3.6.1.5.5.7.3.3,1.3.6.1.4.1.311.10.3.13" -e "01/01/2020" -h 0 -sv app_name.pvk app_name.cer

pvk2pfx -pvk app_name.pvk -pi password -spc app_name.cer -pfx app_name.pfx -po password

Now set phonegap version on your config.xml to cli-6.5.0

Tested and works perfectly.


问:
Spring boot how to read properties file outside jar
in my target folder, there are 2 folders, lib and conf.   all the properties files are placed in conf folder, and jars are placed in lib foulder.

previous to spring boot, we use following configuration in spring.xml to use @value

```<code><context:property-placeholder location="classpath*:*.properties"/>
</code>```

and in java code like:

```<code>@Value("${name}")

private String name;
</code>```

but in spring boot, i don't know how to do the same in java code.

i have tried following, but not work

```<code>@Configuration
@PropertySource(value = "classpath:aaa.properties")
public class AppConfig {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
    }
}
</code>```

答:
I am not sure if you are dealing with the same situation than me, but in my case I have a jar and a *.properties file outside of it. What I did to get the  *.properties file located outside the jar was the next:

```<code>@Configuration
public class ApplicationContext {

  @Bean
  public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
    properties.setLocation(new FileSystemResource("application.properties"));
    properties.setIgnoreResourceNotFound(false);

    return properties;
  }
}
</code>```

When I am setting the location of the application.properties file I created FileSystemResource object, which allow me get the properties.files which is located next to the jar. If your .properties files are in classpath, for example, you can use other classes (like ClassPathResource). You can read other  classes that spring offers to get a Resource object under the package org.springframework.core.io. .

I hope this comments helps.

Body:
in my target folder, there are 2 folders, lib and conf.   all the properties files are placed in conf folder, and jars are placed in lib foulder.

previous to spring boot, we use following configuration in spring.xml to use @value

<context:property-placeholder location="classpath*:*.properties"/>

and in java code like:

@Value("${name}")

private String name;

but in spring boot, i don't know how to do the same in java code.

i have tried following, but not work

@Configuration
@PropertySource(value = "classpath:aaa.properties")
public class AppConfig {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
    }
}

Body:
I am not sure if you are dealing with the same situation than me, but in my case I have a jar and a *.properties file outside of it. What I did to get the  *.properties file located outside the jar was the next:

@Configuration
public class ApplicationContext {

  @Bean
  public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
    properties.setLocation(new FileSystemResource("application.properties"));
    properties.setIgnoreResourceNotFound(false);

    return properties;
  }
}

When I am setting the location of the application.properties file I created FileSystemResource object, which allow me get the properties.files which is located next to the jar. If your .properties files are in classpath, for example, you can use other classes (like ClassPathResource). You can read other  classes that spring offers to get a Resource object under the package org.springframework.core.io. .

I hope this comments helps.


问:
jQuery - set button title
I want to change the title of a button using jQuery

```<code><button id="pub2" class="pub2" title="ok">Bibtex</button>
<script>Tippy('.pub2', {interactive : true})</script>
</code>```

Also, I have a small paragraph to test

```<code><p id="testP">
   text
</p>
</code>```

To change the properties, I'm doing the following:

```<code>$(document).ready(function(){
   $("#testP").text("test worked");
   $("#pub2").attr("title", "new title not working");
});
</code>```

Updating the text of the paragraph works just fine, but the title of the button won't change, why?

答:
Your code working fine:-

$(document).ready(function(){
    $("#testP").text("test worked");
    $("#pub2").attr("title", "new title not working");// you can use prop() also
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="pub2" class="pub2" title="ok"> Bibtex </button>

<p id="testP">
 text
</p></code>```

Note:-

You have this code under button

```<code><script>Tippy('.pub2', {interactive : true})</script>
</code>```

Try to remove it from there and add into you script code like below:-

```<code>$(document).ready(function(){
  $("#testP").text("test worked");
  Tippy('.pub2', {interactive : true})
  $("#pub2").attr("title", "new title not working");// you can use prop() also
});
</code>```

Title: jQuery - set button title

Body:
I want to change the title of a button using jQuery

<button id="pub2" class="pub2" title="ok">Bibtex</button>

Also, I have a small paragraph to test

   text

To change the properties, I'm doing the following:

$(document).ready(function(){
   $("#testP").text("test worked");
   $("#pub2").attr("title", "new title not working");
});

Updating the text of the paragraph works just fine, but the title of the button won't change, why?

Body:
Your code working fine:-

$(document).ready(function(){
    $("#testP").text("test worked");
    $("#pub2").attr("title", "new title not working");// you can use prop() also
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="pub2" class="pub2" title="ok"> Bibtex </button>

<p id="testP">
 text
</p>

Note:-

You have this code under button

<script>Tippy('.pub2', {interactive : true})</script>

Try to remove it from there and add into you script code like below:-

$(document).ready(function(){
  $("#testP").text("test worked");
  Tippy('.pub2', {interactive : true})
  $("#pub2").attr("title", "new title not working");// you can use prop() also
});


问:
How to draw a "speech bubble" on an iPhone?
I'm trying to get a "speech bubble" effect similar to the one in Mac OS X when you right click on something in the dock.  Here's what I have now:

I need to get the "triangle" part of the lower portion.  Is there any way I can draw something like that and get a border around it?  This will be for an iPhone app.

Thanks in advance!

EDIT:  Many thanks to Brad Larson, here's what it looks like now:

答:
Perhaps a simpler question is "Is there code that does this for me already", to which the answer is "Yes".

Behold MAAttachedWindow:

Granted, you may not want the whole "Attached window" behavior, but at least the drawing code is already there.  (And Matt Gemmell's code is high quality stuff)


问:
ERROR "swiftc failed with exit code 1" when converting to latest syntax
I was trying to convert syntax of old Swift project to new one as per few suggestion on Stack Overflow I tried converting it through Edit > Convert > To latest Syntax that did not work properly instead I started getting new errors shown as below

Command/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
  failed with exit code 1

And

Command /usr/bin/ditto failed with exit code 1

I tried Xcode 6.0.1 Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1, but it's a different situation.

答:
In my case  I deleted few files from project and when try to commit the code, the files was showing there  . To solve this issue.
1. Open terminal
2. Type git clean -n // it will show you list of files which are deleted from project but  still are saved somewhere
3. Type git clean -f // All unwanted files will be removed</p>


问:
why do we need DTO/VIewModels rather than using partial classes in MVC Core?
I have an application in MVC CORE and in this application, i am using DTO/ViewModels. First I get from database and fill into the viewModels/DTOs.
DTOs are more helpful because we can customize it in our own way rather than Microsoft Entity Framework pure generated poco classes.  We can place data annotations, make more properties and can utilize them for more customization.

But now i am facing the performance issues from this layer/DTO/ViewModel.

Because For such large data, c# loops are much slowing down my application.

Can't/Shouldn't i use the Partial Classes and write data annotations and write our own properties there.

What will be the issue in it ?

答:
Because For such large data, c# loops are much slowing down my application

Use restrictions in queries. I dont know why you need 1,000,000 records at once. if you need the 1,000,000 records do paging.
Is not the fact that you are using EF objects directly that is going to give you performance.

You can use the partial classes in EF objects and add new properties and add them Annotations and all that, but my advice is don't use EF objects across your application.
You loose abstraction, low coupling, your Domain model shouldn't be aware of infrastructure concerns(EF). Model should be focus on Model. Look at Uncle Bob, Clean Architecure https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html for some insight. After reading you figure it out, why using EF objects could not be such a great idea.

This is a very vast topic to talk about. Hope help you with my 5 cents


问:
Swift 4: Implementation of a generic protocol with protocol as an associated type
I've experienced a problem during Swift 3.1 to Swift 4 codebase migration.

The problem arrises when you try to implement a generic protocol method that takes a closure with a generic parameter with a protocol as an associated type. It's easier than it sounds :)

The following code works fine in Swift 3.1:

protocol FooType {
    associatedtype BarType

    func foo(bar: BarType)
    func foo(action: (BarType) -> Void)
}

protocol Bar {}

class Foo: FooType {
    typealias BarType = Bar

    // Compiles in both 3.1 and 4
    func foo(bar: Bar) {
    }

    // ERROR: Candidate has non-matching type (Bar) -> Void
    func foo(action: (Bar) -> Void) {
    }
}
```

However in Swift 4 compiler gives me an error about class Foo not conforming to protocol FooType with foo(action:) method implementation missing.

By the way Xcode 9 "fix-it" generates the same implementation I have.

The code compiles if I use BarType as a parameter type, but it's not good to loose concrete type information.

答:
Turns out that removing the line

```<code>typealias BarType = Bar
</code>```

resolves the issue. Which is fair - type inference does its job.

Nevertheless, it should be a legal code and seems like a bug in compiler.

Reported accordingly.

Body:
I've experienced a problem during Swift 3.1 to Swift 4 codebase migration.

The problem arrises when you try to implement a generic protocol method that takes a closure with a generic parameter with a protocol as an associated type. It's easier than it sounds :)

The following code works fine in Swift 3.1:

protocol FooType {
    associatedtype BarType

    func foo(bar: BarType)
    func foo(action: (BarType) -> Void)
}

protocol Bar {}

class Foo: FooType {
    typealias BarType = Bar

    // Compiles in both 3.1 and 4
    func foo(bar: Bar) {
    }

    // ERROR: Candidate has non-matching type (Bar) -> Void
    func foo(action: (Bar) -> Void) {
    }
}

However in Swift 4 compiler gives me an error about class Foo not conforming to protocol FooType with foo(action:) method implementation missing.

By the way Xcode 9 "fix-it" generates the same implementation I have.

The code compiles if I use BarType as a parameter type, but it's not good to loose concrete type information.

Body:
Turns out that removing the line

typealias BarType = Bar

resolves the issue. Which is fair - type inference does its job.

Nevertheless, it should be a legal code and seems like a bug in compiler.

Reported accordingly.


问:
Benefits/Disadvantages of using XSL to render entire web pages
I am in the preliminary stages of planning a project with a client to redo their current website. I took a look at their current site to see what issues they are currently dealing with and upon inspection I noticed that every page is being rendered entirely using XSLT. I am familiar with XSLT, I have used it to render custom controls that need to be refreshed often on the client-side, but never to render an entire page. </p>

<p>Help me become less ignorant, what could be the reasoning behind this? What benefits or disadvantages does this bring to the table? </p>

答: I think XSLT is great when built the right way(We use a framework of templates at work).</p>

Body:
I am in the preliminary stages of planning a project with a client to redo their current website. I took a look at their current site to see what issues they are currently dealing with and upon inspection I noticed that every page is being rendered entirely using XSLT. I am familiar with XSLT, I have used it to render custom controls that need to be refreshed often on the client-side, but never to render an entire page.

Help me become less ignorant, what could be the reasoning behind this? What benefits or disadvantages does this bring to the table?

OwnerDisplayName: Sveisvei


问:
are there any Query Optimization Tools for SQL Server?
Are there any tools that do Query Optimizations for SQL Server 2005 and above?

I've searched & didn't find anything.

What do you recommend?

If this Question was repeated before you can close it but I didn't see anything similar

答:
As John Saunders commented, the best tool at your disposal is your own mind. Following bernd_k's comment, here are a few suggestions for sharpening that tool.

SQL Server 2008 Query Performance Tuning Distilled

Professional SQL Server 2008 Internals and Troubleshooting

SQL Server MVP Deep Dives


问:
Unknown column in where clause with CASE
What is the wrong here, or missing?

```<code>SELECT CASE WHEN (f_username = '$username' AND table1.code = table2.code) THEN '1'
            ELSE '0'
             END as is_favorite
 FROM (
      SELECT *
        FROM favorites
       WHERE f_username='$username'
         AND code = table2.code
     ) table1
INNER JOIN (
       SELECT *
         FROM groups
        WHERE gname LIKE '%$text%'
     ) table2
</code>```

there error is

Unknown column 'table2.code' in 'where clause'

EDIT

I have two tables (groups / favorites)

groups structure is:
gname / code

favorites structure is:
code / f_username

What am looking for is I want to get list of groups in specific query and I want to loop for each group check the favorites based on username if he added as favorite or not.

答:
I think this is what you are after:</p>

```<code>SELECT  gname, CASE WHEN favorites.code IS NULL THEN '0'
                ELSE '1'
                END as is_favorite
FROM    groups
WHERE   WHERE gname LIKE '%$text%'
LEFT JOIN favorites ON groups.code = favorites.code
</code>```

Body:
What is the wrong here, or missing?

SELECT CASE WHEN (f_username = '$username' AND table1.code = table2.code) THEN '1'
            ELSE '0'
             END as is_favorite
 FROM (
      SELECT *
        FROM favorites
       WHERE f_username='$username'
         AND code = table2.code
     ) table1
INNER JOIN (
       SELECT *
         FROM groups
        WHERE gname LIKE '%$text%'
     ) table2

there error is

Unknown column 'table2.code' in 'where clause'

EDIT

I have two tables (groups / favorites)

groups structure is:
gname / code

favorites structure is:
code / f_username

What am looking for is I want to get list of groups in specific query and I want to loop for each group check the favorites based on username if he added as favorite or not.

Body:
I think this is what you are after:

SELECT  gname, CASE WHEN favorites.code IS NULL THEN '0'
                ELSE '1'
                END as is_favorite
FROM    groups
WHERE   WHERE gname LIKE '%$text%'
LEFT JOIN favorites ON groups.code = favorites.code


问:
tsc tsconfig.json settings to compile to JS classes compatible with requirejs?
I have a Typescript interface, an abstract class (which implements the interface), and a class that extends the abstract class.  This Typescript library I'm building uses jQuery quite a bit and takes $ as an argument in it's constructor.

I'd like to use tsc to compile this into Javascript classes that will be included using reactjs, targeting Webkit / Safari 537.

I'm using requirejs to add jQuery and the generated library as follows:

```<code>define(["jquery","vham"],function ($,VHAM) {
    alert('$: ' + $);        // This exists
    alert('VHAM: ' + VHAM);  // This crashes
 ...
</code>```

js/app/main.js

All of my library javascript code is output to js/lib/vham.js; vham.js is the output of the tsc compiler.  What settings are appropriate in tsconfig.json for compiling my classes for use as a dependency included using requirejs?

答:
RequireJS uses Asynchronous Module Definition (AMD). You would need to tell tsc to generate modules in AMD format. Specifically you will need to set the --module flag to "AMD".

See the Typescript Compiler Options for more details:

https://www.typescriptlang.org/docs/handbook/compiler-options.html

Body:
I have a Typescript interface, an abstract class (which implements the interface), and a class that extends the abstract class.  This Typescript library I'm building uses jQuery quite a bit and takes $ as an argument in it's constructor.

I'd like to use tsc to compile this into Javascript classes that will be included using reactjs, targeting Webkit / Safari 537.

I'm using requirejs to add jQuery and the generated library as follows:

define(["jquery","vham"],function ($,VHAM) {
    alert('$: ' + $);        // This exists
    alert('VHAM: ' + VHAM);  // This crashes
 ...

js/app/main.js

All of my library javascript code is output to js/lib/vham.js; vham.js is the output of the tsc compiler.  What settings are appropriate in tsconfig.json for compiling my classes for use as a dependency included using requirejs?


问:
Exercise 1.9 of K&R book
I'm trying to solve the exercise 1.9 of the K&R book , 2nd edition , well I'll write here the exercise and then explain what I think that I need to do and then, my code and my doubts.

Exercise:

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

As far as I can understand, I need to make the program using what I learnt in the chapters before.

My view point is that I need to discover a way to say in the language of C that when appears more than one blank followed by another blank it will give me the phrase with only one blank. But how can I say to the computer that ?

```<code>#include <stdio.h>
/* ToDo - make a program where when the user input a phrase or
 * something that contains more than one blank followed by another
 * it will transform the input with only one blank */
int main()
{
    int c, b;
    b = ' ';
    while ((c = getchar()) != EOF){ /*don't need explanation*/
        /*my doubts start here , how can i say more than one blank ?*/
        /* or how can i say if the getchar has  one blank followed by another ?*/

        if (c == +b) /* trying to say if the getchar has more than one blank but i think this is not correct*/
            c = b;   /*then it will turn in only one blank*/
    }
    putchar(c);
}
</code>```

答:
Old question but because I just solved that exercise I thought about sharing it here:

```<code>#include <stdio.h>

int
main()
{
        int c, nspaces;

        nspaces = 0;
        c = getchar();

        while(c != EOF) {
                if (c == ' ') {
                        if (nspaces > 0) {
                                ++nspaces;
                        } else {
                                putchar(c);
                                ++nspaces;
                        }
                } else {
                        putchar(c);
                        nspaces = 0;
                }
                c = getchar();
        }

        return(0);
}
</code>```

For my solution I just have a counter that keeps track on how many consecutive empty space characters are found. Only if nspaces is 0 then c is printed back to the terminal. Finding a non space char resets the nspaces back to 0. With this there is no need to keep track of the previous char or calling getchar() multiple times.

Title: Exercise 1.9 of K&R book

Body:
I'm trying to solve the exercise 1.9 of the K&R book , 2nd edition , well I'll write here the exercise and then explain what I think that I need to do and then, my code and my doubts.

Exercise:

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

As far as I can understand, I need to make the program using what I learnt in the chapters before.

My view point is that I need to discover a way to say in the language of C that when appears more than one blank followed by another blank it will give me the phrase with only one blank. But how can I say to the computer that ?

#include <stdio.h>
/* ToDo - make a program where when the user input a phrase or
 * something that contains more than one blank followed by another
 * it will transform the input with only one blank */
int main()
{
    int c, b;
    b = ' ';
    while ((c = getchar()) != EOF){ /*don't need explanation*/
        /*my doubts start here , how can i say more than one blank ?*/
        /* or how can i say if the getchar has  one blank followed by another ?*/

        if (c == +b) /* trying to say if the getchar has more than one blank but i think this is not correct*/
            c = b;   /*then it will turn in only one blank*/
    }
    putchar(c);
}

Body:
Old question but because I just solved that exercise I thought about sharing it here:

#include <stdio.h>

int
main()
{
        int c, nspaces;

        nspaces = 0;
        c = getchar();

        while(c != EOF) {
                if (c == ' ') {
                        if (nspaces > 0) {
                                ++nspaces;
                        } else {
                                putchar(c);
                                ++nspaces;
                        }
                } else {
                        putchar(c);
                        nspaces = 0;
                }
                c = getchar();
        }

        return(0);
}

For my solution I just have a counter that keeps track on how many consecutive empty space characters are found. Only if nspaces is 0 then c is printed back to the terminal. Finding a non space char resets the nspaces back to 0. With this there is no need to keep track of the previous char or calling getchar() multiple times.