问:
OnClick event only works second time on edittext
I have an edittext, and when the user clicks this edittext I want to show an alertdialog.

My code is the following :

```<code>            edt.setInputType(InputType.TYPE_NULL);
            edt.setFocusableInTouchMode(true);
            edt.requestFocus();

            edt.setCursorVisible(false);

            edt.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    CommentDialog.buildDialog(mContext, identifier, false, edt.getId());
                }
            });
</code>```

I don't want the keyboard to show up when the user clicks the edittext, so I set the inputtype to TYPE_NULL.

But when the edittext doesn't have focus and I click it, the onClick event isn't executed. When I click it a second time, the alertdialog shows up correctly.

How do I fix this?

答:
This was a real problem for me when trying to reproduce a "click" sound from the EditText when the soft keyboard pops up; I was only getting a click every second time. What fixed it for me was the the opposite of what worked for @neaGaze. This worked for me in my_layout.xml :

```<code><EditText android:focusable="true"  android:focusableInTouchMode="true" ... />
</code>```

It allows the click sound/event to happen each time when user enters the EditText, while also allowing the soft keyboard to show. You have to handle the OnClickListener of course for this to happen, even if you do nothing with it, like so :

```<code>myEditText = (EditText) findViewById(R.id.myEditText);
...

// implement the onClick listener so we get the click sound and event if needed
myEditText.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        //do something or nothing; up to you
    }
});
</code>```

Speaking of that pesky soft keyboard, if I finished from my Dialog style Activity with the soft keyboard up, no matter what I tried the keyboard remained up when I was returned to MainActivity. I had tried all the usual suggestions such as Close/Hide the Android soft keyboard , How to close Android soft keyboard programmatically etc. None of that worked.

In my case I did not need the soft keyboard in MainActivity. What did work was the following in my AndroidManifest.xml file, within the MainActivity section

```<code><activity

    android:name=".MainActivity"
    android:windowSoftInputMode="stateAlwaysHidden">

</activity>
</code>```

Body:
I have an edittext, and when the user clicks this edittext I want to show an alertdialog.

My code is the following :

            edt.setInputType(InputType.TYPE_NULL);
            edt.setFocusableInTouchMode(true);
            edt.requestFocus();

            edt.setCursorVisible(false);

            edt.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    CommentDialog.buildDialog(mContext, identifier, false, edt.getId());
                }
            });

I don't want the keyboard to show up when the user clicks the edittext, so I set the inputtype to TYPE_NULL.

But when the edittext doesn't have focus and I click it, the onClick event isn't executed. When I click it a second time, the alertdialog shows up correctly.

How do I fix this?

Body:
This was a real problem for me when trying to reproduce a "click" sound from the EditText when the soft keyboard pops up; I was only getting a click every second time. What fixed it for me was the the opposite of what worked for @neaGaze. This worked for me in my_layout.xml :

<EditText android:focusable="true"  android:focusableInTouchMode="true" ... />

It allows the click sound/event to happen each time when user enters the EditText, while also allowing the soft keyboard to show. You have to handle the OnClickListener of course for this to happen, even if you do nothing with it, like so :

myEditText = (EditText) findViewById(R.id.myEditText);
...

// implement the onClick listener so we get the click sound and event if needed
myEditText.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        //do something or nothing; up to you
    }
});

Speaking of that pesky soft keyboard, if I finished from my Dialog style Activity with the soft keyboard up, no matter what I tried the keyboard remained up when I was returned to MainActivity. I had tried all the usual suggestions such as Close/Hide the Android soft keyboard , How to close Android soft keyboard programmatically etc. None of that worked.

In my case I did not need the soft keyboard in MainActivity. What did work was the following in my AndroidManifest.xml file, within the MainActivity section

<activity

    android:name=".MainActivity"
    android:windowSoftInputMode="stateAlwaysHidden">

</activity>


来源: stackexchange

问:
self.tabBarController sometimes nil
I have UIViewController (first) which has tab bar at the bottom. I have next code in this controller:

```<code>let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
</code>```

It's working fine, but when I'm going from this first to next one (second) controller and then pressing Back button and returning to first, self.tabBarController is nil. Why does it happen? I have only one version, that stack of controllers is overcrowded.

How can I fix this? I need this height to calculate some value for constraint change in keyboardWillShow function.

UPDATE:

How do I call it:

```<code>// MARK: - Scroll view on keyboard show/hide
extension CommentariesController: UITextFieldDelegate {
    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
           let keyboardHeight = keyboardSize.height
           let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
           UIView.animate(withDuration: 1.0, animations: {
               self.newCommentViewBotConstraint.constant = -keyboardHeight + tabBarHeight!
               self.view.layoutIfNeeded()
           })
        }
    }

    // other code
}
</code>```

Update 2:

I can see tab bar. But it is nil.

Structure (with Show segues): tabbar -> navbar -> viewcontroller -> viewcontroller -> viewcontroller (first) -> viewcontroller (second).

Thanks

答:
TabBar controller is set as the root and then navigation controller as tabBar's one of the item and the TestViewController as the root of that navigation controller. Then this TestViewController has a textfield to check the keyboardWillShow function and on tapping the UIButton - "button" new viewcontroller is pushed. On tapping back and again checking keyboardWillShow function self.tabBarController is not nil and I'm getting the correct height of tabBar inside that function

```<code> NotificationCenter.default.addObserver(self, selector: #selector(TestViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    extension TestViewController {
    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
            let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
            UIView.animate(withDuration: 1.0, animations: {
                print("tabBarheight - \(tabBarHeight)")

            })
        }
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: self.tabBarController sometimes nil

Body:
I have UIViewController (first) which has tab bar at the bottom. I have next code in this controller:

let tabBarHeight = self.tabBarController?.tabBar.frame.size.height

It's working fine, but when I'm going from this first to next one (second) controller and then pressing Back button and returning to first, self.tabBarController is nil. Why does it happen? I have only one version, that stack of controllers is overcrowded.

How can I fix this? I need this height to calculate some value for constraint change in keyboardWillShow function.

UPDATE:

How do I call it:

// MARK: - Scroll view on keyboard show/hide
extension CommentariesController: UITextFieldDelegate {
    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
           let keyboardHeight = keyboardSize.height
           let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
           UIView.animate(withDuration: 1.0, animations: {
               self.newCommentViewBotConstraint.constant = -keyboardHeight + tabBarHeight!
               self.view.layoutIfNeeded()
           })
        }
    }

    // other code
}

Update 2:

I can see tab bar. But it is nil.

Structure (with Show segues): tabbar -> navbar -> viewcontroller -> viewcontroller -> viewcontroller (first) -> viewcontroller (second).

Thanks

Body:
TabBar controller is set as the root and then navigation controller as tabBar's one of the item and the TestViewController as the root of that navigation controller. Then this TestViewController has a textfield to check the keyboardWillShow function and on tapping the UIButton - "button" new viewcontroller is pushed. On tapping back and again checking keyboardWillShow function self.tabBarController is not nil and I'm getting the correct height of tabBar inside that function

 NotificationCenter.default.addObserver(self, selector: #selector(TestViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    extension TestViewController {
    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
            let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
            UIView.animate(withDuration: 1.0, animations: {
                print("tabBarheight - \(tabBarHeight)")

            })
        }
    }

}


问:
cartopy: zoom in to a region
I would like to use Cartopy to plot only a region (in my case, North and South America).

I am currently using the following code:

```<code>import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

lon, lat, freq = .., ..., ...  # initialize longitude and latitude and line width
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()
ax.add_feature(cartopy.feature.LAND)
ax.add_feature(cartopy.feature.OCEAN)
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)

for la, lo, fq in zip(lat, lon, freq):
    plt.plot(lo, la, color='red', linewidth=fq, marker='o', transform=ccrs.PlateCarree())
</code>```

Then it produces:

What I want (zoomed-in version):

Is there anyway to do this?

答:
You can use ax.set_extent()</p>

```<code>ax.set_extent([-150, -20, -90, 90])
</code>```

Title: cartopy: zoom in to a region

Body:
I would like to use Cartopy to plot only a region (in my case, North and South America).

I am currently using the following code:

import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

lon, lat, freq = .., ..., ...  # initialize longitude and latitude and line width
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()
ax.add_feature(cartopy.feature.LAND)
ax.add_feature(cartopy.feature.OCEAN)
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)

for la, lo, fq in zip(lat, lon, freq):
    plt.plot(lo, la, color='red', linewidth=fq, marker='o', transform=ccrs.PlateCarree())

Then it produces:

What I want (zoomed-in version):

Is there anyway to do this?

Body:
You can use ax.set_extent()

ax.set_extent([-150, -20, -90, 90])


问:
QML image widget visibility
I have a window with a QML image in it that needs to flash, so I use a Timer and toggle the visible flag every 500ms. The image has its size, max size, min size and preferred size set to 24. However, the widget next to it in the RowLayout moves backwards and forwards when the visibility changes. How can I make the icon flash without invalidating the layout?</p>

答:
Set opacity: 0 instead of visible: false.

Or, alternatively, do something like this:

```<code>RowLayout {
    // ...
    Item {
        width: 24
        height: 24
        Image {
            anchors.fill: parent
            // ...
        }
    }
</code>```

... and just toggle the visible property of the Image, like you've been doing.

Title: QML image widget visibility

Body:
Set opacity: 0 instead of visible: false.

Or, alternatively, do something like this:

RowLayout {
    // ...
    Item {
        width: 24
        height: 24
        Image {
            anchors.fill: parent
            // ...
        }
    }

... and just toggle the visible property of the Image, like you've been doing.


问:
SharedPreferences and ViewPager Unique Key
In school we have to develop our first Android app. Android is new to me and I'm here to learn something.

Today I worked the first time with SharedPreferences to save information about an ImageButton state. The layout uses a ViewPager. There are 10 items which the user can swipe. The ViewPager contains a TextView that counts the items. That works fine: e.g. the TextView of the first items shows [1/10] and the last one [10/10]. After the TextView you can find an image. That works also pretty good.

Now to my problem: under the Image I have installed an ImageButton. It signals if an item is a favorite or not. Favorite is pictured as red heart and no favorite as grey heart (default ImageResource).

This is my ViewPager of the main layout:

```<code><android.support.v4.view.ViewPager
    android:id="@+id/image_swipe"
    android:layout_width="match_parent"
    android:layout_height="590dp"
    android:layout_marginTop="130dp" />
</code>```

And this is the pagers layout:

```<code><TextView
    android:id="@+id/image_count"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Here we count..."
    android:textColor="@android:color/black"
    android:textSize="16sp" />

<ImageView
    android:id="@+id/swipe_image"
    android:layout_width="match_parent"
    android:layout_height="365dp"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_marginTop="30dp"
    android:adjustViewBounds="false"
    android:onClick="onClickImage" />

<ImageButton
    android:id="@+id/favourite_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:background="@android:color/transparent"
    android:scaleType="fitCenter"
    android:src="@drawable/heart"
    android:onClick="onClickFav" />
</code>```

All items need an unique key in order to save every items ImageButton state. The key is composed of the String "fav" and a counter (can be 1-10). That means we have 10 unique keys: fav1 - fav10. When the page is created for the given item position, I try to check if something is stored for the given key.

There can be 2 possible values behind a key: 0 and 1. 0 means no favorite, 1 is a favorite. If there is not yet any key set, the value will be 0 which is the default ImageButton state. After getting the value of the item key, the ImageResource of the ImageButton can be set.

The next step when creating the page, is to save a new key. That key has the name "count" and indicates which item is loaded at this moment.

All I just told you is in this adapter method (instantiateItem):

```<code>     /*
        Create the page for the given position
        Set image resources and text about current position
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
        TextView textView = (TextView) item_view.findViewById(R.id.image_count);
        ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);

        imageView.setImageResource(image_resources[position]);
        textView.setText("["+(position+1)+"/10]");

        SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // get the unique key consisting of fav and the current item position
        String key = "fav" + (position+1);

        String value = prefs.getString(key, "0");

        // check if value of favorite key is 0
        // set image resource dependent on what value is set
        if (value.equals("1")) {
            imageButton.setImageResource(R.drawable.heart_red);
        } else {
            imageButton.setImageResource(R.drawable.heart);
        }

        int p = (position+1);
        String count = Integer.toString(p);

        // store index of current adapter item as shared pref
        editor.putString("count", count);
        editor.commit();

        container.addView(item_view);

        return item_view;
    }
</code>```

So this was when a item is loaded. After that the user can click on the ImageButton which activates following onClick method in the main activity:

```<code>/*
    Method for click actions on the favorite button
    @heart grey heart symbolizes no favorite (flag 0)
    @heart_red red heart symbolizes marked as favorite (flag 1)
*/
public void onClickFav(View v) {
    ImageButton favouriteButton = (ImageButton) findViewById(R.id.favourite_button);

    SharedPreferences prefs = getSharedPreferences("favInfo", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    // get the count value of the item which is loaded at the moment
    String count = prefs.getString("count", "");

    // get the unique key consisting of fav and the count text
    String key = "fav" + count;

    // get value stored with that key, default: if no value exists take 0
    String value = prefs.getString(key, "0");

    // check if value of favorite key is 0,
    // set image resource dependent on what value is stored behind the key
    if (value.equals("0")) {
        favouriteButton.setImageResource(R.drawable.heart_red);
    } else {
        favouriteButton.setImageResource(R.drawable.heart);
    }

    String isFav;

    // switch value to opposite
    if (value.equals("0")) {
        isFav = "1";
    } else {
        isFav = "0";
    }

    // store shared preferences
    editor.putString(key, isFav);
    editor.commit();
}
</code>```

Basically what I do here is: get the current item ("count" key) and build the unique key with it. Then check the value behind it and set the ImageResource accordingly. After that I change the value to opposite and save the unique key.

My problem: there happens something, but not the right thing. When the user clicks the ImageButton, the ImageButton of the item before are after it changes. e.g. the user clicks the ImageButton of item 7. Not the ImageButton of item 7 changes, but the ImageButton of item 6 or 8.

答:
Your problem is you using "count" value in SharedPreferences which overrides all the time in adapter so you have to update existing keyvalue so as you say you create key using

```<code>String key = "fav" + count;
</code>```

but in update you just updating random count

```<code>// get the count value of the item which is loaded at the moment
    String count = prefs.getString("count", "");
     String key = "fav" + count;
</code>```

so your key mismatches here so do one thing add position as tag for imagebutton as in instantiateItem  method add below line

```<code>// get the unique key consisting of fav and the current item position
        String key = "fav" + (position+1);
    imageButton.setTag(key)
</code>```

now in onClick

replace

```<code>// get the unique key consisting of fav and the count text
    String key = "fav" + count;
</code>```

with

```<code>// get the unique key consisting of fav and the count text
        String key =v.getTag().toString();
</code>```

you also don't need to find button in onClick

replace

```<code>ImageButton favouriteButton = (ImageButton) findViewById(R.id.favourite_button);
</code>```

with

```<code> ImageButton favouriteButton = (ImageButton)v;
</code>```

because it is already same button's click event and instance

also this sharepreference method only work for fixed image only, for dynamic it will better to use SQLite.

EDIT

For sending current position to new activity

In your instantiateItem method set

```<code>    ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
 imageView.setTag(postion);//set tag as current position

/*
    Method for click actions on the suggestion image
*/

 public void onClickImage(View v){

        Intent detailIntent = new Intent(activity, DetailActivity.class);
        detailIntent.putExtra("key_position",Integer.parseInt(v.getTag().toString()));///get tag and send it as int extra
        startActivity(detailIntent);
    }
</code>```

Now in new activity oncreate

```<code>/* onCreate method in new activity (DetailActivity) */

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

        ImageView imageView = (ImageView) findViewById(R.id.swipe_image);

        Toolbar sToolbar = (Toolbar) findViewById(R.id.detail_toolbar);
        setSupportActionBar(sToolbar);

        int count = getIntent().getIntExtra("key_position",0);//get int extra from calling activity

        TextView headline = (TextView) findViewById(R.id.island_name);
        ImageView image = (ImageView) findViewById(R.id.detailImage);
        TextView description = (TextView) findViewById(R.id.description);

        headline.setText(island_name[count]);
        image.setImageResource(image_resources[count]);
        description.setText(description_text[count]);
    }
</code>```

Body:
In school we have to develop our first Android app. Android is new to me and I'm here to learn something.

Today I worked the first time with SharedPreferences to save information about an ImageButton state. The layout uses a ViewPager. There are 10 items which the user can swipe. The ViewPager contains a TextView that counts the items. That works fine: e.g. the TextView of the first items shows [1/10] and the last one [10/10]. After the TextView you can find an image. That works also pretty good.

Now to my problem: under the Image I have installed an ImageButton. It signals if an item is a favorite or not. Favorite is pictured as red heart and no favorite as grey heart (default ImageResource).

This is my ViewPager of the main layout:

<android.support.v4.view.ViewPager
    android:id="@+id/image_swipe"
    android:layout_width="match_parent"
    android:layout_height="590dp"
    android:layout_marginTop="130dp" />

And this is the pagers layout:

<TextView
    android:id="@+id/image_count"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Here we count..."
    android:textColor="@android:color/black"
    android:textSize="16sp" />

<ImageView
    android:id="@+id/swipe_image"
    android:layout_width="match_parent"
    android:layout_height="365dp"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_marginTop="30dp"
    android:adjustViewBounds="false"
    android:onClick="onClickImage" />

<ImageButton
    android:id="@+id/favourite_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:background="@android:color/transparent"
    android:scaleType="fitCenter"
    android:src="@drawable/heart"
    android:onClick="onClickFav" />

All items need an unique key in order to save every items ImageButton state. The key is composed of the String "fav" and a counter (can be 1-10). That means we have 10 unique keys: fav1 - fav10. When the page is created for the given item position, I try to check if something is stored for the given key.

There can be 2 possible values behind a key: 0 and 1. 0 means no favorite, 1 is a favorite. If there is not yet any key set, the value will be 0 which is the default ImageButton state. After getting the value of the item key, the ImageResource of the ImageButton can be set.

The next step when creating the page, is to save a new key. That key has the name "count" and indicates which item is loaded at this moment.

All I just told you is in this adapter method (instantiateItem):

     /*
        Create the page for the given position
        Set image resources and text about current position
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
        TextView textView = (TextView) item_view.findViewById(R.id.image_count);
        ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);

        imageView.setImageResource(image_resources[position]);
        textView.setText("["+(position+1)+"/10]");

        SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // get the unique key consisting of fav and the current item position
        String key = "fav" + (position+1);

        String value = prefs.getString(key, "0");

        // check if value of favorite key is 0
        // set image resource dependent on what value is set
        if (value.equals("1")) {
            imageButton.setImageResource(R.drawable.heart_red);
        } else {
            imageButton.setImageResource(R.drawable.heart);
        }

        int p = (position+1);
        String count = Integer.toString(p);

        // store index of current adapter item as shared pref
        editor.putString("count", count);
        editor.commit();

        container.addView(item_view);

        return item_view;
    }

So this was when a item is loaded. After that the user can click on the ImageButton which activates following onClick method in the main activity:

/*
    Method for click actions on the favorite button
    @heart grey heart symbolizes no favorite (flag 0)
    @heart_red red heart symbolizes marked as favorite (flag 1)
*/
public void onClickFav(View v) {
    ImageButton favouriteButton = (ImageButton) findViewById(R.id.favourite_button);

    SharedPreferences prefs = getSharedPreferences("favInfo", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    // get the count value of the item which is loaded at the moment
    String count = prefs.getString("count", "");

    // get the unique key consisting of fav and the count text
    String key = "fav" + count;

    // get value stored with that key, default: if no value exists take 0
    String value = prefs.getString(key, "0");

    // check if value of favorite key is 0,
    // set image resource dependent on what value is stored behind the key
    if (value.equals("0")) {
        favouriteButton.setImageResource(R.drawable.heart_red);
    } else {
        favouriteButton.setImageResource(R.drawable.heart);
    }

    String isFav;

    // switch value to opposite
    if (value.equals("0")) {
        isFav = "1";
    } else {
        isFav = "0";
    }

    // store shared preferences
    editor.putString(key, isFav);
    editor.commit();
}

Basically what I do here is: get the current item ("count" key) and build the unique key with it. Then check the value behind it and set the ImageResource accordingly. After that I change the value to opposite and save the unique key.

My problem: there happens something, but not the right thing. When the user clicks the ImageButton, the ImageButton of the item before are after it changes. e.g. the user clicks the ImageButton of item 7. Not the ImageButton of item 7 changes, but the ImageButton of item 6 or 8.

Body:
Your problem is you using "count" value in SharedPreferences which overrides all the time in adapter so you have to update existing keyvalue so as you say you create key using

String key = "fav" + count;

but in update you just updating random count

// get the count value of the item which is loaded at the moment
    String count = prefs.getString("count", "");
     String key = "fav" + count;

so your key mismatches here so do one thing add position as tag for imagebutton as in instantiateItem  method add below line

// get the unique key consisting of fav and the current item position
        String key = "fav" + (position+1);
    imageButton.setTag(key)

now in onClick

replace

// get the unique key consisting of fav and the count text
    String key = "fav" + count;

with

// get the unique key consisting of fav and the count text
        String key =v.getTag().toString();

you also don't need to find button in onClick

replace

ImageButton favouriteButton = (ImageButton) findViewById(R.id.favourite_button);

with

 ImageButton favouriteButton = (ImageButton)v;

because it is already same button's click event and instance

also this sharepreference method only work for fixed image only, for dynamic it will better to use SQLite.

EDIT

For sending current position to new activity

In your instantiateItem method set

    ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
 imageView.setTag(postion);//set tag as current position

/*
    Method for click actions on the suggestion image
*/

 public void onClickImage(View v){

        Intent detailIntent = new Intent(activity, DetailActivity.class);
        detailIntent.putExtra("key_position",Integer.parseInt(v.getTag().toString()));///get tag and send it as int extra
        startActivity(detailIntent);
    }

Now in new activity oncreate

/* onCreate method in new activity (DetailActivity) */

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

        ImageView imageView = (ImageView) findViewById(R.id.swipe_image);

        Toolbar sToolbar = (Toolbar) findViewById(R.id.detail_toolbar);
        setSupportActionBar(sToolbar);

        int count = getIntent().getIntExtra("key_position",0);//get int extra from calling activity

        TextView headline = (TextView) findViewById(R.id.island_name);
        ImageView image = (ImageView) findViewById(R.id.detailImage);
        TextView description = (TextView) findViewById(R.id.description);

        headline.setText(island_name[count]);
        image.setImageResource(image_resources[count]);
        description.setText(description_text[count]);
    }


问:
How do you make tooltip show up for longer in IE
i got the following

```<code><span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">
</code>```

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?

答: You might be able to change the answer on jquery dynamic tooltip to your needs</p>

ContentLicense: CC BY-SA 2.5

Body:
i got the following

<span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?


问:
Angular 4 pass data between 2 not related components
I have a questions about passing data in Angular.

First, I don't have a structure as <parent><child [data]=parent.data></child></parent>

My structure is

```<code><container>
  <navbar>
    <summary></summary>
    <child-summary><child-summary>
  </navbar>
  <content></content>
</container>
</code>```

So, in  I have a select that do send value to <child-summary /> and <content />.

OnSelect method is well fired with (change) inside  component.

So, I tried with @Input, @Output and @EventEmitter directives, but I don't see how retrieve the event as @Input of the component, unless to go on parent/child pattern. All examples I've founded has a relation between component.

EDIT : Example with BehaviorSubject not working (all connected service to API works well, only observable is fired at start but not when select has value changed)

shared service = company.service.ts (used to retrieve company data)

```<code>import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SrvCompany {

    private accountsNumber = new BehaviorSubject<string[]>([]);
    currentAccountsNumber = this.accountsNumber.asObservable();

    changeMessage(accountsNumber: string[]) {
        this.accountsNumber.next(accountsNumber);
    }

    private _companyUrl = 'api/tiers/';

    constructor(private http: Http) { }

    getSociete(): Promise<Response> {
        let url = this._companyUrl;
        return this.http.get(url).toPromise();
    }
}
</code>```

invoice.component.ts (the "child")

```<code>import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvInvoice } from './invoice.service';
import { SrvCompany } from '../company/company.service';

@Component({
    selector: 'invoice',
    templateUrl: 'tsScripts/invoice/invoice.html',
    providers: [SrvInvoice, SrvCompany]
})

export class InvoiceComponent implements OnInit  {

    invoice: any;

    constructor(private srvInvoice: SrvInvoice, private srvCompany: SrvCompany)
    {

    }

    ngOnInit(): void {
        //this.getInvoice("F001");

        // Invoice data is linked to accounts number from company.
        this.srvCompany.currentAccountsNumber.subscribe(accountsNumber => {
            console.log(accountsNumber);
            if (accountsNumber.length > 0) {
                this.srvInvoice.getInvoice(accountsNumber).then(data => this.invoice = data.json());
            }
        });
    }

    //getInvoice(id: any) {
    //    this.srvInvoice.getInvoice(id).then(data => this.invoice = data.json());
    //}
}
</code>```

company.component.ts (the trigerring "parent")

```<code>import { Component, Inject, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvCompany } from './company.service';

@Component({
    selector: 'company',
    templateUrl: 'tsScripts/company/company.html',
    providers: [SrvCompany]
})

export class CompanyComponent implements OnInit {

    societes: any[];
    soc: Response[]; // debug purpose
    selectedSociete: any;

    ville: any;
    ref: any;
    cp: any;
    accountNumber: any[];

    constructor(private srvSociete: SrvCompany)
    {

    }

    ngOnInit(): void {
        this.getSocietes();
    }

    getSocietes(): void {

        this.srvSociete.getSociete()
            .then(data => this.societes = data.json())
            .then(data => this.selectItem(this.societes[0].Id));
    }

    selectItem(value: any) {
        this.selectedSociete = this.societes.filter((item: any) => item.Id === value)[0];
        this.cp = this.selectedSociete.CodePostal;
        this.ville = this.selectedSociete.Ville;
        this.ref = this.selectedSociete.Id;
        this.accountNumber = this.selectedSociete.Accounts;
        console.log(this.accountNumber);
        this.srvSociete.changeMessage(this.accountNumber);
    }
}
</code>```

答:
if component are not related than you need use Service

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

ContentLicense: CC BY-SA 4.0

Body:
I have a questions about passing data in Angular.

First, I don't have a structure as <parent><child [data]=parent.data></child></parent>

My structure is

<container>
  <navbar>

    <child-summary><child-summary>
  </navbar>
  <content></content>
</container>

So, in  I have a select that do send value to <child-summary /> and <content />.

OnSelect method is well fired with (change) inside  component.

So, I tried with @Input, @Output and @EventEmitter directives, but I don't see how retrieve the event as @Input of the component, unless to go on parent/child pattern. All examples I've founded has a relation between component.

EDIT : Example with BehaviorSubject not working (all connected service to API works well, only observable is fired at start but not when select has value changed)

shared service = company.service.ts (used to retrieve company data)

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SrvCompany {

    private accountsNumber = new BehaviorSubject<string[]>([]);
    currentAccountsNumber = this.accountsNumber.asObservable();

    changeMessage(accountsNumber: string[]) {
        this.accountsNumber.next(accountsNumber);
    }

    private _companyUrl = 'api/tiers/';

    constructor(private http: Http) { }

    getSociete(): Promise<Response> {
        let url = this._companyUrl;
        return this.http.get(url).toPromise();
    }
}

invoice.component.ts (the "child")

import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvInvoice } from './invoice.service';
import { SrvCompany } from '../company/company.service';

@Component({
    selector: 'invoice',
    templateUrl: 'tsScripts/invoice/invoice.html',
    providers: [SrvInvoice, SrvCompany]
})

export class InvoiceComponent implements OnInit  {

    invoice: any;

    constructor(private srvInvoice: SrvInvoice, private srvCompany: SrvCompany)
    {

    }

    ngOnInit(): void {
        //this.getInvoice("F001");

        // Invoice data is linked to accounts number from company.
        this.srvCompany.currentAccountsNumber.subscribe(accountsNumber => {
            console.log(accountsNumber);
            if (accountsNumber.length > 0) {
                this.srvInvoice.getInvoice(accountsNumber).then(data => this.invoice = data.json());
            }
        });
    }

    //getInvoice(id: any) {
    //    this.srvInvoice.getInvoice(id).then(data => this.invoice = data.json());
    //}
}

company.component.ts (the trigerring "parent")

import { Component, Inject, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvCompany } from './company.service';

@Component({
    selector: 'company',
    templateUrl: 'tsScripts/company/company.html',
    providers: [SrvCompany]
})

export class CompanyComponent implements OnInit {

    societes: any[];
    soc: Response[]; // debug purpose
    selectedSociete: any;

    ville: any;
    ref: any;
    cp: any;
    accountNumber: any[];

    constructor(private srvSociete: SrvCompany)
    {

    }

    ngOnInit(): void {
        this.getSocietes();
    }

    getSocietes(): void {

        this.srvSociete.getSociete()
            .then(data => this.societes = data.json())
            .then(data => this.selectItem(this.societes[0].Id));
    }

    selectItem(value: any) {
        this.selectedSociete = this.societes.filter((item: any) => item.Id === value)[0];
        this.cp = this.selectedSociete.CodePostal;
        this.ville = this.selectedSociete.Ville;
        this.ref = this.selectedSociete.Id;
        this.accountNumber = this.selectedSociete.Accounts;
        console.log(this.accountNumber);
        this.srvSociete.changeMessage(this.accountNumber);
    }
}


问:
how to use indexof in array set in angularjs
```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() {
            var a = this.drop.state;  }
});
</script>
<body>

<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>
</div>
</body>
</code>```

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

答:
you can assign code as value to option

```<code><option ng-repeat = "x in state" ng-value="x.code"> {{x.name}}
</code>```

Demo

var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.drop = {}
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() {
            var a = $scope.drop.state
            console.log(a)
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code> </code>```

State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}} </option>
</select>

```

Body:
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

Body:
you can assign code as value to option

<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}}

Demo

var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.drop = {}
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() {
            var a = $scope.drop.state
            console.log(a)
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}} </option>
</select>
</div>


问:
MongoDB instance not inserting data
I don't have MongoDB installed on my system, an instance is created virtually to the before mentioned IP address.

```<code>from pymongo import MongoClient

client = MongoClient('mongodb://....../')

mydb = client.test_database

import datetime

myrecord = {
        "author": "Duke",
        "title" : "PyMongo 101",
        "tags" : ["MongoDB", "PyMongo", "Tutorial"],
        "date" : datetime.datetime.utcnow()
        }

record_id = mydb.mytable.insert_one(myrecord)

print (record_id)
print (mydb.collection_names())
</code>```

This the error I am getting

答:
The MongoClient does not connect immediately. It is a "lazy" connection. Which means it doesn't attempt to connect until you run the insert method. The specific error you are receiving indicates that the driver was unable to connect to 5.9.84.39:5555.

You need to ensure the client can connect to the server. You should check the following items on both the machine running the Python code and the server running MongoDB.

Firewalls

Whitelists

Connectivity with the Mongo Shell

Title: MongoDB instance not inserting data

Body:
I don't have MongoDB installed on my system, an instance is created virtually to the before mentioned IP address.

from pymongo import MongoClient

client = MongoClient('mongodb://....../')

mydb = client.test_database

import datetime

myrecord = {
        "author": "Duke",
        "title" : "PyMongo 101",
        "tags" : ["MongoDB", "PyMongo", "Tutorial"],
        "date" : datetime.datetime.utcnow()
        }

record_id = mydb.mytable.insert_one(myrecord)

print (record_id)
print (mydb.collection_names())

This the error I am getting


问:
Google Apps Script: Setting color of an event using Calendar API
I would like to set specific colors for events.

I believe I have to use the Calendar API. I cannot figure out how to do this.

The code I am trying is:

```<code>var event = CalendarApp.getOwnedCalendarById(calendarID).createEvent(class, startTime, endTime, {description:lessonPlanDataComplete[t], colorId: 11});
</code>```

The colorId 11 should set as red, but all events coming out as default color.

Any helps/hints gratefully received,

Many thanks, Simon

答:
This is always possible. Try it out instead.

in your function:

```<code>var newEvent = calendar.createEvent(event_title, event_start_time, event_end_time,
  {
    location: event_location,
    guests: newGuests,
    sendInvites: 'true',
    description: event_description
  }
);

newEvent.setColor('4');
</code>```

Refer to: https://developers.google.com/apps-script/reference/calendar/event-color

The string to set is the numerical string representation of event color.

Body:
I would like to set specific colors for events.

I believe I have to use the Calendar API. I cannot figure out how to do this.

The code I am trying is:

var event = CalendarApp.getOwnedCalendarById(calendarID).createEvent(class, startTime, endTime, {description:lessonPlanDataComplete[t], colorId: 11});

The colorId 11 should set as red, but all events coming out as default color.

Any helps/hints gratefully received,

Many thanks, Simon

Body:
This is always possible. Try it out instead.

in your function:

var newEvent = calendar.createEvent(event_title, event_start_time, event_end_time,
  {
    location: event_location,
    guests: newGuests,
    sendInvites: 'true',
    description: event_description
  }
);

newEvent.setColor('4');

Refer to: https://developers.google.com/apps-script/reference/calendar/event-color

The string to set is the numerical string representation of event color.


问:
C# Memorystream is not fully saved to the file
I am exporting an object to csv using MemoryStream and StreamWriter. But after saving the file, I see that the end of the file is missing. Its cut of in the middle of a line.

Below is my code:

```<code>public void Export(ProductExport productExport)
{
    var country = (Country)(int.Parse(productExport.Firma.Code));

    using(var stream = new MemoryStream())
    {
        var sw = new StreamWriter(stream);

        // Write header row
        sw.WriteLine(
            "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
            "Groep",
            "TecDoc Leverancier",
            "TecDoc Ref",
            "SA",
            "EAN",
            "Omschrijving NL",
            "V/E",
            "VPE",
            "Prijs per",
            "Bruto prijs"
        );

        foreach(var product in productExport.Products)
        {
            // Write header row
            sw.WriteLine(
                "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
                product.Artgrp,
                product.TecDoc != null ? product.TecDoc.Supplier : "",
                product.TecDoc != null ? product.TecDoc.Value : "",
                product.Ids.Where<Id>(i => i.Type == "SA").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Ids.Where<Id>(i => i.Type == "EN").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Descriptions.Where<Description>(d => d.Lang == "NL").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.SalesUnit,
                product.PackingUnit.Value,
                product.PriceUnit.Value,
                product.Prices.First<Price>(p => p.Type == "BR" && p.Country == country.ToString()).Value
            );
        }

        FileSystem.AddFile(country + "-" + String.Format("{0:yyyyMMdd}", DateTime.Now) + ".csv", stream);

        sw.Flush();
    }
}
</code>```

And this is the code of the FileSystem.AddFile() function:

```<code>public void AddFile(string path, System.IO.Stream stream)
{
    var fullPath = GetFullPath(path);

    var directory = Path.GetDirectoryName(fullPath);
    if (directory == null) throw new InvalidOperationException("Can't get the directory.");
    Directory.CreateDirectory(directory); // Make sure the directory is created!

    if (stream.CanSeek)
        stream.Seek(0, SeekOrigin.Begin);

    using (var destination = (Stream)File.Create(fullPath))
        stream.CopyTo(destination);
}
</code>```

答: You need to flush the StreamWriter first and then create the file from the stream.

Body:
I am exporting an object to csv using MemoryStream and StreamWriter. But after saving the file, I see that the end of the file is missing. Its cut of in the middle of a line.

Below is my code:

public void Export(ProductExport productExport)
{
    var country = (Country)(int.Parse(productExport.Firma.Code));

    using(var stream = new MemoryStream())
    {
        var sw = new StreamWriter(stream);

        // Write header row
        sw.WriteLine(
            "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
            "Groep",
            "TecDoc Leverancier",
            "TecDoc Ref",
            "SA",
            "EAN",
            "Omschrijving NL",
            "V/E",
            "VPE",
            "Prijs per",
            "Bruto prijs"
        );

        foreach(var product in productExport.Products)
        {
            // Write header row
            sw.WriteLine(
                "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
                product.Artgrp,
                product.TecDoc != null ? product.TecDoc.Supplier : "",
                product.TecDoc != null ? product.TecDoc.Value : "",
                product.Ids.Where<Id>(i => i.Type == "SA").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Ids.Where<Id>(i => i.Type == "EN").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.Descriptions.Where<Description>(d => d.Lang == "NL").Select(i => i.Value).DefaultIfEmpty("").First(),
                product.SalesUnit,
                product.PackingUnit.Value,
                product.PriceUnit.Value,
                product.Prices.First<Price>(p => p.Type == "BR" && p.Country == country.ToString()).Value
            );
        }

        FileSystem.AddFile(country + "-" + String.Format("{0:yyyyMMdd}", DateTime.Now) + ".csv", stream);

        sw.Flush();
    }
}

And this is the code of the FileSystem.AddFile() function:

public void AddFile(string path, System.IO.Stream stream)
{
    var fullPath = GetFullPath(path);

    var directory = Path.GetDirectoryName(fullPath);
    if (directory == null) throw new InvalidOperationException("Can't get the directory.");
    Directory.CreateDirectory(directory); // Make sure the directory is created!

    if (stream.CanSeek)
        stream.Seek(0, SeekOrigin.Begin);

    using (var destination = (Stream)File.Create(fullPath))
        stream.CopyTo(destination);
}


问:
Why isn't counter() called in "false && counter()"?
I am trying to figure out how this boolean expression is evaluated:

```<code>int i = 0;
boolean exp = i > 1 && counter();
</code>```

In the following code:

```<code>public class Main {

    static int num = 0;

    public static boolean counter(){
            num++;
         if(num == 6){
             return true;
         }
          return false;
     }
    public static void main(String[] args) {
            //int i = 2;
              int i = 0;
            boolean exp = i > 1 && counter();
            System.out.println(num); // 0
            System.out.println(exp); // false
    }
 }
</code>```

Since i = 0, i > 1 is false and counter() returns false. However, I'm confused because the value of static variable num doesn't change despite the counter() function being in the boolean expression:

```<code>exp = i > 1 && counter();
</code>```

I was expecting the output to be

```<code>1
false
</code>```

but it is

```<code>0
false
</code>```

Why does counter() not seem to be called?

答:
&& operator evaluates the right side expression if the left side expression is true.

If any one of the expressions is false then the entire expression would be false in the && operator case -> no need to evaluate the other expressions. So the counter() expression is not at all executed in your case.

0 > 1 fails..

Hence counter() is not at all evaluated.

Body:
I am trying to figure out how this boolean expression is evaluated:

int i = 0;
boolean exp = i > 1 && counter();

In the following code:

public class Main {

    static int num = 0;

    public static boolean counter(){
            num++;
         if(num == 6){
             return true;
         }
          return false;
     }
    public static void main(String[] args) {
            //int i = 2;
              int i = 0;
            boolean exp = i > 1 && counter();
            System.out.println(num); // 0
            System.out.println(exp); // false
    }
 }

Since i = 0, i > 1 is false and counter() returns false. However, I'm confused because the value of static variable num doesn't change despite the counter() function being in the boolean expression:

exp = i > 1 && counter();

I was expecting the output to be

1
false

but it is

0
false

Why does counter() not seem to be called?


问:
NoSuchNodeError when determine tables in file
I use PyTables, I want to check whether a table has been created or not, if not, then create it.

I use the following code:

```<code>if handle.__contains__(handle.root.grades)==False:
    handle.create_table('/', 'grades', grades)
</code>```

while when there is no such table named "grades", the program report error:"NoSuchNodeError: group / does not have a child named grades"

once there is a table named "grades", the following

```<code>handle.__contains__(handle.root.grades)
</code>```

returns True.

How should I determine whether there is certain table?

答:
I  use the following expression to deal with the problem.

```<code>import tables as tb
try:
   handle.__contains__(handle.root.grades)
   print('contains grades')
except tb.NoSuchNodeError:
   print('there is no grades, will create it')
   handle.create_table('/', 'grades', grades)
</code>```

and in Pytables, the expression for file.contains is

```<code>def __contains__(self, path):

    try:
        self.get_node(path)
    except NoSuchNodeError:
        return False
    else:
        return True
</code>```

so, does pytables have some problems? or I don't import tables correctly?

Body:
I use PyTables, I want to check whether a table has been created or not, if not, then create it.

I use the following code:

if handle.__contains__(handle.root.grades)==False:
    handle.create_table('/', 'grades', grades)

while when there is no such table named "grades", the program report error:"NoSuchNodeError: group / does not have a child named grades"

once there is a table named "grades", the following

handle.__contains__(handle.root.grades)

returns True.

How should I determine whether there is certain table?

Body:
I  use the following expression to deal with the problem.

import tables as tb
try:
   handle.__contains__(handle.root.grades)
   print('contains grades')
except tb.NoSuchNodeError:
   print('there is no grades, will create it')
   handle.create_table('/', 'grades', grades)

and in Pytables, the expression for file.contains is

def __contains__(self, path):

    try:
        self.get_node(path)
    except NoSuchNodeError:
        return False
    else:
        return True

so, does pytables have some problems? or I don't import tables correctly?


问:
Error with WaterMarkTextBox
I'm trying to get this project to work but I keep getting two errors:

Error 1  The type 'xctk:WatermarkTextBox' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

Error 2  The attachable property 'Text' was not found in type 'WatermarkTextBox'.

I tried including namespace in two ways:

```<code>xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
</code>```

and like this:

```<code>xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
</code>```

Here is look at part of code that gives me errors when I use it:

```<code><xctk:WatermarkTextBox Name="txtSign" Grid.Column="1" Grid.Row="1" Margin="20,3,27,20"  Watermark="Put your sign here" >
                <xctk:WatermarkTextBox.Text>
                    <Binding Path="Type.Sign" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <validation:ValidacionType1 ValidationStep="RawProposedValue" />
                            <validation:ValidacionType1 ValidationStep="RawProposedValue" />
                        </Binding.ValidationRules>
                    </Binding>
                </xctk:WatermarkTextBox.Text>

                <Validation.ErrorTemplate>
                    <ControlTemplate>
                        <TextBlock Text="{Binding [0].ErrorContent}"  Margin="0,25,0,0" Foreground="White" Background="Black" />
                    </ControlTemplate>
                </Validation.ErrorTemplate>
            </xctk:WatermarkTextBox>
</code>```

Everything worked until I added this. What am I doing wrong?

答:
You need to download the Extended WPF Toolkit assemblies from somewhere and reference them from your application. These assemblies are not part of the .NET Framework.

The easiest way to do this is to use the NuGet package manager console from within Visual Studio.

Select Tools->NuGet Package Manager->Package Manager Console in Visual Studio and type in the Install-Package command suggested by @Ed Plunkett. This command will download and reference the appropriate assemblies (.dll files) for you.

You should then be able to build your application and use the WatermarkTextBox control.

Title: Error with WaterMarkTextBox

Body:
I'm trying to get this project to work but I keep getting two errors:

Error 1  The type 'xctk:WatermarkTextBox' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

Error 2  The attachable property 'Text' was not found in type 'WatermarkTextBox'.

I tried including namespace in two ways:

xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"

and like this:

xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"

Here is look at part of code that gives me errors when I use it:

<xctk:WatermarkTextBox Name="txtSign" Grid.Column="1" Grid.Row="1" Margin="20,3,27,20"  Watermark="Put your sign here" >
                <xctk:WatermarkTextBox.Text>
                    <Binding Path="Type.Sign" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <validation:ValidacionType1 ValidationStep="RawProposedValue" />
                            <validation:ValidacionType1 ValidationStep="RawProposedValue" />
                        </Binding.ValidationRules>
                    </Binding>
                </xctk:WatermarkTextBox.Text>

                <Validation.ErrorTemplate>
                    <ControlTemplate>
                        <TextBlock Text="{Binding [0].ErrorContent}"  Margin="0,25,0,0" Foreground="White" Background="Black" />
                    </ControlTemplate>
                </Validation.ErrorTemplate>
            </xctk:WatermarkTextBox>

Everything worked until I added this. What am I doing wrong?


问:
jquery/javascript - hide div if containing image is broken
i have a div with the class 'userFeatureProductImage'. this div is repeated however occasionally a broken image might come through so i want to hide the div as a precaution if this does happen. how can i do this?</p>

答:
You might try something like this:

```<code><script type="text/javascript"
        src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
     function hideBrokenImage(id) {
          $(id.+"userFeatureProductImage").hide();
     }
</script>
<div id="imageFilename" class="userFeatureProductImage">
     <img src="imageFilename.gif" onerror="hideBrokenImage(imageFilename);" />
</div>
</code>```

Where imageFilename is obviously dynamically created.

Body:
You might try something like this:

<script type="text/javascript"
        src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
     function hideBrokenImage(id) {
          $(id.+"userFeatureProductImage").hide();
     }
</script>
<div id="imageFilename" class="userFeatureProductImage">
     <img src="imageFilename.gif" onerror="hideBrokenImage(imageFilename);" />
</div>

Where imageFilename is obviously dynamically created.


问:
Editing existing SSRS report - issue with formatting
I've been editing/creating SSRS report for a bit sometime now but today I came across something that I'm really not sure about.

The report has a Tablix with about 8 columns. I needed to add an additional column in between some of the columns. However, i'm not able to format it (vertical align) as the other ones are formatted. If I try to change the formatting of the header of existing fields from Default to Middle it simply does not do anything. Also, I noticed that if I right click on one of the already existing headers in the tablix, the Expression is greyed out, basically not able to select it (as shown below)

In this case DOB is an already existing field, so right clicking on it prevents me from choosing Expression. Also, as the textbox in pic shows, both have the Vertical Align set to DEFAULT yet "Blah" looks out of place. Changing vertical align of DOB does not move it at all. It seems locked in place is there such a thing?

答:
It seems that there are blank lines (cr/lf) in "DOB" and/or "Blah". Double click on the cell and make sure to remove the extra lines.
This should make "expression" to show in the drop down and also responsive to alignment.</p>


问:
Is there any way to get the "Me" card from iPhone Address Book API?
So I'm stumped on this one.

In Mac OS X there is an easy way to get the "Me" card (the owner of the Mac/account) from the built-in address book API.

Has anyone found a way to find out which contact (if it exists) belongs to the owner of the iPhone?

答:
I came up with a partial solution to this

you can get the device name as follows

```<code>NSString *ownerName = [[UIDevice currentDevice] name];
</code>```

in English a device is originally called, for example, 'Joe Blogg's iPhone'

the break out the name

```<code> NSRange t = [ownerName rangeOfString:@"’s"];
    if (t.location != NSNotFound) {
        ownerName = [ownerName substringToIndex:t.location];
    }
</code>```

you can then take that name and search the contacts

CNContactStore *contactStore = [CNContactStore new];

```<code> NSPredicate *usersNamePredicate = [CNContact predicateForContactsMatchingName:usersName];

    NSArray * keysToFetch = @[[CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactSocialProfilesKey, ];

 NSArray * matchingContacts = [contactStore unifiedContactsMatchingPredicate:usersNamePredicate keysToFetch:keysToFetch error:nil];
</code>```

Of course other languages differ in the device name string e.g. 'iPhone Von Johann Schmidt' so more parsing needs to be done for other languages and it only works if the user hasn't changed the name of the device in iTunes to something like "Joes phone'  but it gives you a starting point

well... it gives you an array of matching items :) So if there is more than one contact with that array you just have to use pot luck and go with the first one or work thru multiple cards and take what you need from each.

I did say its a partial solution and even though it won't work for all user cases you might find it works for many of your users and reduces a little friction

Body:
I came up with a partial solution to this

you can get the device name as follows

NSString *ownerName = [[UIDevice currentDevice] name];

in English a device is originally called, for example, 'Joe Blogg's iPhone'

the break out the name

 NSRange t = [ownerName rangeOfString:@"’s"];
    if (t.location != NSNotFound) {
        ownerName = [ownerName substringToIndex:t.location];
    }

you can then take that name and search the contacts

CNContactStore *contactStore = [CNContactStore new];

 NSPredicate *usersNamePredicate = [CNContact predicateForContactsMatchingName:usersName];

    NSArray * keysToFetch = @[[CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactSocialProfilesKey, ];

 NSArray * matchingContacts = [contactStore unifiedContactsMatchingPredicate:usersNamePredicate keysToFetch:keysToFetch error:nil];

Of course other languages differ in the device name string e.g. 'iPhone Von Johann Schmidt' so more parsing needs to be done for other languages and it only works if the user hasn't changed the name of the device in iTunes to something like "Joes phone'  but it gives you a starting point

well... it gives you an array of matching items :) So if there is more than one contact with that array you just have to use pot luck and go with the first one or work thru multiple cards and take what you need from each.

I did say its a partial solution and even though it won't work for all user cases you might find it works for many of your users and reduces a little friction


问:
Remove items from array of documents in Spring+Mongo
I have a collection of documents like this in a mongo db :

```<code>"_id" : ObjectId("592bc37c339e7a23788b4c7c"),
"trips" : [
    {
        "tripGcsId" : "5937f86e339e7a2a58ac3186",
        "tripCounter" : NumberLong(1283),
        "tripRef" : "hjkhjk"
    },
    {
        "tripGcsId" : "5937f914339e7a2a58ac318b",
        "tripCounter" : NumberLong(1284),
        "tripRef" : "fjh"
    }
]
</code>```

and a method on the server side (Spring+Mongo):

```<code>public List<String> removeTripObject( List<String> tripIds )
{
    Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );

    Update update = new Update().pullAll( "trips.tripGcsId", new Object[] { tripIds } );
    getMongoTemplate().updateMulti( query, update, "ORDER" );
    return updatedOrders;
}
</code>```

The parameter tripIds is a list of tripGcsIds to be removed from trips array. The method above gives me the error: Write failed with error code 16837 and error message 'cannot use the part (trips of trips.tripGcsId) to traverse the element.

When I try with the $ operator, as described in other SO answers like this:

```<code>public List<String> removeTripObject( List<String> tripIds )
{
    Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );

    Update update = new Update().pullAll( "trips.$.tripGcsId", new Object[] { tripIds } );
    getMongoTemplate().updateMulti( query, update, "ORDER" );
    return updatedOrders;
}
</code>```

i got this error: Write failed with error code 16837 and error message 'Can only apply $pullAll to an array.

I'm not sure how should this pullAll command look like on the server side.

答:
You need to use $pull update operator which takes the query to match and delete all the matching rows in embedded array.

Something like

```<code>public List<String> removeTripObject( List<String> tripIds ) {
    Query query = Query.query( Criteria.where( "tripGcsId" ).in( tripIds ) );
    Update update = new Update().pull("trips", query );
    getMongoTemplate().updateMulti( new Query(), update, "ORDER" );
    return updatedOrders;
}
</code>```

Reference

https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents

Body:
I have a collection of documents like this in a mongo db :

"_id" : ObjectId("592bc37c339e7a23788b4c7c"),
"trips" : [
    {
        "tripGcsId" : "5937f86e339e7a2a58ac3186",
        "tripCounter" : NumberLong(1283),
        "tripRef" : "hjkhjk"
    },
    {
        "tripGcsId" : "5937f914339e7a2a58ac318b",
        "tripCounter" : NumberLong(1284),
        "tripRef" : "fjh"
    }
]

and a method on the server side (Spring+Mongo):

public List<String> removeTripObject( List<String> tripIds )
{
    Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );

    Update update = new Update().pullAll( "trips.tripGcsId", new Object[] { tripIds } );
    getMongoTemplate().updateMulti( query, update, "ORDER" );
    return updatedOrders;
}

The parameter tripIds is a list of tripGcsIds to be removed from trips array. The method above gives me the error: Write failed with error code 16837 and error message 'cannot use the part (trips of trips.tripGcsId) to traverse the element.

When I try with the $ operator, as described in other SO answers like this:

public List<String> removeTripObject( List<String> tripIds )
{
    Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );

    Update update = new Update().pullAll( "trips.$.tripGcsId", new Object[] { tripIds } );
    getMongoTemplate().updateMulti( query, update, "ORDER" );
    return updatedOrders;
}

i got this error: Write failed with error code 16837 and error message 'Can only apply $pullAll to an array.

I'm not sure how should this pullAll command look like on the server side.

Body:
You need to use $pull update operator which takes the query to match and delete all the matching rows in embedded array.

Something like

public List<String> removeTripObject( List<String> tripIds ) {
    Query query = Query.query( Criteria.where( "tripGcsId" ).in( tripIds ) );
    Update update = new Update().pull("trips", query );
    getMongoTemplate().updateMulti( new Query(), update, "ORDER" );
    return updatedOrders;
}

Reference

https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents


问:
Bootstrap 4 checkbox changes size with background-color change
When I change the background of my checkbox, the size of the check icon resizes too for some reason. How can I stop that from happening?

Take a look at my code and see what I mean:

.custom-checkbox .custom-control-indicator {
  border-radius: 50%;
  height: 25px;
  width: 25px;
  background-color: #fff;
  border: 1px solid #2c2b2c;
}
.custom-control-description {
  color: #2c2b2c;
  text-transform: uppercase;
  line-height: 2.7;
  font-size: 12px;
}
/* When I remove background the icon goes back to that default size */
.custom-control-input:checked~.custom-control-indicator {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="form-check">
  <label class="custom-control custom-checkbox">
     <input type="checkbox" class="custom-control-input">
     <span class="custom-control-indicator"></span>
     <span class="custom-control-description ml-4">Checkbox</span>
   </label>
</div> <!-- /.form-check --></code>```

答:
With the shorthand-property background you overwrite all the background-* properties, set by Bootstrap 4. I think you want to change only the background-color property, so you can use the following solution:

solution using Bootstrap 4 (alpha) - original answer:

.custom-checkbox .custom-control-indicator {
  background-color: #fff;
  border: 1px solid #2c2b2c;
  border-radius: 50%;
  height: 25px;
  width: 25px;
}
.custom-control-description {
  color: #2c2b2c;
  font-size: 12px;
  line-height: 2.7;
  text-transform: uppercase;
}

/* When I remove background the icon goes back to that default size */
.custom-control-input:checked ~ .custom-control-indicator {
  background-color: red !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="form-check">
  <label class="custom-control custom-checkbox">
     <input type="checkbox" class="custom-control-input">
     <span class="custom-control-indicator"></span>
     <span class="custom-control-description ml-4">Checkbox</span>
   </label>
</div></code>```

solution using Bootstrap 4 (stable - not alpha or beta):

.form-check .custom-control-label {
  color: #2c2b2c;
  font-size: 12px;
  line-height: 2.7;
  padding-left:15px;
  text-transform: uppercase;
}
.form-check .custom-control-label::after,
.form-check .custom-control-label::before {
  height: 25px;
  width: 25px;
}
.form-check .custom-control-label::before {
  background-color: #fff;
  border: 1px solid #2c2b2c;
  border-radius: 50%;
}

/* When I remove background the icon goes back to that default size */
.custom-control-input:checked ~ .custom-control-label::before {
  background-color: red !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="form-check">
  <div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input" id="customControlID">
    <label class="custom-control-label" for="customControlID">Checkbox</label>
  </div>
</div></code>```

What is happening using the background shorthand property?

By only using the background property you overwrite the following CSS rules:

```<code>background-size: 50% 50%;
background-repeat: no-repeat;
background-position: center;
</code>```

Body:
When I change the background of my checkbox, the size of the check icon resizes too for some reason. How can I stop that from happening?

Take a look at my code and see what I mean:

.custom-checkbox .custom-control-indicator {
  border-radius: 50%;
  height: 25px;
  width: 25px;
  background-color: #fff;
  border: 1px solid #2c2b2c;
}
.custom-control-description {
  color: #2c2b2c;
  text-transform: uppercase;
  line-height: 2.7;
  font-size: 12px;
}
/* When I remove background the icon goes back to that default size */
.custom-control-input:checked~.custom-control-indicator {
  background: red;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

     <input type="checkbox" class="custom-control-input">

     Checkbox

Body:
With the shorthand-property background you overwrite all the background-* properties, set by Bootstrap 4. I think you want to change only the background-color property, so you can use the following solution:

solution using Bootstrap 4 (alpha) - original answer:

.custom-checkbox .custom-control-indicator {
  background-color: #fff;
  border: 1px solid #2c2b2c;
  border-radius: 50%;
  height: 25px;
  width: 25px;
}
.custom-control-description {
  color: #2c2b2c;
  font-size: 12px;
  line-height: 2.7;
  text-transform: uppercase;
}

/* When I remove background the icon goes back to that default size */
.custom-control-input:checked ~ .custom-control-indicator {
  background-color: red !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="form-check">
  <label class="custom-control custom-checkbox">
     <input type="checkbox" class="custom-control-input">
     <span class="custom-control-indicator"></span>
     <span class="custom-control-description ml-4">Checkbox</span>
   </label>
</div>

solution using Bootstrap 4 (stable - not alpha or beta):

.form-check .custom-control-label {
  color: #2c2b2c;
  font-size: 12px;
  line-height: 2.7;
  padding-left:15px;
  text-transform: uppercase;
}
.form-check .custom-control-label::after,
.form-check .custom-control-label::before {
  height: 25px;
  width: 25px;
}
.form-check .custom-control-label::before {
  background-color: #fff;
  border: 1px solid #2c2b2c;
  border-radius: 50%;
}

/* When I remove background the icon goes back to that default size */
.custom-control-input:checked ~ .custom-control-label::before {
  background-color: red !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="form-check">
  <div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input" id="customControlID">
    <label class="custom-control-label" for="customControlID">Checkbox</label>
  </div>
</div>

What is happening using the background shorthand property?

By only using the background property you overwrite the following CSS rules:

background-size: 50% 50%;
background-repeat: no-repeat;
background-position: center;


问:
Playing a wav file in Java after compiling it to JAR
so I am making a birthday present for a programmer friend of mine. I am not that good with code but I made a window + gif + sound. But once I test it on another PC the sound won't work anymore, but the JAR file is big enough to contain the WAV. PLease help me, I really want to make a nice birthday gift. Here is the Sound code + main </p>

```<code> public static void play() {
    try {

        File file = new File("C:/Users/timma/IdeaProjects/BirthdayAshley/1" + ".wav");
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
        Thread.sleep(clip.getMicrosecondLength());

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

public static void main(String[] args){
    JFrame jf = new JFrame ("Happy Birthday");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(617,345);
    jf.add(new Birthday());
    jf.setVisible(true);
    jf.setResizable(false);
    play();

}
</code>```

答:
If the WAV is inside a JAR, it can't be referenced via a file.
But you can open it via Class.getResourceAsStream(). Everything else should stay the same.

```<code>InputStream stream =
    SomeClassInTheSameJar.class.getResourceAsStream("/BirthdayAshley/1.wav");
</code>```

Body:
so I am making a birthday present for a programmer friend of mine. I am not that good with code but I made a window + gif + sound. But once I test it on another PC the sound won't work anymore, but the JAR file is big enough to contain the WAV. PLease help me, I really want to make a nice birthday gift. Here is the Sound code + main

 public static void play() {
    try {

        File file = new File("C:/Users/timma/IdeaProjects/BirthdayAshley/1" + ".wav");
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
        Thread.sleep(clip.getMicrosecondLength());

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

public static void main(String[] args){
    JFrame jf = new JFrame ("Happy Birthday");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(617,345);
    jf.add(new Birthday());
    jf.setVisible(true);
    jf.setResizable(false);
    play();

}

Body:
If the WAV is inside a JAR, it can't be referenced via a file.
But you can open it via Class.getResourceAsStream(). Everything else should stay the same.

InputStream stream =
    SomeClassInTheSameJar.class.getResourceAsStream("/BirthdayAshley/1.wav");


问:
native heap usage android
I need to know the amount of the heap usage of an applications and how the memory is allocated. Is there any chance to get a general picture of this? I want something like an hprof but more complete.

thanks in advance.

答: Only by modifying the firmware. Getting a heap dump of another application would be a serious security hole.</p>

Title: native heap usage android


问:
Will PickupDeliveryLocation work when using an outgoing mail server on a different domain than our own?
What happens when the outgoing mail server is not part of the local domain?  For example, I work for company xyz.com and our smtp server is mail.xyz.com.  We host client sites in a multitennant application.  We allow our users to point to their own smtp server using email configurations we store in our database.

The code we use to send emails loads the configuration with the smtp information and the authorization needed to send an email on behalf of our clients through their email system.

Currently we are running into concurrency issue that is causing timeouts for various clients when notifications are being processed.  They are currently configured to be sent immediately.  I've read that moving to the local pickup directory can solve this issue.

I am concerned if I specify a path like C:\Temp\Mail but use an SMTP connection to a clients mail server is that going to work?  Doesn't the email being created and sent from the pickup location need to be on the same domain as the smtp server?

How will the clients SMTP server know .eml file has been generated for their domain and needs to be sent out without having to change our client's environment?   If someone can provide any information as to how the SMTP and Specified Pickup Locations work I would greatly appreciate it.

答:
The basic operation of an SMTP server in this sense is to monitor a specific set of folders and perform an action when an event occurs. Where your concern is is in that a file dropped into the pickup location is parsed and sent.

The basic SMTP operation allows any email server to send any email regardless of the domain that the email says it is from. This obviously caused issues with fraudulent emails and has been mitigated originally by Designated Sender and further extended via SPF, DIM, and DMARC.

So what your client would need to do is to have their SMTP setup properly and configured for your email domain(s). On your end it would be recommended to only allow the Designated Senders generate emails, and set up SPF etc for those clients as well

Microsoft has a good article on the SMTP basics How SMTP Works
Google has plenty of lists for SPF, DKIM, and DMARC as well.


问:
Open itinerary on iOS device with ionic 2
I try to open native map of an iOS with an itinerary.

With Android I use this :

```<code>openNativeMap() {
    var coords = this.group.latitude + "," + this.group.latitude;
    let address_to_request = this.group.address + "+" +  this.group.city;
    window.open("http://maps.google.com/maps?q=" + coords + "&daddr="+ address_to_request +"&f=d&mode=driving");
    return;
}
</code>```

It works on android but obviously not on ios.

So I found this solution :

```<code>openNativeMap() {
    var coords = this.group.latitude + "," + this.group.latitude;
    let address_to_request = this.group.address + "+" +  this.group.city;
    window.open('maps://?q=' + 'MyLocation' + '&saddr=' + '200' + ',' + '200' + '&daddr=' + coords, '_system');
    return;
}
</code>```

I tried to run it on my iOS device, but when I run this function, nothing append.

Q : How can I open native iOS maps application like I do it for android ?

答:
I found a solution.

I write this code in my .ts file :

```<code>openNativeMap() {
    var coords = this.group.latitude + "," + this.group.longitude;
    let url: string = "maps://maps.apple.com/?q=" + coords;
    let address_to_request = this.group.address + "+" +  this.group.city;
    window.location.href = url;
    return;
  }
</code>```

And I add this line in my config.xml

```<code><allow-navigation href="*"/>
</code>```

It works fine.

Body:
I try to open native map of an iOS with an itinerary.

With Android I use this :

openNativeMap() {
    var coords = this.group.latitude + "," + this.group.latitude;
    let address_to_request = this.group.address + "+" +  this.group.city;
    window.open("http://maps.google.com/maps?q=" + coords + "&daddr="+ address_to_request +"&f=d&mode=driving");
    return;
}

It works on android but obviously not on ios.

So I found this solution :

openNativeMap() {
    var coords = this.group.latitude + "," + this.group.latitude;
    let address_to_request = this.group.address + "+" +  this.group.city;
    window.open('maps://?q=' + 'MyLocation' + '&saddr=' + '200' + ',' + '200' + '&daddr=' + coords, '_system');
    return;
}

I tried to run it on my iOS device, but when I run this function, nothing append.

Q : How can I open native iOS maps application like I do it for android ?

Body:
I found a solution.

I write this code in my .ts file :

openNativeMap() {
    var coords = this.group.latitude + "," + this.group.longitude;
    let url: string = "maps://maps.apple.com/?q=" + coords;
    let address_to_request = this.group.address + "+" +  this.group.city;
    window.location.href = url;
    return;
  }

And I add this line in my config.xml

<allow-navigation href="*"/>

It works fine.


答:
Even though the other answer is valid, this is the right way to go about it:

```<code><select id="stat" ng-model="drop.state" ng-options="x.code as x.name for x in state" ng-change="onChange()">
  <option value="">Select a value</option>
</select>
</code>```

If the purpose of the ng-change was to get the state code, this way it's not needed. Your ng-model will be equal to the selected state code.

Title: how to use indexof in array set in angularjs

Body:
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

Body:
Even though the other answer is valid, this is the right way to go about it:

<select id="stat" ng-model="drop.state" ng-options="x.code as x.name for x in state" ng-change="onChange()">
  <option value="">Select a value</option>
</select>

If the purpose of the ng-change was to get the state code, this way it's not needed. Your ng-model will be equal to the selected state code.


问:
How can i get the DD/MM/YYYY formar in my datepicker?
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

```
</div>
</div>
</p>

<p>I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)</p>

<p>I have more information in that file, there are all the scripts i use</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="<?=$base_url?>js/es-ES.js"></script>
<script src="<?=$base_url?>js/jquery.min.js"></script>
<script src="<?=$base_url?>js/moment.js"></script>
<script src="<?=$base_url?>js/bootstrap.min.js"></script>
<script src="<?=$base_url?>js/bootstrap-datetimepicker.js"></script>
<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />
<script src="<?=$base_url?>js/bootstrap-datetimepicker.es.js"></script></code>```

答:
I just noticed there is a mistake in your code that it could be affecting:

                        <input type='text' id="from" name="from" class="form-control" readonly  />

                    Final de castigo

                        <input type='text' name="to" id="to" class="form-control" readonly />

```
</div>
</div>
</p>

<p>Here you are using twice the id "from" and the id "to". The id value must to be unique. It should be only one in all the code. And in this case it should be in the div with the class 'input-group'.</p>

<p>Look this example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class='input-group date' id='datepicker1'>
               <input type='text' class="form-control" placeholder="Select preferred meeting date"/>
               <span class="input-group-addon">
                   <span class="glyphicon glyphicon-calendar"></span>
               </span>
           </div></code>```

After that you can choose the format of the datepicker by the next javascript code:

 ```

This should work perfectly. I hope this could help you.

Body:
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)

I have more information in that file, there are all the scripts i use

<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />

Body:
I just noticed there is a mistake in your code that it could be affecting:

 <div class='input-group date' id='from'>
                        <input type='text' id="from" name="from" class="form-control" readonly  />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
                    </div>

                    <br>

                    <label for="to">Final de castigo </label>
                    <div class='input-group date' id='to'>
                        <input type='text' name="to" id="to" class="form-control" readonly />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
                    </div>

Here you are using twice the id "from" and the id "to". The id value must to be unique. It should be only one in all the code. And in this case it should be in the div with the class 'input-group'.

Look this example:

  <div class='input-group date' id='datepicker1'>
               <input type='text' class="form-control" placeholder="Select preferred meeting date"/>
               <span class="input-group-addon">
                   <span class="glyphicon glyphicon-calendar"></span>
               </span>
           </div>

After that you can choose the format of the datepicker by the next javascript code:

 <script type="text/javascript">
                $(function () {
                    $('#datepicker1').datetimepicker({
                      viewMode: 'days',
                      format: 'DD/MM/YYYY'
                    });
                });
        </script>

This should work perfectly. I hope this could help you.


问:
Returning a value produced in Kotlin coroutine
I am trying to return a value generated from coroutine

```<code>fun nonSuspending (): MyType {
    launch(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    //Do something to get the value out of coroutine context
    return somehowGetMyValue
}
</code>```

I have come up with the following solution (not very safe!):

```<code>fun nonSuspending (): MyType {
    val deferred = async(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    while (deferred.isActive) Thread.sleep(1)
    return deferred.getCompleted()
}
</code>```

I also thought about using event bus, but is there a more elegant solution to this problem?

Thanks in advance.

答:
You can do

```<code>val result = runBlocking(CommonPool) {
    suspendingFunctionThatReturnsMyValue()
}
</code>```

to block until the result is available.

Body:
I am trying to return a value generated from coroutine

fun nonSuspending (): MyType {
    launch(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    //Do something to get the value out of coroutine context
    return somehowGetMyValue
}

I have come up with the following solution (not very safe!):

fun nonSuspending (): MyType {
    val deferred = async(CommonPool) {
        suspendingFunctionThatReturnsMyValue()
    }
    while (deferred.isActive) Thread.sleep(1)
    return deferred.getCompleted()
}

I also thought about using event bus, but is there a more elegant solution to this problem?

Thanks in advance.

Body:
You can do

val result = runBlocking(CommonPool) {
    suspendingFunctionThatReturnsMyValue()
}

to block until the result is available.


答:
use <MyClass>.class().getAsStream("/1.wav") to load the file. So it will loaded from your jar not with an absolut Path that not exists.

```<code>clip.open(AudioSystem.getAudioInputStream(<MyClass>.class.getAsStream("/1.wav")));
</code>```

Title: Playing a wav file in Java after compiling it to JAR

Body:
use <MyClass>.class().getAsStream("/1.wav") to load the file. So it will loaded from your jar not with an absolut Path that not exists.

clip.open(AudioSystem.getAudioInputStream(<MyClass>.class.getAsStream("/1.wav")));


问:
Index on a Date column - use Between/And or Greater/Less
I was asked this question at an interview. AdventurWorks2012.Sales.CreditCard table. First, I created a non-clustered index on ModifiedDate column to simulate the interview question. I need to find records for, let's say July, 2007

```<code>SELECT cc.CreditCardID, cc.ModifiedDate
FROM sales.CreditCard cc
WHERE cc.ModifiedDate >= '07/01/2007' OR cc.ModifiedDate < '08/01/2007'
------------
SELECT cc.CreditCardID, cc.ModifiedDate
FROM sales.CreditCard cc
WHERE cc.ModifiedDate BETWEEN '07/01/2007' AND  '07/31/2007'
------------
SELECT cc.CreditCardID,  cc.ModifiedDate
FROM sales.CreditCard cc
WHERE Year(cc.ModifiedDate) = 2007 AND month(cc.ModifiedDate) = 7
</code>```

Here are the execution plans. 1) I don't get it why Between is the fastest query and the only one using NCIndex, whereas I was told standard SQL(first query) would be the fastest. 2) They say, avoid using functions in where clause, but, it is showing the same result with the first query where I don't use a function.

答: As noted in the comments. The first statments where clause is incorrectly using OR instead of AND and will make the statement return all rows which will be slower than a subset of the rows. </p>

Body:
I was asked this question at an interview. AdventurWorks2012.Sales.CreditCard table. First, I created a non-clustered index on ModifiedDate column to simulate the interview question. I need to find records for, let's say July, 2007

SELECT cc.CreditCardID, cc.ModifiedDate
FROM sales.CreditCard cc
WHERE cc.ModifiedDate >= '07/01/2007' OR cc.ModifiedDate < '08/01/2007'
------------
SELECT cc.CreditCardID, cc.ModifiedDate
FROM sales.CreditCard cc
WHERE cc.ModifiedDate BETWEEN '07/01/2007' AND  '07/31/2007'
------------
SELECT cc.CreditCardID,  cc.ModifiedDate
FROM sales.CreditCard cc
WHERE Year(cc.ModifiedDate) = 2007 AND month(cc.ModifiedDate) = 7

Here are the execution plans. 1) I don't get it why Between is the fastest query and the only one using NCIndex, whereas I was told standard SQL(first query) would be the fastest. 2) They say, avoid using functions in where clause, but, it is showing the same result with the first query where I don't use a function.


问:
Check time in stored procedure
I have a stored procedure that takes a lot of time to execute. We want it to execute during the night, but it has to check for the current time every now and then, and at a given time it has to stop executing. How do I do that? Please provide me with the code I can use in my stored procedure. We are using Microsoft SQL Server 2005.</p>

答:
Why woudl you want to exist a proc that is not finished? Wouldn't you be leaving things in a bad state as far as data integrity or rolling back all the work you just did??

Wouldn't it be a better solution to try to improve the performance of the proc?

Title: Check time in stored procedure