问:
Send data with POST method, android studio singleton
I'm creating an app that include a login form, I'm using a singleton class, jsonobject request and volley library. Can someone tell me how to get email and password from the edit text in order to send them in post method to the URL?

Here's the login.java code:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;

public class Login extends AppCompatActivity {

private EditText email,password;
private Button login;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    email = (EditText) findViewById(R.id.email);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.bLogin);
    //ip azienda
    //final String url = "http://192.168.10.59/mygymapi/Login.php";
    //ip casa mia
    final String url = "http://192.168.56.1/mygymapi/Login.php";
    login.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){

        JsonObjectRequest jsObjRequest = new JsonObjectRequest

                    (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {

                            Toast.makeText(getBaseContext(),"Response: " + response.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub
                            VolleyLog.e("Error: ", error.getMessage());
                        }
                    });
            MySingleton.getInstance(getBaseContext()).addToRequestQueue(jsObjRequest);
        }
    });
}
}
</code>```

Singleton code:

```<code>import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.Request;
import com.android.volley.toolbox.Volley;

public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}
}
</code>```

答:
You can try on following code.

Code

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

    private EditText email,password;
    private Button login;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.bLogin);
        //ip azienda
        //final String url = "http://192.168.10.59/mygymapi/Login.php";
        //ip casa mia
        final String url = "http://192.168.56.1/mygymapi/Login.php";
        login.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){

                JSONObject params = new JSONObject();
                String Email = email.getText().toString();
                String Password = password.getText().toString();

                try{
                        params.put("user_mail", Email);
                        params.put("user_pass", Password);
                }
                catch(JSONException e){
                        e.printStackTrace();
                }

            JsonObjectRequest jsObjRequest = new JsonObjectRequest

                        (Request.Method.POST, url, params, new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                int errorcode = response.getInt("errorCode");
                                String errormessage = response.getString("errorMessage");
                                JSONObject data = response.getJSONObject("data");
                                String token = data.getString("token");
                                Toast.makeText(getBaseContext(),"Token: " + token, Toast.LENGTH_SHORT).show();
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // TODO Auto-generated method stub
                                VolleyLog.e("Error: ", error.getMessage());
                            }
                        });
                MySingleton.getInstance(getBaseContext()).addToRequestQueue(jsObjRequest);
            }
        });
    }
}
</code>```

Body:
I'm creating an app that include a login form, I'm using a singleton class, jsonobject request and volley library. Can someone tell me how to get email and password from the edit text in order to send them in post method to the URL?

Here's the login.java code:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;

public class Login extends AppCompatActivity {

private EditText email,password;
private Button login;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    email = (EditText) findViewById(R.id.email);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.bLogin);
    //ip azienda
    //final String url = "http://192.168.10.59/mygymapi/Login.php";
    //ip casa mia
    final String url = "http://192.168.56.1/mygymapi/Login.php";
    login.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){

        JsonObjectRequest jsObjRequest = new JsonObjectRequest

                    (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {

                            Toast.makeText(getBaseContext(),"Response: " + response.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub
                            VolleyLog.e("Error: ", error.getMessage());
                        }
                    });
            MySingleton.getInstance(getBaseContext()).addToRequestQueue(jsObjRequest);
        }
    });
}
}

Singleton code:

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.Request;
import com.android.volley.toolbox.Volley;

public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}
}

Body:
You can try on following code.

Code

public class Login extends AppCompatActivity {

    private EditText email,password;
    private Button login;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.bLogin);
        //ip azienda
        //final String url = "http://192.168.10.59/mygymapi/Login.php";
        //ip casa mia
        final String url = "http://192.168.56.1/mygymapi/Login.php";
        login.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){

                JSONObject params = new JSONObject();
                String Email = email.getText().toString();
                String Password = password.getText().toString();

                try{
                        params.put("user_mail", Email);
                        params.put("user_pass", Password);
                }
                catch(JSONException e){
                        e.printStackTrace();
                }

            JsonObjectRequest jsObjRequest = new JsonObjectRequest

                        (Request.Method.POST, url, params, new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                int errorcode = response.getInt("errorCode");
                                String errormessage = response.getString("errorMessage");
                                JSONObject data = response.getJSONObject("data");
                                String token = data.getString("token");
                                Toast.makeText(getBaseContext(),"Token: " + token, Toast.LENGTH_SHORT).show();
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // TODO Auto-generated method stub
                                VolleyLog.e("Error: ", error.getMessage());
                            }
                        });
                MySingleton.getInstance(getBaseContext()).addToRequestQueue(jsObjRequest);
            }
        });
    }
}


来源: stackexchange

问:
How to list all the items related to a certain category
I want to display all the items related to a certain category when the relevant category name is clicked from the navigation panel.
This is my navigation panel

```<code><ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li><%=link_to "About us" ,pages_about_path %></li>
     <li><%=link_to "Contact us" ,pages_contact_path %></li>
        <% @categories.each do |category| %>
                <li><%=link_to category.name,category %><br></li>
        <%end%>
    </ul>
</code>```

This is the code for my show view for categories

```<code><div class="container">
<div class="col-md-12">
    <h1><%= @category.name %></h1>
        <div>
            <% @items.each do |item| %>
                    <div class="col-sm-4">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                    <%= link_to item.title,item,class:"btn btn-primary btn-block" %>
                            </div>
                            <div class="panel-body">
                                Quantity  :<%= item.qty %><br>
                                Price  : <%= number_to_currency(item.price, unit: "RS " ) %><br>
                            </div>
                            <div class="panel-footer">
                                <%= link_to "Edit" ,edit_item_path(item) , class: "btn btn-default" %>
                                <%= link_to "Delete" ,item , :confirm => "Are you sure?" , :method => :delete , class: "btn btn-danger"%>
                            <hr>
                            </div>
                        </div>
                    </div>
                <%end%>
</code>```

This is the method at the categories controller.

```<code>def show
  @category =Category.find(params[:id])
  @items = Item.all
end
</code>```

When i use these blocks all the items are being displayed .

This is how the database tables are

```<code>class CreateItems < ActiveRecord::Migration[5.0]
  def change
    create_table :items do |t|
      t.string :title
      t.float :qty
      t.decimal :price
      t.integer :category_id

      t.timestamps
    end
  end
end

class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps
    end
  end
end
</code>```

答:
@items = Item.all returns all items irrespective of a category. You need to change it to @items = @category.items

```<code>def show
  @category = Category.find(params[:id])
  @items = @category.items
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to display all the items related to a certain category when the relevant category name is clicked from the navigation panel.
This is my navigation panel

Home

<%=link_to "About us" ,pages_about_path %>

<%=link_to "Contact us" ,pages_contact_path %>

        <% @categories.each do |category| %>

<%=link_to category.name,category %>

        <%end%>

This is the code for my show view for categories

<%= @category.name %>

            <% @items.each do |item| %>

                                    <%= link_to item.title,item,class:"btn btn-primary btn-block" %>

                                Quantity  :<%= item.qty %>

                                Price  : <%= number_to_currency(item.price, unit: "RS " ) %>

                                <%= link_to "Edit" ,edit_item_path(item) , class: "btn btn-default" %>
                                <%= link_to "Delete" ,item , :confirm => "Are you sure?" , :method => :delete , class: "btn btn-danger"%>

                <%end%>

This is the method at the categories controller.

def show
  @category =Category.find(params[:id])
  @items = Item.all
end

When i use these blocks all the items are being displayed .

This is how the database tables are

class CreateItems < ActiveRecord::Migration[5.0]
  def change
    create_table :items do |t|
      t.string :title
      t.float :qty
      t.decimal :price
      t.integer :category_id

      t.timestamps
    end
  end
end

class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps
    end
  end
end

Body:
@items = Item.all returns all items irrespective of a category. You need to change it to @items = @category.items

def show
  @category = Category.find(params[:id])
  @items = @category.items
end


问:
after postback bootstrap font size changing (increasing)
After searching 2 hours continuously i didn't getting answer
I am developing web application in asp.net but
after postback bootstrap font size changing (increasing)

```<code>when loading first time page
    body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
}

    after post back

    scaffolding.less:31
    body {
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 14px;
        line-height: 1.42857143;
        color: #333;
        background-color: #fff;
    }
</code>```

as look same CSS but change in view
Is there any solution......
Thanks!!

答:
You're CSS is getting overwritten by something... Use the Chrome development tools and inspect the element... It should tell you what's causing your CSS to be overwritten...

Also, try this as a long shot:

```<code>  body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px !important;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
  }
</code>```

The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.

Body:
After searching 2 hours continuously i didn't getting answer
I am developing web application in asp.net but
after postback bootstrap font size changing (increasing)

when loading first time page
    body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
}

    after post back

    scaffolding.less:31
    body {
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 14px;
        line-height: 1.42857143;
        color: #333;
        background-color: #fff;
    }

as look same CSS but change in view
Is there any solution......
Thanks!!

Body:
You're CSS is getting overwritten by something... Use the Chrome development tools and inspect the element... It should tell you what's causing your CSS to be overwritten...

Also, try this as a long shot:

  body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px !important;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
  }

The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.


问:
php array how get in array value for using foreach
I have multiple array, I want particular value get using foreach below my code

Notice: Undefined index: transId in  on line 52

```<code>$test = array(
    'messages' => Array
    (
        'resultCode' => 'Ok',
        'message' => Array
        (
            'code' => 'I00001',
            'text' => 'Successful',
        ),

    ),
    'transactionResponse' => Array
    (
        'responseCode' => '1',
        'authCode' => 'Z7K31J',
        'avsResultCode' => 'Y',
        'cvvResultCode' => 'P',
        'cavvResultCode' => '2',
        'transId' => '40004672975',
        'refTransID' => Array
        (
        ),

        'transHash' => '163382584395AB06470CF365AD6F7381',
        'testRequest' => '0',
        'accountNumber' => 'XXXX4242',
        'accountType' => 'Visa',
        'messages' => Array
        (
            'message' => Array
                (
                    'code' => '1',
                    'description' => 'This transaction has been approved',
                ),

        ),
        'transHashSha2' => Array
        (
        ),
    ),
);
</code>```

above my array, execute $test in foreach

I want display value of transid, response, transhash

```<code>foreach ($test as $key => $value) {
    $response = $value['resultCode'];
    $transId = $value['transId'];
    $authCode = $value['authCode'];
    $transHash = $value['transHash'];
}
</code>```

答:
use array_walk_recursive() where you don't have to go in each level of the array to echo your values like below:

```<code><?php
  array_walk_recursive($test, function ($item, $key){
    if($key == 'transId' || $key == 'transHash' || $key == 'resultCode'){
        echo $key." => ".$item."<br>";
    }
});
</code>```

Body:
I have multiple array, I want particular value get using foreach below my code

Notice: Undefined index: transId in  on line 52

$test = array(
    'messages' => Array
    (
        'resultCode' => 'Ok',
        'message' => Array
        (
            'code' => 'I00001',
            'text' => 'Successful',
        ),

    ),
    'transactionResponse' => Array
    (
        'responseCode' => '1',
        'authCode' => 'Z7K31J',
        'avsResultCode' => 'Y',
        'cvvResultCode' => 'P',
        'cavvResultCode' => '2',
        'transId' => '40004672975',
        'refTransID' => Array
        (
        ),

        'transHash' => '163382584395AB06470CF365AD6F7381',
        'testRequest' => '0',
        'accountNumber' => 'XXXX4242',
        'accountType' => 'Visa',
        'messages' => Array
        (
            'message' => Array
                (
                    'code' => '1',
                    'description' => 'This transaction has been approved',
                ),

        ),
        'transHashSha2' => Array
        (
        ),
    ),
);

above my array, execute $test in foreach

I want display value of transid, response, transhash

foreach ($test as $key => $value) {
    $response = $value['resultCode'];
    $transId = $value['transId'];
    $authCode = $value['authCode'];
    $transHash = $value['transHash'];
}

Body:
use array_walk_recursive() where you don't have to go in each level of the array to echo your values like below:

<?php
  array_walk_recursive($test, function ($item, $key){
    if($key == 'transId' || $key == 'transHash' || $key == 'resultCode'){
        echo $key." => ".$item."<br>";
    }
});


问:
Error during installing HAXM, VT-X not working
I am an entry-level Android software developer. I recently heard about HAXM that support emulator in rendering graphics more smoothly. I downloaded appropriate file HAXM file for Windows 7 64 bit, unpacked and started installing. However, during the installation process I get this error:

"This computer meets requirements for HAXM, but VT-x is not turned
  on..."

I checked many forum about this problem, including checking the version of BIOS and enabling Virtual Technology on BIOS. I followed the steps posted in the following forum:

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

However, I don't have any lines about Hyperlaunch and I could not find Hyper-V options in my Windows features. I don't have any idea how to solve this problem.

答:
for Mac users,
install the Intel HAXM kernel extension to allow the emulator to make use of CPU virtualization extensions.

The steps to configure VM acceleration are as follows:

Open the SDK Manager.

Click the SDK Update Sites tab and then select Intel HAXM.

Click OK.

After the download finishes, execute the installer.
For example, it might be in this location:
sdk/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_version.dmg.

To begin installation, in the Finder, double-click the IntelHAXM.dmg file and then the IntelHAXM.mpkg file.

Follow the on-screen instructions to complete the installation.

After installation finishes, confirm that the new kernel extension is operating correctly by opening a terminal window and running the following command:

kextstat | grep intel

You should see a status message containing the following extension name, indicating that the kernel extension is loaded:

com.intel.kext.intelhaxm

Reference:

https://developer.android.com/studio/run/emulator-acceleration.html#vm-mac

ContentLicense: CC BY-SA 4.0


问:
UL height incorrect. related to transform-origin or perspective-origin or -webkit-min-logical-width
I am implementing account page from Rokaux M-store template. For some reason it looks different in my machine.

Difference is UL height which is 0px whereas it should be 57px in original. Other computed items different were transform-origin or perspective-origin or -webkit-min-logical-width.

Where does the difference come from?

It should look like:

However it looks like

答:
The Problem is with the float

Just add this style to your CSS. Make .nav-tabs > li to float: none;

Make this style more specific to this section only, by referring it with some custom class to parent. eg: .customClass .nav-tabs > li.

CSS:

```<code>.nav-tabs > li {
    float: none;
    margin-bottom: -1px;
}
</code>```

Body:
The Problem is with the float

Just add this style to your CSS. Make .nav-tabs > li to float: none;

Make this style more specific to this section only, by referring it with some custom class to parent. eg: .customClass .nav-tabs > li.

CSS:

.nav-tabs > li {
    float: none;
    margin-bottom: -1px;
}


问:
Android old drawable not updated
EDIT AT THE END

I was trying to implement a SplashScreen following this guideline. So I'm setting a drawable with a layer-list and using an icon, but the icon is too big so I make a new file that's smaller. The result never showed up in my app: the first drawable I made is always showing up, never updating.

I renamed the picture file, the drawable

I renamed the style that's
used in the manifest

I cleaned the project

I rebuilt the project

I
synchroinized

I used the Invalidate cache/restart option

I updated
Android Studio

I moved my project folder, created a new one and
copy-pasted only the java and xml files because I thougt then the
cache files would be deleted

Nada, the old drawable is always showing when I deploy the apk on my phone.
What is this, whichcraft? What am I missing? Where do I find the cache? I looked for a bin folder, I read on some forums I should delete it but it's not in my workspace.

I'm posting my code below:

AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="lu.intech.mcfc">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.InitActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activity.LoginActivity" />
    </application>
</manifest>
</code>```

styles.xml:

```<code><resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/splash_screen</item>
    </style>
</resources>
</code>```

splash_screen.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/colorPrimary"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/logo_wega_100x31"/>
    </item>
</layer-list>
</code>```

EDIT
I did try my app on another phone and it worked as intended straight away. So I'm guessing the problem lies on the phone. Even if I uninstalled the app everytime I tested again, the old drawable was shown. What more than uninstalling the app can I do to clean the cache on the phone?

答:
Cf. another similar problem I had: Android status bar hide/change color in splash screen

It's not the first time I have a cache problem with that kind of screen, it must be the particular condition of having no layout and a drawable as a background. I tried invalidating the cache in Android Studio, I cleaned and rebuilt the project, I uninstalled the app on the phone but nothing works. So if you are in this cofiguration, just try to run your app on another phone if you can, just to check that your solution isn't already working, just not updating on your device.

Title: Android old drawable not updated

Body:
EDIT AT THE END

I was trying to implement a SplashScreen following this guideline. So I'm setting a drawable with a layer-list and using an icon, but the icon is too big so I make a new file that's smaller. The result never showed up in my app: the first drawable I made is always showing up, never updating.

I renamed the picture file, the drawable

I renamed the style that's
used in the manifest

I cleaned the project

I rebuilt the project

I
synchroinized

I used the Invalidate cache/restart option

I updated
Android Studio

I moved my project folder, created a new one and
copy-pasted only the java and xml files because I thougt then the
cache files would be deleted

Nada, the old drawable is always showing when I deploy the apk on my phone.
What is this, whichcraft? What am I missing? Where do I find the cache? I looked for a bin folder, I read on some forums I should delete it but it's not in my workspace.

I'm posting my code below:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="lu.intech.mcfc">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.InitActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activity.LoginActivity" />
    </application>
</manifest>

styles.xml:

<resources>

</resources>

splash_screen.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/colorPrimary"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/logo_wega_100x31"/>
    </item>
</layer-list>

EDIT
I did try my app on another phone and it worked as intended straight away. So I'm guessing the problem lies on the phone. Even if I uninstalled the app everytime I tested again, the old drawable was shown. What more than uninstalling the app can I do to clean the cache on the phone?


问:
Confirming the difference between import * and from xxx import *
I was surprised to find out that

```<code>import foo
</code>```

and

```<code>from foo import *
</code>```

had different effects on global members.  I wanted to confirm that my experiments are the correct behavior.

In the first example, changing a member in module foo will reflect in all code that imports foo.  However, changing that member in the later case only seems to affect the file into which it was imported.  In other words, using the later approach will give each importing file its own copy of the members from foo.

the behavior i want is to have access to foo.x from all files, be able to change it from all files, and have that change reflected in all files ( a true global if you will).

答:
Considering that global variables are generally considered to be a bad thing, I suspect a "true global" variable would be an exceedingly bad thing.

One other way to get similar behavior is to use class-scope attributes in a singleton object, and just import that. Then it is clearer where you are getting the "global" variable from.

Body:
I was surprised to find out that

import foo

and

from foo import *

had different effects on global members.  I wanted to confirm that my experiments are the correct behavior.

In the first example, changing a member in module foo will reflect in all code that imports foo.  However, changing that member in the later case only seems to affect the file into which it was imported.  In other words, using the later approach will give each importing file its own copy of the members from foo.

the behavior i want is to have access to foo.x from all files, be able to change it from all files, and have that change reflected in all files ( a true global if you will).

ContentLicense: CC BY-SA 2.5


问:
C# Unit testing - check if a private method was reached
I am using C# MOQ library.

Lets say I want to create a UnitTest for this piece of code:

```<code>if(condition){
    privateMethod();
}
else{
    logger.info("didn't hit")
}
</code>```

I want to check if privateMethod was hit, I can't use the Verify function as it is private. How can I do that?

I thought about adding a Status member dedicated for the unit testing, which will hold the last location before exiting the tested method.

答:
Don't test private methods. They are private implementation details of the class. You should only test the results of executing public methods.

Properly designed SOLID code will never put you in a position which will require you to do private mocking.

Depending on whether you want to change your design or not, there are few approaches you could take:

don't try to mock private details, focus on public API (doesn't help with design issue)

extract private method to class, introduce dependency (long-term solution, improves design and makes code easily testable)

make private method protected, override in test (doesn't help with design issue, might not yield valuable test)

Whichever you chose I leave up to you. However, I'll emphasize it one more time - mocking private method is not unit testing, library or tools problem - it is a design problem and is best solvable as such.

Body:
I am using C# MOQ library.

Lets say I want to create a UnitTest for this piece of code:

if(condition){
    privateMethod();
}
else{
    logger.info("didn't hit")
}

I want to check if privateMethod was hit, I can't use the Verify function as it is private. How can I do that?

I thought about adding a Status member dedicated for the unit testing, which will hold the last location before exiting the tested method.


答:
you can use this

```<code>foreach ($test as $key => $value)
{
   if(!empty($value['message']))
   {
      $response = $value['messages']['resultCode'];
   }
   elseif(!empty($value['transactionResponse']))
   {
        $transId = $value['transactionResponse']['transId'];
        $authCode = $value['transactionResponse']['authCode'];
        $transHash = $value['transactionResponse']['transHash'];
   }
}
</code>```

if you want proper then you have to take it to array and key as your transid

Title: php array how get in array value for using foreach

Body:
you can use this

foreach ($test as $key => $value)
{
   if(!empty($value['message']))
   {
      $response = $value['messages']['resultCode'];
   }
   elseif(!empty($value['transactionResponse']))
   {
        $transId = $value['transactionResponse']['transId'];
        $authCode = $value['transactionResponse']['authCode'];
        $transHash = $value['transactionResponse']['transHash'];
   }
}

if you want proper then you have to take it to array and key as your transid


问:
Linux script with curl to check webservice is up
I have a webservice provided at http://localhost/test/testweb

I want to write a script to check if webservice is up with curl

If there a curl parameter given, returns 200 OK ok true false so that I can use it is if-else block in linux script

答:
Same as @burhan-khalid, but added --connect-timeout 3 and --max-time 5.

```<code>test_command='curl -sL \
    -w "%{http_code}\\n" \
    "http://www.google.com:8080/" \
    -o /dev/null \
    --connect-timeout 3 \
    --max-time 5'
if [ $(test_command) == "200" ] ;
then
   echo "OK" ;
else
   echo "KO" ;
fi
</code>```

Body:
Same as @burhan-khalid, but added --connect-timeout 3 and --max-time 5.

test_command='curl -sL \
    -w "%{http_code}\\n" \
    "http://www.google.com:8080/" \
    -o /dev/null \
    --connect-timeout 3 \
    --max-time 5'
if [ $(test_command) == "200" ] ;
then
   echo "OK" ;
else
   echo "KO" ;
fi


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答:
Check out comments on Prevayler on this question. Prevayler is a transactional wrapper around object serialization - roughly, use objects in plain java and persist to disk through java API w/o sql, a bit neater than writing your own serialization.

Caveats- with serialization as a persistance mechanism, you run the risk of invalidating your saved data when you update the class. Even with a wrapper library you'll probably want to customize the serialization/deserialization handling. It also helps to include the serialVersionUID in the class so you override the JVM's idea of when the class is updated (and therefore can't reload your saved serialized data).

OwnerDisplayName: Steve B.


问:
VBA Copy a pivot table and rename
I am working on the following code in Excel VBA. I copied a pivot table to L8 and want to rename this pivot table to "PivotTable00". However error message "Object Doesn't support this property or method" when it goes to the second line here.

Is there a way to fix it? Many thanks.

```<code>wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
wsPvtTbl.Range("L8").Activate
ActiveCell.pivotTable.Name = "PivotTable00"
</code>```

答: Instead of wsPvtTbl.Range("L8").Active use wsPvtTbl.Range("L8").Activate

Title: VBA Copy a pivot table and rename

Body:
I am working on the following code in Excel VBA. I copied a pivot table to L8 and want to rename this pivot table to "PivotTable00". However error message "Object Doesn't support this property or method" when it goes to the second line here.

Is there a way to fix it? Many thanks.

wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
wsPvtTbl.Range("L8").Activate
ActiveCell.pivotTable.Name = "PivotTable00"


问:
Compress-Archive error: not a supported format
I created this script to compress some folder:

```<code>$timer = (Get-Date -Format yyy-MM-dd_HH-mm-ss)
$version = 1.1.2
$folder = New-Item -Name "test_$vesion_$timer" -ItemType directory
Copy-Item -Path test1\log -Destination $folder -Recurse
Compress-Archive -Path $folder -DestinationPath $folder
Remove-Item $folder  -Recurse
</code>```

But when I try it, I get this error:

```<code>Compress-Archive : 1.1.2_2017-06-05_08-58-19 is not a supported archive file format. .zip is the only supported archive file format.
+ Compress-Archive -Path $folder -DestinationPath $folder
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (1.1.2_2017-06-05_08-58-19:String) [Compress-Archive], IOException
    + FullyQualifiedErrorId : NotSupportedArchiveFileExtension,Compress-Archive
</code>```

答:
You're giving the zip file the same name as the folder, which in your example is test_1.1.2_2017-06-05_08-58-19. The problem is that the . character introduced by your $version variable makes the rest of the name look like a file extension. If you give the archive an extension other than .zip, the Compress-Archive cmdlet will return this error.

You should be able to fix this by simply adding .zip to the end of the archive name, like so:

```<code>Compress-Archive -Path $folder -DestinationPath "$folder.zip"
</code>```

Body:
I created this script to compress some folder:

$timer = (Get-Date -Format yyy-MM-dd_HH-mm-ss)
$version = 1.1.2
$folder = New-Item -Name "test_$vesion_$timer" -ItemType directory
Copy-Item -Path test1\log -Destination $folder -Recurse
Compress-Archive -Path $folder -DestinationPath $folder
Remove-Item $folder  -Recurse

But when I try it, I get this error:

Compress-Archive : 1.1.2_2017-06-05_08-58-19 is not a supported archive file format. .zip is the only supported archive file format.
+ Compress-Archive -Path $folder -DestinationPath $folder
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (1.1.2_2017-06-05_08-58-19:String) [Compress-Archive], IOException
    + FullyQualifiedErrorId : NotSupportedArchiveFileExtension,Compress-Archive

Body:
You're giving the zip file the same name as the folder, which in your example is test_1.1.2_2017-06-05_08-58-19. The problem is that the . character introduced by your $version variable makes the rest of the name look like a file extension. If you give the archive an extension other than .zip, the Compress-Archive cmdlet will return this error.

You should be able to fix this by simply adding .zip to the end of the archive name, like so:

Compress-Archive -Path $folder -DestinationPath "$folder.zip"


问:
Why is an exe file compiled by gcc so big?
I wrote a very simple code and compiled it with gcc. After compilation I saw exe is 48kB. Why is it so big? Is it possible to decrease it's size? Should I use some kind of compilation parameters?

gcc .\001_simpleMain.c

```<code>int func()
{
    return 0x1234;
}

int main()
{
    func();
    return 0;
}
</code>```

答:
You can use this with gcc

-Os

Optimize for size. -Os enables all -O2optimizations that  do not typically increase code size. It also performs further optimizations designed to reduce code size.

-Os disables the following optimization flags:

```<code>-falign-functions -falign-jumps -falign-loops -falign-labels -freorder-blocks -freorder-blocks-algorithm=stc -freorder-blocks-and-partition -fprefetch-loop-arrays
</code>```

Body:
I wrote a very simple code and compiled it with gcc. After compilation I saw exe is 48kB. Why is it so big? Is it possible to decrease it's size? Should I use some kind of compilation parameters?

gcc .\001_simpleMain.c

int func()
{
    return 0x1234;
}

int main()
{
    func();
    return 0;
}

Body:
You can use this with gcc

-Os

Optimize for size. -Os enables all -O2optimizations that  do not typically increase code size. It also performs further optimizations designed to reduce code size.

-Os disables the following optimization flags:

-falign-functions -falign-jumps -falign-loops -falign-labels -freorder-blocks -freorder-blocks-algorithm=stc -freorder-blocks-and-partition -fprefetch-loop-arrays


问:
Phoenix framework distribution
I have a phoenix project that must be AP in the CAP theorem
so I need to detect network partitions and ensure my node connects to at least one node.

My solution is a GenServer that calls a function every 30 secs and checks Node.list and if it is [] stop the node.

I have a questions

Is this the best solution or Erlang/OTP have  a straight forward solution for that?

I searched and didn't find my answer on this document: http://erlang.org/doc/design_principles/distributed_applications.html

答:
There's :global_group.monitor/1 function that can be used to get notification when some node in cluster went up or down:</p>

```<code>defmodule NodeMonitor do
  def start_link do
    {:ok, spawn_link fn ->
      :global_group.monitor_nodes true
      monitor()
    end}
  end

  def monitor do
    receive do
      {:nodeup, node}   -> Logger.info "NodeMonitor: #{node} joined"
      {:nodedown, node} -> Logger.warn "NodeMonitor: #{node} left"
    end
    monitor()
  end
end
</code>```

Title: Phoenix framework distribution

Body:
There's :global_group.monitor/1 function that can be used to get notification when some node in cluster went up or down:

defmodule NodeMonitor do
  def start_link do
    {:ok, spawn_link fn ->
      :global_group.monitor_nodes true
      monitor()
    end}
  end

  def monitor do
    receive do
      {:nodeup, node}   -> Logger.info "NodeMonitor: #{node} joined"
      {:nodedown, node} -> Logger.warn "NodeMonitor: #{node} left"
    end
    monitor()
  end
end


问:
How to get $http response and assign to local variable using services?
service.js

```<code>     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);

  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}
</code>```

i want to make a call to $http.get('http://localhost:5000/api/studentsList'); and assign the response.data to a local variable tableData in service.js

答:
You must bind your variable in your service to your controller.

$http.get('http://localhost:500/api/studentList').then(function(res){
  tableService.tableData = res; });

There are lot of ways to bind them. It's really up to you on how you will manipulate your codes.

Body:
service.js

     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);

  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}

i want to make a call to $http.get('http://localhost:5000/api/studentsList'); and assign the response.data to a local variable tableData in service.js


问:
GAE Python Search API not working
The following code:

```<code>from google.appengine.api import search
index = search.Index(name='members')
document = search.Document(
    fields=[
        search.TextField(name='full_name', value='sample text')
    ])
index.put(document)
results = index.search('full_name:tex')
logging.info(results)
</code>```

returns:

```<code>search.SearchResults(number_found=0L)
</code>```

What am I doing wrong?

答:
Found the answer. Looks like GAE Search API is a Full Text search and does not support Partial Matching. Tokenized data based on the answer here:
Partial matching GAE search API</p>

Title: GAE Python Search API not working

Body:
The following code:

from google.appengine.api import search
index = search.Index(name='members')
document = search.Document(
    fields=[
        search.TextField(name='full_name', value='sample text')
    ])
index.put(document)
results = index.search('full_name:tex')
logging.info(results)

returns:

search.SearchResults(number_found=0L)

What am I doing wrong?


问:
Back button from activity 2 closes down the app instead of going to activity 1 in Android 7
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.

Then the whole app closed when pressing back button from the second activity.

I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.

I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.

It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).

Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:

Activity 1:

```<code>Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
</code>```

答:
For going first to second activity...

```<code>  Intent i=new Intent(FirstActivity.this,SecondActivity.class);
            startActivity(i);
</code>```

Use below code for going in previous activity...

```<code>  @Override
public void onBackPressed() {
    super.onBackPressed();

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

Body:
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.

Then the whole app closed when pressing back button from the second activity.

I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.

I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.

It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).

Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:

Activity 1:

Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

Body:
For going first to second activity...

  Intent i=new Intent(FirstActivity.this,SecondActivity.class);
            startActivity(i);

Use below code for going in previous activity...

  @Override
public void onBackPressed() {
    super.onBackPressed();

    Intent i=new Intent(SecondActivity.this, FirstActivity.class);
    startActivity(i);
}


问:
Postgres sql count number of days active in month
I have a table like so:

```<code>meterId | startDate  | endDate  |location
meter01 | 2017-05-01 |2017-05-16| locA
meter02 | 2017-05-01 |9999-12-31| locB
meter03 | 2017-01-01 |9999-12-31| locA
meter04 | 2017-01-01 |9999-12-31| locB
</code>```

I need to return a count for how many days a location had activity for in a given month.  The query would need to return this:
(Given there is 31 days in May)

```<code>location |  Month  |  days  |
locA     |  May-17 |    47  |
locB     |  May-17 |    62  |
</code>```

what i have tried so far is something like this: (note i am joining to another table which isn't optimum and shown here)

```<code>SELECT count(distinct(read_date)) AS days, location from t where EXTRACT(MONTH FROM read_date) = 5 and EXTRACT(YEAR FROM read_date) = 2017
</code>```

It's somewhat close.  It has duplicates of location however.  I also need the date in the format as above.

New edit for @StanislavL

```<code>    select SUM(sub.intervalEnd - sub.intervalStart +1) as days,
     location
from (select
    location,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd
from my_table

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31'))sub
  group by location
</code>```

答:
You should introduce first a select to retrieve desired intervals.

```<code>select
    location,
    case when startDate> :monthBegin then startDate else :monthBegin end as intervalStart,
    case when endDate< :monthEnd then endDate else :monthEnd end as intervalEnd,
from the_table t
where (startDate<=:monthBegin and endDate>:monthBegin)
   OR (startDate<:monthEnd and endDate>=:monthEnd)
</code>```

where monthBegin=01.05.2017 and monthEnd=31.05.2015

Then place the select in the FROM section of another one

```<code>select SUM(sub.intervalEnd - sub.intervalStart) as days,
       sub.location
from (subselect) sub
</code>```

where you need to sum interval differences

Body:
I have a table like so:

meterId | startDate  | endDate  |location
meter01 | 2017-05-01 |2017-05-16| locA
meter02 | 2017-05-01 |9999-12-31| locB
meter03 | 2017-01-01 |9999-12-31| locA
meter04 | 2017-01-01 |9999-12-31| locB

I need to return a count for how many days a location had activity for in a given month.  The query would need to return this:
(Given there is 31 days in May)

location |  Month  |  days  |
locA     |  May-17 |    47  |
locB     |  May-17 |    62  |

what i have tried so far is something like this: (note i am joining to another table which isn't optimum and shown here)

SELECT count(distinct(read_date)) AS days, location from t where EXTRACT(MONTH FROM read_date) = 5 and EXTRACT(YEAR FROM read_date) = 2017

It's somewhat close.  It has duplicates of location however.  I also need the date in the format as above.

New edit for @StanislavL

    select SUM(sub.intervalEnd - sub.intervalStart +1) as days,
     location
from (select
    location,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd
from my_table

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31'))sub
  group by location

Body:
You should introduce first a select to retrieve desired intervals.

select
    location,
    case when startDate> :monthBegin then startDate else :monthBegin end as intervalStart,
    case when endDate< :monthEnd then endDate else :monthEnd end as intervalEnd,
from the_table t
where (startDate<=:monthBegin and endDate>:monthBegin)
   OR (startDate<:monthEnd and endDate>=:monthEnd)

where monthBegin=01.05.2017 and monthEnd=31.05.2015

Then place the select in the FROM section of another one

select SUM(sub.intervalEnd - sub.intervalStart) as days,
       sub.location
from (subselect) sub

where you need to sum interval differences


问:
Angular Span update event
I have a set of code which update the span dynamically.

```<code><div id="ddlType" class="dropdown ddWrap">
    <div data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <span class="icon 1Icon"></span> <span class="dseleced">span</span>
        <span class="caret pull-right"></span>
    </div>
    <ul class="dropdown-menu" aria-labelledby="dLabel">
         <li data-value="1"><a href="#"><span class="iconDD 1Icon"></span> type 1</a></li>
         <li data-value="2"><a href="#"><span class="iconDD 2Icon"></span> type 2</a></li>
         <li data-value="3"><a href="#"><span class="iconDD 3Icon"></span> type 3</a></li>
         <li data-value="4"><a href="#"><span class="iconDD 4Icon"></span> type 4</a></li>
    </ul>
</div>
</code>```

when user select li it update '.dseleced' span with value class ,and data-value, then after I need to update in db

Thank

答:
Try this,

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.dvalue = "";
    $scope.updateDValue = function(ths){
      $scope.dvalue=ths.target.parentNode.getAttribute('data-value');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <div id="ddlType" class="dropdown ddWrap">
    <div data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <span class="icon 1Icon"></span> <span class="dseleced {{dvalue}}" data-value="{{dvalue}}">span {{dvalue}}</span>
      <span class="caret pull-right"></span>
    </div>
    <ul class="dropdown-menu" aria-labelledby="dLabel">
      <li data-value="1"><span class="iconDD 1Icon"></span> type 1</li>
      <li data-value="2"><span class="iconDD 2Icon"></span> type 2</li>
      <li data-value="3"><span class="iconDD 3Icon"></span> type 3</li>
      <li data-value="4"><span class="iconDD 4Icon"></span> type 4</li>
    </ul>
  </div>
</div></code>```

Title: Angular Span update event

Body:
I have a set of code which update the span dynamically.

         span

 type 1

 type 2

 type 3

 type 4

when user select li it update '.dseleced' span with value class ,and data-value, then after I need to update in db

Thank

Body:
Try this,

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.dvalue = "";
    $scope.updateDValue = function(ths){
      $scope.dvalue=ths.target.parentNode.getAttribute('data-value');
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <div id="ddlType" class="dropdown ddWrap">
    <div data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <span class="icon 1Icon"></span> <span class="dseleced {{dvalue}}" data-value="{{dvalue}}">span {{dvalue}}</span>
      <span class="caret pull-right"></span>
    </div>
    <ul class="dropdown-menu" aria-labelledby="dLabel">
      <li data-value="1"><a href="#" ng-click="updateDValue($event)"><span class="iconDD 1Icon"></span> type 1</a></li>
      <li data-value="2"><a href="#" ng-click="updateDValue($event)"><span class="iconDD 2Icon"></span> type 2</a></li>
      <li data-value="3"><a href="#" ng-click="updateDValue($event)"><span class="iconDD 3Icon"></span> type 3</a></li>
      <li data-value="4"><a href="#" ng-click="updateDValue($event)"><span class="iconDD 4Icon"></span> type 4</a></li>
    </ul>
  </div>
</div>


问:
Resizing Custom MKAnnotationView According to MapKit Zoom Level
Here is the situation:
I am displaying images on the map by using custom annotations. Everything works fine but I would like to improve it visually by resizing the AnnotationView so that it shrinks as the map is zoomed out. I want to do this because, obviously, more annotations fill up the screen and need to be shrunk so that they don't overlap each other too much and the user can see more annotations. (Of course, I would like to enlarge AnnotationViews when the map is zoomed in again).

I have achieved this by removing all annotations from the map and adding them back again, whenever regionDidChangeAnimated is called. However, these images are loaded from the internet, so downloading the images again (since the annotations have been removed) doesn't seem to make sense.

I hope I have explained the situation well, and hope to contribute to SO in the future.

Thanks in advance.

P.S. I'm developing with iOS 4.0

答:
Since you are using iOS 4.0 I would suggest using a class that conforms to the MKOverlay protocol instead of MKAnnotationView. Overlays zoom with the map and will scale appropriately. You can probably use 1 overlay to handle all your annotations. Check out the HazardMap demo Apple provided in the 2010 WWDC talks on http://developer.apple.com

Alternatively, you could use something like the k nearest neighbors algorithm to group annotations per zoom scale. However, that can be kind of slow if you have a lot of annotations. I tried it once with several thousand annotations and did not like the performance hit that was incurred. I think < 1000 annotations might have decent performance with this method though.


答:
```<code>=INT(C27/1000)&"M"
</code>```

You may say I have to fix your formula and spot its obvious syntax error. No, I say you have to do it this way, and you always have to look for some neat, simple and deductive alternative before abandoning to the ugly, error-prone and difficult-to-maintain nested IFs.

And indeed, such alternative exists most of the time.

p.s. by the way why is it M and not K? may be you have a multiplicative unit implicitly in your data, well...

Title: IF function and nested function

Body:
Please help with this formula

=if(C27>=16000,16M,if(C27,=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

Body:
=INT(C27/1000)&"M"

You may say I have to fix your formula and spot its obvious syntax error. No, I say you have to do it this way, and you always have to look for some neat, simple and deductive alternative before abandoning to the ugly, error-prone and difficult-to-maintain nested IFs.

And indeed, such alternative exists most of the time.

p.s. by the way why is it M and not K? may be you have a multiplicative unit implicitly in your data, well...


问:
Log out user by admin Spring Security
I'd like your help to get how implement this function:
admin gets all logged in users using sessionRegistry.getAllPrincipals() and then can log off someone.
I know how to log off current user (session.invalidate()), but have no idea how to force log out other users.

This code gets me all logged in users

```<code>public List<User> getAllLoggedInUsers() {
    List<Object> principals = sessionRegistry.getAllPrincipals();
    List<User> usersNamesList = new ArrayList<>();
    for (Object principal : principals) {
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            usersNamesList.add(dao.findByLogin(((org.springframework.security.core.userdetails.User) principal).getUsername()));
        }
    }
    return usersNamesList;
}
</code>```

Thanks a lot.

EDIT 1: I want next: admin chooses a user, bans it (change info in DB) and then if this user is active - log him off.

答:
First, you need a sessionRegistry, this can get all sessions and register new session:

```<code>@Bean
SessionRegistry sessionRegistry() {
    return new SessionRegistryImpl();
}
</code>```

Second, you need enable the sessionRegistry and use the ConcurrentSessionFilter to control the invalidate session.

```<code>http
 .sessionManagement()
    .maximumSessions(-1)
    .sessionRegistry(sessionRegistry());
</code>```

the -1 means no limit, BUT this will register the ConcurrentSessionFilter and RegisterSessionAuthenticationStrategy automatic. based the last spring security configuration, If you use xml or old version of spring security, please find this page for help.

ConcurrentSessionFilter will get the session from sessionRegistry, and will do logout when the session is expired.

The last thing is inject the same sessionRegistry bean to your application when try to get session by user and expire the user's session.

You can list a user’s sessions by calling the getAllSessions(Object principal, boolean includeExpiredSessions) method, which returns a list of SessionInformation objects. You can also expire a user’s session by calling expireNow() on a SessionInformation instance. When the user returns to the application, they will be prevented from proceeding.

Title: Log out user by admin Spring Security

Body:
I'd like your help to get how implement this function:
admin gets all logged in users using sessionRegistry.getAllPrincipals() and then can log off someone.
I know how to log off current user (session.invalidate()), but have no idea how to force log out other users.

This code gets me all logged in users

public List<User> getAllLoggedInUsers() {
    List<Object> principals = sessionRegistry.getAllPrincipals();
    List<User> usersNamesList = new ArrayList<>();
    for (Object principal : principals) {
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            usersNamesList.add(dao.findByLogin(((org.springframework.security.core.userdetails.User) principal).getUsername()));
        }
    }
    return usersNamesList;
}

Thanks a lot.

EDIT 1: I want next: admin chooses a user, bans it (change info in DB) and then if this user is active - log him off.

Body:
First, you need a sessionRegistry, this can get all sessions and register new session:

@Bean
SessionRegistry sessionRegistry() {
    return new SessionRegistryImpl();
}

Second, you need enable the sessionRegistry and use the ConcurrentSessionFilter to control the invalidate session.

http
 .sessionManagement()
    .maximumSessions(-1)
    .sessionRegistry(sessionRegistry());

the -1 means no limit, BUT this will register the ConcurrentSessionFilter and RegisterSessionAuthenticationStrategy automatic. based the last spring security configuration, If you use xml or old version of spring security, please find this page for help.

ConcurrentSessionFilter will get the session from sessionRegistry, and will do logout when the session is expired.

The last thing is inject the same sessionRegistry bean to your application when try to get session by user and expire the user's session.

You can list a user’s sessions by calling the getAllSessions(Object principal, boolean includeExpiredSessions) method, which returns a list of SessionInformation objects. You can also expire a user’s session by calling expireNow() on a SessionInformation instance. When the user returns to the application, they will be prevented from proceeding.


问:
How to solve "An unhandled exception occured" with a Google Maps Android App? -Xamarin
I made an app that runs google maps and then takes your input to find the desired place. Every time I run it through the emulator though it pops up with the message "An unhandled exception occurred". I don't know how to over come this and if this is a problem with the emulator or something wrong with my code?

This is my Main Activity:

```<code>using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using Android.Locations;
using System.Linq;
using Android.Util;
using System.Threading.Tasks;

namespace SafeandSound
{
[Activity(Label = "SafeandSound", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    private GoogleMap mMap;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        SetUpMap();
    }
    private void SetUpMap()
    {
        if (mMap == null)
        {
            FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
        }
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        mMap = googleMap;

    }
    // Button to Search for Address//
    public async System.Threading.Tasks.Task onMapSearchAsync(View view)
    {
        EditText gotAddress = (EditText)FindViewById(Resource.Id.searchText);
        string addressnew = gotAddress.Text;
        if (!Geocoder.IsPresent)
        {
            Log.Error("SO", "Geocoder is not present");
        }
        else
        {
            var geocoder = new Geocoder(this);
            var retry = 0;
            do
            {
                var addressList = await geocoder.GetFromLocationNameAsync(addressnew, 5);
                if (addressList.Count > 0)
                {
                    foreach (var address in addressList)
                    {
                        Log.Debug("SO", $"{address.Latitude}:{address.Longitude} - {address.FeatureName} : {address.GetAddressLine(0)} : {address.GetAddressLine(1)}");
                        LatLng latLng = new LatLng(address.Latitude, address.Longitude);
                        CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
                        builder.Target(latLng);
                        builder.Zoom(10);
                        CameraPosition cameraPosition = builder.Build();
                        CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);

                    }
                    break;
                }
                retry++;
                Log.Warn("SO", $"No addresses returned...., retrying in {retry * 2} secs");
                await Task.Delay(retry * 1000);
            } while (retry < 5);
        }

    }
}
}
</code>```

And this is my Main code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/background_light">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/searchText"
        android:layout_width="303.5dp"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:hint="Search Location..."
        android:textColor="#000000" />
    <Button
        android:id="@+id/search_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:onClick="onMapSearch"
        android:text="Search" />
</LinearLayout>
<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.google.android.gms.maps.MapFragment"/>
 </LinearLayout>
</code>```

答:
Note: This assumes you are starting with a template-based Xamarin.Android project...

Add Google Maps:

Add the Xamarin.GooglePlayServices.Maps package to your project

Main.axml

Change your default Main.axml to:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_weight="0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:layout_weight="10"
            android:id="@+id/searchText"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:hint="Search Location..."/>
        <Button
            android:layout_weight="1"
            android:id="@+id/search_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Search" />
    </LinearLayout>
    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.MapFragment"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" />
</LinearLayout>
</code>```

MainActivty.cs:

Replace the entire MainActivity class with:

```<code>[Activity(Label = "Google Map and GeoCode Example", MainLauncher = true)]
public class MainActivity : Activity, IOnMapReadyCallback
{
    GoogleMap googleMap;
    EditText searchTextEdit;
    Geocoder geoCoder;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Main);

        var searchButton = FindViewById<Button>(Resource.Id.search_button);
        searchButton.Click += SearchButtonClick;
        searchButton.Enabled &= Geocoder.IsPresent;

        searchTextEdit = FindViewById<EditText>(Resource.Id.searchText);
        searchTextEdit.Enabled &= Geocoder.IsPresent;

        var mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
        mapFragment.GetMapAsync(this);
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        this.googleMap = googleMap;
        geoCoder = new Geocoder(this);
    }

    async void SearchButtonClick(object sender, EventArgs e)
    {
        for (int i = 1; i < 6; i++)
        {
            try
            {
                var addressList = await geoCoder.GetFromLocationNameAsync(searchTextEdit.Text, 10);
                for (int j = 0; j < addressList.Count(); j++)
                {
                    var address = addressList[j];
                    var latLng = new LatLng(address.Latitude, address.Longitude);
                    if (j == 0) // Move the map to the first address return
                    {
                        var cameraPosition = CameraPosition.InvokeBuilder()
                           .Target(latLng)
                           .Zoom(15)
                           .Build();
                        var cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
                        googleMap.MoveCamera(cameraUpdate);
                    }
                    var marker = new MarkerOptions(); // Add markers for all addresses found
                    marker.SetTitle($"{address.FeatureName}");
                    marker.SetPosition(latLng);
                    googleMap.AddMarker(marker);
                }
                if (addressList.Any()) { i = 99; break; }
                await Task.Delay(1000 * i);
            }
            catch (Exception ex) // Google Server timeouts will throw....
            {
                Log.Error("SO", ex.Message);
            }
        }
    }
}
</code>```

Google Map API key:

You will need a Google map API key assigned to this app:

```<code>http://console.developers.google.com/
</code>```

AndroidManifest.xml

Once you obtain a key, add it to your project. Instead of manually modifying your AndroidManifest.xml, you can add an Assembly-level MetaData attribute.

Adding the following to your Properties/AssemblyInfo.cs:

```<code>[assembly: MetaData("com.google.android.geo.API_KEY", Value = "YourGoogleMapApiKeyGoesHere")]
</code>```

Results on searching "Starbucks 98101":

Body:
I made an app that runs google maps and then takes your input to find the desired place. Every time I run it through the emulator though it pops up with the message "An unhandled exception occurred". I don't know how to over come this and if this is a problem with the emulator or something wrong with my code?

This is my Main Activity:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using Android.Locations;
using System.Linq;
using Android.Util;
using System.Threading.Tasks;

namespace SafeandSound
{
[Activity(Label = "SafeandSound", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    private GoogleMap mMap;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        SetUpMap();
    }
    private void SetUpMap()
    {
        if (mMap == null)
        {
            FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
        }
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        mMap = googleMap;

    }
    // Button to Search for Address//
    public async System.Threading.Tasks.Task onMapSearchAsync(View view)
    {
        EditText gotAddress = (EditText)FindViewById(Resource.Id.searchText);
        string addressnew = gotAddress.Text;
        if (!Geocoder.IsPresent)
        {
            Log.Error("SO", "Geocoder is not present");
        }
        else
        {
            var geocoder = new Geocoder(this);
            var retry = 0;
            do
            {
                var addressList = await geocoder.GetFromLocationNameAsync(addressnew, 5);
                if (addressList.Count > 0)
                {
                    foreach (var address in addressList)
                    {
                        Log.Debug("SO", $"{address.Latitude}:{address.Longitude} - {address.FeatureName} : {address.GetAddressLine(0)} : {address.GetAddressLine(1)}");
                        LatLng latLng = new LatLng(address.Latitude, address.Longitude);
                        CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
                        builder.Target(latLng);
                        builder.Zoom(10);
                        CameraPosition cameraPosition = builder.Build();
                        CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);

                    }
                    break;
                }
                retry++;
                Log.Warn("SO", $"No addresses returned...., retrying in {retry * 2} secs");
                await Task.Delay(retry * 1000);
            } while (retry < 5);
        }

    }
}
}

And this is my Main code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/background_light">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/searchText"
        android:layout_width="303.5dp"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:hint="Search Location..."
        android:textColor="#000000" />
    <Button
        android:id="@+id/search_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:onClick="onMapSearch"
        android:text="Search" />
</LinearLayout>
<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.google.android.gms.maps.MapFragment"/>
 </LinearLayout>

Body:
Note: This assumes you are starting with a template-based Xamarin.Android project...

Add Google Maps:

Add the Xamarin.GooglePlayServices.Maps package to your project

Main.axml

Change your default Main.axml to:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_weight="0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:layout_weight="10"
            android:id="@+id/searchText"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:hint="Search Location..."/>
        <Button
            android:layout_weight="1"
            android:id="@+id/search_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Search" />
    </LinearLayout>
    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.MapFragment"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" />
</LinearLayout>

MainActivty.cs:

Replace the entire MainActivity class with:

[Activity(Label = "Google Map and GeoCode Example", MainLauncher = true)]
public class MainActivity : Activity, IOnMapReadyCallback
{
    GoogleMap googleMap;
    EditText searchTextEdit;
    Geocoder geoCoder;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Main);

        var searchButton = FindViewById<Button>(Resource.Id.search_button);
        searchButton.Click += SearchButtonClick;
        searchButton.Enabled &= Geocoder.IsPresent;

        searchTextEdit = FindViewById<EditText>(Resource.Id.searchText);
        searchTextEdit.Enabled &= Geocoder.IsPresent;

        var mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
        mapFragment.GetMapAsync(this);
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        this.googleMap = googleMap;
        geoCoder = new Geocoder(this);
    }

    async void SearchButtonClick(object sender, EventArgs e)
    {
        for (int i = 1; i < 6; i++)
        {
            try
            {
                var addressList = await geoCoder.GetFromLocationNameAsync(searchTextEdit.Text, 10);
                for (int j = 0; j < addressList.Count(); j++)
                {
                    var address = addressList[j];
                    var latLng = new LatLng(address.Latitude, address.Longitude);
                    if (j == 0) // Move the map to the first address return
                    {
                        var cameraPosition = CameraPosition.InvokeBuilder()
                           .Target(latLng)
                           .Zoom(15)
                           .Build();
                        var cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
                        googleMap.MoveCamera(cameraUpdate);
                    }
                    var marker = new MarkerOptions(); // Add markers for all addresses found
                    marker.SetTitle($"{address.FeatureName}");
                    marker.SetPosition(latLng);
                    googleMap.AddMarker(marker);
                }
                if (addressList.Any()) { i = 99; break; }
                await Task.Delay(1000 * i);
            }
            catch (Exception ex) // Google Server timeouts will throw....
            {
                Log.Error("SO", ex.Message);
            }
        }
    }
}

Google Map API key:

You will need a Google map API key assigned to this app:

http://console.developers.google.com/

AndroidManifest.xml

Once you obtain a key, add it to your project. Instead of manually modifying your AndroidManifest.xml, you can add an Assembly-level MetaData attribute.

Adding the following to your Properties/AssemblyInfo.cs:

[assembly: MetaData("com.google.android.geo.API_KEY", Value = "YourGoogleMapApiKeyGoesHere")]

Results on searching "Starbucks 98101":


问:
Get the current row index of WPF DataGrid in XAML
How can I get the current selected row index of WPF data grid in XAML. I know how to get current row index in code behind. But i want to get the selected row index to pass it as command parameter, so that I can delete the corresponding itemfrom the collection, passing the index.

I've tried CommandParameter="{Binding Items.CurrentPosition, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}", but it is not working(giving -1 as selectedindex). Is it possible to get the current row index in XAML, if yes how?

答:
This works okay for me, I use this on a button within a row:</p>

```<code>Command="{Binding Path=DataContext.MyClickRowEventCommand,
   RelativeSource= {RelativeSource FindAncestor,
   AncestorType={x:Type DataGrid}}}"
   CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"
</code>```

Body:
This works okay for me, I use this on a button within a row:

Command="{Binding Path=DataContext.MyClickRowEventCommand,
   RelativeSource= {RelativeSource FindAncestor,
   AncestorType={x:Type DataGrid}}}"
   CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"


问:
Removing dynamically an element from a list
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

```<code>def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test
</code>```

I am getting the following output:

```<code>[5]
</code>```

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

答:
As your description you can also go through this way.  </p>

```<code>ls = [1,2,3,4]
ls_length = len(ls)
i = 0
condition_satisfied = True
while ls_length:
    if i<ls_length:
        test_num = ls[i]
        i = i + 1
        if condition_satisfied:
            ls.remove(test_num)
            ls_length = len(ls)
            i = 0
print(ls)
</code>```

Body:
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test

I am getting the following output:

[5]

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

Body:
As your description you can also go through this way.

ls = [1,2,3,4]
ls_length = len(ls)
i = 0
condition_satisfied = True
while ls_length:
    if i<ls_length:
        test_num = ls[i]
        i = i + 1
        if condition_satisfied:
            ls.remove(test_num)
            ls_length = len(ls)
            i = 0
print(ls)


问:
Finding unique file names from an html file
```<code>$ cat downloaded_file.html

1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
</code>```

How do I search an html file from my shell script and select the unique filenames those start with STDMON and end with _company.txt

答:
```<code> awk -F'>|<' '$3 ~ /STDMON[0-9]+_company.txt/ && !a[$0=$3]++' download_file.html
</code>```

Input

```<code>$ cat downloaded_file.html
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON14959440_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON14959440_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON12342440_company.txt</A><br> Monday, November 22, 2010  1:31 AM
</code>```

Output

```<code>$ awk -F'>|<' '$3 ~ /STDMON[0-9]+_company.txt/ && !a[$0=$3]++'
STDMON11202010_company.txt
STDMON14959440_company.txt
STDMON12342440_company.txt
</code>```

Body:
$ cat downloaded_file.html

1373 STDMON11202010_company.txt
 Monday, November 22, 2010  1:31 AM

How do I search an html file from my shell script and select the unique filenames those start with STDMON and end with _company.txt

Body:
 awk -F'>|<' '$3 ~ /STDMON[0-9]+_company.txt/ && !a[$0=$3]++' download_file.html

Input

$ cat downloaded_file.html
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON14959440_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON14959440_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON11202010_company.txt</A><br> Monday, November 22, 2010  1:31 AM
1373 <A HREF="http://site.com/STDMON11202010_company.txt">STDMON12342440_company.txt</A><br> Monday, November 22, 2010  1:31 AM

Output

$ awk -F'>|<' '$3 ~ /STDMON[0-9]+_company.txt/ && !a[$0=$3]++'
STDMON11202010_company.txt
STDMON14959440_company.txt
STDMON12342440_company.txt


问:
Java ComboBox will not get populated
I have tried everything to figure out why my combobox will not get populated but nothing works.

In my FXML file I have.

```<code><ComboBox fx:id="comboBox" layoutX="162.0" layoutY="15.0" prefHeight="25.0" prefWidth="334.0" promptText="Select past popular pizza" />
</code>```

In my controller I have the following

```<code>public class ServeController {
public ObservableList<String> pizzas1 = FXCollections.observableArrayList();
@FXML public ComboBox<String> comboBox;
private void initialize() {
comboBox.getItems().addAll(
        "jacob.smith@example.com",
        "isabella.johnson@example.com",
        "ethan.williams@example.com",
        "emma.jones@example.com",
        "michael.brown@example.com"
    );
}
</code>```

I have even tried with

```<code>public ObservableList<String> pizzas1 = FXCollections.observableArrayList("1","2","3","4");
</code>```

to try to get some kind of data to show up but nothing seems to be working.

答:
I assume that if you add a printout to initialize() you'll see that it is not invoked.
To get initialize() invoked you need to annotate it: @FXML private void initialize()

Title: Java ComboBox will not get populated

Body:
I have tried everything to figure out why my combobox will not get populated but nothing works.

In my FXML file I have.

<ComboBox fx:id="comboBox" layoutX="162.0" layoutY="15.0" prefHeight="25.0" prefWidth="334.0" promptText="Select past popular pizza" />

In my controller I have the following

public class ServeController {
public ObservableList<String> pizzas1 = FXCollections.observableArrayList();
@FXML public ComboBox<String> comboBox;
private void initialize() {
comboBox.getItems().addAll(
        "jacob.smith@example.com",
        "isabella.johnson@example.com",
        "ethan.williams@example.com",
        "emma.jones@example.com",
        "michael.brown@example.com"
    );
}

I have even tried with

public ObservableList<String> pizzas1 = FXCollections.observableArrayList("1","2","3","4");

to try to get some kind of data to show up but nothing seems to be working.