问:
activity switching not working without finish() method
My code is as shown below:

TableActivity.java

```<code>public class TableActivity extends AppCompatActivity {

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_selection);
        itemName = (TextView) findViewById(R.id.itemName);
        foodMenuLayout = (LinearLayout) findViewById(R.id.foodMenuLayout);
        drinkMenuLayout = (LinearLayout) findViewById(R.id.drinksMenuLayout);
        tableNo = (TextView) findViewById(R.id.tableNo);
        foodMenu = (TextView) findViewById(R.id.foodMenu);
        drinksMenu = (TextView) findViewById(R.id.drinksMenu);
        tapLayout = (LinearLayout) findViewById(R.id.tapLayout);
        foodImage = (ImageView) findViewById(R.id.foodImage);
        drinkImage = (ImageView) findViewById(R.id.drinkImage);

        getFoodTruckInfo();

        tapLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tableList = TableList.getInstance(MyCart.getInstance().getTableNo());
                tableList.setItemListener(TableActivity.this);
                tableList.setCancelable(false);
                tableList.show(getSupportFragmentManager(), null);
            }
        });

        setFontStyle();

        foodMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchItemActivity();
                }
            }
        });

        drinkMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchDrinksActivity();
                }
            }
        });
    }

    private void lauchItemActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckItemsActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, false);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckItemList());

        startActivityForResult(intent, Consts.ITEMS_ACTIVITY);
    }

    private void lauchDrinksActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckDrinksActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, true);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckDrinkList());
        startActivityForResult(intent, Consts.DRINKS_ACTIVITY);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Consts.ITEMS_ACTIVITY) {
                lauchDrinksActivity();
            } else if (requestCode == Consts.DRINKS_ACTIVITY) {
                lauchItemActivity();
            }
        }
    }
}
</code>```

FoodTruckItemsActivity.java

```<code>public class FoodTruckItemsActivity extends AppCompatActivity implements
        FoodTruckItemsAdapter.OnItemClickListener, FoodTruckItemFragment.FoodTruckItemListener,
        ViewPager.OnPageChangeListener, View.OnClickListener {

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

 routeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routeToAnotherMenu();
            }
        });
    }

 private void routeToAnotherMenu() {
        setResult(Activity.RESULT_OK);

    }
}
</code>```

FoodTruckItemsActivity.java and FoodTruckDrinksActivity.java are identical. So what I want here is if I press routeView, it should switch from FoodTruckItemsActivity.java to FoodTruckDrinksActivity.java and vice-versa.
  For that I have written routeToAnotherMenu() method. Now problem here is if I do not write finish() inside routeToAnotherMenu, it does not load another activity. But if I write finish after setResult() then it works perfectly.

The main  reason why I do not prefer finish() inside that method because it will erase the data . So is there any way through which I can do it without writing finish() method?

答:
In Your case FoodTruckItemActivity is Common activity from where you open your FoodTruckDrinkActivity.

Now, For E.g declare the ArrayList in TableActivity to store all your selected data in that arrayList.

Now When you startActivityForResult() for FoodTruckItemsActivity. In FoodTruckItemsActivity declare the ArrayList for adding the data. Now when you route to another menu write this.

```<code>Intent intent=new Intent();
intent.putStringArrayList("FOODITEMLIST", myItemList);
setResult(intent);
finish();
</code>```

Now In your Table activity the result comes here in onActivityResult.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == Consts.ITEMS_ACTIVITY) {
            // Get the arraylist and add that list in Table Activity Main ArrayList
            // which we declare earlier in Table Activity.
            lauchDrinksActivity();
        } else if (requestCode == Consts.DRINKS_ACTIVITY) {
            lauchItemActivity();
        }
    }
}
</code>```

Body:
My code is as shown below:

TableActivity.java

public class TableActivity extends AppCompatActivity {

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_selection);
        itemName = (TextView) findViewById(R.id.itemName);
        foodMenuLayout = (LinearLayout) findViewById(R.id.foodMenuLayout);
        drinkMenuLayout = (LinearLayout) findViewById(R.id.drinksMenuLayout);
        tableNo = (TextView) findViewById(R.id.tableNo);
        foodMenu = (TextView) findViewById(R.id.foodMenu);
        drinksMenu = (TextView) findViewById(R.id.drinksMenu);
        tapLayout = (LinearLayout) findViewById(R.id.tapLayout);
        foodImage = (ImageView) findViewById(R.id.foodImage);
        drinkImage = (ImageView) findViewById(R.id.drinkImage);

        getFoodTruckInfo();

        tapLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tableList = TableList.getInstance(MyCart.getInstance().getTableNo());
                tableList.setItemListener(TableActivity.this);
                tableList.setCancelable(false);
                tableList.show(getSupportFragmentManager(), null);
            }
        });

        setFontStyle();

        foodMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchItemActivity();
                }
            }
        });

        drinkMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchDrinksActivity();
                }
            }
        });
    }

    private void lauchItemActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckItemsActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, false);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckItemList());

        startActivityForResult(intent, Consts.ITEMS_ACTIVITY);
    }

    private void lauchDrinksActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckDrinksActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, true);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckDrinkList());
        startActivityForResult(intent, Consts.DRINKS_ACTIVITY);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Consts.ITEMS_ACTIVITY) {
                lauchDrinksActivity();
            } else if (requestCode == Consts.DRINKS_ACTIVITY) {
                lauchItemActivity();
            }
        }
    }
}

FoodTruckItemsActivity.java

public class FoodTruckItemsActivity extends AppCompatActivity implements
        FoodTruckItemsAdapter.OnItemClickListener, FoodTruckItemFragment.FoodTruckItemListener,
        ViewPager.OnPageChangeListener, View.OnClickListener {

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

 routeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routeToAnotherMenu();
            }
        });
    }

 private void routeToAnotherMenu() {
        setResult(Activity.RESULT_OK);

    }
}

FoodTruckItemsActivity.java and FoodTruckDrinksActivity.java are identical. So what I want here is if I press routeView, it should switch from FoodTruckItemsActivity.java to FoodTruckDrinksActivity.java and vice-versa.
  For that I have written routeToAnotherMenu() method. Now problem here is if I do not write finish() inside routeToAnotherMenu, it does not load another activity. But if I write finish after setResult() then it works perfectly.

The main  reason why I do not prefer finish() inside that method because it will erase the data . So is there any way through which I can do it without writing finish() method?

Body:
In Your case FoodTruckItemActivity is Common activity from where you open your FoodTruckDrinkActivity.

Now, For E.g declare the ArrayList in TableActivity to store all your selected data in that arrayList.

Now When you startActivityForResult() for FoodTruckItemsActivity. In FoodTruckItemsActivity declare the ArrayList for adding the data. Now when you route to another menu write this.

Intent intent=new Intent();
intent.putStringArrayList("FOODITEMLIST", myItemList);
setResult(intent);
finish();

Now In your Table activity the result comes here in onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == Consts.ITEMS_ACTIVITY) {
            // Get the arraylist and add that list in Table Activity Main ArrayList
            // which we declare earlier in Table Activity.
            lauchDrinksActivity();
        } else if (requestCode == Consts.DRINKS_ACTIVITY) {
            lauchItemActivity();
        }
    }
}


来源: stackexchange

问:
how to add id to a autogenerafted text box
I have a pop up menu(kendo) in that there is a text box which created by Kendo

```<code>< input name="Fname" class="k-input k-textbox" type="text" data-bind="value:Fname >
</code>```

I want to give it an id,since its generated by Kendo how should I do that?

答:
element = document.getElementsByName("Fname")

here you have your element

element.id = "MortDeLol"

here you set your Id

ContentLicense: CC BY-SA 3.0

Body:
I have a pop up menu(kendo) in that there is a text box which created by Kendo

< input name="Fname" class="k-input k-textbox" type="text" data-bind="value:Fname >

I want to give it an id,since its generated by Kendo how should I do that?


问:
Package 'php5-gd' has no installation candidate
"PHP module gd: Missing" I received such an error. and I'm trying to install php5-gd.

```<code>apt-get install php5-gd
</code>```

I am using Ubuntu 16.10 and PHP version 7. I made all the updates.

When I tried to install php5-gd, I got an error like below.

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package php5-gd is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'php5-gd' has no installation candidate
</code>```

答:
First check which php version you have by sudo php -v. I have php7 so the result is:

```<code>PHP 7.0.18-0ubuntu0.17.04.1 (cli) (built: Apr 26 2017 23:59:48) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.18-0ubuntu0.17.04.1, Copyright (c) 1999-2017, by Zend Technologies
</code>```

since i have php7, I will do the following to list the php packages

```<code>sudo apt-cache search php7-*
</code>```

this returned

```<code>libapache2-mod-php7.0 - server-side, HTML-embedded scripting language (Apache 2 module)
php-all-dev - package depending on all supported PHP development packages
php7.0 - server-side, HTML-embedded scripting language (metapackage)
php7.0-cgi - server-side, HTML-embedded scripting language (CGI binary)
php7.0-cli - command-line interpreter for the PHP scripting language
php7.0-common - documentation, examples and common module for PHP
php7.0-curl - CURL module for PHP
php7.0-dev - Files for PHP7.0 module development
php7.0-gd - GD module for PHP
php7.0-gmp - GMP module for PHP
php7.0-json - JSON module for PHP
php7.0-ldap - LDAP module for PHP
php7.0-mysql - MySQL module for PHP
php7.0-odbc - ODBC module for PHP
php7.0-opcache - Zend OpCache module for PHP
php7.0-pgsql - PostgreSQL module for PHP
php7.0-pspell - pspell module for PHP
php7.0-readline - readline module for PHP
php7.0-recode - recode module for PHP
php7.0-snmp - SNMP module for PHP
php7.0-sqlite3 - SQLite3 module for PHP
php7.0-tidy - tidy module for PHP
php7.0-xml - DOM, SimpleXML, WDDX, XML, and XSL module for PHP
php7.0-xmlrpc - XMLRPC-EPI module for PHP
libphp7.0-embed - HTML-embedded scripting language (Embedded SAPI library)
php-amqp - AMQP extension for PHP
php-apcu - APC User Cache for PHP
php-gearman - PHP wrapper to libgearman
php-geoip - GeoIP module for PHP
php-gmagick - Provides a wrapper to the GraphicsMagick library
php-gnupg - PHP wrapper around the gpgme library
php-http - PECL HTTP module for PHP Extended HTTP Support
php-igbinary - igbinary PHP serializer
php-imagick - Provides a wrapper to the ImageMagick library
php-libsodium - PHP wrapper for the Sodium cryptographic library
php-mailparse - Email message manipulation for PHP
php-memcache - memcache extension module for PHP
php-memcached - memcached extension module for PHP, uses libmemcached
php-mongodb - MongoDB driver for PHP
php-msgpack - PHP extension for interfacing with MessagePack
php-oauth - OAuth 1.0 consumer and provider extension
php-pinba - Pinba module for PHP
...and do on
</code>```

now to install packages run the following command with your desired package

```<code>sudo apt-get install php7.0-mysql php7.0-gd php7.0-curl php7.0-recode
</code>```

note:php7.0-mysql php7.0-gd php7.0-curl php7.0-recode are the package that are listed above.

UPDATE

dont forget to restart apache sudo service apache2 reload

Body:
"PHP module gd: Missing" I received such an error. and I'm trying to install php5-gd.

apt-get install php5-gd

I am using Ubuntu 16.10 and PHP version 7. I made all the updates.

When I tried to install php5-gd, I got an error like below.

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package php5-gd is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'php5-gd' has no installation candidate

Body:
First check which php version you have by sudo php -v. I have php7 so the result is:

PHP 7.0.18-0ubuntu0.17.04.1 (cli) (built: Apr 26 2017 23:59:48) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.18-0ubuntu0.17.04.1, Copyright (c) 1999-2017, by Zend Technologies

since i have php7, I will do the following to list the php packages

sudo apt-cache search php7-*

this returned

libapache2-mod-php7.0 - server-side, HTML-embedded scripting language (Apache 2 module)
php-all-dev - package depending on all supported PHP development packages
php7.0 - server-side, HTML-embedded scripting language (metapackage)
php7.0-cgi - server-side, HTML-embedded scripting language (CGI binary)
php7.0-cli - command-line interpreter for the PHP scripting language
php7.0-common - documentation, examples and common module for PHP
php7.0-curl - CURL module for PHP
php7.0-dev - Files for PHP7.0 module development
php7.0-gd - GD module for PHP
php7.0-gmp - GMP module for PHP
php7.0-json - JSON module for PHP
php7.0-ldap - LDAP module for PHP
php7.0-mysql - MySQL module for PHP
php7.0-odbc - ODBC module for PHP
php7.0-opcache - Zend OpCache module for PHP
php7.0-pgsql - PostgreSQL module for PHP
php7.0-pspell - pspell module for PHP
php7.0-readline - readline module for PHP
php7.0-recode - recode module for PHP
php7.0-snmp - SNMP module for PHP
php7.0-sqlite3 - SQLite3 module for PHP
php7.0-tidy - tidy module for PHP
php7.0-xml - DOM, SimpleXML, WDDX, XML, and XSL module for PHP
php7.0-xmlrpc - XMLRPC-EPI module for PHP
libphp7.0-embed - HTML-embedded scripting language (Embedded SAPI library)
php-amqp - AMQP extension for PHP
php-apcu - APC User Cache for PHP
php-gearman - PHP wrapper to libgearman
php-geoip - GeoIP module for PHP
php-gmagick - Provides a wrapper to the GraphicsMagick library
php-gnupg - PHP wrapper around the gpgme library
php-http - PECL HTTP module for PHP Extended HTTP Support
php-igbinary - igbinary PHP serializer
php-imagick - Provides a wrapper to the ImageMagick library
php-libsodium - PHP wrapper for the Sodium cryptographic library
php-mailparse - Email message manipulation for PHP
php-memcache - memcache extension module for PHP
php-memcached - memcached extension module for PHP, uses libmemcached
php-mongodb - MongoDB driver for PHP
php-msgpack - PHP extension for interfacing with MessagePack
php-oauth - OAuth 1.0 consumer and provider extension
php-pinba - Pinba module for PHP
...and do on

now to install packages run the following command with your desired package

sudo apt-get install php7.0-mysql php7.0-gd php7.0-curl php7.0-recode

note:php7.0-mysql php7.0-gd php7.0-curl php7.0-recode are the package that are listed above.

UPDATE

dont forget to restart apache sudo service apache2 reload


问:
np.append when one of the values could be empty or None
I have this pseudo code:

```<code>a = np.zeros([3,3])
b = np.zeros([3,3])
c = np.append(a,b,axis=0)
</code>```

But the problem is, a or b or both could be None instead of the array that they are. So I have done this:

```<code>def emptyappend(a,b):
    if type(a)==np.ndarray and b is None:
        return a
    elif type(b)==np.ndarray and a is None:
        return b
    elif type(a)==np.ndarray and type(b)==np.ndarray:
        return np.append(a,b,axis=0)
    else:
        return None
</code>```

This seems really ugly and not very "pythonic", but I can't figure out a simple way to do this... any ideas?

答:
You can append the arrays only if the conditions match otherwise return one of the two short-circuiting with or:

```<code>def emptyappend(a, b):
    if type(a) is np.ndarray and type(b) is np.ndarray:
        return np.append(a, b, axis=0)
    return a or b
</code>```

Body:
I have this pseudo code:

a = np.zeros([3,3])
b = np.zeros([3,3])
c = np.append(a,b,axis=0)

But the problem is, a or b or both could be None instead of the array that they are. So I have done this:

def emptyappend(a,b):
    if type(a)==np.ndarray and b is None:
        return a
    elif type(b)==np.ndarray and a is None:
        return b
    elif type(a)==np.ndarray and type(b)==np.ndarray:
        return np.append(a,b,axis=0)
    else:
        return None

This seems really ugly and not very "pythonic", but I can't figure out a simple way to do this... any ideas?

Body:
You can append the arrays only if the conditions match otherwise return one of the two short-circuiting with or:

def emptyappend(a, b):
    if type(a) is np.ndarray and type(b) is np.ndarray:
        return np.append(a, b, axis=0)
    return a or b


问:
Get SpecialFolder.MyDocuments folders of each user
I have a windows service running on my machine. How can I get MyDocuments folders of each users?

For example:

For Windows XP I must get list:

C:\Documents and Settings\User1\My Documents

C:\Documents and Settings\User2\My Documents

...

For Windows 10 I must get list:

C:\Users\User1\Documents\

C:\Users\User2\Documents\

...

How can I get these lists ?

答:
I would suggest using this solution and then just enumerate folders ( for each user ).</p>

```<code>// getUserProfilesPath() is a method from https://stackoverflow.com/a/41752173/3179310
string path = getUserProfilesPath();
// now use WMIC to get all users on the local machine
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject result in searcher.Get())
{
    // and check if their folder exists
    if(Directory.Exists(Path.Combine(path, result["Name"])))
    {
        // user folder exists so now check if it has Documents folder
        if(DirectoryExists(Path.Combine(path, result["Name"], "Documents")))
        {
            DirectoryInfo userDocuments = new DirectoryInfo(Path.Combine(path, result["Name"], "Documents"));
            // userDocuments is now a directory info of that user's documents folder
        }
    }
}
</code>```

Body:
I would suggest using this solution and then just enumerate folders ( for each user ).

// getUserProfilesPath() is a method from https://stackoverflow.com/a/41752173/3179310
string path = getUserProfilesPath();
// now use WMIC to get all users on the local machine
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject result in searcher.Get())
{
    // and check if their folder exists
    if(Directory.Exists(Path.Combine(path, result["Name"])))
    {
        // user folder exists so now check if it has Documents folder
        if(DirectoryExists(Path.Combine(path, result["Name"], "Documents")))
        {
            DirectoryInfo userDocuments = new DirectoryInfo(Path.Combine(path, result["Name"], "Documents"));
            // userDocuments is now a directory info of that user's documents folder
        }
    }
}


问:
Full size Silverlight application dimensions
How can I set the dimensions of my root layout in the XAML to 100% width and height of the <object> tag that houses the Silverlight App.

I have tried specifying 100%, but the width and height properties only take unit literals (exact pixels). Is there a way I can have the Silverlight app take up all the available space in the <object> tag?

答:
Right now (this could change in the version next of Silverlight), pretty much the only way to do this is figure out the dimensions in JavaScript on the page, then pass those to the Silverlight object.

One other option would be to use the Silverlight/JavaScript inter-op API

ContentLicense: CC BY-SA 2.5


问:
Android SharedPreference Values load automatically
In the code written below whenever my cart activity is launched and when the compiler reach on line : HashMap<String, String> cart = session2.getUserDetails(); then it by default loads the default item values instead of loading null values The values loaded are the values given in previous run. Can anyone pleas suggest me where i am wrong in my code?

```<code>public class Cart extends AppCompatActivity {

ListView lvCartItems;
Button bClear;
Button bShop;
TextView tvTotalPrice;

// Session Manager Class
ProductSessionManager session2;

ArrayList<CartItem> cartItems = new ArrayList<CartItem>();
Context context = Cart.this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_cart);

    textHome = (TextView) findViewById(R.id.text_home);
    textSchedules = (TextView) findViewById(R.id.text_account);
    textMusic = (TextView) findViewById(R.id.text_cart);
    tvTotalPrice=(TextView)findViewById(R.id.tvTotalPrice);

    lvCartItems = (ListView) findViewById(R.id.lvCartItems);
    LayoutInflater layoutInflater = getLayoutInflater();

    // Session class instance
    session2 = new ProductSessionManager(this);

    // get user data from session
    HashMap<String, String> cart = session2.getUserDetails();

    // item
    String item1 = cart.get(ProductSessionManager.KEY_item1);
    //quantity
    String quantity1 = cart.get(ProductSessionManager.KEY_quantity1);
    //rate
    String rate1 = cart.get(ProductSessionManager.KEY_rate1);
</code>```

答:
Use this to clear your session.  </p>

```<code> SharedPreferences pref  =
 context.getSharedPreferences("shared_preferences_name", "mode");
 SharedPreferences.Editor editor = pref.edit();
 editor.clear();
 editor.commit();
</code>```

Body:
In the code written below whenever my cart activity is launched and when the compiler reach on line : HashMap<String, String> cart = session2.getUserDetails(); then it by default loads the default item values instead of loading null values The values loaded are the values given in previous run. Can anyone pleas suggest me where i am wrong in my code?

public class Cart extends AppCompatActivity {

ListView lvCartItems;
Button bClear;
Button bShop;
TextView tvTotalPrice;

// Session Manager Class
ProductSessionManager session2;

ArrayList<CartItem> cartItems = new ArrayList<CartItem>();
Context context = Cart.this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_cart);

    textHome = (TextView) findViewById(R.id.text_home);
    textSchedules = (TextView) findViewById(R.id.text_account);
    textMusic = (TextView) findViewById(R.id.text_cart);
    tvTotalPrice=(TextView)findViewById(R.id.tvTotalPrice);

    lvCartItems = (ListView) findViewById(R.id.lvCartItems);
    LayoutInflater layoutInflater = getLayoutInflater();

    // Session class instance
    session2 = new ProductSessionManager(this);

    // get user data from session
    HashMap<String, String> cart = session2.getUserDetails();

    // item
    String item1 = cart.get(ProductSessionManager.KEY_item1);
    //quantity
    String quantity1 = cart.get(ProductSessionManager.KEY_quantity1);
    //rate
    String rate1 = cart.get(ProductSessionManager.KEY_rate1);

Body:
Use this to clear your session.

 SharedPreferences pref  =
 context.getSharedPreferences("shared_preferences_name", "mode");
 SharedPreferences.Editor editor = pref.edit();
 editor.clear();
 editor.commit();


问:
iOS Mapkit Annotation is not getting draggable
I am new to iOS development and I need to implement a draggable annotation in iOS maps. my code is given below.whater ever I do I can't get a draggable annotation can anyone help with the annotations  after that  I need  to get address of the location where the pin is pointing

RegistrationViewController.swift

```<code>class RegistrationViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        var centerLocation = CLLocationCoordinate2DMake(12.964370125970357, 77.59643554937497)
        var mapspan = MKCoordinateSpanMake(0.01, 0.01)
        var mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
        self.mapView.setRegion(mapregion, animated: true)

        let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
        mapView.addAnnotation(pin)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        if annotation is MKPointAnnotation {
            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
            pinAnnotationView.pinColor = .purple
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            return pinAnnotationView
        }

        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch newState {
        case .starting:
            view.dragState = .dragging
        case .ending, .canceling:
            view.dragState = .none
        default: break
        }
    }
</code>```

pinAnnotation.swift

```<code>import MapKit

class pinAnnotation:NSObject,MKAnnotation {
    var title:String?
    var subtitle: String?
    var coordinate: CLLocationCoordinate2D
    init(title:String,subtitle:String,coordinate:CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}
</code>```

答:
In your case annotation is not an MKPointAnnotation type. Thats why its not entering into if annotation is MKPointAnnotation { condition.

It should be like:

```<code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is pinAnnotation {

        let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
        pinAnnotationView.pinTintColor = .purple
        pinAnnotationView.isDraggable = true
        pinAnnotationView.canShowCallout = true
        pinAnnotationView.animatesDrop = true

        return pinAnnotationView
    }

    return nil
}
</code>```

Because annotation is pinAnnotation type.

And I can not see mapView.delegate  = self in your code. But if you assign it via storyboard thats fine otherwise add it in viewDidLoad method.

And your complete code will be:

```<code>import UIKit
import MapKit

class ViewController: UIViewController,MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate  = self
        let centerLocation = CLLocationCoordinate2D(latitude: 12.964370125970357, longitude: 77.59643554937497)
        let mapspan = MKCoordinateSpanMake(0.01, 0.01)
        let mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
        self.mapView.setRegion(mapregion, animated: true)

        let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
        mapView.addAnnotation(pin)

    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if annotation is pinAnnotation {

            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
            pinAnnotationView.pinTintColor = .purple
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            return pinAnnotationView
        }

        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch newState {
        case .starting:
            view.dragState = .dragging
        case .ending, .canceling:
            view.dragState = .none
        default: break
        }
    }
}
</code>```

EDIT

You can get new location with view.annotation?.coordinate

check below code:

```<code>func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
    switch newState {
    case .starting:
        view.dragState = .dragging
    case .ending, .canceling:
        //New cordinates
        print(view.annotation?.coordinate)
        view.dragState = .none
    default: break
    }
}
</code>```

Body:
I am new to iOS development and I need to implement a draggable annotation in iOS maps. my code is given below.whater ever I do I can't get a draggable annotation can anyone help with the annotations  after that  I need  to get address of the location where the pin is pointing

RegistrationViewController.swift

class RegistrationViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        var centerLocation = CLLocationCoordinate2DMake(12.964370125970357, 77.59643554937497)
        var mapspan = MKCoordinateSpanMake(0.01, 0.01)
        var mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
        self.mapView.setRegion(mapregion, animated: true)

        let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
        mapView.addAnnotation(pin)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        if annotation is MKPointAnnotation {
            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
            pinAnnotationView.pinColor = .purple
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            return pinAnnotationView
        }

        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch newState {
        case .starting:
            view.dragState = .dragging
        case .ending, .canceling:
            view.dragState = .none
        default: break
        }
    }

pinAnnotation.swift

import MapKit

class pinAnnotation:NSObject,MKAnnotation {
    var title:String?
    var subtitle: String?
    var coordinate: CLLocationCoordinate2D
    init(title:String,subtitle:String,coordinate:CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}

Body:
In your case annotation is not an MKPointAnnotation type. Thats why its not entering into if annotation is MKPointAnnotation { condition.

It should be like:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is pinAnnotation {

        let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
        pinAnnotationView.pinTintColor = .purple
        pinAnnotationView.isDraggable = true
        pinAnnotationView.canShowCallout = true
        pinAnnotationView.animatesDrop = true

        return pinAnnotationView
    }

    return nil
}

Because annotation is pinAnnotation type.

And I can not see mapView.delegate  = self in your code. But if you assign it via storyboard thats fine otherwise add it in viewDidLoad method.

And your complete code will be:

import UIKit
import MapKit

class ViewController: UIViewController,MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate  = self
        let centerLocation = CLLocationCoordinate2D(latitude: 12.964370125970357, longitude: 77.59643554937497)
        let mapspan = MKCoordinateSpanMake(0.01, 0.01)
        let mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
        self.mapView.setRegion(mapregion, animated: true)

        let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
        mapView.addAnnotation(pin)

    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if annotation is pinAnnotation {

            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
            pinAnnotationView.pinTintColor = .purple
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            return pinAnnotationView
        }

        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch newState {
        case .starting:
            view.dragState = .dragging
        case .ending, .canceling:
            view.dragState = .none
        default: break
        }
    }
}

EDIT

You can get new location with view.annotation?.coordinate

check below code:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
    switch newState {
    case .starting:
        view.dragState = .dragging
    case .ending, .canceling:
        //New cordinates
        print(view.annotation?.coordinate)
        view.dragState = .none
    default: break
    }
}


问:
How to for loop in userDefaults swift
I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function </p>

```<code>    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)
</code>```

答:
I think is not a correct way to do.

I suggest you to put your values into a dictionary and set the dictionary into the UserDefaults.

```<code>let DictKey = "MyKeyForDictionary"
var userDefaults = UserDefaults.standard

// create your dictionary
let dict: [String : Any] = [
    "value1": "Test",
    "value2": 2
]

// set the dictionary
userDefaults.set(dict, forKey: DictKey)

// get the dictionary
let dictionary = userDefaults.object(forKey: DictKey) as? [String: Any]

// get value from
let value = dictionary?["value2"]

// iterate on all keys
guard let dictionary = dictionary else {
    return
}
for (key, val) in dictionary.enumerated() {

}
</code>```

Title: How to for loop in userDefaults swift

Body:
I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function

    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)

Body:
I think is not a correct way to do.

I suggest you to put your values into a dictionary and set the dictionary into the UserDefaults.

let DictKey = "MyKeyForDictionary"
var userDefaults = UserDefaults.standard

// create your dictionary
let dict: [String : Any] = [
    "value1": "Test",
    "value2": 2
]

// set the dictionary
userDefaults.set(dict, forKey: DictKey)

// get the dictionary
let dictionary = userDefaults.object(forKey: DictKey) as? [String: Any]

// get value from
let value = dictionary?["value2"]

// iterate on all keys
guard let dictionary = dictionary else {
    return
}
for (key, val) in dictionary.enumerated() {

}


问:
SQL COUNT DISTINCT for each ID in MS Access
Say I had a table as follows:

```<code>id  category       app
------------------------
1   game           angry birds
1   game           happy dogs
2   productivity   calculator
3   health         fitness tracker
1   game           angry birds
2   game           snake
</code>```

The table shows every app that the user opens over time. For example, pretend you wrote down each time you opened an app on your phone. Now repeat this for 100 people. All of that data is stored in one table, as above.

I am trying to figure out how to count how many distinct apps each person uses within a particular category. For example, for the 'game' category, I would expect:

```<code>id  num_apps
------------
1   2
2   1
3   0
</code>```

I understand that one cannot use COUNT(DISTINCT ..) in MS-Access, and have seen other posts on how to achieve this - I haven't been able to apply it to this case though.

I have tried the following, which I believe gives me a non-distinct count of how each app anyone ever used in a particular category:

```<code>SELECT COUNT(*)
FROM
(SELECT DISTINCT id AS gamer_id
FROM UseList
WHERE category = 'game')
AS b, UseList AS ul
WHERE b.gamer_id = ul.id AND category = 'game'
GROUP BY b.gamer_id;
</code>```

How could I apply to distinct search to this? I've thought of somehow looping through each gamer_id, but that doesn't seem too straightforward either.
Thanks!

答:
you could use  </p>

```<code>  select t.id, count(*)
  from (
  select distinct id, app
  from  UseList
  where categorty ='game') t

  group by t.id
</code>```

Body:
Say I had a table as follows:

id  category       app
------------------------
1   game           angry birds
1   game           happy dogs
2   productivity   calculator
3   health         fitness tracker
1   game           angry birds
2   game           snake

The table shows every app that the user opens over time. For example, pretend you wrote down each time you opened an app on your phone. Now repeat this for 100 people. All of that data is stored in one table, as above.

I am trying to figure out how to count how many distinct apps each person uses within a particular category. For example, for the 'game' category, I would expect:

id  num_apps
------------
1   2
2   1
3   0

I understand that one cannot use COUNT(DISTINCT ..) in MS-Access, and have seen other posts on how to achieve this - I haven't been able to apply it to this case though.

I have tried the following, which I believe gives me a non-distinct count of how each app anyone ever used in a particular category:

SELECT COUNT(*)
FROM
(SELECT DISTINCT id AS gamer_id
FROM UseList
WHERE category = 'game')
AS b, UseList AS ul
WHERE b.gamer_id = ul.id AND category = 'game'
GROUP BY b.gamer_id;

How could I apply to distinct search to this? I've thought of somehow looping through each gamer_id, but that doesn't seem too straightforward either.
Thanks!

Body:
you could use

  select t.id, count(*)
  from (
  select distinct id, app
  from  UseList
  where categorty ='game') t

  group by t.id


问:
Declare Field as Parameterized List Using java assist
We can declare field like following code.

```<code>evalClass.addField(CtField.make("private java.util.List abc;", evalClass));
</code>```

How can we declare field List<String> abc using java assist?

答:
First, generics are not supported by Javassist.
From the Javassist documentation:

Generics

The lower-level API of Javassist fully supports generics introduced by
  Java 5. On the other hand, the higher-level API such as CtClass does
  not directly support generics. However, this is not a serious problem
  for bytecode transformation.

The generics of Java is implemented by the erasure technique. After
  compilation, all type parameters are dropped off. For example, suppose
  that your source code declares a parameterized type Vector:

```<code>Vector<String> v = new Vector<String>();
String s = v.get(0);
</code>```

The compiled bytecode is equivalent to the following code:

```<code>Vector v = new Vector();
String s = (String)v.get(0);
</code>```

So when you
  write a bytecode transformer, you can just drop off all type
  parameters. Because the compiler embedded in Javassist does not
  support generics, you must insert an explicit type cast at the caller
  site if the source code is compiled by Javassist, for example, through
  CtMethod.make(). No type cast is necessary if the source code is
  compiled by a normal Java compiler such as javac.

So you can basically use the method you wrot in your question in order to add a List without generic specification and that's gonna do the work

Body:
We can declare field like following code.

evalClass.addField(CtField.make("private java.util.List abc;", evalClass));

How can we declare field List<String> abc using java assist?

Body:
First, generics are not supported by Javassist.
From the Javassist documentation:

Generics

The lower-level API of Javassist fully supports generics introduced by
  Java 5. On the other hand, the higher-level API such as CtClass does
  not directly support generics. However, this is not a serious problem
  for bytecode transformation.

The generics of Java is implemented by the erasure technique. After
  compilation, all type parameters are dropped off. For example, suppose
  that your source code declares a parameterized type Vector:

Vector<String> v = new Vector<String>();
String s = v.get(0);

The compiled bytecode is equivalent to the following code:

Vector v = new Vector();
String s = (String)v.get(0);

So when you
  write a bytecode transformer, you can just drop off all type
  parameters. Because the compiler embedded in Javassist does not
  support generics, you must insert an explicit type cast at the caller
  site if the source code is compiled by Javassist, for example, through
  CtMethod.make(). No type cast is necessary if the source code is
  compiled by a normal Java compiler such as javac.

So you can basically use the method you wrot in your question in order to add a List without generic specification and that's gonna do the work


问:
get the hostname(Base URL) using javascript
I get too many ways to get the hostname like code below:

```<code>window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath
</code>```

In my case I want something different. For example:

My QA site name is example.com/testsite/index.html

My PROD site name is example.com/index.html

The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com

However for QA I need to return example.com/testsite

For PROD i need to return example.com

Is it possible with the single code? Thanks in advance.

答:
Best method that works for both PROD & QA</p>

```<code>var BASE_URL = window.location.href;
    BASE_URL = BASE_URL.split("testsite");
    if (BASE_URL.length > 1)
    {
        BASE_URL = BASE_URL[0];
        BASE_URL = BASE_URL + 'testsite';
    } else{
        BASE_URL = window.location.origin;
   }
</code>```

Body:
I get too many ways to get the hostname like code below:

window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath

In my case I want something different. For example:

My QA site name is example.com/testsite/index.html

My PROD site name is example.com/index.html

The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com

However for QA I need to return example.com/testsite

For PROD i need to return example.com

Is it possible with the single code? Thanks in advance.

Body:
Best method that works for both PROD & QA

var BASE_URL = window.location.href;
    BASE_URL = BASE_URL.split("testsite");
    if (BASE_URL.length > 1)
    {
        BASE_URL = BASE_URL[0];
        BASE_URL = BASE_URL + 'testsite';
    } else{
        BASE_URL = window.location.origin;
   }


问:
Java-based workflow solutions
We currently use a sequential workflow to process documents. We have a total of 10 distinct workflow steps. We have re-analyzed the workflow and realized that we could restructure the workflow to process in parallel a number of the workflow steps. Basically we are able to process steps 1,2,3,4 in parallel, wait until steps 1-4 are completed and then process step 5, then process steps 6,7,8,9 in parallel wait until steps 6-9 are completed and then finally process step 10. If we were able to implement this new workflow we could boost our processing throughput dramatically.

My question is: What java-based open-source workflow projects would you recommend? Do they typically support what I outlined above?

Thanks for all the replies. After taking a quick look at the the websites you all have listed I think I have more than enough to chew on for a while.

答:
I have used jBPM, and it's pretty nice. It has the parallel processing (forking) and waiting for tasks to be done (joining) the workflow.

The latest version supports a standard notation for business processes - BPMN 2.0

Title: Java-based workflow solutions


问:
Android Tabbed Activity Searchview not opening in Toolbar
the problem

I've used the Setting Up The Search interface doc from the official Android documentation but I'm not getting far for some strange reason as the SearchView refuses to open in the Toolbar
cfr. Android docs

the code

I've added the menu item as such:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="...">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        android:actionViewClass="android.widget.SearchView"/>
</menu>
```

<p>(Sidenote, I've also tried the v7 <code>SearchView</code> view class, but result is no different)
<br /><br /><br />
This is how the toolbar is laid out</p>

<pre class="lang-xml prettyprint-override"><code><android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        app:theme="@style/AppTheme.Toolbar"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>
</code>```

I have also added the SEARCH intent in the manifest and the menu gets properly inflated in the onCreateOptionsMenu method.

edit, manifest.xml and searchable.xml
Added these by request although I don't believe they are relevant to the issue.

<activity
    android:name=".HomeActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.SEND" />
        <action android:name="android.intent.action.SEARCH" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
```

<p>Searchable.xml
</p>

```<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="" />
```

Now according to the Android doc the SearchView is supposed to show up but when I press the search icon in the Toolbar nothing happens.

Any ideas what could be wrong?

答:
After looking around a lot I've finally found the solution.
android:actionViewClass should be app:actionViewClass.

This is never pointed out in the Android documentation.

Body:
the problem

I've used the Setting Up The Search interface doc from the official Android documentation but I'm not getting far for some strange reason as the SearchView refuses to open in the Toolbar
cfr. Android docs

the code

I've added the menu item as such:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="...">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        android:actionViewClass="android.widget.SearchView"/>
</menu>

(Sidenote, I've also tried the v7 SearchView view class, but result is no different)

This is how the toolbar is laid out

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        app:theme="@style/AppTheme.Toolbar"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

I have also added the SEARCH intent in the manifest and the menu gets properly inflated in the onCreateOptionsMenu method.

edit, manifest.xml and searchable.xml
Added these by request although I don't believe they are relevant to the issue.

<activity
    android:name=".HomeActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.SEND" />
        <action android:name="android.intent.action.SEARCH" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Searchable.xml

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="" />

Now according to the Android doc the SearchView is supposed to show up but when I press the search icon in the Toolbar nothing happens.

Any ideas what could be wrong?


问:
mailer preview not working
My mailer is named send_invoice_mailer.rb (it works in dev and in prod).

I want to be able to preview the send_checkout_invoice function using the mailer preview.

routes.rb :

```<code>scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
  #app routes
end
</code>```

/spec/mailers/previews/send_invoice_preview.rb AND /test/mailers/previews/send_invoice_preview.rb (not sure wich one is the correct one so I symlinked the file)

```<code>class SendInvoicePreview < ActionMailer::Preview

  def send_checkout_invoice
    #initializing foo
    SendInvoice.send_checkout_invoice(foo)
  end
end
</code>```

When I go to  : /rails/mailers/send_invoice/send_checkout_invoice I am redirected to /fr/rails/mailers/send_invoice/send_checkout_invoice with this error:

```<code>No route matches [GET] "/fr/rails/mailers/send_invoice/send_checkout_invoice"
</code>```

EDIT : rails is 4.2 and this is done in dev with passenger. App has been upgraded from previous rails versions multiple times.

EDIT 2 : /rails/mailers also does not work. Is it because of the locale scope?

答:
The location of the mailer previews directory can be configured using the preview_path option which has a default of test/mailers/previews:

Try updating your configuration path for action mailer preview as below:

```<code>config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
</code>```

which fails if test directory was not in production.

Check this link, this may helps

https://richonrails.com/articles/action-mailer-previews-in-ruby-on-rails-4-1

Title: mailer preview not working

Body:
My mailer is named send_invoice_mailer.rb (it works in dev and in prod).

I want to be able to preview the send_checkout_invoice function using the mailer preview.

routes.rb :

scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
  #app routes
end

/spec/mailers/previews/send_invoice_preview.rb AND /test/mailers/previews/send_invoice_preview.rb (not sure wich one is the correct one so I symlinked the file)

class SendInvoicePreview < ActionMailer::Preview

  def send_checkout_invoice
    #initializing foo
    SendInvoice.send_checkout_invoice(foo)
  end
end

When I go to  : /rails/mailers/send_invoice/send_checkout_invoice I am redirected to /fr/rails/mailers/send_invoice/send_checkout_invoice with this error:

No route matches [GET] "/fr/rails/mailers/send_invoice/send_checkout_invoice"

EDIT : rails is 4.2 and this is done in dev with passenger. App has been upgraded from previous rails versions multiple times.

EDIT 2 : /rails/mailers also does not work. Is it because of the locale scope?

Body:
The location of the mailer previews directory can be configured using the preview_path option which has a default of test/mailers/previews:

Try updating your configuration path for action mailer preview as below:

config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"

which fails if test directory was not in production.

Check this link, this may helps

https://richonrails.com/articles/action-mailer-previews-in-ruby-on-rails-4-1


问:
Using Jquery to add comma's on textbox
I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.

```<code>    $('#salary').keydown(function (e) {
        var keyCode = e.which;
        if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
            if (keyCode < 48) {
                e.preventDefault();
            } else if (keyCode > 57 && keyCode < 96) {
                e.preventDefault();
            } else if (keyCode > 105) {
                e.preventDefault();
            }
        }
    });
</code>```

What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:

```<code>1,000,000.00
</code>```

I am clueless on what to do or use to add comma's on the textbox.

答:
Could you please try with script below. Comma will be remove on click on textbox and thousand seperator will be added after focus out

$( "#salary" ).click(function() {

   $( "#salary" ).val(  $("#salary").val().replace(/,/g, ''));

});

$( "#salary" ).blur(function() {

   $( "#salary" ).val( addCommas($( "#salary" ).val());

});

function addCommas(nStr) {

    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;

}```

Title: Using Jquery to add comma's on textbox

Body:
I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.

    $('#salary').keydown(function (e) {
        var keyCode = e.which;
        if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
            if (keyCode < 48) {
                e.preventDefault();
            } else if (keyCode > 57 && keyCode < 96) {
                e.preventDefault();
            } else if (keyCode > 105) {
                e.preventDefault();
            }
        }
    });

What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:

1,000,000.00

I am clueless on what to do or use to add comma's on the textbox.


问:
How to check if background data is enabled on the android?
I want to check if the user enabled background data on his/her device and display a message if it is disabled.

How can I check if it has been enabled?
I tried

```<code>import android.provider.Settings;

//...
Settings.System.getString(getContentResolver(), Settings.Secure.BACKGROUND_DATA);
//and
Settings.Secure.getString(getContentResolver(), Settings.Secure.BACKGROUND_DATA);
</code>```

But they are returning null.

Thank you,
Achie.

答:
You want to use the Connectivity Manager to get this info.</p>

```<code>ConnectivityManager mgr = (ConnectivityManager)Context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean bgData = mgr.<a href="http://developer.android.com/intl/de/reference/android/net/ConnectivityManager.html#getBackgroundDataSetting%28%29" rel="noreferrer">getBackgroundDataSetting()</a>;</code>```

Body:
I want to check if the user enabled background data on his/her device and display a message if it is disabled.

How can I check if it has been enabled?
I tried

import android.provider.Settings;

//...
Settings.System.getString(getContentResolver(), Settings.Secure.BACKGROUND_DATA);
//and
Settings.Secure.getString(getContentResolver(), Settings.Secure.BACKGROUND_DATA);

But they are returning null.

Thank you,
Achie.

Body:
You want to use the Connectivity Manager to get this info.

ConnectivityManager mgr = (ConnectivityManager)Context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean bgData = mgr.getBackgroundDataSetting();


问:
how to get all lat and lng point by zip code?
my problem is that

as I image see I want all location of by zip code, not just center.
I check many ways just give me response like google reponse

but that give northeast and southwest point

but my project wants all the point of that zip code.
how do I get all the points?

答:
This is not currently possible.

There is a very popular feature request that seems like a good fit though:

Automatic polygon generation to specified geographic boundary


问:
Migrating Orient Vertex to Cosmos DB using gremlin query
So i have an orient 2.0.0 db, and i want to move this db to cosmos db. The technology i am using is .Net, so i can not use java, and the other richer drivers.

The main problem i am facing during migration is that my orient vertex contain properties that are objects. So is there a way to add objects as property using gremlin query into cosmos db.

The examples on tinkerpop doc, and Azure Cosmos DB Docs for gremlin all show adding simple data types only.

答:
As far as I know, add objects as property is not supported using gremlin query into cosmos db currently.

My workaroud is that we could flat the object. I wrote a test demo, you could add you own logical to it.

The following is my detail steps:

1.Create a C# project and add Microsoft.Azure.Graphs SDK, more detail please refer to packages.config section.

2.Add a custom class to the project

```<code>public class Custom
    {
        public string Type { get; set; }
        public string Name { get; set; }
    }
</code>```

3. Add a function to covert object to Gremlin string

```<code> public static string CovertToGremlinString(object pObject,string type)
        {
            var propertyList = new List<string>();
           // var dic = new Dictionary<string, string>();
            if (pObject == null) return null;
            var jobject = JObject.FromObject(pObject);
            propertyList.AddRange(pObject.GetType().GetProperties().Select(prop => prop.Name));
            var s = propertyList.Aggregate($"g.addV('{type}')", (current, property) => current + $".property('{property}','{jobject[property]})')");
           // dic.Add(type, s);
            return s;
        }
</code>```

4.Add RunAsync function, we also could get the demo code from Azure portal

```<code>public async Task RunAsync(DocumentClient client)
    {
        Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "graphdb" });

        DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
            UriFactory.CreateDatabaseUri("graphdb"),
            new DocumentCollection { Id = "Custom" },
            new RequestOptions { OfferThroughput = 1000 });

        // Azure Cosmos DB supports the Gremlin API for working with Graphs. Gremlin is a functional programming language composed of steps.
        // Here, we run a series of Gremlin queries to show how you can add vertices, edges, modify properties, perform queries and traversals
        // For additional details, see https://aka.ms/gremlin for the complete list of supported Gremlin operators
        var custom = new Custom
        {
            Name = "Tom",
            Type = "1"
        };
        var s = CovertToGremlinString(custom, "custom");
        Dictionary<string, string> gremlinQueries = new Dictionary<string, string>
        {
            {"Cleanup", "g.V().drop()"},
            {"AddVertex 1", s}
        };

        foreach (KeyValuePair<string, string> gremlinQuery in gremlinQueries)
        {
            Console.WriteLine($"Running {gremlinQuery.Key}: {gremlinQuery.Value}");

            // The CreateGremlinQuery method extensions allow you to execute Gremlin queries and iterate
            // results asychronously
            IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, (string) gremlinQuery.Value);
            while (query.HasMoreResults)
            {
                foreach (dynamic result in await query.ExecuteNextAsync())
                {
                    Console.WriteLine($"\t {JsonConvert.SerializeObject(result)}");
                }
            }

            Console.WriteLine();
        }
</code>```

5.Test it on the local.

```<code>    string endpoint = ConfigurationManager.AppSettings["Endpoint"];
    string authKey = ConfigurationManager.AppSettings["AuthKey"];

    using (DocumentClient client = new DocumentClient(
                new Uri(endpoint),
                authKey,
                new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }))
            {
                Program p = new Program();
                p.RunAsync(client).Wait();
            }
</code>```

packages.config

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.DocumentDB" version="1.14.0" targetFramework="net452" />
  <package id="Microsoft.Azure.Graphs" version="0.2.0-preview" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Analyzers" version="1.1.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Common" version="1.3.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.CSharp" version="1.3.0" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net452" />
  <package id="System.Collections" version="4.0.0" targetFramework="net452" />
  <package id="System.Collections.Immutable" version="1.1.37" targetFramework="net452" />
  <package id="System.Diagnostics.Debug" version="4.0.0" targetFramework="net452" />
  <package id="System.Globalization" version="4.0.0" targetFramework="net452" />
  <package id="System.Linq" version="4.0.0" targetFramework="net452" />
  <package id="System.Reflection.Metadata" version="1.2.0" targetFramework="net452" />
  <package id="System.Resources.ResourceManager" version="4.0.0" targetFramework="net452" />
  <package id="System.Runtime" version="4.0.0" targetFramework="net452" />
  <package id="System.Runtime.Extensions" version="4.0.0" targetFramework="net452" />
  <package id="System.Threading" version="4.0.0" targetFramework="net452" />
</packages>
</code>```

Body:
As far as I know, add objects as property is not supported using gremlin query into cosmos db currently.

My workaroud is that we could flat the object. I wrote a test demo, you could add you own logical to it.

The following is my detail steps:

1.Create a C# project and add Microsoft.Azure.Graphs SDK, more detail please refer to packages.config section.

2.Add a custom class to the project

public class Custom
    {
        public string Type { get; set; }
        public string Name { get; set; }
    }

3. Add a function to covert object to Gremlin string

 public static string CovertToGremlinString(object pObject,string type)
        {
            var propertyList = new List<string>();
           // var dic = new Dictionary<string, string>();
            if (pObject == null) return null;
            var jobject = JObject.FromObject(pObject);
            propertyList.AddRange(pObject.GetType().GetProperties().Select(prop => prop.Name));
            var s = propertyList.Aggregate($"g.addV('{type}')", (current, property) => current + $".property('{property}','{jobject[property]})')");
           // dic.Add(type, s);
            return s;
        }

4.Add RunAsync function, we also could get the demo code from Azure portal

public async Task RunAsync(DocumentClient client)
    {
        Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "graphdb" });

        DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
            UriFactory.CreateDatabaseUri("graphdb"),
            new DocumentCollection { Id = "Custom" },
            new RequestOptions { OfferThroughput = 1000 });

        // Azure Cosmos DB supports the Gremlin API for working with Graphs. Gremlin is a functional programming language composed of steps.
        // Here, we run a series of Gremlin queries to show how you can add vertices, edges, modify properties, perform queries and traversals
        // For additional details, see https://aka.ms/gremlin for the complete list of supported Gremlin operators
        var custom = new Custom
        {
            Name = "Tom",
            Type = "1"
        };
        var s = CovertToGremlinString(custom, "custom");
        Dictionary<string, string> gremlinQueries = new Dictionary<string, string>
        {
            {"Cleanup", "g.V().drop()"},
            {"AddVertex 1", s}
        };

        foreach (KeyValuePair<string, string> gremlinQuery in gremlinQueries)
        {
            Console.WriteLine($"Running {gremlinQuery.Key}: {gremlinQuery.Value}");

            // The CreateGremlinQuery method extensions allow you to execute Gremlin queries and iterate
            // results asychronously
            IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, (string) gremlinQuery.Value);
            while (query.HasMoreResults)
            {
                foreach (dynamic result in await query.ExecuteNextAsync())
                {
                    Console.WriteLine($"\t {JsonConvert.SerializeObject(result)}");
                }
            }

            Console.WriteLine();
        }

5.Test it on the local.

    string endpoint = ConfigurationManager.AppSettings["Endpoint"];
    string authKey = ConfigurationManager.AppSettings["AuthKey"];

    using (DocumentClient client = new DocumentClient(
                new Uri(endpoint),
                authKey,
                new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }))
            {
                Program p = new Program();
                p.RunAsync(client).Wait();
            }

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.DocumentDB" version="1.14.0" targetFramework="net452" />
  <package id="Microsoft.Azure.Graphs" version="0.2.0-preview" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Analyzers" version="1.1.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Common" version="1.3.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.CSharp" version="1.3.0" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net452" />
  <package id="System.Collections" version="4.0.0" targetFramework="net452" />
  <package id="System.Collections.Immutable" version="1.1.37" targetFramework="net452" />
  <package id="System.Diagnostics.Debug" version="4.0.0" targetFramework="net452" />
  <package id="System.Globalization" version="4.0.0" targetFramework="net452" />
  <package id="System.Linq" version="4.0.0" targetFramework="net452" />
  <package id="System.Reflection.Metadata" version="1.2.0" targetFramework="net452" />
  <package id="System.Resources.ResourceManager" version="4.0.0" targetFramework="net452" />
  <package id="System.Runtime" version="4.0.0" targetFramework="net452" />
  <package id="System.Runtime.Extensions" version="4.0.0" targetFramework="net452" />
  <package id="System.Threading" version="4.0.0" targetFramework="net452" />
</packages>


问:
Importing an App to Fiori Launchpad - Error
So I'm having this problem with the My Leave Requests App (V.2) for SAP Business Suite. I'm trying to import it to 'my' Fiori Launchpad (image 1) but I'm having this error and I cannot solve it. I've searched about it but I couldn't find anything that helped me.

App on Fiori Launchpad:

The ERROR:

Any help will be appreciated :)

Thank You for your time.

答:
Try /IWFND/CACHE_CLEANUP for the gateway and /IWBEP/CACHE_CLEANUP for the gateway and the backend.

Try /UI2/CHIP_SYNCHRONIZE_CACHE. Afterwards run /UI2/CHIP_CHDR and check it for errors.

Try /UI2/DELETE_CACHE_AFTER_IMP. Afterwards run /UI2/DELETE_CACHE.

Try /UI5/UPDATE_CACHEBUSTER. Afterwards run /UI2/INVALIDATE_GLOBAL_CACHES.

And did you activate the services? Run SICF and check if /sap/bc/ui5_ui5/sap/hcm_lrq_cre is activated. Same for BSP. Run SICF and check if sap/bc/bsp/hcm_lrq_cre is activated.


问:
jquery touchstart is not working on android device
I created a App with cordova , that uses the jquery touchstart event:

```<code>    $("#jqmbtn").on("touchstart", function (event) {
      alert("touchstart")
      if ($("#Suchfeld").val() != ""){
          startsearch($("#Suchfeld").val());
      }
    })
</code>```

The touchstart event fires at any of the Simulate in Browser options provided by visual Studio 2017 and it also fires at multiple AndroidVirtualDevice(AVD) provided by Android Studio.
But when I run the app on my device the touchstart event doesn t trigger.
My device has Android 4.2.2 installed and I also tryed the to get a bug report from the Developer Options of my device , but all I got is a 5MB text file where I can t find any usefull information.
Is there a option I could use to debug the app on my device or does anyone have a Idea what the reason for this could be ? I really don t know what i can do as I don t get any errors when I run on a emulator.
Thank you for your help !

答:
There was a glitch with "click" event not working in IOS Devices(Safari Browser).

So, to quick fix that, I used "touchstart" event for that.

I think you have to use "click" instead of "touchstart" to make that thing work on Android.

Body:
I created a App with cordova , that uses the jquery touchstart event:

    $("#jqmbtn").on("touchstart", function (event) {
      alert("touchstart")
      if ($("#Suchfeld").val() != ""){
          startsearch($("#Suchfeld").val());
      }
    })

The touchstart event fires at any of the Simulate in Browser options provided by visual Studio 2017 and it also fires at multiple AndroidVirtualDevice(AVD) provided by Android Studio.
But when I run the app on my device the touchstart event doesn t trigger.
My device has Android 4.2.2 installed and I also tryed the to get a bug report from the Developer Options of my device , but all I got is a 5MB text file where I can t find any usefull information.
Is there a option I could use to debug the app on my device or does anyone have a Idea what the reason for this could be ? I really don t know what i can do as I don t get any errors when I run on a emulator.
Thank you for your help !


问:
JavaParser: Constructor ParseException(String) is undefined
in another thread about JavaParser you wrote: "it should not have any dependency". But JavaParser has a dependency to a special ParseException:

In JavaParser, line 205: throw new ParseException(ioe.getMessage())

The constructor ParseException(String) is undefined
      - Add argument to match ParseException(String, int)
    E.g. java.text.ParseException (and three others) has one more int parameter, errorOffset.

In line 125 (and 8 more lines): new InstanceJavaParser(reader1).parse...()

The method parse() from the type InstanceJavaParser refers to the missing type ParseException

Which jar can I download from where to get this special ParseException?

(edited)

Maybe I should provide more details than fit into a comment:

In Windows 10:  Maven installed, mkdir D:\workspaces\trunk\JavaParser-from-Maven\

```<code>cmd
D:
cd D:\workspaces\trunk\JavaParser-from-Maven\
D:\workspaces\trunk\JavaParser-from-Maven>mvn archetype:generate -DgroupId=com.github.javaparser -DartifactId=javaparser-core -DinteractiveMode=false    =>
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-container-default/1.0-alpha-9-stable-1/plexus-container-default-1.0-alpha-9-stable-1.pom (4 KB at 35.4 KB/sec)
[...] and many more .pom files [...]
[INFO] Generating project in Batch mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 38.5 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 5.5 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: D:\workspaces\trunk\JavaParser-from-Maven
[INFO] Parameter: package, Value: com.github.javaparser
[INFO] Parameter: groupId, Value: com.github.javaparser
[INFO] Parameter: artifactId, Value: javaparser-core
[INFO] Parameter: packageName, Value: com.github.javaparser
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
</code>```

[...] =>
D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core\pom.xml  created

D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core\src\main\java\com\github\javaparser\App.java  (1 KB) created, saying "Hello World"

=> a lot of .pom files and a App.java have been downloades, but no JavaParser files yet => acc. to "how To Compile Sources":

Trying with a version argument:

```<code>D:\workspaces\trunk\JavaParser-from-Maven>mvn archetype:generate -DgroupId=com.github.javaparser -DartifactId=javaparser-core -Dversion=2.1.0 -DinteractiveMode=false    =>
[...]  Building Maven Stub Project (No POM) 1
[...] [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generate-sources @ standalone-pom >>>
</code>```

=> a lot of .pom files and one App.java have been downloades, but no JavaParser files yet

=> acc. to "how To Compile Sources":

```<code>cd javaparser-core     // where the POM.xml resides
mvn clean install    =>
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-core/2.0.6/maven-core-2.0.6.jar (149 KB at 152.8 KB/sec)
[...] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ javaparser-core ---
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-plugin-api/2.0.9/maven-plugin-api-2.0.9.pom [...]
[...] [INFO] Changes detected - recompiling the module!
[...]  T E S T S
Running com.github.javaparser.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 sec
</code>```

To generate the additional source files:

```<code>D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core>mvn javacc:javacc    =>
[INFO] Scanning for projects...
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/javacc-maven-plugin/maven-metadata.xml [...]
[...] [INFO] Building javaparser-core 2.1.0 [...]
Downloaded: ... .pom files ...
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-plugin-api/2.0.4/maven-plugin-api-2.0.4.jar
Downloaded: ... another 57 .jar files ...
[INFO] Skipping non-existing source directory: D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core\src\main\javacc
[INFO] BUILD SUCCESS
</code>```

Why do I just get a dummy App.java and nothing concerning JavaParser?

Where do all the .pom and .jar go?

What do all the .pom and .jar affect?

答:
The file is generated when you build the JavaParser project. That's why it is not in the repository, and that's why we can still have zero dependencies.

If the problem is that your IDE cannot find this file, make it point to the directory inside the target folder containing the generated sources.

Body:
in another thread about JavaParser you wrote: "it should not have any dependency". But JavaParser has a dependency to a special ParseException:

In JavaParser, line 205: throw new ParseException(ioe.getMessage())

The constructor ParseException(String) is undefined
      - Add argument to match ParseException(String, int)
    E.g. java.text.ParseException (and three others) has one more int parameter, errorOffset.

In line 125 (and 8 more lines): new InstanceJavaParser(reader1).parse...()

The method parse() from the type InstanceJavaParser refers to the missing type ParseException

Which jar can I download from where to get this special ParseException?

(edited)

Maybe I should provide more details than fit into a comment:

In Windows 10:  Maven installed, mkdir D:\workspaces\trunk\JavaParser-from-Maven\

cmd
D:
cd D:\workspaces\trunk\JavaParser-from-Maven\
D:\workspaces\trunk\JavaParser-from-Maven>mvn archetype:generate -DgroupId=com.github.javaparser -DartifactId=javaparser-core -DinteractiveMode=false    =>
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-container-default/1.0-alpha-9-stable-1/plexus-container-default-1.0-alpha-9-stable-1.pom (4 KB at 35.4 KB/sec)
[...] and many more .pom files [...]
[INFO] Generating project in Batch mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 38.5 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 5.5 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: D:\workspaces\trunk\JavaParser-from-Maven
[INFO] Parameter: package, Value: com.github.javaparser
[INFO] Parameter: groupId, Value: com.github.javaparser
[INFO] Parameter: artifactId, Value: javaparser-core
[INFO] Parameter: packageName, Value: com.github.javaparser
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

[...] =>
D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core\pom.xml  created

D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core\src\main\java\com\github\javaparser\App.java  (1 KB) created, saying "Hello World"

=> a lot of .pom files and a App.java have been downloades, but no JavaParser files yet => acc. to "how To Compile Sources":

Trying with a version argument:

D:\workspaces\trunk\JavaParser-from-Maven>mvn archetype:generate -DgroupId=com.github.javaparser -DartifactId=javaparser-core -Dversion=2.1.0 -DinteractiveMode=false    =>
[...]  Building Maven Stub Project (No POM) 1
[...] [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generate-sources @ standalone-pom >>>

=> a lot of .pom files and one App.java have been downloades, but no JavaParser files yet

=> acc. to "how To Compile Sources":

cd javaparser-core     // where the POM.xml resides
mvn clean install    =>
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-core/2.0.6/maven-core-2.0.6.jar (149 KB at 152.8 KB/sec)
[...] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ javaparser-core ---
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-plugin-api/2.0.9/maven-plugin-api-2.0.9.pom [...]
[...] [INFO] Changes detected - recompiling the module!
[...]  T E S T S
Running com.github.javaparser.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 sec

To generate the additional source files:

D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core>mvn javacc:javacc    =>
[INFO] Scanning for projects...
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/javacc-maven-plugin/maven-metadata.xml [...]
[...] [INFO] Building javaparser-core 2.1.0 [...]
Downloaded: ... .pom files ...
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-plugin-api/2.0.4/maven-plugin-api-2.0.4.jar
Downloaded: ... another 57 .jar files ...
[INFO] Skipping non-existing source directory: D:\workspaces\trunk\JavaParser-from-Maven\javaparser-core\src\main\javacc
[INFO] BUILD SUCCESS

Why do I just get a dummy App.java and nothing concerning JavaParser?

Where do all the .pom and .jar go?

What do all the .pom and .jar affect?


问:
TFS - undo merge after get latest
I did a search on this issue and found a lot posts and questions but none seems to target my situation.

I had pending changes and i did "Get Latest", i got the conflicts window and wanted to resolve them, so i did a merge as i wanted to keep both my changes and the server's new code. but i forgot to check the block of codes and i just clicked merge (did not  checked in yet!).  i had a conflict on one of the cproj files and now i lost some .cs files as well.

I think i lost both versions of code and i want to go back and do that merge all over again and do it right, but i don't have a time machine! :)

Any help would be appreciated.

答: If you haven't checked in merged changes yet, you still have an option to compare merged files with latest server version and undo all those changes which got merged from server to your local changes manually(especially csproj file in your case). Later, you can be careful to merge again and select all the required blocks. </p>

Title: TFS - undo merge after get latest

ContentLicense: CC BY-SA 4.0


问:
login and signup tab does not work xml
I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.

Android classes

SignUpScreen.java

```<code> final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });
</code>```

my LoginScreen.java

```<code>final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });
</code>```

答:
Inside setOnClickListener, why you have given setContentView(R.layout.login_screen);
    Actually in onCreate only, setContentView should be present.

Better your full code will help to guide.

Title: login and signup tab does not work xml

Body:
I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.

Android classes

SignUpScreen.java

 final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });

my LoginScreen.java

final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });


答:
try above code for SignUpScreen.java

```<code>TextView b = (TextView) findViewById(R.id.text1);

b.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
        startActivity(i);
    }
});
</code>```

and for LoginScreen.java

```<code>TextView c = (TextView) findViewById(R.id.text4);

c.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {

        Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
        startActivity(i);
    }
});
</code>```

Title: login and signup tab does not work xml

Body:
try above code for SignUpScreen.java

TextView b = (TextView) findViewById(R.id.text1);

b.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
        startActivity(i);
    }
});

and for LoginScreen.java

TextView c = (TextView) findViewById(R.id.text4);

c.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {

        Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
        startActivity(i);
    }
});


问:
Get awk result greater than X
Command:

```<code>grep "redirect=on" access_log | awk '{print $1}' | sort -n | uniq -c | sort -nr | head -3
</code>```

Output is:

```<code>34  3.247.44.149
6   5.218.131.185
3   7.173.135.94
</code>```

Question: How to output only where the NR is greater then 10. In this case:

```<code>34  3.247.44.149
</code>```

I tried already to play with $1 > 10 but $1 is the IP and not the number.

Thank you.

答:
With single awk:

```<code>awk -F'[[:space:]]+|?' '$8=="redirect=on"{ a[$1]++ }
     END{ for(ip in a) if(a[ip] > 10) print a[ip],ip }' access_log
</code>```

-F'[[:space:]]+|?' - field separator

$8=="redirect=on" - considering only records with query param "redirect=on"

a[$1]++ - count same IP address occurrences

Title: Get awk result greater than X

Body:
Command:

grep "redirect=on" access_log | awk '{print $1}' | sort -n | uniq -c | sort -nr | head -3

Output is:

34  3.247.44.149
6   5.218.131.185
3   7.173.135.94

Question: How to output only where the NR is greater then 10. In this case:

34  3.247.44.149

I tried already to play with $1 > 10 but $1 is the IP and not the number.

Thank you.

Body:
With single awk:

awk -F'[[:space:]]+|?' '$8=="redirect=on"{ a[$1]++ }
     END{ for(ip in a) if(a[ip] > 10) print a[ip],ip }' access_log

-F'[[:space:]]+|?' - field separator

$8=="redirect=on" - considering only records with query param "redirect=on"

a[$1]++ - count same IP address occurrences