问:
Cassandra query failure (Tombstones)
So this is driving me crazy. i tried querying one of my table in Cassandra and it showed query failure. i tried digging dip in to the reason behind it and found that it was because of tombstone. i changed GC_GRACE_SECONDS to Zero and triggered Compaction using nodetool, And when i queried again it worked fine. however on a subsequent calls query failed again with a same reason. i am using cassandra-nodejs driver.
This is my data model.

```<code>CREATE TABLE my_table (
    firstname text,
    lastname text,
    email text,
    mobile text,
    date timeuuid,
    value float,
    PRIMARY KEY (firstname, lastname, email, mobile)
) WITH CLUSTERING ORDER BY (lastname ASC, email ASC, mobile ASC);
</code>```

this is the query i want to perform on that data model.

```<code>SELECT firstname, email, toDate(date) as date, mobile, value FROM my_table  WHERE date >= minTimeuuid('2017-03-25 00:00:00+0000') AND date <= minTimeuuid('2017-03-28 23:59:59+0000') ALLOW FILTERING;
</code>```

the result will have approx 40k rows.
this shows that if we delete something it will be marked as tombstone and will get deleted After GC_GRACE_SECONDS setted for given table. If i understand it correctly then.

how come there be tombstone problem when i never delete any row of table?

Is that true a row will be marked as Tombstone if and only if we delete a row?

clearing tombstones and then querying the same works sometimes and sometimes it does not, why is so?.

is it a good idea to increase tombstone_failure_threshold value? (single node cluster application)

I am using cassandra 3.5, with cqlsh version 5.0.1. And the query works fine with terminal, but gives error when we execute using external client (express app using nodejs driver for cassandra). i have a single node cluster app.

EDIT 1

This is the log of my Inserted null value in field (i inserted only name and timestamp);

```<code>  activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:28:27.342000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval45'; [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |             64
                                                       Preparing statement [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            101
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            210
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            223
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            243
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            288
                                         Read 2 live and 0 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            310
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            323
                                                                                Request complete | 2017-03-29 10:28:27.342385 | 172.31.34.179 |            385
</code>```

And this is the log when i query on filed which i have executed a delete query. Initially  user Dhaval15 has firstname 'aaaa' and then i the cell aaa. then again executing select query on same user gave me this log.

```<code>       activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:35:18.581000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval15'; [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |             65
                                                       Preparing statement [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            113
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            223
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            235
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            256
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            305
                                         Read 1 live and 1 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            338
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            351
                                                                                Request complete | 2017-03-29 10:35:18.581430 | 172.31.34.179 |            430
</code>```

答:
how come there be tombstone problem when i never delete any row of table?

@Ashraful Islam's answer is correct.

In addition,
If you explicitly insert data with NULL values, it will internally create tombstones.

Ex: insert into my_table (firstname,lastname,email,mobile, .....) values ('abd', 'gef', 'xxx@abc.com', '+67899...', null, null, .....);

There will be null values for other columns (internally generating tombstones as Cassandra has to indicate with something that those columns do not exists or have values).

As you have mentioned too many columns as primary keys it will create too large wide rows (which is also  discouraged) with too many null values thus end up with lots of tombstones. It may have crossed the threshold limit in you case.

As @Ashraful stated this data model is not okay. As you need to query by time
you should design your model such that you can do some range queries on time. Query without mentioning partition key thus using ALLOW FILTERING in a large data set is an anti-pattern in Cassandra.

Is that true a row will be marked as Tombstone if and only if we delete a row?

You can delete a complete or a specific column. If a row is deleted, the entire row is marked as tombstone. If a specific column is deleted (or insert/UPDATE NULL value) tombstones will be created on that specific column (which is also discouraged) I guess that happens in your case.

clearing tombstones and then querying the same works sometimes and sometimes it does not, why is so?.

I think you may now determine why this happens :).

is it a good idea to increase tombstone_failure_threshold value? (single node cluster application)

Increasing tombstone_failure_threshold will just lessen the amount of error but does not solve the actual problem. It will not increase performance and cross the threshold as data set increases.

And importantly, in single node cluster application you can set GC_GRACE_SECONDS to 0. Tombstones will be deleted instantly after compaction occurs. GC_GRACE_SECONDS is vital while using multi-node cluster which is the actual purpose of using NoSQL I guess.

Title: Cassandra query failure (Tombstones)

Body:
So this is driving me crazy. i tried querying one of my table in Cassandra and it showed query failure. i tried digging dip in to the reason behind it and found that it was because of tombstone. i changed GC_GRACE_SECONDS to Zero and triggered Compaction using nodetool, And when i queried again it worked fine. however on a subsequent calls query failed again with a same reason. i am using cassandra-nodejs driver.
This is my data model.

CREATE TABLE my_table (
    firstname text,
    lastname text,
    email text,
    mobile text,
    date timeuuid,
    value float,
    PRIMARY KEY (firstname, lastname, email, mobile)
) WITH CLUSTERING ORDER BY (lastname ASC, email ASC, mobile ASC);

this is the query i want to perform on that data model.

SELECT firstname, email, toDate(date) as date, mobile, value FROM my_table  WHERE date >= minTimeuuid('2017-03-25 00:00:00+0000') AND date <= minTimeuuid('2017-03-28 23:59:59+0000') ALLOW FILTERING;

the result will have approx 40k rows.
this shows that if we delete something it will be marked as tombstone and will get deleted After GC_GRACE_SECONDS setted for given table. If i understand it correctly then.

how come there be tombstone problem when i never delete any row of table?

Is that true a row will be marked as Tombstone if and only if we delete a row?

clearing tombstones and then querying the same works sometimes and sometimes it does not, why is so?.

is it a good idea to increase tombstone_failure_threshold value? (single node cluster application)

I am using cassandra 3.5, with cqlsh version 5.0.1. And the query works fine with terminal, but gives error when we execute using external client (express app using nodejs driver for cassandra). i have a single node cluster app.

EDIT 1

This is the log of my Inserted null value in field (i inserted only name and timestamp);

  activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:28:27.342000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval45'; [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |             64
                                                       Preparing statement [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            101
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            210
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            223
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            243
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            288
                                         Read 2 live and 0 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            310
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            323
                                                                                Request complete | 2017-03-29 10:28:27.342385 | 172.31.34.179 |            385

And this is the log when i query on filed which i have executed a delete query. Initially  user Dhaval15 has firstname 'aaaa' and then i the cell aaa. then again executing select query on same user gave me this log.

       activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:35:18.581000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval15'; [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |             65
                                                       Preparing statement [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            113
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            223
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            235
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            256
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            305
                                         Read 1 live and 1 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            338
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            351
                                                                                Request complete | 2017-03-29 10:35:18.581430 | 172.31.34.179 |            430


来源: stackexchange

问:
Android - Custom EditText prefix color
I've created a prefix modification for my custom EditText by the help of SO and Copy Paste.

Here's the particular code for prefix :

```<code>private String mPrefix = "";
private Rect mPrefixRect = new Rect();

public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

private void applyPrefix(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);
    String fontFace;

    try {
        fontFace = a.getString(R.styleable.OpenSansET_prefix);
    } finally {
        a.recycle();
    }
    if (fontFace != null){
        mPrefix = fontFace;
    } else {
        mPrefix = "";
    }
}

protected void setmPrefix(String prefix){
    this.mPrefix = prefix;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")){
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}
</code>```

Basically what it does is if I've supplied a prefix from xml or through code, it draws that prefix onto the start of the EditText. For example :

```<code><com.asta.classes.OpenSansEditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/min"
    app:prefix="$"/>
</code>```

This code produces :

But the problem is, if I set textColorHint, the color of the prefix will be the same as the color of the hint like :

How to modify the color of the prefix to a specified color? In my case it is to let it have its own color rather than using hint color.

答:
Update onDraw method

E.g:

```<code>@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        Paint paint = getPaint();
        paint.setColor(color);
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android - Custom EditText prefix color

Body:
I've created a prefix modification for my custom EditText by the help of SO and Copy Paste.

Here's the particular code for prefix :

private String mPrefix = "";
private Rect mPrefixRect = new Rect();

public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

private void applyPrefix(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);
    String fontFace;

    try {
        fontFace = a.getString(R.styleable.OpenSansET_prefix);
    } finally {
        a.recycle();
    }
    if (fontFace != null){
        mPrefix = fontFace;
    } else {
        mPrefix = "";
    }
}

protected void setmPrefix(String prefix){
    this.mPrefix = prefix;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")){
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}

Basically what it does is if I've supplied a prefix from xml or through code, it draws that prefix onto the start of the EditText. For example :

<com.asta.classes.OpenSansEditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/min"
    app:prefix="$"/>

This code produces :

But the problem is, if I set textColorHint, the color of the prefix will be the same as the color of the hint like :

How to modify the color of the prefix to a specified color? In my case it is to let it have its own color rather than using hint color.

Body:
Update onDraw method

E.g:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        Paint paint = getPaint();
        paint.setColor(color);
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
    }
}


问:
Apple API fsckup: how do I make unsafepointerof 0 a.k.a. NULL / 0x0 in swift?
I have a case when parameter should have been UIViewController!
to map from objc properly, but it is, sadly, UIViewController.

This

```<code>func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController currentVC: UIViewController) -> UIViewController? {
    guard unsafeAddressOf(currentVC).hashValue != 0 else { // 31316097 filed with apple
</code>```

feels a bit fragile. hashValue might map to 0 for pointers other than 0x0.
How do I make an unsafe pointer for NULL to compare unsafeAddressOf(currentVC) against?

Swift 2.3 in case it's a typical lets do with for swift 2 but but but we have made it much, much better in swift 3! Kind of answer is required.

答: currentVC can't be nil. It's not an Optional type.

Body:
I have a case when parameter should have been UIViewController!
to map from objc properly, but it is, sadly, UIViewController.

This

func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController currentVC: UIViewController) -> UIViewController? {
    guard unsafeAddressOf(currentVC).hashValue != 0 else { // 31316097 filed with apple

feels a bit fragile. hashValue might map to 0 for pointers other than 0x0.
How do I make an unsafe pointer for NULL to compare unsafeAddressOf(currentVC) against?

Swift 2.3 in case it's a typical lets do with for swift 2 but but but we have made it much, much better in swift 3! Kind of answer is required.


问:
How do you set an ssh key for docker image containing a private git repo?
I'm trying to get a docker image to build that requires it to clone a private github repo.</p>

答:
I had a hard time figuring out how to do this without copying my ssh keys over - my eventual solution was to use a github basic auth token in URL format passed into docker as a build argument.

In Dockerfile

ARG GITHUB_URL
RUN git config --global url.$GITHUB_URL.insteadOf "https://github.com/"

RUN go get -u github.com/YOUR_USERNAME/YOUR_REPO

When Building

docker build -t YOUR_TAG . --build-arg GITHUB_URL="https://[YOUR_GITHUB_TOKEN]:x-oauth-basic@github.com/"


问:
Why another user is required to run hadoop?
I have a question regarding hadoop configuration
why we need to create a user for running hadoop can we not run hadoop on a root user?</p>

答: It is not at all required to create a new user to run hadoop. Also, hadoop user need not be (should not be) in sudoers file or a root user [ref]. Your login user for the machine can also act as a hadoop user. But as mentioned by @Luis and @franklinsijo, it is a good practice to have a specific user for a specific service.</p>


问:
Android hint not showing in edit text
Here my edit text

```<code>   <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/orange"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="Drawer With Swipe Tabs" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

        <EditText
                android:id="@+id/editMobileNo"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:background="@drawable/login_edittext"
                android:textColor="@color/orange"
                android:hint="@string/search"
                android:drawableLeft="@drawable/search1"
                android:gravity="left"
                android:layout_weight="0.9">
            </EditText>
            <ImageButton
                android:layout_width="0dp"
                android:layout_height="30dp"
                android:layout_weight="0.1"
                android:layout_margin="5dp"
                android:ems="10"
                android:background="@drawable/alarm1"
                android:gravity="center"
                >
            </ImageButton>
        </LinearLayout>

</android.support.v7.widget.Toolbar>
</code>```

Here @drawable/login_edittext

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:endColor="@color/white"
                android:startColor="@color/white" />
            <stroke
                android:width="1dp"
                android:color="@color/orange" />
            <corners
                android:bottomRightRadius="15dp"
                android:bottomLeftRadius="15dp"
                android:topLeftRadius="15dp"
                android:topRightRadius="15dp" />
            <padding
                android:bottom="10dp"

                android:right="10dp"
                android:top="10dp" />
        </shape>
    </item>

</selector>
</code>```

Here my @style/ThemeOverlay.AppCompat.Dark.ActionBar

```<code><style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:textColorHint">@android:color/holo_orange_dark</item>
</style>
</code>```

Here android:hint is not visible in my edit text.

答:
Use attribute android:textColorHint to change hint text color.

For example: I have used android:textColorHint="#000000" to set color BLACK as hint text color.

Update your EditText as below:

```<code><EditText
    android:id="@+id/editMobileNo"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_marginTop="5dp"
    android:background="@drawable/login_edittext"
    android:textColor="@color/orange"
    android:hint="@string/search"
    android:textColorHint="#000000"
    android:drawableLeft="@drawable/search1"
    android:gravity="left"
    android:layout_weight="0.9">
</EditText>
</code>```

Hope this will help~

Title: Android hint not showing in edit text

Body:
Here my edit text

   <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/orange"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="Drawer With Swipe Tabs" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

        <EditText
                android:id="@+id/editMobileNo"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:background="@drawable/login_edittext"
                android:textColor="@color/orange"
                android:hint="@string/search"
                android:drawableLeft="@drawable/search1"
                android:gravity="left"
                android:layout_weight="0.9">
            </EditText>
            <ImageButton
                android:layout_width="0dp"
                android:layout_height="30dp"
                android:layout_weight="0.1"
                android:layout_margin="5dp"
                android:ems="10"
                android:background="@drawable/alarm1"
                android:gravity="center"
                >
            </ImageButton>
        </LinearLayout>

</android.support.v7.widget.Toolbar>

Here @drawable/login_edittext

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:endColor="@color/white"
                android:startColor="@color/white" />
            <stroke
                android:width="1dp"
                android:color="@color/orange" />
            <corners
                android:bottomRightRadius="15dp"
                android:bottomLeftRadius="15dp"
                android:topLeftRadius="15dp"
                android:topRightRadius="15dp" />
            <padding
                android:bottom="10dp"

                android:right="10dp"
                android:top="10dp" />
        </shape>
    </item>

</selector>

Here my @style/ThemeOverlay.AppCompat.Dark.ActionBar

Here android:hint is not visible in my edit text.

Body:
Use attribute android:textColorHint to change hint text color.

For example: I have used android:textColorHint="#000000" to set color BLACK as hint text color.

Update your EditText as below:

<EditText
    android:id="@+id/editMobileNo"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_marginTop="5dp"
    android:background="@drawable/login_edittext"
    android:textColor="@color/orange"
    android:hint="@string/search"
    android:textColorHint="#000000"
    android:drawableLeft="@drawable/search1"
    android:gravity="left"
    android:layout_weight="0.9">
</EditText>

Hope this will help~


问:
Can't find named elements
Something is not clicking for me with this code:

```<code>var cfgDoc = XElement.Load(_cfgFile);
foreach (var x in cfgDoc.Elements("property"))
{
    Console.WriteLine(x);
}
</code>```

I am expecting to be able to output only nodes that are named property, but getting zilch. If I leave the XName parameter out, I get the document (below), which shows at least it is being loaded correctly.

What am I missing?

<session-factory xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.release_mode">on_close</property>
    <property name="show_sql">true</property>
</session-factory>
```

<p><strong>2nd try</strong></p>

```var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
var properties = cfgDoc.Elements(ns + "property");
Assert.That(properties.Count() > 0);
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}
```

答:
You haven't provided the namespace which is effectively inherited by the child elements. Try this:</p>

```<code>var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}
</code>```

Title: Can't find named elements

Body:
Something is not clicking for me with this code:

var cfgDoc = XElement.Load(_cfgFile);
foreach (var x in cfgDoc.Elements("property"))
{
    Console.WriteLine(x);
}

I am expecting to be able to output only nodes that are named property, but getting zilch. If I leave the XName parameter out, I get the document (below), which shows at least it is being loaded correctly.

What am I missing?

<session-factory xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.release_mode">on_close</property>
    <property name="show_sql">true</property>
</session-factory>

2nd try

var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
var properties = cfgDoc.Elements(ns + "property");
Assert.That(properties.Count() > 0);
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}

Body:
You haven't provided the namespace which is effectively inherited by the child elements. Try this:

var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}

ContentLicense: CC BY-SA 2.5


问:
How to insert images to TImagelist in FireMonkey programmaticaly?
I try to populate TListView

Current code

```<code>MyList.Items.Clear;
 for I := 0 to List.Count-1 do
  begin
  Item:=  MyList.Items.Add;
  Item.Text:= List[i];

  si:=ImageList.Source.Add;
  src:='https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg';
  ms:=LoadWebImage(src);
  si. MultiResBitmap.LoadItemFromStream( ms,100);

  Item.ImageIndex := i;

  end;
</code>```

Images loaded without errors

```<code> function LoadWebImage(url: string) : TMemoryStream;
        var
          idhttp : TIdHTTP;
        begin
          IdHTTP := TIdHTTP.Create(nil);
          Result := TMemoryStream.Create;
          try
            idhttp.Get (url, Result);
            Result.Position := 0;
          finally
            idhttp.Free;
          end;
        end;
</code>```

In result i see only text and one image when i added manually for test

ItemAppeariance set as ImageListItem

答:
Here is simple helper for TImageList

```<code>type
  TImageListHelper = class helper for TImageList
    function Add(aBitmap: TBitmap): integer;
  end;

function TImageListHelper.Add(aBitmap: TBitmap): integer;
const
  SCALE = 1;
var
  vSource: TCustomSourceItem;
  vBitmapItem: TCustomBitmapItem;
  vDest: TCustomDestinationItem;
  vLayer: TLayer;
begin
  Result := -1;
  if (aBitmap.Width = 0) or (aBitmap.Height = 0) then exit;

  // add source bitmap
  vSource := Source.Add;
  vSource.MultiResBitmap.TransparentColor := TColorRec.Fuchsia;
  vSource.MultiResBitmap.SizeKind := TSizeKind.Source;
  vSource.MultiResBitmap.Width := Round(aBitmap.Width / SCALE);
  vSource.MultiResBitmap.Height := Round(aBitmap.Height / SCALE);
  vBitmapItem := vSource.MultiResBitmap.ItemByScale(SCALE, True, True);
  if vBitmapItem = nil then
  begin
    vBitmapItem := vSource.MultiResBitmap.Add;
    vBitmapItem.Scale := Scale;
  end;
  vBitmapItem.Bitmap.Assign(aBitmap);

  vDest := Destination.Add;
  vLayer := vDest.Layers.Add;
  vLayer.SourceRect.Rect := TRectF.Create(TPoint.Zero, vSource.MultiResBitmap.Width,
      vSource.MultiResBitmap.Height);
  vLayer.Name := vSource.Name;
  Result := vDest.Index;
end;
</code>```

Then you can easily add an image in Image list:

```<code>ImageList1.Add(MyBitmap);
</code>```

Body:
I try to populate TListView

Current code

MyList.Items.Clear;
 for I := 0 to List.Count-1 do
  begin
  Item:=  MyList.Items.Add;
  Item.Text:= List[i];

  si:=ImageList.Source.Add;
  src:='https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg';
  ms:=LoadWebImage(src);
  si. MultiResBitmap.LoadItemFromStream( ms,100);

  Item.ImageIndex := i;

  end;

Images loaded without errors

 function LoadWebImage(url: string) : TMemoryStream;
        var
          idhttp : TIdHTTP;
        begin
          IdHTTP := TIdHTTP.Create(nil);
          Result := TMemoryStream.Create;
          try
            idhttp.Get (url, Result);
            Result.Position := 0;
          finally
            idhttp.Free;
          end;
        end;

In result i see only text and one image when i added manually for test

ItemAppeariance set as ImageListItem

Body:
Here is simple helper for TImageList

type
  TImageListHelper = class helper for TImageList
    function Add(aBitmap: TBitmap): integer;
  end;

function TImageListHelper.Add(aBitmap: TBitmap): integer;
const
  SCALE = 1;
var
  vSource: TCustomSourceItem;
  vBitmapItem: TCustomBitmapItem;
  vDest: TCustomDestinationItem;
  vLayer: TLayer;
begin
  Result := -1;
  if (aBitmap.Width = 0) or (aBitmap.Height = 0) then exit;

  // add source bitmap
  vSource := Source.Add;
  vSource.MultiResBitmap.TransparentColor := TColorRec.Fuchsia;
  vSource.MultiResBitmap.SizeKind := TSizeKind.Source;
  vSource.MultiResBitmap.Width := Round(aBitmap.Width / SCALE);
  vSource.MultiResBitmap.Height := Round(aBitmap.Height / SCALE);
  vBitmapItem := vSource.MultiResBitmap.ItemByScale(SCALE, True, True);
  if vBitmapItem = nil then
  begin
    vBitmapItem := vSource.MultiResBitmap.Add;
    vBitmapItem.Scale := Scale;
  end;
  vBitmapItem.Bitmap.Assign(aBitmap);

  vDest := Destination.Add;
  vLayer := vDest.Layers.Add;
  vLayer.SourceRect.Rect := TRectF.Create(TPoint.Zero, vSource.MultiResBitmap.Width,
      vSource.MultiResBitmap.Height);
  vLayer.Name := vSource.Name;
  Result := vDest.Index;
end;

Then you can easily add an image in Image list:

ImageList1.Add(MyBitmap);


问:
Avoiding complex if statements
I have the following function

```<code>const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}
</code>```

is there a better way to express this? How would such a code be written in functional programming style

答:
You can also try something like this:

Instead of creating a block section, for if(type), make it if(!type) as in that case you would return a function call.

Instead of a && b and then a, simply check, if a exists, then check for b and return accordingly. If a does not exists, there is no need to check for b

Ternary operator

const getVal = (type, a, b, val) => {
  if(!type) return toPx(val);
  return a ? (b ? val : toPercent(val) ) : undefined;
}
```

<h3>if..else ladder</h3>

<pre class="lang-js prettyprint-override"><code>const getVal = (type, a, b, val) => {
  if(!type) return toPx(val);
  if(a){
    if(b) return val;
    return toPercent(val);
  }
}
</code>```

Title: Avoiding complex if statements

Body:
I have the following function

const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}

is there a better way to express this? How would such a code be written in functional programming style

Body:
You can also try something like this:

Instead of creating a block section, for if(type), make it if(!type) as in that case you would return a function call.

Instead of a && b and then a, simply check, if a exists, then check for b and return accordingly. If a does not exists, there is no need to check for b

Ternary operator

const getVal = (type, a, b, val) => {
  if(!type) return toPx(val);
  return a ? (b ? val : toPercent(val) ) : undefined;
}

if..else ladder

const getVal = (type, a, b, val) => {
  if(!type) return toPx(val);
  if(a){
    if(b) return val;
    return toPercent(val);
  }
}


问:
App fails to compile and run in Android Studio
I have made a basic application with one Splash Screen Activity and one Main Screen Activity(with Navigation Drawer). When I click "Run" Button, one error is shown in the Messages Box.

Android Studio Version: 2.2.3.

The code in build.gradle:

```<code>    buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

The error goes as this:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Could not expand ZIP 'C:\Users\vijtech\AndroidStudioProjects\Deadline\app\build\intermediates\exploded-aar\com.android.support\design\25.3.1\jars\classes.jar'.

Please help. Thanks in advance.

答: It looks like you don't have permission to the file. Double check if you can read or write to that folder.</p>

Body:
I have made a basic application with one Splash Screen Activity and one Main Screen Activity(with Navigation Drawer). When I click "Run" Button, one error is shown in the Messages Box.

Android Studio Version: 2.2.3.

The code in build.gradle:

    buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

The error goes as this:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Could not expand ZIP 'C:\Users\vijtech\AndroidStudioProjects\Deadline\app\build\intermediates\exploded-aar\com.android.support\design\25.3.1\jars\classes.jar'.

Please help. Thanks in advance.


问:
Unable to display local image icon on Google Maps with rails helpers image_tag or image_path
I'm setting a marker icon picture on my google maps and it works perfectly when I pass in an url, but when I set an image_tag that links to a local asset, it finds the asset but does not display it on the map. Here is my code:

@home.marker(view_context.image_path("i-home.png", size: '80x80', class: 'text-size'))

the helper gives me the following path

"/assets/i-home-afcc4167c5d6c4a0bffbe87848bb9694437b7f506c3fb5465fe597642d6a41f2.png"

I am also wondering why it doesn't work without the 'view_context', which used to work before.

I have even tried to add css attributes as well :

```<code>.text-size {
  width: 80px !important;
  height: 80px !important;
}
</code>```

Here is the code with url that works :

```<code>@home.marker("http://res.cloudinary.com/dndagbvyi/image/upload/c_scale,w_80/v1490692341/dog-shadow-02_m1vpet.png")
</code>```

And the 'marker' method :

```<code>    def marker(image)
      Gmaps4rails.build_markers(self) do |address, marker|
      marker.lat address.latitude
      marker.lng address.longitude
      marker.infowindow address.name
      marker.picture({
                  anchor: [40, 58],
                  url: image,
                  width: 500,
                  height: 500,
                 })
     end
   end
</code>```

答:
Try using single parameter to image_path method.</p>

```<code>@home.marker(view_context.image_path("i-home.png"))
</code>```

Body:
I'm setting a marker icon picture on my google maps and it works perfectly when I pass in an url, but when I set an image_tag that links to a local asset, it finds the asset but does not display it on the map. Here is my code:

@home.marker(view_context.image_path("i-home.png", size: '80x80', class: 'text-size'))

the helper gives me the following path

"/assets/i-home-afcc4167c5d6c4a0bffbe87848bb9694437b7f506c3fb5465fe597642d6a41f2.png"

I am also wondering why it doesn't work without the 'view_context', which used to work before.

I have even tried to add css attributes as well :

.text-size {
  width: 80px !important;
  height: 80px !important;
}

Here is the code with url that works :

@home.marker("http://res.cloudinary.com/dndagbvyi/image/upload/c_scale,w_80/v1490692341/dog-shadow-02_m1vpet.png")

And the 'marker' method :

    def marker(image)
      Gmaps4rails.build_markers(self) do |address, marker|
      marker.lat address.latitude
      marker.lng address.longitude
      marker.infowindow address.name
      marker.picture({
                  anchor: [40, 58],
                  url: image,
                  width: 500,
                  height: 500,
                 })
     end
   end

Body:
Try using single parameter to image_path method.

@home.marker(view_context.image_path("i-home.png"))


问:
Java : Occurances of a character in a String
I need help on my code in Java.

This is the problem :

Example input : AaaaaAa

Output : A appears 7.

The problem is I need it to ignore cases.

Please help me, my code works fine, except that it doesn't ignore cases.

```<code>import java.io.*;

public class letter_bmp{
    public static BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
    public static void main(String[] args) throws Exception

    {

    String string1;
    String pick;

    String ans;
    do
    {
    int count=0;
    System.out.print("En taro Adun, Executor! Input desired string : ");
    string1 = input.readLine();
    System.out.print("Now, Executor...which character shall I choose : ");
    pick = input.readLine();

    for(int counter = 0; counter < string1.length(); counter++)
        {
        if(pick.charAt(0) == string1.charAt(counter))
        count++;
        }
    System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+".");

    System.out.println("\nWould you like to try again, Executor? (Yes/No): ");
    ans = input.readLine();
    }
    while(ans.equalsIgnoreCase("Yes"));
    }

}
</code>```

答:
I understand that the question is old and the OP might have got his answer. But i am putting this out here just in case if anybody needs it in the future.</p>

```<code>public static void main(String[] args) {
    String s="rEmember";

    for(int i = 0; i <= s.length() - 1; i++){
        int count = 0;
        for(int j = 0; j <= s.length() - 1; j++){
            if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){
                count++;
            }
        }
        System.out.println(s.charAt(i) + " = " + count + " times");
    }

}
</code>```

Body:
I need help on my code in Java.

This is the problem :

Example input : AaaaaAa

Output : A appears 7.

The problem is I need it to ignore cases.

Please help me, my code works fine, except that it doesn't ignore cases.

import java.io.*;

public class letter_bmp{
    public static BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
    public static void main(String[] args) throws Exception

    {

    String string1;
    String pick;

    String ans;
    do
    {
    int count=0;
    System.out.print("En taro Adun, Executor! Input desired string : ");
    string1 = input.readLine();
    System.out.print("Now, Executor...which character shall I choose : ");
    pick = input.readLine();

    for(int counter = 0; counter < string1.length(); counter++)
        {
        if(pick.charAt(0) == string1.charAt(counter))
        count++;
        }
    System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+".");

    System.out.println("\nWould you like to try again, Executor? (Yes/No): ");
    ans = input.readLine();
    }
    while(ans.equalsIgnoreCase("Yes"));
    }

}

Body:
I understand that the question is old and the OP might have got his answer. But i am putting this out here just in case if anybody needs it in the future.

public static void main(String[] args) {
    String s="rEmember";

    for(int i = 0; i <= s.length() - 1; i++){
        int count = 0;
        for(int j = 0; j <= s.length() - 1; j++){
            if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){
                count++;
            }
        }
        System.out.println(s.charAt(i) + " = " + count + " times");
    }

}


问:
Efficient way of parsing Jax-ws Restful Response
I need to parse the jax-ws rest response and I tried the following two ways of parsing the response.Both works good.But I am in need to know the best efficient way of implementation.Please provide me your view.

First Approach:

Use getEntity Object and get the response as Input Stream.

Using Jackson ObjectMapper readValue() -covert the inputstream to java
object.

Using getters and setters of nested java class get the response objects member values.

Second Approach:

Use getEntity Object and get the response as Input Stream and and
convert the Input Stream to String.

Using Google Json API,convert the string to json object.

Using Json parser and get the nested objects member values.

答:
I would say the first approach is better for two reasons:

You don't go through the intermediate process of reading the response payload into String

The setter methods that are called during Jackson deserialization may perform validation on input and throw appropriate exceptions, so you do validation during deserialization.


问:
Stored procedure expects parameter though parameter is provided
I am using VS 2015 and SQL Server 2016.

In my C# code, I am assigning the parameters which my stored procedure expects, but am getting an error as my stored procedure is expecting a parameter.

My stored procedure:

```<code>CREATE PROCEDURE [dbo].[SDDeleteTAR]
    @TARKey int
AS
BEGIN
    DELETE technical_assistance_requests
    WHERE request_id = @TARKey
END
</code>```

My C# code:

```<code>Label id = (Label)e.Item.FindControl("REQUEST_ID");
var x = id.Text;
int rid = Convert.ToInt32(x);

string cs = ConfigurationManager.AppSettings.Get("connectionString").ToString();

using (SqlConnection con = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@RequestID", rid);

    con.Open();
    cmd.ExecuteNonQuery();
}
</code>```

When I run this, I get this error:

Procedure or function 'SDDeleteTAR' expects parameter '@TARKey', which was not supplied.

I am passing the required parameters and executing my command type as CommandType.StoredProcedure, and am not able to resolve this.

I also checked the same issue in StackOverflow here but the submitter is missing the command type declaration.

Any help is appreciated, in pointing out where I am going wrong.

答:
You can safely execute a stored procedure without directly specifying the names, by using SqlCommandBuilder.DeriveParameters. This will retrieve the parameters from the server and create the SQLParameter collection for you.</p>

```<code>SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
SqlCommandBuilder.DeriveParameters(cmd);
cmd.Parameters[0].Value = rid;
</code>```

Body:
I am using VS 2015 and SQL Server 2016.

In my C# code, I am assigning the parameters which my stored procedure expects, but am getting an error as my stored procedure is expecting a parameter.

My stored procedure:

CREATE PROCEDURE [dbo].[SDDeleteTAR]
    @TARKey int
AS
BEGIN
    DELETE technical_assistance_requests
    WHERE request_id = @TARKey
END

My C# code:

Label id = (Label)e.Item.FindControl("REQUEST_ID");
var x = id.Text;
int rid = Convert.ToInt32(x);

string cs = ConfigurationManager.AppSettings.Get("connectionString").ToString();

using (SqlConnection con = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@RequestID", rid);

    con.Open();
    cmd.ExecuteNonQuery();
}

When I run this, I get this error:

Procedure or function 'SDDeleteTAR' expects parameter '@TARKey', which was not supplied.

I am passing the required parameters and executing my command type as CommandType.StoredProcedure, and am not able to resolve this.

I also checked the same issue in StackOverflow here but the submitter is missing the command type declaration.

Any help is appreciated, in pointing out where I am going wrong.

Body:
You can safely execute a stored procedure without directly specifying the names, by using SqlCommandBuilder.DeriveParameters. This will retrieve the parameters from the server and create the SQLParameter collection for you.

SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
SqlCommandBuilder.DeriveParameters(cmd);
cmd.Parameters[0].Value = rid;


问:
Can the Android drawable directory contain subdirectories?
In the Android SDK documentation, all of the examples used with the @drawable/my_image xml syntax directly address images that are stored in the res/drawable directory in my project.

I am wondering if it is explicitly not okay to create a sub directory within the drawable directory.

For example, if I had the following directory layout:

```<code>res/drawable
-- sandwiches
  -- tunaOnRye.png
  -- hamAndSwiss.png
-- drinks
  -- coldOne.png
  -- hotTea.png
</code>```

Could I reference the image of a tuna salad sandwich as @drawable/sandwiches/tunaOnRye

Or do I have to keep the hierarchy flat in the drawable directory.

答:
create a folder in main.
 like: 'res_notification_btn'

and create tree folder in. like 'drawable' or 'layout'

then in 'build.gradle' add this

```<code>sourceSets
            {
                main
                {
                    res
                    {
                        srcDirs = ['src/main/res_notification_btn', 'src/main/res']
                      or
                        srcDir 'src/main/res_notification_btn'
                    }
                }
            }
</code>```

Body:
In the Android SDK documentation, all of the examples used with the @drawable/my_image xml syntax directly address images that are stored in the res/drawable directory in my project.

I am wondering if it is explicitly not okay to create a sub directory within the drawable directory.

For example, if I had the following directory layout:

res/drawable
-- sandwiches
  -- tunaOnRye.png
  -- hamAndSwiss.png
-- drinks
  -- coldOne.png
  -- hotTea.png

Could I reference the image of a tuna salad sandwich as @drawable/sandwiches/tunaOnRye

Or do I have to keep the hierarchy flat in the drawable directory.

Body:
create a folder in main.
 like: 'res_notification_btn'

and create tree folder in. like 'drawable' or 'layout'

then in 'build.gradle' add this

sourceSets
            {
                main
                {
                    res
                    {
                        srcDirs = ['src/main/res_notification_btn', 'src/main/res']
                      or
                        srcDir 'src/main/res_notification_btn'
                    }
                }
            }


问:
Valid SSL cert for laptop not connected to the internet
We have a laptop which isn't connected to the internet via wifi or mobile data, it has a wifi hotspot which is used to serve a website to an android phone. We want to demonstrate a webpage which uses the appcache technology on the phone

The problem is in chrome you require a valid certificate for a appcache, but how do you get a certificate for a laptop which isn't connected to anything?

答:
In case the laptop is running linux.
You could try to create your own self-signed certificate using openssl.

```<code>openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
</code>```

Body:
In case the laptop is running linux.
You could try to create your own self-signed certificate using openssl.

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365


问:
LDAP authentication in Docker container
By default, when Docker container is started the user inside is sudo.

I want:

Lock sudo user in container by default.

Use LDAP authentication in container instead of the default (when the users are provided along with the image, or created by sudo user when container is running).

For that, I ran a container and configured it to communicate with LDAP server. Next, I created an image from this container.

Now, I can run a container using this image (but only as a sudo user) and perform su LDAP_USER to change the current user to the LDAP user. However, when I try to run container with -u LDAP_USER, I get an error that user does not exists.

So the question is: Is it possible to use LDAP authentication to run containers with -u LDAP_USER? Maybe I can somehow use host machine to do that?

Thanks.

答:
Check out this potential workaround and my own further description of the caveats of this workaround:

https://serverfault.com/questions/789321/openldap-client-inside-a-docker-container/841202#841202

I'm happy to share my Dockerfile to modify the container to support LDAP lookup if you ask...

Title: LDAP authentication in Docker container


问:
TClientDataset - XML mapping
I'm trying to save data in a TClientDataSet to an XML file, but it doesn't like some of my fields.  The helpfile says to create a definition, in one of two ways: either with the xmlmapper.exe file in my \bin folder or with an IDOMDocument interface.

Problem is, xmlmapper.exe isn't there, and IDOMDocument is one of those annoying structures that Delphi 2009 was released without writing up documentation for.  So I have to choose between a non-existent EXE or an interface with no documentation and no indication of which objects implement it or how to create them.

Does anyone know what I'm supposed to do in this case?

答:
If you are using fields that are unsupported in delphi's XML serialisation, you need to create your own functions for XML loading/saving.

It's not hard, and if you do it, that code can be expanded for other serialisation formats (JSON, CSV, XLSX, ...).

OwnerDisplayName: Mason Wheeler

Title: TClientDataset - XML mapping

OwnerDisplayName: dmajkic


问:
How do I select the master Redis pod in this Kubernetes example?
Here's the example I have modeled after.

In the Readme's "Delete our manual pod" section:

The redis sentinels themselves, realize that the master has disappeared from the cluster, and begin the election procedure for selecting a new master. They perform this election and selection, and chose one of the existing redis server replicas to be the new master.

How do I select the new master? All 3 Redis server pods controlled by the redis replication controller from redis-controller.yaml still have the same

```<code>labels:
  name: redis
</code>```

which is what I currently use in my Service to select them. How will the 3 pods be distinguishable so that from Kubernetes I know which one is the master?

答:
Your client Redis library can actually handle this. For example with ioredis:

ioredis guarantees that the node you connected to is always a master even after a failover.

So, you actually connect to a redis-sentinel instead of a redis-client.

Body:
Here's the example I have modeled after.

In the Readme's "Delete our manual pod" section:

The redis sentinels themselves, realize that the master has disappeared from the cluster, and begin the election procedure for selecting a new master. They perform this election and selection, and chose one of the existing redis server replicas to be the new master.

How do I select the new master? All 3 Redis server pods controlled by the redis replication controller from redis-controller.yaml still have the same

labels:
  name: redis

which is what I currently use in my Service to select them. How will the 3 pods be distinguishable so that from Kubernetes I know which one is the master?


问:
Convert a date interval into rows of individual dates
In SAS, I have a column with a start_date in the past and a column with an end_date of today.  I also have a price and an ID. ID is distinct.

I need to pivot the dates vertically to have unique date, price and ID.

START:

```<code>start         end          price    ID
------------------------------------------
3/26/2017   3/28/2017    3.25     12345678
</code>```

END:

```<code>ID        price      date
------------------------------
12345678  3.25       3/26/2017
12345678  3.25       3/27/2017
12345678  3.25       3/28/2017
</code>```

答:
Alright, as I interpret the question. (No offence meant.)

You have date interval and you wish to have row for each date between them while retaining ID and price.

First we generate a bit of data.

```<code>data Begin;
    input start :DATE9. end :DATE9. price ID;
    datalines;
    '26MAR17'd '28MAR17'd 3.25 12345678
    '1JAN17'd '4JAN17'd 5.6 876543221
    ;
run;
</code>```

We always want to sort thins out.

```<code>proc sort data= begin; by start; run;

data wanted(keep=ID price date);
    set begin;
    by start; /*Each start date begins the following loop*/
        do while (start <= end);
            date=start; /*This is just that we get the right name out from output*/
            output;
            start= start+1;
        end;
run;
</code>```

Please make sure that end>begin or you'll hit endless loop. (Or add comparison to the code.)

ContentLicense: CC BY-SA 4.0

Body:
In SAS, I have a column with a start_date in the past and a column with an end_date of today.  I also have a price and an ID. ID is distinct.

I need to pivot the dates vertically to have unique date, price and ID.

START:

start         end          price    ID
------------------------------------------
3/26/2017   3/28/2017    3.25     12345678

END:

ID        price      date
------------------------------
12345678  3.25       3/26/2017
12345678  3.25       3/27/2017
12345678  3.25       3/28/2017

Body:
Alright, as I interpret the question. (No offence meant.)

You have date interval and you wish to have row for each date between them while retaining ID and price.

First we generate a bit of data.

data Begin;
    input start :DATE9. end :DATE9. price ID;
    datalines;
    '26MAR17'd '28MAR17'd 3.25 12345678
    '1JAN17'd '4JAN17'd 5.6 876543221
    ;
run;

We always want to sort thins out.

proc sort data= begin; by start; run;

data wanted(keep=ID price date);
    set begin;
    by start; /*Each start date begins the following loop*/
        do while (start <= end);
            date=start; /*This is just that we get the right name out from output*/
            output;
            start= start+1;
        end;
run;

Please make sure that end>begin or you'll hit endless loop. (Or add comparison to the code.)


答:
File -> Settings -> Build,Execution,Deployment ->Build tools -> gradle -> check Use Default gradle wrapper(recommended) radiobutton.

You can try File > Invalidate Caches/Restart too

Title: App fails to compile and run in Android Studio


问:
codeIgniter form_error() not display error when validation fails
codeIgniter validation error not displaying errors when validation fails, i have tried var_dumping the validation_errors() and form_error() function. This is annoying because i have used form_validation in 6 CI projects.

public function create(){
    $error = '';
    $this->form_validation->set_rules('username','Username','trim|required');
  $this->form_validation->set_rules('email','Email','trim|required|valid_email');
    $this->form_validation->set_rules('password','Password','trim|required');
  $this->form_validation->set_rules('passwordConfirm','Confirm Password','trim|matches[password]');
  $this->form_validation->set_rules('phone','Phone','trim|required');
  $this->form_validation->set_rules('bank_name','Bank name','trim|required');
  $this->form_validation->set_rules('bank_acc_name','Account name','trim|required');
  $this->form_validation->set_rules('bank_acc_no','Account no','trim|required');

  if($this->form_validation->run() === TRUE){

   $response = $this->user_model->create_user();
  }

  if(count($this->form_validation->error_array()) > 0){
   $error = 'Check input provided';
   var_dump(validation_errors()); die();
  }

  $data = [
   'error'=>$error,
   'form'=>[
    'username'=>[
     'value'=>  set_value('username'),
     'error'=>  form_error('username')
    ],
    'email'=>[
     'error'=>  form_error('email'),
     'value'=>  set_value('email')
    ],
    'password'=>[
     'error'=>  form_error('password'),
     'value'=>  set_value('password')
    ],
    'passwordConfirm'=>[
     'error'=>  form_error('passwordConfirm'),
     'value'=>  set_value('passwordConfirm')
    ],
    'phone'=>[
     'error'=>  form_error('phone'),
     'value'=>  set_value('phone')
    ],
    'bank_name'=>[
     'error'=>  form_error('bank_name'),
     'value'=>  set_value('bank_name')
    ],
    'bank_acc_name'=>[
     'error'=>  form_error('bank_acc_name'),
     'value'=>  set_value('bank_acc_name')
    ],
    'bank_acc_no'=>[
     'error'=>  form_error('bank_acc_no'),
     'value'=>  set_value('bank_acc_no')
    ]

   ]
  ];
  //var_dump($data); die();
  $this->load->view('header');
  $this->load->view('register',['data'=> json_decode(json_encode($data),FALSE)]);
  $this->load->view('footer');
 }```

答: I figured out my bug, in my config file, i autoloaded form_Validation instead of "form_validation" with a small later v. Banging my head against the wall</p>


问:
Why doe's fixed positioned div is scrolling instead of staying in the specified location?
I usually find answers here for every problem, but couldn't find this:

I'm trying to make a div to be fixed to top:50px.

However, when I scroll the page, this Div is scrolling up and the mentioned position is only applied as sort of a minimum scrolling position...

html:

```<code>  <div class="homepage-hugger">
    <div class="home-box" id="home-box-1">
      --- Div's Content ---
    </div>
   --- some more stuff ---
</div>
</code>```

JavaScript successfully adds the following css to the #home-box-1 Div:

```<code>$("#home-box-1").css({"position": "fixed", "top" : "50px"});
</code>```

The result css is of course:

```<code>position: fixed; top: 50px;
</code>```

Thanks for reading.

EDIT

Maybe more of my code will help...

So this is the css (scss) for .homepage-hugger and .home-box:

```<code>.homepage-hugger{
  width: 100%;
  background-color: #fff;
  position: relative;
  z-index: 50;
  box-shadow: 0 0px 30px rgba(0,0,0,0.4);

  .home-box{
    position: relative;
    height: 150px;
    box-shadow: 0 -10px 20px -5px rgba(0,0,0,0.1) inset;
    width: 100%;
    max-width: 100%;
  }
}
</code>```

And the full related JavaScript that works as expected (it includes some unrelated code for other scrolling behavior) :

```<code>$(document).ready(function(){

  function mobileCats(){
    var catOffset = $("#home-box-1").offset().top;
    var winScroll = $(window).scrollTop();
    var boxPos = catOffset - winScroll;
    console.log(boxPos <= 50);
    if (boxPos <= 50){
      $("#home-box-1").css({"position": "fixed", "top" : "50px", "left" : "0px"});
    }
  }

  mobileCats();

$(window).scroll(function()
        {
      mobileCats();
            var x = $(this).scrollTop(); /* scroll pos */
            var y = $("html").height();
            var z = x / y;

            curTop = ((z*500));
            $(".main-banners").css("top", (curTop)+"px");
        });
});
</code>```

答:
After further investigation, I was able to find that position: fixed and transform: translate() could not be stacked due to mathematical reasons behind the scenes.

A class added by an add-on to a parent Div has added a transform: translate() style to it which made the position: fixed of the child Div impossible to compute.

To issue was resolved by taking the fixed Div out of all containers, putting it directly under body and repositioning it.

Thank you all for trying to help. appreciated.

Body:
I usually find answers here for every problem, but couldn't find this:

I'm trying to make a div to be fixed to top:50px.

However, when I scroll the page, this Div is scrolling up and the mentioned position is only applied as sort of a minimum scrolling position...

html:

      --- Div's Content ---

   --- some more stuff ---

JavaScript successfully adds the following css to the #home-box-1 Div:

$("#home-box-1").css({"position": "fixed", "top" : "50px"});

The result css is of course:

position: fixed; top: 50px;

Thanks for reading.

EDIT

Maybe more of my code will help...

So this is the css (scss) for .homepage-hugger and .home-box:

.homepage-hugger{
  width: 100%;
  background-color: #fff;
  position: relative;
  z-index: 50;
  box-shadow: 0 0px 30px rgba(0,0,0,0.4);

  .home-box{
    position: relative;
    height: 150px;
    box-shadow: 0 -10px 20px -5px rgba(0,0,0,0.1) inset;
    width: 100%;
    max-width: 100%;
  }
}

And the full related JavaScript that works as expected (it includes some unrelated code for other scrolling behavior) :

$(document).ready(function(){

  function mobileCats(){
    var catOffset = $("#home-box-1").offset().top;
    var winScroll = $(window).scrollTop();
    var boxPos = catOffset - winScroll;
    console.log(boxPos <= 50);
    if (boxPos <= 50){
      $("#home-box-1").css({"position": "fixed", "top" : "50px", "left" : "0px"});
    }
  }

  mobileCats();

$(window).scroll(function()
        {
      mobileCats();
            var x = $(this).scrollTop(); /* scroll pos */
            var y = $("html").height();
            var z = x / y;

            curTop = ((z*500));
            $(".main-banners").css("top", (curTop)+"px");
        });
});


问:
Download google drive folder's file via wget
I want to download google drive folders file via wget how it is possible?

I have folder version in google drive and in that version folder all version apk file of my mobile app.

Folder tree like this

```<code>Version : -> mobileapp1.apk
          -> mobileapp2.apk
          -> mobileapp3.apk
</code>```

And I want to download by passing version name. Is it possible with google drive and wget? I have already make folder Public on the web - Anyone on the Internet

答:
You can download old version files using wget. In order to download old version files, Access token, File ID and Revision ID are required as the materials. The methods for retrieving the materials are follows. wget is used for all methods.

1. Access token

Reference : https://developers.google.com/identity/protocols/OAuth2

This is my old answer related to retrieving access token from Google OAuth2. Refresh Google drive access__token If this is useful for you, I'm glad.

2. File ID

In order to retrieve file ID, it searches it from file name using drive.files.list.

```<code>wget -q --header='Authorization: Bearer ### Access token ###' \
    'https://www.googleapis.com/drive/v3/files?q=name="### FileName ###"&fields=files(id,name)' \
    -O out.txt
</code>```

By this, you can find FileID for the FileName in the out.txt. If there are several files with same name, please select one of them.

Reference : https://developers.google.com/drive/v3/reference/files/list

3. Revision ID

In order to retrieve revision ID, it retrieves revision list for the FileID using drive.revisions.list.

```<code>wget -q --header='Authorization: Bearer ### Access token ###' \
    'https://www.googleapis.com/drive/v3/files/### FileID ###/revisions?fields=revisions(id%2CmodifiedTime)' \
    -O out.txt
</code>```

By this, you can find RevisionID for the FileID in the out.txt. Please select revision ID you want.

Reference : https://developers.google.com/drive/v3/reference/revisions/list

4. File for Revision ID

Retrieves File for Revision ID using drive.revisions.get.

```<code>wget -q --header='Authorization: Bearer ### Access token ###' \
    "https://www.googleapis.com/drive/v3/files/### FileID ###/revisions/### RevisionID ###?alt=media" \
    -O outputfilename
</code>```

By this, a file with name of outputfilename can be retrieved.

Reference : https://developers.google.com/drive/v3/reference/revisions/get

Body:
I want to download google drive folders file via wget how it is possible?

I have folder version in google drive and in that version folder all version apk file of my mobile app.

Folder tree like this

Version : -> mobileapp1.apk
          -> mobileapp2.apk
          -> mobileapp3.apk

And I want to download by passing version name. Is it possible with google drive and wget? I have already make folder Public on the web - Anyone on the Internet

Body:
You can download old version files using wget. In order to download old version files, Access token, File ID and Revision ID are required as the materials. The methods for retrieving the materials are follows. wget is used for all methods.

1. Access token

Reference : https://developers.google.com/identity/protocols/OAuth2

This is my old answer related to retrieving access token from Google OAuth2. Refresh Google drive access__token If this is useful for you, I'm glad.

2. File ID

In order to retrieve file ID, it searches it from file name using drive.files.list.

wget -q --header='Authorization: Bearer ### Access token ###' \
    'https://www.googleapis.com/drive/v3/files?q=name="### FileName ###"&fields=files(id,name)' \
    -O out.txt

By this, you can find FileID for the FileName in the out.txt. If there are several files with same name, please select one of them.

Reference : https://developers.google.com/drive/v3/reference/files/list

3. Revision ID

In order to retrieve revision ID, it retrieves revision list for the FileID using drive.revisions.list.

wget -q --header='Authorization: Bearer ### Access token ###' \
    'https://www.googleapis.com/drive/v3/files/### FileID ###/revisions?fields=revisions(id%2CmodifiedTime)' \
    -O out.txt

By this, you can find RevisionID for the FileID in the out.txt. Please select revision ID you want.

Reference : https://developers.google.com/drive/v3/reference/revisions/list

4. File for Revision ID

Retrieves File for Revision ID using drive.revisions.get.

wget -q --header='Authorization: Bearer ### Access token ###' \
    "https://www.googleapis.com/drive/v3/files/### FileID ###/revisions/### RevisionID ###?alt=media" \
    -O outputfilename

By this, a file with name of outputfilename can be retrieved.

Reference : https://developers.google.com/drive/v3/reference/revisions/get


问:
Uncaught TypeError: Cannot read property '0' of undefined jquery datepicker
I have the following jQuery code for datepicker and I'm getting the error Uncaught TypeError: Cannot read property '0' of undefined.
I want to do some computations in the beforeShowDay callback but because of this error I'm unable to do so. I'm using jQuery 1.10.2 and jQuery-ui 1.10.4

I found a similar question but none of the solutions seems to be working:

datepicker Error = Uncaught TypeError: Cannot read property '0' of undefined

```<code>$(document).ready(function(){
  $("#inline_datepicker").datepicker({
            dateFormat: "yy-mm-dd",
            minDate: 0,
            onSelect: function(){
                fetch_time_slots($(this).datepicker("getDate"));
            },
            beforeShowDay: function(date){
                console.log(date)
            }
    });
});
</code>```

答:
beforeShowDay

Type: Function( Date date )

Default: null

A function that takes a date as a parameter and must return an array with:

[0]: true/false indicating whether or not this date is selectable

[1]: a CSS class name to add to the date's cell or "" for the default presentation

[2]: an optional popup tooltip for this date

The function is called for each day in the datepicker before it is displayed.

```<code>beforeShowDay: function(date) {
                        var day = date.getDate();
                        var month = date.getMonth();
                        if ( day == 30 || day == 31 ) {$("#purchasedate").val(""); return [false];}
                        else{ return [true,""];}
                        },
</code>```

Body:
I have the following jQuery code for datepicker and I'm getting the error Uncaught TypeError: Cannot read property '0' of undefined.
I want to do some computations in the beforeShowDay callback but because of this error I'm unable to do so. I'm using jQuery 1.10.2 and jQuery-ui 1.10.4

I found a similar question but none of the solutions seems to be working:

datepicker Error = Uncaught TypeError: Cannot read property '0' of undefined

$(document).ready(function(){
  $("#inline_datepicker").datepicker({
            dateFormat: "yy-mm-dd",
            minDate: 0,
            onSelect: function(){
                fetch_time_slots($(this).datepicker("getDate"));
            },
            beforeShowDay: function(date){
                console.log(date)
            }
    });
});

Body:
beforeShowDay

Type: Function( Date date )

Default: null

A function that takes a date as a parameter and must return an array with:

[0]: true/false indicating whether or not this date is selectable

[1]: a CSS class name to add to the date's cell or "" for the default presentation

[2]: an optional popup tooltip for this date

The function is called for each day in the datepicker before it is displayed.

beforeShowDay: function(date) {
                        var day = date.getDate();
                        var month = date.getMonth();
                        if ( day == 30 || day == 31 ) {$("#purchasedate").val(""); return [false];}
                        else{ return [true,""];}
                        },


问:
HTML thumbnail size issue
enter image description here

I have an issue with thumbnail size. In the picture, there should have been another picture in white area in the left-middle, but the space is skipped because an image above has a long title. Everytime a picture with a long title is showed up, the size becomes larger. Is there any way I can fix thumbnail size even though the title gets longer?

Here is my HTML code and CSS i don't write anything.

```<code><div class="panel-body">
  <div id="recipeResults" class="row">
    <!-- templates/BasicImages/imageTemplates.js -->
  </div>
</div>
</code>```

Here is actual code. Sorry :)

```<code><div class="col-sm-6 col-md-4">
  <div class="thumbnail">
    <div class="hovereffect">
      <img class="img-responsive center-block" src="{{json.url}}" alt="{{json.alt_name}}">
        <div class="overlay">
           <h3> {{json.hoverDescription}}</h3>
           <a class="info" href="#"><i class="fa fa-clock-o fa-fw" aria-hidden="true"></i>{{json.cookTime}}</a>
        </div>
    </div>
        <div class="caption">
      <p style="font-size: 1pt;"> </p>
      <h4>{{json.name}}</h4>
      <p>{{json.description}}</p>
      <p><button type="button" class="btn btn-default btn-sm" aria-label="Left Align">
        <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Save
        </button></p>
    </div>
  </div>
</div>
</code>```

答:
You can use this code for the box tag (or title tag) in CSS to prevent any over sizing

.class-name{
  overflow: hidden;
}
```

CSS overflow Property

Title: HTML thumbnail size issue

Body:
enter image description here

I have an issue with thumbnail size. In the picture, there should have been another picture in white area in the left-middle, but the space is skipped because an image above has a long title. Everytime a picture with a long title is showed up, the size becomes larger. Is there any way I can fix thumbnail size even though the title gets longer?

Here is my HTML code and CSS i don't write anything.

Here is actual code. Sorry :)

 {{json.hoverDescription}}

           {{json.cookTime}}

{{json.name}}

{{json.description}}

<button type="button" class="btn btn-default btn-sm" aria-label="Left Align">
         Save
        </button>

Body:
You can use this code for the box tag (or title tag) in CSS to prevent any over sizing

.class-name{
  overflow: hidden;
}

CSS overflow Property


问:
How to put confirm deletion popup before the function run?
I'm doing a deleting function for a webpage which basically read input from user and compare it to the data from database and then delete. The code is already running perfectly. Just lack of confirm deletion popup. I've tried multiple method to put it and some of the error is regarding the 'GET' and 'POST' method. I dont want to change anything on the route because the function is already working properly.
Below is some part of code.

```<code><button>
  <a href="delete">Back</a>
</button>

<button>
  <a href="{{URL::to('deleted/'.$d->domain_label.'/'.$d->domain_extension)}}">Delete</a>
</button>
</code>```

And route:

```<code>Route::get('/servicedetails','ServiceDetailsController@showservicedetails');
Route::get('/delete','ManageController@delete');
Route::post('/delete2','ManageController@delete2');
Route::get('deleted/{domain_name}/{ext}','ManageController@deleteConfirm');
</code>```

I want to put the popup on the onClick button and then run the function deleteConfirm().

Hope anybody can help.

答:
You can use confirm() function of jQuery to get confirmation:

Try this:

```<code><a href="{{URL::to('deleted/'.$d->domain_label.'/'.$d->domain_extension)}}" onclick="return confirm(' you want to delete?');">Delete</a>
</code>```

Body:
I'm doing a deleting function for a webpage which basically read input from user and compare it to the data from database and then delete. The code is already running perfectly. Just lack of confirm deletion popup. I've tried multiple method to put it and some of the error is regarding the 'GET' and 'POST' method. I dont want to change anything on the route because the function is already working properly.
Below is some part of code.

<button>
  Back
</button>

<button>
  domain_label.'/'.$d->domain_extension)}}">Delete
</button>

And route:

Route::get('/servicedetails','ServiceDetailsController@showservicedetails');
Route::get('/delete','ManageController@delete');
Route::post('/delete2','ManageController@delete2');
Route::get('deleted/{domain_name}/{ext}','ManageController@deleteConfirm');

I want to put the popup on the onClick button and then run the function deleteConfirm().

Hope anybody can help.

Body:
You can use confirm() function of jQuery to get confirmation:

Try this:

<a href="{{URL::to('deleted/'.$d->domain_label.'/'.$d->domain_extension)}}" onclick="return confirm(' you want to delete?');">Delete</a>


问:
When to .removeObserver ?
The app should load only locally made posts.
Using GeoFire a have a branch "posts_location" in FB.
I want to populate 'nearbyPostsKeys' array first, then load those specific posts from FB's branch posts that has reference REF_POSTS.

In viewDidLoad, I call for a func that has a completion handler(data from FB).

Here is func declaration that takes the completion handler:

```<code>func populateNearbyAndPassIt(completion:@escaping ([String])->()) {

    let theGeoFire = GeoFire(firebaseRef: DB_BASE.child("posts_location"))
    let location = CLLocation(latitude: Location.sharedInstance.currentLatitude, longitude: Location.sharedInstance.currentLongitude)
    let circleQuery = theGeoFire!.query(at: location, withRadius: 6.0)

     let newRefHandle: FIRDatabaseHandle = circleQuery!.observe(.keyEntered, with: { (key, location) in

        self.nearbyPostsKeys.append(key!)
        completion(self.nearbyPostsKeys)
    })
}
</code>```

And here's how I call for that func in 'viewDidLoad':

```<code> populateNearbyAndPassIt{(nearbyPostsKeys) in

        //populate 'posts' based on 'nearby..'

        for key in nearbyPostsKeys {
            let postRef = DataService.ds.REF_POSTS.queryOrdered(byChild: key)
            postRef.observe(.value, with: { (snapshot) in
                self.posts = []
                if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                    for snap in snapshot {
                        if let postDict = snap.value as? Dictionary<String, AnyObject> {
                            let key = snap.key
                            let post = Post(postKey: key, postData: postDict)
                            self.posts.append(post)
                        }
                    }
                }
                self.posts.reverse()

                print("Zhenya: here are all local posts data: \(self.posts)")
            })
        }
    }
</code>```

While having 3 posts on specified location here is what happened:

The .observe is called. 1 posts being retrieved and appends to nearbyPostsKeys -> the completion handler is called. and array with 1 element is passed... and the loop continues.

I wish i could wait until 'nearbyPostsKeys' array is populated and only then pass it as completion handler.

I also learned about .removeObserver func that can stop .observe func but wherever i put it like this:

```<code>    let newRefHandle: FIRDatabaseHandle = circleQuery!.observe(.keyEntered, with: { (key, location) in

        self.nearbyPostsKeys.append(key!)
        completion(self.nearbyPostsKeys)
    })
    circleQuery!.removeObserver(withFirebaseHandle: newRefHandle)
</code>```

it looks as nearbyPostsKeys aren't passed at all.

Please advice on either better logic or on how to use .removeObserver.
Thank you.

答:
You should remove observers when your view controller deinitializes:

```<code>deinit {
    circleQuery!.removeObserver(withFirebaseHandle: newRefHandle)
}
</code>```

Just make circleQuery a property of your viewcontroller.

Title: When to .removeObserver ?

Body:
The app should load only locally made posts.
Using GeoFire a have a branch "posts_location" in FB.
I want to populate 'nearbyPostsKeys' array first, then load those specific posts from FB's branch posts that has reference REF_POSTS.

In viewDidLoad, I call for a func that has a completion handler(data from FB).

Here is func declaration that takes the completion handler:

func populateNearbyAndPassIt(completion:@escaping ([String])->()) {

    let theGeoFire = GeoFire(firebaseRef: DB_BASE.child("posts_location"))
    let location = CLLocation(latitude: Location.sharedInstance.currentLatitude, longitude: Location.sharedInstance.currentLongitude)
    let circleQuery = theGeoFire!.query(at: location, withRadius: 6.0)

     let newRefHandle: FIRDatabaseHandle = circleQuery!.observe(.keyEntered, with: { (key, location) in

        self.nearbyPostsKeys.append(key!)
        completion(self.nearbyPostsKeys)
    })
}

And here's how I call for that func in 'viewDidLoad':

 populateNearbyAndPassIt{(nearbyPostsKeys) in

        //populate 'posts' based on 'nearby..'

        for key in nearbyPostsKeys {
            let postRef = DataService.ds.REF_POSTS.queryOrdered(byChild: key)
            postRef.observe(.value, with: { (snapshot) in
                self.posts = []
                if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                    for snap in snapshot {
                        if let postDict = snap.value as? Dictionary<String, AnyObject> {
                            let key = snap.key
                            let post = Post(postKey: key, postData: postDict)
                            self.posts.append(post)
                        }
                    }
                }
                self.posts.reverse()

                print("Zhenya: here are all local posts data: \(self.posts)")
            })
        }
    }

While having 3 posts on specified location here is what happened:

The .observe is called. 1 posts being retrieved and appends to nearbyPostsKeys -> the completion handler is called. and array with 1 element is passed... and the loop continues.

I wish i could wait until 'nearbyPostsKeys' array is populated and only then pass it as completion handler.

I also learned about .removeObserver func that can stop .observe func but wherever i put it like this:

    let newRefHandle: FIRDatabaseHandle = circleQuery!.observe(.keyEntered, with: { (key, location) in

        self.nearbyPostsKeys.append(key!)
        completion(self.nearbyPostsKeys)
    })
    circleQuery!.removeObserver(withFirebaseHandle: newRefHandle)

it looks as nearbyPostsKeys aren't passed at all.

Please advice on either better logic or on how to use .removeObserver.
Thank you.

Body:
You should remove observers when your view controller deinitializes:

deinit {
    circleQuery!.removeObserver(withFirebaseHandle: newRefHandle)
}

Just make circleQuery a property of your viewcontroller.


问:
Using COUNTIFS with multiple options from cell references
I found a similar formula to the below in this forum and it works brilliantly (thank you!) but I'm wondering if "Training A" and "Training B" can be replaced with cell references instead of specific words? The reason being, at some stage down the track our training requirements are likely to change (e.g. Training A may be completed and Training C introduced) so it would be ideal if our users can simply update the headings instead of formulas needing updating.

So, more specifically, what I'm hoping is that "Training A" can be replaced with a reference to cell C21, and "Training B" with a reference to cell J21. I've only included 2x here, but there are currently 8x training headings that would be incorporated into the final formula. Thanks in advance for any assistance!

```<code>=SUM(COUNTIFS(A:A,{"Training A","Training B"}))
</code>```

To put it into context, it would help simplify the reporting of completed training (%) for each of our 31 sites (listed in Reporting cells B4:B19). 8 headings are in Reporting rows 21, 55, 89 & 123 (2 each row, columns C & J) that relate to training modules in the Data tab; additional modules in the Data need to be ignored. Maybe there's another solution altogether? I’d like to avoid helper tables, and arrays tend to slow our spreadsheets down considerably here for some reason, although I’m happy to try if an array is the cleanest solution.

This formula works:
    =(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$21,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$21,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$55,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$55,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$89,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$89,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$123,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$123,Data!$F:$F,"complete"))/(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$21)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$21)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$55)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$55)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$89)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$89)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$123)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$123))

This also works:
=SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!$F:$F,"complete",Data!A:A,{"Safety at ABCD","ABCD Policies - Professional","ABCD Policies - Operational","COR - Staff Management - Basic Staff Management","COR - Staff Management - Advanced Staff Management","ABCD Group - General Safety Awareness"}))/SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,{"Safety at ABCD","ABCD Policies - Professional","ABCD Policies - Operational","COR - Staff Management - Basic Staff Management","COR - Staff Management - Advanced Staff Management","ABCD Group - General Safety Awareness"}))

If the above module names could be replaced by cell references it would be ideal:
    =SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!$F:$F,"complete",Data!A:A,{C21,J21,C55,J55,C89,J89,C123,J123}))/SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,{C21,J21,C55,J55,C89,J89,C123,J123}))

答:
For multiple possibilities (e.g. Training A-H) then you have two options.

Assumes that there is a list in range A2:A17 and some items to look for in range C2:C5. E.g.:

Option 1

Use an array formula - you need to enter it and then Ctrl+Shift+Enter

```<code>=SUM(COUNTIFS(A2:A17,C2:C5))
</code>```

After you use Ctrl+Shift+Enter it will appear as:

```<code>{=SUM(COUNTIFS(A2:A17,C2:C5))}
</code>```

Option 2

The other option which avoids using an array formula is to use SUMPRODUCT and multiply the array given by COUNTIFS by an array of 1s which is given by the presence of inputs to the formula:

```<code>=SUMPRODUCT(COUNTIFS(A2:A17,C2:C5),--(C2:C5<>""))
</code>```

So it's a trade off between array formulas and a slightly more complex non-array formula (which still works with arrays).

Update

If the inputs are in a non-contiguous range of cells, I would propose creating a contiguous range of filters and linking those cells to the various other inputs around the workbook. Both the options work with a filter range that has blanks, or numbers or inputs that aren't values in the list that is the target of the COUNTIF:

Body:
I found a similar formula to the below in this forum and it works brilliantly (thank you!) but I'm wondering if "Training A" and "Training B" can be replaced with cell references instead of specific words? The reason being, at some stage down the track our training requirements are likely to change (e.g. Training A may be completed and Training C introduced) so it would be ideal if our users can simply update the headings instead of formulas needing updating.

So, more specifically, what I'm hoping is that "Training A" can be replaced with a reference to cell C21, and "Training B" with a reference to cell J21. I've only included 2x here, but there are currently 8x training headings that would be incorporated into the final formula. Thanks in advance for any assistance!

=SUM(COUNTIFS(A:A,{"Training A","Training B"}))

To put it into context, it would help simplify the reporting of completed training (%) for each of our 31 sites (listed in Reporting cells B4:B19). 8 headings are in Reporting rows 21, 55, 89 & 123 (2 each row, columns C & J) that relate to training modules in the Data tab; additional modules in the Data need to be ignored. Maybe there's another solution altogether? I’d like to avoid helper tables, and arrays tend to slow our spreadsheets down considerably here for some reason, although I’m happy to try if an array is the cleanest solution.

This formula works:
    =(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$21,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$21,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$55,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$55,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$89,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$89,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$123,Data!$F:$F,"complete")+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$123,Data!$F:$F,"complete"))/(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$21)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$21)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$55)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$55)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$89)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$89)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$C$123)+COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,Reporting!$J$123))

This also works:
=SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!$F:$F,"complete",Data!A:A,{"Safety at ABCD","ABCD Policies - Professional","ABCD Policies - Operational","COR - Staff Management - Basic Staff Management","COR - Staff Management - Advanced Staff Management","ABCD Group - General Safety Awareness"}))/SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,{"Safety at ABCD","ABCD Policies - Professional","ABCD Policies - Operational","COR - Staff Management - Basic Staff Management","COR - Staff Management - Advanced Staff Management","ABCD Group - General Safety Awareness"}))

If the above module names could be replaced by cell references it would be ideal:
    =SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!$F:$F,"complete",Data!A:A,{C21,J21,C55,J55,C89,J89,C123,J123}))/SUM(COUNTIFS(Data!$E:$E,Reporting!B4,Data!A:A,{C21,J21,C55,J55,C89,J89,C123,J123}))

Body:
For multiple possibilities (e.g. Training A-H) then you have two options.

Assumes that there is a list in range A2:A17 and some items to look for in range C2:C5. E.g.:

Option 1

Use an array formula - you need to enter it and then Ctrl+Shift+Enter

=SUM(COUNTIFS(A2:A17,C2:C5))

After you use Ctrl+Shift+Enter it will appear as:

{=SUM(COUNTIFS(A2:A17,C2:C5))}

Option 2

The other option which avoids using an array formula is to use SUMPRODUCT and multiply the array given by COUNTIFS by an array of 1s which is given by the presence of inputs to the formula:

=SUMPRODUCT(COUNTIFS(A2:A17,C2:C5),--(C2:C5<>""))

So it's a trade off between array formulas and a slightly more complex non-array formula (which still works with arrays).

Update

If the inputs are in a non-contiguous range of cells, I would propose creating a contiguous range of filters and linking those cells to the various other inputs around the workbook. Both the options work with a filter range that has blanks, or numbers or inputs that aren't values in the list that is the target of the COUNTIF:


问:
SQL: Select Vegetarians
i'm stuck with a small problem here and i can't seem to find the right answer.

I have a DB with multiple Tables, in which i have ANIMALS and their FOOD. I have to select which ANIMALS only eat VEGETARIAN meals. The table is set up with a BOOLEAN. 0 = MEAT 1 = VEGETARIAN.

There are ANIMALS in the Table who eat MEAT and VEGETARIAN. I don't need them, i strictly need Animals who only eat VEGETARIAN.

Thanks in advance.

答:
You can try this (but it's only mok, since you didn't write anything else):</p>

```<code>SELECT *
FROM ANIMALS A
INNER JOIN BR_ANIMALS_FOOD B ON A.ID = B.ID_ANI
INNER JOIN FOODS C ON B.ID_FOODS = C.ID
WHERE NOT EXISTS (SELECT 1 FROM FOODS D WHERE B.ID_FOODS = D.ID AND D.FOOD_TYPE = 0)
 AND C.FOOD_TYPE = 1
</code>```

Title: SQL: Select Vegetarians

Body:
You can try this (but it's only mok, since you didn't write anything else):

SELECT *
FROM ANIMALS A
INNER JOIN BR_ANIMALS_FOOD B ON A.ID = B.ID_ANI
INNER JOIN FOODS C ON B.ID_FOODS = C.ID
WHERE NOT EXISTS (SELECT 1 FROM FOODS D WHERE B.ID_FOODS = D.ID AND D.FOOD_TYPE = 0)
 AND C.FOOD_TYPE = 1


问:
How to have python waiting for input until input unchanged for a certain time
My overall objective is to enter the output of speech recognition software into Python as strings. The speech recognition software types what it hears into whatever field is open in real-time. It is not possible to get the output any other way. Sentences are separated by several seconds of silence, during which the speech recognition software will not type anything. I would like each sentence to be a separate string in Python.

Therefore , what I would like to do is to have my script constantly listening for input, and whenever the current input does not change for a fixed amount of time, save the current input in a string and listen for new input.

Something like:

```<code>    While true:
        start timer
        While timer <= t:
            Listen for input
            if input changes: set timer to 0
        save input to string
</code>```

Anyone know how to accomplish this or have a better way of accomplishing my objective? Many thanks!

答:
Do multi-threading. Threads allow you do some tasks simultaneously. I suggest you do the input-fetching operation as a thread and a timer operation on another thread. So now, you can check the timer while fetching the input and pause/resume the fetch when the timer reaches a particular limit.
In case you need references on multi-threading: Multi-Threading tutorial in tutorialspoint </p>

Body:
My overall objective is to enter the output of speech recognition software into Python as strings. The speech recognition software types what it hears into whatever field is open in real-time. It is not possible to get the output any other way. Sentences are separated by several seconds of silence, during which the speech recognition software will not type anything. I would like each sentence to be a separate string in Python.

Therefore , what I would like to do is to have my script constantly listening for input, and whenever the current input does not change for a fixed amount of time, save the current input in a string and listen for new input.

Something like:

    While true:
        start timer
        While timer <= t:
            Listen for input
            if input changes: set timer to 0
        save input to string

Anyone know how to accomplish this or have a better way of accomplishing my objective? Many thanks!