问:
Android Service: Detect when device is idle for X minutes
I need to know to detect when the android device has been idle for a certain period of time when my app is currently in the background (and if it is idle, bring my app to the front). The only two ways I could think of to do this are:

Somehow detect user interaction outside of the app, and if there hasn't been any input for X number of minutes, bring my app to the front.

or:

When the device goes into sleep mode, bring my app to the front.

I can't figure out how to either of these, but 2 seems like the most feasible option to me. What would be the code for this?

答:
I was able to accomplish 1. by using "transparent" view which was placed on top of all views, which checks for user touches

Steps for achieving the needed effect:

1) Create a Service which in its onCreate method creates the transparent view and attach it to the views stack

2) onStartCommand call the initTimer() method

3) implement View.OnTouchListener on the service

4) override onTouch method

5) onTouch event received - call initTimer()

6) on onDestroy of the service - remove the transparent view from the views stack

7) start the service when onPause of your main activity is called

8) stop the service when the app opens

Here is the code:

```<code>private Handler mHandler;
private Runnable mRunnable;
private final int mTimerDelay = 60000;//inactivity delay in milliseconds
private LinearLayout mTouchLayout;//the transparent view

@Override
public IBinder onBind(Intent intent) {
    return null;
}

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

    mTouchLayout = new LinearLayout(this);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    mTouchLayout.setLayoutParams(lp);

    // set on touch listener
    mTouchLayout.setOnTouchListener(this);

    // fetch window manager object
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    // set layout parameter of window manager

    WindowManager.LayoutParams mParams = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT
    );

    mParams.gravity = Gravity.LEFT | Gravity.TOP;
    windowManager.addView(mTouchLayout, mParams);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    initTimer();

    return START_NOT_STICKY;
}

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    Log.d("IdleDetectorService", "Touch detected. Resetting timer");
    initTimer();
    return false;
}

@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mRunnable);
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    if (windowManager != null && mTouchLayout != null) {
        windowManager.removeView(mTouchLayout);
    }
}

/**
 * (Re)sets the timer to send the inactivity broadcast
 */
private void initTimer() {
    // Start timer and timer task
    if (mRunnable == null) {

        mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("IdleDetectorService", "Inactivity detected. Sending broadcast to start the app");

                try {
                    boolean isInForeground = new ForegroundCheckTask().execute(getApplicationContext()).get();

                    if (!isInForeground) {
                        Intent launchIntent = getApplication()
                                .getPackageManager()
                                .getLaunchIntentForPackage("<your-package-name>");
                        if (launchIntent != null) {
                            LogUtil.d("IdleDetectorService", "App started");
                            getApplication().startActivity(launchIntent);
                        }
                    }

                    stopSelf();
                } catch (Exception e) {
                }
            }
        };
    }

    if (mHandler == null) {
        mHandler = new Handler();
    }

    mHandler.removeCallbacks(mRunnable);
    mHandler.postDelayed(mRunnable, mTimerDelay);
}

private class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Context... params) {
        final Context context = params[0];
        return isAppOnForeground(context);
    }

    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = null;

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            appProcesses = activityManager.getRunningAppProcesses();
        } else {
            //for devices with Android 5+ use alternative methods
            appProcesses = AndroidProcesses.getRunningAppProcessInfo(getApplication());
        }

        if (appProcesses == null) {
            return false;
        }

        final String packageName = context.getPackageName();

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
                    appProcess.processName.equals(packageName)) {
                return true;
            }
        }

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

Note that you should add additional permission in your AndroidManifest.xml file:
android:name="android.permission.SYSTEM_ALERT_WINDOW"

Body:
I was able to accomplish 1. by using "transparent" view which was placed on top of all views, which checks for user touches

Steps for achieving the needed effect:

1) Create a Service which in its onCreate method creates the transparent view and attach it to the views stack

2) onStartCommand call the initTimer() method

3) implement View.OnTouchListener on the service

4) override onTouch method

5) onTouch event received - call initTimer()

6) on onDestroy of the service - remove the transparent view from the views stack

7) start the service when onPause of your main activity is called

8) stop the service when the app opens

Here is the code:

private Handler mHandler;
private Runnable mRunnable;
private final int mTimerDelay = 60000;//inactivity delay in milliseconds
private LinearLayout mTouchLayout;//the transparent view

@Override
public IBinder onBind(Intent intent) {
    return null;
}

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

    mTouchLayout = new LinearLayout(this);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    mTouchLayout.setLayoutParams(lp);

    // set on touch listener
    mTouchLayout.setOnTouchListener(this);

    // fetch window manager object
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    // set layout parameter of window manager

    WindowManager.LayoutParams mParams = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT
    );

    mParams.gravity = Gravity.LEFT | Gravity.TOP;
    windowManager.addView(mTouchLayout, mParams);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    initTimer();

    return START_NOT_STICKY;
}

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    Log.d("IdleDetectorService", "Touch detected. Resetting timer");
    initTimer();
    return false;
}

@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mRunnable);
    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    if (windowManager != null && mTouchLayout != null) {
        windowManager.removeView(mTouchLayout);
    }
}

/**
 * (Re)sets the timer to send the inactivity broadcast
 */
private void initTimer() {
    // Start timer and timer task
    if (mRunnable == null) {

        mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("IdleDetectorService", "Inactivity detected. Sending broadcast to start the app");

                try {
                    boolean isInForeground = new ForegroundCheckTask().execute(getApplicationContext()).get();

                    if (!isInForeground) {
                        Intent launchIntent = getApplication()
                                .getPackageManager()
                                .getLaunchIntentForPackage("<your-package-name>");
                        if (launchIntent != null) {
                            LogUtil.d("IdleDetectorService", "App started");
                            getApplication().startActivity(launchIntent);
                        }
                    }

                    stopSelf();
                } catch (Exception e) {
                }
            }
        };
    }

    if (mHandler == null) {
        mHandler = new Handler();
    }

    mHandler.removeCallbacks(mRunnable);
    mHandler.postDelayed(mRunnable, mTimerDelay);
}

private class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Context... params) {
        final Context context = params[0];
        return isAppOnForeground(context);
    }

    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = null;

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            appProcesses = activityManager.getRunningAppProcesses();
        } else {
            //for devices with Android 5+ use alternative methods
            appProcesses = AndroidProcesses.getRunningAppProcessInfo(getApplication());
        }

        if (appProcesses == null) {
            return false;
        }

        final String packageName = context.getPackageName();

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
                    appProcess.processName.equals(packageName)) {
                return true;
            }
        }

        return false;
    }
}

Note that you should add additional permission in your AndroidManifest.xml file:
android:name="android.permission.SYSTEM_ALERT_WINDOW"


来源: stackexchange

问:
NHibernates QueryOver and reverse associations
How do I find any C classes without references using NHibernate's QueryOver?

```<code>public class A {
    public List<C> c { get; set; }
}

public class B {
    public List<C> c { get; set; }
}

public class C {
}
</code>```

The same in SQL:

```<code>select C.* from C
left join A on C.Id = A.C
left join B on C.Id = B.C
where A.Id is null and B.Id is null
</code>```

If I had only one join, something like this would work:

```<code>session.QueryOver<A>(() => a)
    .Right.JoinQueryOver(() => a.C, () => c)
    .WhereRestrictionOn(() => a.DbId)
    .IsNull
    .List() // TODO: use transfomer to select C
</code>```

EDIT: I'm not sure if it matters if the references are List<C> or just plain C.

Anyway, I'm interested how I could I root the query at C and then do joins where I have no direct path available

答:
Something like this seems to work, but not the answer I was hoping for:

```<code>C c = null;
var aSubquery = QueryOver.Of<A>()
    .JoinAlias(a => a.C, () => c)
    .Select(Projections.Property(() => c.Id));
var bSubquery = QueryOver.Of<B>()
    .JoinAlias(b => b.C, () => c)
    .Select(Projections.Property(() => c.Id));
session.QueryOver<C>()
    .WithSubquery
    .WhereProperty(x => x.Id).NotIn(aSubquery)
    .WithSubquery
    .WhereProperty(x => x.Id).NotIn(bSubquery);
</code>```

If you have a better answer, please provide an alternative.

ContentLicense: CC BY-SA 3.0

Body:
How do I find any C classes without references using NHibernate's QueryOver?

public class A {
    public List<C> c { get; set; }
}

public class B {
    public List<C> c { get; set; }
}

public class C {
}

The same in SQL:

select C.* from C
left join A on C.Id = A.C
left join B on C.Id = B.C
where A.Id is null and B.Id is null

If I had only one join, something like this would work:

session.QueryOver(() => a)
    .Right.JoinQueryOver(() => a.C, () => c)
    .WhereRestrictionOn(() => a.DbId)
    .IsNull
    .List() // TODO: use transfomer to select C

EDIT: I'm not sure if it matters if the references are List<C> or just plain C.

Anyway, I'm interested how I could I root the query at C and then do joins where I have no direct path available

Body:
Something like this seems to work, but not the answer I was hoping for:

C c = null;
var aSubquery = QueryOver.Of<A>()
    .JoinAlias(a => a.C, () => c)
    .Select(Projections.Property(() => c.Id));
var bSubquery = QueryOver.Of<B>()
    .JoinAlias(b => b.C, () => c)
    .Select(Projections.Property(() => c.Id));
session.QueryOver<C>()
    .WithSubquery
    .WhereProperty(x => x.Id).NotIn(aSubquery)
    .WithSubquery
    .WhereProperty(x => x.Id).NotIn(bSubquery);

If you have a better answer, please provide an alternative.


问:
Sending data from one view controller to another not working
I am trying to send some data from one view controller to another. But I can't seem to get this code to work! It should change a label to a variable that was passed to it but it doesn't change anything.

ViewController.swift

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "SVCSegue" {
        let controller = segue.destination as! SecondViewController
        if let user = FIRAuth.auth()?.currentUser {
            controller.email = user.email
        }
    }
}
</code>```

SecondViewController.swift

```<code>@IBOutlet weak var usernameLabel: UILabel!

    var email:String!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.usernameLabel.text = self.email

    }
</code>```

EDIT I also have this code AFTER override func prepare

```<code>@IBAction func loginAction(_ sender: Any) {

        if self.emailField.text == "" || self.passwordField.text == "" {
            let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

            alertController.addAction(defaultAction)

            self.present(alertController, animated: true, completion: nil)
        } else {
            FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
                if error == nil {
                    self.emailField.text = ""
                    self.passwordField.text = ""
                } else {
                    let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

                    alertController.addAction(defaultAction)
                }
            })
        }
    }
</code>```

答:
I'm not sure, but depending on when the different lifecycle functions of SecondViewController are called during the seque, viewDidLoad might have been called before the prepare code is executed.

Try to give the email a default value so you can if it's that value that are used. Also, set the email value to something else in the else part in the prepare method to see if it's the if condition that fails.

Body:
I am trying to send some data from one view controller to another. But I can't seem to get this code to work! It should change a label to a variable that was passed to it but it doesn't change anything.

ViewController.swift

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "SVCSegue" {
        let controller = segue.destination as! SecondViewController
        if let user = FIRAuth.auth()?.currentUser {
            controller.email = user.email
        }
    }
}

SecondViewController.swift

@IBOutlet weak var usernameLabel: UILabel!

    var email:String!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.usernameLabel.text = self.email

    }

EDIT I also have this code AFTER override func prepare

@IBAction func loginAction(_ sender: Any) {

        if self.emailField.text == "" || self.passwordField.text == "" {
            let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

            alertController.addAction(defaultAction)

            self.present(alertController, animated: true, completion: nil)
        } else {
            FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
                if error == nil {
                    self.emailField.text = ""
                    self.passwordField.text = ""
                } else {
                    let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

                    alertController.addAction(defaultAction)
                }
            })
        }
    }


问:
What is new() function here?
I've been learning design patterns and I saw such a method call from a class :

```<code>class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}
</code>```

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.

答: I can't see how that compiles. "new" in this context is the new operator and this always expects a typename per C# syntax.</p>

ContentLicense: CC BY-SA 2.5

Title: What is new() function here?

Body:
I've been learning design patterns and I saw such a method call from a class :

class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.


问:
Warning 'myframe-Bridging-Header.h' in Xcode 8.3
I updated Xcode to Version 8.3 (8E162) and in my unit test file I have this warning:

Implicit import of bridging header 'myframe-Bridging-Header.h' via
  module 'myframe' is deprecated and will be removed in a later version
  of Swift

on this line:

```<code>@testable import myframe
</code>```

How to fix this warning?

答:
That article helped me to fix the warning: https://bugs.swift.org/browse/SR-3801

I selected:

chain the import by adding #import "App-Bridging-Header.h" to any
  existing unit test bridging header you have

Body:
I updated Xcode to Version 8.3 (8E162) and in my unit test file I have this warning:

Implicit import of bridging header 'myframe-Bridging-Header.h' via
  module 'myframe' is deprecated and will be removed in a later version
  of Swift

on this line:

@testable import myframe

How to fix this warning?


问:
Remove/Add References and Compile antique VB6 application using Powershell
I've been given the task of researching whether one can use Powershell to automate the managing of References in VB6 application and then compile it's projects afterwards.

There are 3 projects. I requirement is to remove a specific reference in each project. Then, compile projects from bottom up (server > client > interface) and add reference back in along the way. (remove references, compile server.dll >add client reference to server.dll, compile client.dll > add interface reference to client.dll, compile interface.exe)

I'm thinking no, but I was still given the task of finding out for sure. Of course, where does one go to find this out? Why here of course, StackOverflow.

答:
References are stored in the project .VBP files which are just text files. A given reference takes up exactly one line of the file.

For example, here is a reference to DAO database components:

Reference=*\G{00025E01-0000-0000-C000-000000000046}#5.0#0#C:\WINDOWS\SysWow64\dao360.dll#Microsoft DAO 3.6 Object Library

The most important info is everything to the left of the path which contains the GUID (i.e., the unique identifier of the library, more or less). The filespec and description text are unimportant as VB6 will update that to whatever it finds in the registry for the referenced DLL.

An alternate form of reference is for GUI controls, such as:

Object={BDC217C8-ED16-11CD-956C-0000C04E4C0A}#1.1#0; tabctl32.ocx

which for whatever reason never seem to have a path anyway. Most likely you will not need to modify this type of reference, because it would almost certainly break forms in the project which rely on them.

So in your Powershell script, the key task would be to either add or remove the individual reference lines mentioned in the question. Unless you are using no form of binary compatibility, the GUID will remain stable. Therefore, you could essentially hardcode the strings you need to add/remove.

Aside from all that, its worth thinking through why you need to take this approach at all. Normally to build a VB6 solution it is totally unnecessary to add/remove references along the way. Also depending on your choice of deployment techniques, you are probably using either project or binary compatibility which tends to keep the references stable.

Lastly, I'll mention that there are existing tools such as Kinook's Visual Build Pro which already know how to build groups of VB6 projects and if using a 3rd party tool like that is an option, could save you a lot of work.


问:
How to specify dependecies to Ansible Galaxy roles from other roles?
I've specified dependency for my role by declaring it inside meta/main.yml.

```<code>---
dependencies:
  - role: angstwad.docker_ubuntu
    src: https://github.com/angstwad/docker.ubuntu
    scm: git
    version: v2.3.0
</code>```

However when I try to execute Ansible playbook I'm seeing error message:

```<code>ERROR! the role 'angstwad.docker_ubuntu' was not found in /home/.../ansible/roles:/etc/ansible/roles:/home/.../ansible/roles:/home/.../ansible

The error appears to have been in '/home/.../roles/docker-node/meta/main.yml': line 5, column 5, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  - role: angstwad.docker_ubuntu
    ^ here
</code>```

From the error message I conclude that external role angstwad.docker_ubuntu hasn't be imported, even if it has been explicitly mentioned in docker-node/meta/main.yml.

Can I specify external dependencies from Ansible Galaxy even if my role itself has not been uploaded to Ansible Galaxy?

Or do I need to explicitly import them using ansible-galaxy?

From Ansible documentation:

Roles can also be dependent on other roles, and when you install a
  role that has dependencies, those dependenices will automatically be
  installed.

You specify role dependencies in the meta/main.yml file by providing a
  list of roles. If the source of a role is Galaxy, you can simply
  specify the role in the format username.role_name. The more complex
  format used in requirements.yml is also supported, allowing you to
  provide src, scm, version and name.

By following suggestions from another SO question (How to automatically install Ansible Galaxy roles?) it sounds like downloading external dependencies needs to be done explicitly either manually or with workaround.

答:
As per documentation you linked, you see:

When dependencies are encountered by ansible-galaxy, it will automatically install each dependency to the roles_path.

Downloading of dependencies is handled by ansible-galaxy only, the src meta information doesn't affect ansible-playbook, which just looks inside your role directory and if it don't see a corresponding folder - it fails. As in answer in question you linked, you can indeed create a first task, or include in you playbook to run ansible galaxy before each start.

Body:
I've specified dependency for my role by declaring it inside meta/main.yml.

---
dependencies:
  - role: angstwad.docker_ubuntu
    src: https://github.com/angstwad/docker.ubuntu
    scm: git
    version: v2.3.0

However when I try to execute Ansible playbook I'm seeing error message:

ERROR! the role 'angstwad.docker_ubuntu' was not found in /home/.../ansible/roles:/etc/ansible/roles:/home/.../ansible/roles:/home/.../ansible

The error appears to have been in '/home/.../roles/docker-node/meta/main.yml': line 5, column 5, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  - role: angstwad.docker_ubuntu
    ^ here

From the error message I conclude that external role angstwad.docker_ubuntu hasn't be imported, even if it has been explicitly mentioned in docker-node/meta/main.yml.

Can I specify external dependencies from Ansible Galaxy even if my role itself has not been uploaded to Ansible Galaxy?

Or do I need to explicitly import them using ansible-galaxy?

From Ansible documentation:

Roles can also be dependent on other roles, and when you install a
  role that has dependencies, those dependenices will automatically be
  installed.

You specify role dependencies in the meta/main.yml file by providing a
  list of roles. If the source of a role is Galaxy, you can simply
  specify the role in the format username.role_name. The more complex
  format used in requirements.yml is also supported, allowing you to
  provide src, scm, version and name.

By following suggestions from another SO question (How to automatically install Ansible Galaxy roles?) it sounds like downloading external dependencies needs to be done explicitly either manually or with workaround.


问:
Working with Pandas DataFrame / Sorting
I'm working with a big dataset within Excel in which I'm trying to sort a number by top 25 per index value.

The datasite looks like this:

The Final PAC ID is the company number and changes (this does not show in the given data). The PAC contribution is the number I want to sort by.

So for example, there will be 50 contributions done by company C00003590, to different candidates with amount 'PAC contribution', I would like to sort the top 25 contributions done per company.

I've tried working with dictionaries, creating a dictionary for each company and adding in the candidate numbers as a string key, and the contribution as a value.

The code I have so far is the following (this might be the completely wrong way to go about it though):

```<code>import pandas as pd

df1 = pd.read_excel('Test2.xlsx')

dict_company = {}
k1 = str(df1['Final PAC ID'])
k2 = str(df1['Candidate ID'])

for each in range(0,100):
    dict_company[k1)[each]] = {}
    dict_company[k1)[each]] = k2[each]
    if each % 50 == 0:
        print(each)

print(dict_company)

for each in range(0,100):
    dict_company[k1][k2][each] = round(float(k1[each]))
    if each % 50:
        print(each)

print(dict_company)
</code>```

答:
I think you need nlargest:

```<code>df1 = df.groupby('Final PAC ID')['PAC contribution'].nlargest(50)
</code>```

If need all columns:

```<code>cols = df.columns[~df.columns.isin(['PAC contribution','Final PAC ID'])].tolist()
df1 = df.set_index(cols)
         .groupby('Final PAC ID')['PAC contribution']
         .nlargest(50)
         .reset_index()
</code>```

Another solution (can be slowier):

```<code>df1 = df.sort_values('PAC contribution', ascending=False).groupby('Final PAC ID').head(50)
</code>```

Last save to excel by to_excel:

```<code>df1.to_excel('filename.xlsx')
</code>```

Title: Working with Pandas DataFrame / Sorting

Body:
I'm working with a big dataset within Excel in which I'm trying to sort a number by top 25 per index value.

The datasite looks like this:

The Final PAC ID is the company number and changes (this does not show in the given data). The PAC contribution is the number I want to sort by.

So for example, there will be 50 contributions done by company C00003590, to different candidates with amount 'PAC contribution', I would like to sort the top 25 contributions done per company.

I've tried working with dictionaries, creating a dictionary for each company and adding in the candidate numbers as a string key, and the contribution as a value.

The code I have so far is the following (this might be the completely wrong way to go about it though):

import pandas as pd

df1 = pd.read_excel('Test2.xlsx')

dict_company = {}
k1 = str(df1['Final PAC ID'])
k2 = str(df1['Candidate ID'])

for each in range(0,100):
    dict_company[k1)[each]] = {}
    dict_company[k1)[each]] = k2[each]
    if each % 50 == 0:
        print(each)

print(dict_company)

for each in range(0,100):
    dict_company[k1][k2][each] = round(float(k1[each]))
    if each % 50:
        print(each)

print(dict_company)

Body:
I think you need nlargest:

df1 = df.groupby('Final PAC ID')['PAC contribution'].nlargest(50)

If need all columns:

cols = df.columns[~df.columns.isin(['PAC contribution','Final PAC ID'])].tolist()
df1 = df.set_index(cols)
         .groupby('Final PAC ID')['PAC contribution']
         .nlargest(50)
         .reset_index()

Another solution (can be slowier):

df1 = df.sort_values('PAC contribution', ascending=False).groupby('Final PAC ID').head(50)

Last save to excel by to_excel:

df1.to_excel('filename.xlsx')


问:
accessing file from jmeter beanshell sample using filepath
I'm trying to access one file from beanshell sampler. However it shows me error as below :

Encounter "(C:"at line 9, column 2)

file path name is C:/Test/test.txt.
It seems i can't use C:/ drive in beanshell sampler? please let me know how can I resolve this

答:
Most likely you have a syntax error in your Beanshell script, try using the below reference code which is reading the file and prints its contents into jmeter.log

```<code>String test = org.apache.commons.io.FileUtils.readFileToString(new File("C:/Test/test.txt"));
log.info("test.txt file content is: " + test);
</code>```

Demo:

See How to Use BeanShell: JMeter's Favorite Built-in Component article to learn more about Beanshell scripting in JMeter.

NB: it may be faster and easier to use __FileToString function like:

```<code>${__FileToString(c:\test\test.txt,,)}
</code>```

Body:
Most likely you have a syntax error in your Beanshell script, try using the below reference code which is reading the file and prints its contents into jmeter.log

String test = org.apache.commons.io.FileUtils.readFileToString(new File("C:/Test/test.txt"));
log.info("test.txt file content is: " + test);

Demo:

See How to Use BeanShell: JMeter's Favorite Built-in Component article to learn more about Beanshell scripting in JMeter.

NB: it may be faster and easier to use __FileToString function like:

${__FileToString(c:\test\test.txt,,)}


问:
Conditional template logic Vuejs
```<code>    <template>
    <div>
     <div v-if="context=='home'"  v-for="item in filteredItems"  @mouseover="activate" @mouseout="deactivate" @click="openlink" class="item" :data-link="item.link" v-bind:class="item.class">

     <div v-else  v-for="item in filteredItems"  @mouseover="activate" @mouseout="deactivate" @click="openlink" :data-link="item.link">
</code>```

I have a vuejs component, in the template I want to swap out the v-bind:class="item.class" and only add it if the context is home.

```<code>  <work context="home"></work>
</code>```

The context is passed in via a prop.

Any idea how I can achieve this?

Thanks,

答:
```<code>:class="{'class_name': 'your_condition'}"
</code>```

So in your case

```<code>:class="{'class_name': context === 'home'}"
</code>```

and make sure the value of context is in lowercase to make it work. or use toLowerCase() function on the context variable.

```<code>:class="{'class_name': context.toLowerCase() === 'home'}"
</code>```

[UPDATED]
 You can create a method like below to get this working. I created a jsBin with following method. check it out here  substitute class name

```<code>getClass: function() {
  return this.context === 'home' ? this.item.class : '';
}
</code>```

Title: Conditional template logic Vuejs

Body:
    <template>

I have a vuejs component, in the template I want to swap out the v-bind:class="item.class" and only add it if the context is home.

  <work context="home"></work>

The context is passed in via a prop.

Any idea how I can achieve this?

Thanks,

Body:
:class="{'class_name': 'your_condition'}"

So in your case

:class="{'class_name': context === 'home'}"

and make sure the value of context is in lowercase to make it work. or use toLowerCase() function on the context variable.

:class="{'class_name': context.toLowerCase() === 'home'}"

[UPDATED]
 You can create a method like below to get this working. I created a jsBin with following method. check it out here  substitute class name

getClass: function() {
  return this.context === 'home' ? this.item.class : '';
}


问:
Dockerfile for on and off proxy
I run docker-compose up -d to build and run two containers

```<code>-- docker-compose.yml

node:
  build: .
  links:
    - mongo
  ports:
    - "80:80"
    - "443:443"
    - "8080"
    - "9000:9000"
mongo:
  image: mongo:3.2
  ports:
    - "27017"
</code>```

In my Dockerfile I set http_proxy and https_proxy ENV vars

```<code>-- Dockerfile
ENV http_proxy http://proxy-address.co.uk:80/
ENV https_proxy http://proxy-address.co.uk:80/
</code>```

I need to be able to run this though on and off a proxy so ideally it would be great if I could just pass the VARS on the command line if I need to set them.

Is there a way to do this?

答:
In case it helps anybody else this is what i ended up doing to resolve this. So docker-compose can read ENV vars from the host machine.

```<code>--Added the following to my Dockerfile
ARG http_proxy
ARG https_proxy
</code>```

and my docker-compose.yml

```<code>version: "2.0"
services:
  node:
    build:
      context: .
  args:
    http_proxy: ${http_proxy}
    https_proxy: ${http_proxy}
  links:
    - mongo
  ports:
    - "80:80"
    - "443:443"
    - "8080"
    - "9000:9000"
  mongo:
    image: mongo:3.2
  ports:
    - "27017"
</code>```

Title: Dockerfile for on and off proxy

Body:
I run docker-compose up -d to build and run two containers

-- docker-compose.yml

node:
  build: .
  links:
    - mongo
  ports:
    - "80:80"
    - "443:443"
    - "8080"
    - "9000:9000"
mongo:
  image: mongo:3.2
  ports:
    - "27017"

In my Dockerfile I set http_proxy and https_proxy ENV vars

-- Dockerfile
ENV http_proxy http://proxy-address.co.uk:80/
ENV https_proxy http://proxy-address.co.uk:80/

I need to be able to run this though on and off a proxy so ideally it would be great if I could just pass the VARS on the command line if I need to set them.

Is there a way to do this?

Body:
In case it helps anybody else this is what i ended up doing to resolve this. So docker-compose can read ENV vars from the host machine.

--Added the following to my Dockerfile
ARG http_proxy
ARG https_proxy

and my docker-compose.yml

version: "2.0"
services:
  node:
    build:
      context: .
  args:
    http_proxy: ${http_proxy}
    https_proxy: ${http_proxy}
  links:
    - mongo
  ports:
    - "80:80"
    - "443:443"
    - "8080"
    - "9000:9000"
  mongo:
    image: mongo:3.2
  ports:
    - "27017"


问:
Running local node verison different than global with gulp and node-sass
I have a project that is using node npm and gulp. When we build the project node 5 is installed in the local directory and runs npm install (compiling all node modules agains node v5) I globally have node version 7 installed.

We have a gulp task that uses node-sass which is compiled against v5 but when I try to run the task it uses the global version and node-sass errors out out "Missing binding"

How can I run it using the local version of node?

答:
To expand upon @dmfay's answer, you should have node 5 installed (via nvm or tj's n).

However you can include in your package.json for the project such that it relies on node 5. (Under the "engine" property)


问:
Google Analytics Management API 500 Internal Server Error
I have an application which gets Google Analytics metadata and statistics for a couple dozens google users from Management and Reporting API.

Everything was ok for a long period (several month), but yesterday around 21:00 pm UTC one of them (user) started getting this error: 500, Backend Error or sometimes InternalError

His Management API requests:

get all Accounts response is 200 with with 360 items

get all WebProperties response is 200 with 170 items

get all Profiles response is 200 with 1000 items

get all Goals response is 500 with error [should be 1000 items, but error now]

And still getting this error for now (More than 24 hours).

By the way, Reporting API for this client works fine too (for one of his view/profile)

What i researched:

I've tried to request goals not for all, but for one specific account > specific property > specific profile, and api response is 200 OK! in this case!

Earlier request goals for all profiles worked fine, for a long period! But not today.

答: The problem was resolved by google team on their side! Thank you!</p>


问:
Roman Numeral C++ Programming Conversion Issue
I am currently developing some code that is used to convert an inputted integer to  ROMAN numerals. It is working how it should be except for the cases where I am using the character I, it isn't adding them up correctly. I have done the same syntax as the other characters which work so I am baffled as to why it doesn't work for the "I" character. Here is a snippet of what I have:

```<code>else if(roman_Numeral == 'V')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 2) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 5;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 5;
            continue;
        }
    }

    else if(roman_Numeral == 'I')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral), 2 != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral -1;
            break;
        }
        else
        {
            arabic_Numeral += 1 ;
            continue;
        }
    }
    else
        break;
}
cout << arabic_Numeral << endl;
return 0;
</code>```

The other characters, such as M, C, D etc are similar in layout, however with I obviously the desired output for something such as VI is 6 and it outputs 4. Any help would be appreciated.

The complete code is:

```<code>    #include <string>
#include <iostream>
using namespace std;

std::string numerals = "IVXLCDM";

int main()
{
char roman_Numeral;
int arabic_Numeral = 0;

cout << "Enter the Roman Numeral in Capital letters (e.g. CCXIX) : ";
while(cin.get(roman_Numeral))
{
    if(roman_Numeral == 'M')
        arabic_Numeral = arabic_Numeral + 1000;

    else if(roman_Numeral == 'D')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 5) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 500;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 500;
            continue;
        }
    }

    else if(roman_Numeral == 'C')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 4) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 100;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 100;
            continue;
        }
    }

    else if(roman_Numeral == 'L')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 3) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 50;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 50;
            continue;
        }
    }

    else if(roman_Numeral == 'X')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 2) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 10;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 10;
            continue;
        }
    }

    else if(roman_Numeral == 'V')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 2) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 5;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 5;
            continue;
        }
    }

    else if(roman_Numeral == 'I')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral), 2 != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral -1;
            break;
        }
        else
        {
            arabic_Numeral += 1 ;
            continue;
        }
    }
    else
        break;
}
cout << arabic_Numeral << endl;
return 0;
}
</code>```

I initially found the code online and will be making additional changes later on. Currently the most of the test combinations of my code works. It's just implementing the I's so I can get test for singular cases of I such as III = 3, etc. III currently outputs -1 which is obviosuly not correct. I believe the issue is soemthing to do with the way it adds them together but not entirely sure. I am fairly new to coding after all.

Kind regards.

答: Your observation is correct. The code indeed has a bug for the 'I' section. Just read the code carefully and try to compare it with other working sections. Hint: missing parenthesis ;)

Body:
I am currently developing some code that is used to convert an inputted integer to  ROMAN numerals. It is working how it should be except for the cases where I am using the character I, it isn't adding them up correctly. I have done the same syntax as the other characters which work so I am baffled as to why it doesn't work for the "I" character. Here is a snippet of what I have:

else if(roman_Numeral == 'V')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 2) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 5;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 5;
            continue;
        }
    }

    else if(roman_Numeral == 'I')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral), 2 != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral -1;
            break;
        }
        else
        {
            arabic_Numeral += 1 ;
            continue;
        }
    }
    else
        break;
}
cout << arabic_Numeral << endl;
return 0;

The other characters, such as M, C, D etc are similar in layout, however with I obviously the desired output for something such as VI is 6 and it outputs 4. Any help would be appreciated.

The complete code is:

    #include <string>
#include <iostream>
using namespace std;

std::string numerals = "IVXLCDM";

int main()
{
char roman_Numeral;
int arabic_Numeral = 0;

cout << "Enter the Roman Numeral in Capital letters (e.g. CCXIX) : ";
while(cin.get(roman_Numeral))
{
    if(roman_Numeral == 'M')
        arabic_Numeral = arabic_Numeral + 1000;

    else if(roman_Numeral == 'D')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 5) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 500;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 500;
            continue;
        }
    }

    else if(roman_Numeral == 'C')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 4) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 100;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 100;
            continue;
        }
    }

    else if(roman_Numeral == 'L')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 3) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 50;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 50;
            continue;
        }
    }

    else if(roman_Numeral == 'X')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 2) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 10;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 10;
            continue;
        }
    }

    else if(roman_Numeral == 'V')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral, 2) != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral - 5;
            continue;
        }
        else
        {
            arabic_Numeral = arabic_Numeral + 5;
            continue;
        }
    }

    else if(roman_Numeral == 'I')
    {
        roman_Numeral = cin.peek();
        if(numerals.find(roman_Numeral), 2 != std::string::npos)
        {
            arabic_Numeral = arabic_Numeral -1;
            break;
        }
        else
        {
            arabic_Numeral += 1 ;
            continue;
        }
    }
    else
        break;
}
cout << arabic_Numeral << endl;
return 0;
}

I initially found the code online and will be making additional changes later on. Currently the most of the test combinations of my code works. It's just implementing the I's so I can get test for singular cases of I such as III = 3, etc. III currently outputs -1 which is obviosuly not correct. I believe the issue is soemthing to do with the way it adds them together but not entirely sure. I am fairly new to coding after all.

Kind regards.


问:
calculate method execution time in Visual Studio Express (No profiler available)?
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

```<code>        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);
</code>```

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?

答:
You might consider using the Scenario class which supports simple begin/end usage, with optional logging via ETW.

From their Wiki:

You can use the Scenario class to add performance instrumentation to an application (either .NET or native C++). The shortest description of a Scenario is "a named stopwatch that can log when you start and stop it".

Body:
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?


问:
How to create a base Ext.app.ViewController common to other view controllers?
I want to create an base ViewController for all other controllers used in an ExtJS app.

The problem is that ExtJs is looking for the base class in /classic/src/view instead of /app/view....

Here is an example:
in /app/view/base/BaseController.js

```<code>Ext.define('myApp.view.base.BaseController', {
    extend: 'Ext.app.ViewController',

    doStuff: function(msg) {
        alert(msg);
    }
});
</code>```

in /app/view/another/AnotherController.js

```<code>Ext.define('myApp.view.another.AnotherController', {
    extend: 'myApp.view.base.BaseController',

    onButtonClick: function() {
        doStuff('Button clicked');
    }
});
</code>```

in /app/classic/src/view/another/Another.js

```<code>Ext.define('myApp.view.another.Another', {
    extend: 'Ext.panel.Panel',
    xtype: 'another',
    alias: 'view.another',
    id: 'panel_another',

    controller: 'another',
    items: [{
        xtype: 'button',
        text: 'The Button',
        handler: onButtonClick
    }]
});
</code>```

However when i run the app, ExtJs throws an error saying that /classic/src/view/base/BaseController.js was not found!

What am i doing wrong here?

Thank you for your time, and for your help!

答: You just try building your app by sencha app build.It will solve this issue.

Body:
I want to create an base ViewController for all other controllers used in an ExtJS app.

The problem is that ExtJs is looking for the base class in /classic/src/view instead of /app/view....

Here is an example:
in /app/view/base/BaseController.js

Ext.define('myApp.view.base.BaseController', {
    extend: 'Ext.app.ViewController',

    doStuff: function(msg) {
        alert(msg);
    }
});

in /app/view/another/AnotherController.js

Ext.define('myApp.view.another.AnotherController', {
    extend: 'myApp.view.base.BaseController',

    onButtonClick: function() {
        doStuff('Button clicked');
    }
});

in /app/classic/src/view/another/Another.js

Ext.define('myApp.view.another.Another', {
    extend: 'Ext.panel.Panel',
    xtype: 'another',
    alias: 'view.another',
    id: 'panel_another',

    controller: 'another',
    items: [{
        xtype: 'button',
        text: 'The Button',
        handler: onButtonClick
    }]
});

However when i run the app, ExtJs throws an error saying that /classic/src/view/base/BaseController.js was not found!

What am i doing wrong here?

Thank you for your time, and for your help!


问:
Looping Java switch statement
My system is a banking system and I want my program to loop after the user has interacted with one of the processes (withdraw, view balance etc).

After user get result I want to give a chance to continue with another process:

```<code>package smartcode.atm.h.w;

import java.util.Scanner;

public class SmartCodeATMHW {

    public static void main(String[] args) {
        int p;
        int y = 1234;
        int Amount = 500;
        int result;
        int info;
        int f;
        int g;

        Scanner in = new Scanner(System.in);

        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter PIN Number ");
            p = in.nextInt();

            if (p == y) {
                System.out.println("You have entered correct PIN number \n\n*****************");

                profile pr = new profile();
                pr.setName("Prapashtica");
                System.out.println("Welcome mr." + pr.getName());

                //loop from here
                boolean end = false;
                do{
                    System.out.println("\nPress 1 to View Bank Account");
                    System.out.println("Press 2 to Deposit money");
                    System.out.println("Press 3 to Withdraw money");
                    System.out.println("Press 4 to Cancle the Process \n\n********************");
                    info = in.nextInt();

                    switch (info) {
                        case 1:
                            System.out.println("You have  " + Amount + "$ available");
                            return;

                        case 2:
                            System.out.println("You have  " + Amount + "$ available");
                            System.out.println("Please enter the amount you wish to deposit");
                            f = in.nextInt();

                            result = Amount + f;
                            System.out.println("You have  " + result + "$ available");
                            break;
                        case 3:
                            for (int l = 0; l < 3; l++) {
                                System.out.println("You have  " + Amount + "  $ available");
                                System.out.println("Please eter the amount you wish to withdraw");
                                g = in.nextInt();
                                if (g > 500) {
                                    System.out.println("You cannot withdraw more than your current amount");
                                } else {
                                    System.out.println("You have succesfully withdrawed  " + g + " $");
                                    result = Amount - g;

                                    System.out.println("You now have  " + result + "  $ available");
                                }
                            }
                            System.out.println("Your card is now blocked");
                            break;
                        case 4:
                            System.out.println("You have canceled the proccess");
                            break;
                        default:
                            System.out.println("Error \nInvalid number");
                            break;

                    }
                    return;
                }while (end == false);
            } else {
                System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
            }
        }
        System.out.println("Your card is now blocked");
    }
}
</code>```

答:
I can see from the code you have already handled the requirement using end==false.

You need to remove the return; statement used after the switch case.

Also, for case 1 use break; instead of return;

```<code>public static void main(String[] args) {
    int p;
    int y = 1234;
    int Amount = 500;
    int result;
    int info;
    int f;
    int g;

    Scanner in = new Scanner(System.in);

    for (int i = 0; i < 3; i++) {
        System.out.println("Please enter PIN Number ");
        p = in.nextInt();

        if (p == y) {
            System.out.println("You have entered correct PIN number \n\n*****************");

            profile pr = new profile();
            pr.setName("Prapashtica");
            System.out.println("Welcome mr." + pr.getName());

            //loop from here
            boolean end = false;
            do{
                System.out.println("\nPress 1 to View Bank Account");
                System.out.println("Press 2 to Deposit money");
                System.out.println("Press 3 to Withdraw money");
                System.out.println("Press 4 to Cancle the Process \n\n********************");
                info = in.nextInt();

                switch (info) {
                    case 1:
                        System.out.println("You have  " + Amount + "$ available");
                        break;

                    case 2:
                        System.out.println("You have  " + Amount + "$ available");
                        System.out.println("Please enter the amount you wish to deposit");
                        f = in.nextInt();

                        result = Amount + f;
                        System.out.println("You have  " + result + "$ available");
                        break;
                    case 3:
                        for (int l = 0; l < 3; l++) {
                            System.out.println("You have  " + Amount + "  $ available");
                            System.out.println("Please eter the amount you wish to withdraw");
                            g = in.nextInt();
                            if (g > 500) {
                                System.out.println("You cannot withdraw more than your current amount");
                            } else {
                                System.out.println("You have succesfully withdrawed  " + g + " $");
                                result = Amount - g;

                                System.out.println("You now have  " + result + "  $ available");
                            }
                        }
                        System.out.println("Your card is now blocked");
                        break;
                    case 4:
                        System.out.println("You have canceled the proccess");
                        break;
                    default:
                        System.out.println("Error \nInvalid number");
                        break;

                }

            }while (end == false);
        } else {
            System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
        }
    }
    System.out.println("Your card is now blocked");
}
</code>```

You can also take input from the User whether he wants to continue or not and depending on the response, display the options again.

Title: Looping Java switch statement

Body:
My system is a banking system and I want my program to loop after the user has interacted with one of the processes (withdraw, view balance etc).

After user get result I want to give a chance to continue with another process:

package smartcode.atm.h.w;

import java.util.Scanner;

public class SmartCodeATMHW {

    public static void main(String[] args) {
        int p;
        int y = 1234;
        int Amount = 500;
        int result;
        int info;
        int f;
        int g;

        Scanner in = new Scanner(System.in);

        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter PIN Number ");
            p = in.nextInt();

            if (p == y) {
                System.out.println("You have entered correct PIN number \n\n*****************");

                profile pr = new profile();
                pr.setName("Prapashtica");
                System.out.println("Welcome mr." + pr.getName());

                //loop from here
                boolean end = false;
                do{
                    System.out.println("\nPress 1 to View Bank Account");
                    System.out.println("Press 2 to Deposit money");
                    System.out.println("Press 3 to Withdraw money");
                    System.out.println("Press 4 to Cancle the Process \n\n********************");
                    info = in.nextInt();

                    switch (info) {
                        case 1:
                            System.out.println("You have  " + Amount + "$ available");
                            return;

                        case 2:
                            System.out.println("You have  " + Amount + "$ available");
                            System.out.println("Please enter the amount you wish to deposit");
                            f = in.nextInt();

                            result = Amount + f;
                            System.out.println("You have  " + result + "$ available");
                            break;
                        case 3:
                            for (int l = 0; l < 3; l++) {
                                System.out.println("You have  " + Amount + "  $ available");
                                System.out.println("Please eter the amount you wish to withdraw");
                                g = in.nextInt();
                                if (g > 500) {
                                    System.out.println("You cannot withdraw more than your current amount");
                                } else {
                                    System.out.println("You have succesfully withdrawed  " + g + " $");
                                    result = Amount - g;

                                    System.out.println("You now have  " + result + "  $ available");
                                }
                            }
                            System.out.println("Your card is now blocked");
                            break;
                        case 4:
                            System.out.println("You have canceled the proccess");
                            break;
                        default:
                            System.out.println("Error \nInvalid number");
                            break;

                    }
                    return;
                }while (end == false);
            } else {
                System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
            }
        }
        System.out.println("Your card is now blocked");
    }
}

Body:
I can see from the code you have already handled the requirement using end==false.

You need to remove the return; statement used after the switch case.

Also, for case 1 use break; instead of return;

public static void main(String[] args) {
    int p;
    int y = 1234;
    int Amount = 500;
    int result;
    int info;
    int f;
    int g;

    Scanner in = new Scanner(System.in);

    for (int i = 0; i < 3; i++) {
        System.out.println("Please enter PIN Number ");
        p = in.nextInt();

        if (p == y) {
            System.out.println("You have entered correct PIN number \n\n*****************");

            profile pr = new profile();
            pr.setName("Prapashtica");
            System.out.println("Welcome mr." + pr.getName());

            //loop from here
            boolean end = false;
            do{
                System.out.println("\nPress 1 to View Bank Account");
                System.out.println("Press 2 to Deposit money");
                System.out.println("Press 3 to Withdraw money");
                System.out.println("Press 4 to Cancle the Process \n\n********************");
                info = in.nextInt();

                switch (info) {
                    case 1:
                        System.out.println("You have  " + Amount + "$ available");
                        break;

                    case 2:
                        System.out.println("You have  " + Amount + "$ available");
                        System.out.println("Please enter the amount you wish to deposit");
                        f = in.nextInt();

                        result = Amount + f;
                        System.out.println("You have  " + result + "$ available");
                        break;
                    case 3:
                        for (int l = 0; l < 3; l++) {
                            System.out.println("You have  " + Amount + "  $ available");
                            System.out.println("Please eter the amount you wish to withdraw");
                            g = in.nextInt();
                            if (g > 500) {
                                System.out.println("You cannot withdraw more than your current amount");
                            } else {
                                System.out.println("You have succesfully withdrawed  " + g + " $");
                                result = Amount - g;

                                System.out.println("You now have  " + result + "  $ available");
                            }
                        }
                        System.out.println("Your card is now blocked");
                        break;
                    case 4:
                        System.out.println("You have canceled the proccess");
                        break;
                    default:
                        System.out.println("Error \nInvalid number");
                        break;

                }

            }while (end == false);
        } else {
            System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
        }
    }
    System.out.println("Your card is now blocked");
}

You can also take input from the User whether he wants to continue or not and depending on the response, display the options again.


问:
How to execute promises sequentially, passing the parameters from an array?
```<code>var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))
</code>```

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

答:
You can iterate over the array of elements and pass the params like this:

const arr = [1, 2, 3, 4, 5, 6]
const MyPromiseFunction = num => new Promise(
  (resolve, reject) =>
    // Your logic...
    setTimeout(() => num <= 4
      ? resolve('Success!')
      : reject('Rejected!'), 1000 * num)
)
const logMessage = (num, msg) =>
  console.log(`For number ${num} promise result: ${msg}`)

arr.map(
  async (num) => await MyPromiseFunction(num)
    .then(message => logMessage(num, message))
    .catch(reason => logMessage(num, reason))
)```

ContentLicense: CC BY-SA 4.0

Body:
var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?


问:
Android InApp Billing : How to detect back press interrupting the purchase process?
I'm trying to implement the inApp billing service with IabHelper. I manage to go through the full purchase process without problems.

```<code>//-----------------------------------------------
public void billingServiceLaunchPurchase(String item) {
//-----------------------------------------------
    if (isNetworkAvailableSync(getBaseContext())) {
        currBuyItem=item;
        billingConsummeType=1;
        mHelper.launchPurchaseFlow(BaseActivity.this, item, 10001, mPurchaseFinishedListener, "");
    }
    else {
        onBillingServiceFailed();
    }
}

    //-----------------------------------------------
    mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    //-----------------------------------------------
        public void onIabPurchaseFinished(IabResult result, Purchase purchase)
        {
           if (result.isFailure()) {
              // Handle error
              onBillingServiceFailed();
              return;
         }
         else if (purchase.getSku().equals(currBuyItem)) {
             billingServiceConsumeItem();
         }

        }
    };

@Override
//-----------------------------------------------------------------------
protected void onActivityResult(int requestCode, int resultCode, Intent data)
//-----------------------------------------------------------------------
{
    if (billingServiceConnected) {
          if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
              super.onActivityResult(requestCode, resultCode, data);
          }
          else {
              // onActivityResult handled by IABUtil.
          }
    }
    else
           super.onActivityResult(requestCode, resultCode, data);

}
</code>```

However, I cannot detect the event when the user launches the purchase but then press the backspace on the Google confirmation screen with the button "BUY" to interrupt it.

It neither triggers a failure on onIabPurchaseFinished nor it triggers onActivityResult so my application stays in an intermediary status.

Please help me to solve my problem.

答:
You can access the result code through IabResult class, and compare it with the different result codes in IabHelper class, and use it in your OnIabPurchaseFinishedListener:</p>

```<code>    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
        = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase)
    {

        if (result.isFailure()) {

            if (result.getResponse() == IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED  || result.getResponse() == IabHelper.IABHELPER_USER_CANCELLED){

                // user cancelled purchase

            } else {

            // any oder reasult

            }
            return;
        }

        else if (purchase.getSku().equals(SKU_SPIRIT_LEVEL)) {

            // no error, purchase succeeded

        }
    }
};
</code>```

Body:
I'm trying to implement the inApp billing service with IabHelper. I manage to go through the full purchase process without problems.

//-----------------------------------------------
public void billingServiceLaunchPurchase(String item) {
//-----------------------------------------------
    if (isNetworkAvailableSync(getBaseContext())) {
        currBuyItem=item;
        billingConsummeType=1;
        mHelper.launchPurchaseFlow(BaseActivity.this, item, 10001, mPurchaseFinishedListener, "");
    }
    else {
        onBillingServiceFailed();
    }
}

    //-----------------------------------------------
    mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    //-----------------------------------------------
        public void onIabPurchaseFinished(IabResult result, Purchase purchase)
        {
           if (result.isFailure()) {
              // Handle error
              onBillingServiceFailed();
              return;
         }
         else if (purchase.getSku().equals(currBuyItem)) {
             billingServiceConsumeItem();
         }

        }
    };

@Override
//-----------------------------------------------------------------------
protected void onActivityResult(int requestCode, int resultCode, Intent data)
//-----------------------------------------------------------------------
{
    if (billingServiceConnected) {
          if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
              super.onActivityResult(requestCode, resultCode, data);
          }
          else {
              // onActivityResult handled by IABUtil.
          }
    }
    else
           super.onActivityResult(requestCode, resultCode, data);

}

However, I cannot detect the event when the user launches the purchase but then press the backspace on the Google confirmation screen with the button "BUY" to interrupt it.

It neither triggers a failure on onIabPurchaseFinished nor it triggers onActivityResult so my application stays in an intermediary status.

Please help me to solve my problem.

Body:
You can access the result code through IabResult class, and compare it with the different result codes in IabHelper class, and use it in your OnIabPurchaseFinishedListener:

    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
        = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase)
    {

        if (result.isFailure()) {

            if (result.getResponse() == IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED  || result.getResponse() == IabHelper.IABHELPER_USER_CANCELLED){

                // user cancelled purchase

            } else {

            // any oder reasult

            }
            return;
        }

        else if (purchase.getSku().equals(SKU_SPIRIT_LEVEL)) {

            // no error, purchase succeeded

        }
    }
};


问:
Creating a folder or file in External microSD card
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

```<code>Environment.getExternalStorageDirectory()
</code>```

is not The SD Card Path.

here is my java code :

```<code>package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

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

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}
</code>```

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

```<code>boolean result = folder.mkdirs();
</code>```

is not true. so no folder opens , i also tried :

```<code>boolean result = folder.mkdir();
</code>```

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

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

    package="com.example.thermie.test2">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>
</code>```

Hope it is detail enough.
Thanks you all.

答:
I think the Path that i get from Environment.getExternalStorageDirectory() is not The SD Card Path

Correct.

Use the getExternalFilesDirs() method on Context. If that returns 2+ File objects, the second and subsequent ones will be locations on removable storage that you can read and write, without any permissions.

Body:
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

Environment.getExternalStorageDirectory()

is not The SD Card Path.

here is my java code :

package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

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

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

boolean result = folder.mkdirs();

is not true. so no folder opens , i also tried :

boolean result = folder.mkdir();

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

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

    package="com.example.thermie.test2">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>

Hope it is detail enough.
Thanks you all.


问:
What is new() function here?
I've been learning design patterns and I saw such a method call from a class :

```<code>class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}
</code>```

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.

答:
AFAIK it's wrong, and that code won't even compile.

The new keyword in C# can have only the 3 meanings described in this link:

http://msdn.microsoft.com/en-us/library/51y09td4%28v=VS.80%29.aspx

Title: What is new() function here?

Body:
I've been learning design patterns and I saw such a method call from a class :

class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.


问:
how to delete row for a given date index value
I tried below but was not able to delete the row against the given date...

I tried the below syntax (line 2 below) but it still does not delete the row for index value = '2016-01-25"

```<code>norm_data = normalize_data(data, '^NSEI')
norm_data.drop(pd.to_datetime('2016-01-25'))
print norm_data.head(50)

              ^NSEI_price    ^NSEI_vol
Date

2016-01-20     0.938136     1.674833
2016-01-21     0.933965     1.786934
2016-01-22     0.952659     1.701559
2016-01-25     0.954417  1211.261321
2016-01-27     0.954622     1.392725
</code>```

答:
This:

```<code>norm_data.drop(pd.to_datetime('2016-01-25'))
</code>```

Returns a copy of norm_data. It does not alter the norm_data df. To change it, you can use:

```<code># Setting inplace flag to True
norm_data.drop(pd.to_datetime('2016-01-25'), inplace=True)
</code>```

Or the less efficient, but easier to remember:

```<code># Re-assign df to copy of df
norm_data = norm_data.drop(pd.to_datetime('2016-01-25'))
</code>```

Body:
I tried below but was not able to delete the row against the given date...

I tried the below syntax (line 2 below) but it still does not delete the row for index value = '2016-01-25"

norm_data = normalize_data(data, '^NSEI')
norm_data.drop(pd.to_datetime('2016-01-25'))
print norm_data.head(50)

              ^NSEI_price    ^NSEI_vol
Date

2016-01-20     0.938136     1.674833
2016-01-21     0.933965     1.786934
2016-01-22     0.952659     1.701559
2016-01-25     0.954417  1211.261321
2016-01-27     0.954622     1.392725

Body:
This:

norm_data.drop(pd.to_datetime('2016-01-25'))

Returns a copy of norm_data. It does not alter the norm_data df. To change it, you can use:

# Setting inplace flag to True
norm_data.drop(pd.to_datetime('2016-01-25'), inplace=True)

Or the less efficient, but easier to remember:

# Re-assign df to copy of df
norm_data = norm_data.drop(pd.to_datetime('2016-01-25'))


问:
how can I increase the int through a method?
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

```<code>int health;
int mana;
</code>```

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

```<code>public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}
</code>```

Please give me some insight!

答:
Java method calls use "call by value" argument passing.

Let's neglect non-primitive types where a reference is passed (also by value).
Let's only look at primitive types:

```<code>class Example{
    int field1 = 0;

    void method1( int arg1 )
    {
         arg1 = 5;
    }

    void method2()
    {
         field1 = 5;
    }

    void driver()
    {
         method1(field1); // <= (a copy of) the _value_ of field1 will be
                          // passed to method1. The value of field1 will
                          // stay the same, no matter what happens inside method1.
         // field1 == 0
         method2(); // uses the class's field => change will be visible
         // field1 == 5
    }
}
</code>```

If you use the same name like void method1( int field1 ) it only hides the class field inside the method. Changes will still be locally visible, only.

Body:
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

int health;
int mana;

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}

Please give me some insight!

Body:
Java method calls use "call by value" argument passing.

Let's neglect non-primitive types where a reference is passed (also by value).
Let's only look at primitive types:

class Example{
    int field1 = 0;

    void method1( int arg1 )
    {
         arg1 = 5;
    }

    void method2()
    {
         field1 = 5;
    }

    void driver()
    {
         method1(field1); // <= (a copy of) the _value_ of field1 will be
                          // passed to method1. The value of field1 will
                          // stay the same, no matter what happens inside method1.
         // field1 == 0
         method2(); // uses the class's field => change will be visible
         // field1 == 5
    }
}

If you use the same name like void method1( int field1 ) it only hides the class field inside the method. Changes will still be locally visible, only.


问:
Splitting Large XML FIles Java (StAX)
I am using this code https://github.com/koen-serneels/blog/tree/master/BigXmlTest/src/main/java/be/error/bigxmltest from GitHub to split large XML files(6GB).I am starting with the basic XML File provided to understand the program. The program outputs the header for each file that is split. I am Trying to add a Footer Element now also for each file and having some difficulties, any suggestions or advice on how to go about this would be great.

I have added The footer to the schema and written the code to add a footer in the "openOutputFileAndWriteHeader()" method. However This adds the footer within the Content Element. Shown Below:

```<code>private XMLEventWriter openOutputFileAndWriteHeader(int fileNumber) throws Exception
{

    XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLEventWriter writer = xmlOutputFactory.createXMLEventWriter(new FileOutputStream(new File("C:\\Users\\thamm\\Desktop\\SplitFiles\\File_" + fileNumber + ".xml")));

    writer.setDefaultNamespace(DOCUMENT_NS);
    writer.add(xmlEventFactory.createStartDocument());

    writer.add(xmlEventFactory.createStartElement(new QName(DOCUMENT_NS, ROOT_ELEMENT), null, null));

    HeaderType header = objectFactory.createHeaderType();
    header.setSomeHeaderElement("List of Employees");
    marshaller.marshal(new JAXBElement<HeaderType>(new QName(DOCUMENT_NS, HEADER_ELEMENT, ""), HeaderType.class,
                    HeaderType.class, header), writer);

    writer.add(new StartElementEvent(new QName(DOCUMENT_NS, CONTENT_ELEMENT)));

    FooterType footer = objectFactory.createFooterType();
    footer.setSomeFooterElement("Footer");
    marshaller.marshal(new JAXBElement<FooterType>(new QName(DOCUMENT_NS, FOOTER_ELEMENT,""), FooterType.class,
                      FooterType.class, footer), writer);

    return writer;
}
</code>```

Output:

```<code><?xml version='1.0' encoding='UTF-8'?>
<BigXmlTest xmlns="http://www.sidero.ie/bigxmltest">
    <Header>
        <SomeHeaderElement>List of Employees</SomeHeaderElement>
    </Header>
    <Content>
        <Footer>
            <SomeFooterElement>Footer</SomeFooterElement>
        </Footer>
        <Data>Data4</Data>
        <Data>Data5</Data>
        <Data>Data6</Data>
    </Content>
</BigXmlTest>
</code>```

答:
Name of method openOutputFileAndWriteHeader hints that it will create new file. It's not proper place for footer.

In BigXmlTestIteratorApi.java from line 74 you can see code:

```<code>xmlEventWriter.close(); // Also closes any open Element(s) and the document
xmlEventWriter = openOutputFileAndWriteHeader(++fileNumber); // Continue with next file
dataRepetitions = 0;
</code>```

To add footer, you need add something before closing file:

```<code>writeFooter(footer);
xmlEventWriter.close();
xmlEventWriter = openOutputFileAndWriteHeader(++fileNumber);
dataRepetitions = 0;
</code>```

Please note that creating instance of FooterType for each file may be superfluous. It could be created outside loop, for example at 60 line

Title: Splitting Large XML FIles Java (StAX)

Body:
I am using this code https://github.com/koen-serneels/blog/tree/master/BigXmlTest/src/main/java/be/error/bigxmltest from GitHub to split large XML files(6GB).I am starting with the basic XML File provided to understand the program. The program outputs the header for each file that is split. I am Trying to add a Footer Element now also for each file and having some difficulties, any suggestions or advice on how to go about this would be great.

I have added The footer to the schema and written the code to add a footer in the "openOutputFileAndWriteHeader()" method. However This adds the footer within the Content Element. Shown Below:

private XMLEventWriter openOutputFileAndWriteHeader(int fileNumber) throws Exception
{

    XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLEventWriter writer = xmlOutputFactory.createXMLEventWriter(new FileOutputStream(new File("C:\\Users\\thamm\\Desktop\\SplitFiles\\File_" + fileNumber + ".xml")));

    writer.setDefaultNamespace(DOCUMENT_NS);
    writer.add(xmlEventFactory.createStartDocument());

    writer.add(xmlEventFactory.createStartElement(new QName(DOCUMENT_NS, ROOT_ELEMENT), null, null));

    HeaderType header = objectFactory.createHeaderType();
    header.setSomeHeaderElement("List of Employees");
    marshaller.marshal(new JAXBElement<HeaderType>(new QName(DOCUMENT_NS, HEADER_ELEMENT, ""), HeaderType.class,
                    HeaderType.class, header), writer);

    writer.add(new StartElementEvent(new QName(DOCUMENT_NS, CONTENT_ELEMENT)));

    FooterType footer = objectFactory.createFooterType();
    footer.setSomeFooterElement("Footer");
    marshaller.marshal(new JAXBElement<FooterType>(new QName(DOCUMENT_NS, FOOTER_ELEMENT,""), FooterType.class,
                      FooterType.class, footer), writer);

    return writer;
}

Output:

<?xml version='1.0' encoding='UTF-8'?>
<BigXmlTest xmlns="http://www.sidero.ie/bigxmltest">

        <SomeHeaderElement>List of Employees</SomeHeaderElement>

    <Content>

            <SomeFooterElement>Footer</SomeFooterElement>

        <Data>Data4</Data>
        <Data>Data5</Data>
        <Data>Data6</Data>
    </Content>
</BigXmlTest>

Body:
Name of method openOutputFileAndWriteHeader hints that it will create new file. It's not proper place for footer.

In BigXmlTestIteratorApi.java from line 74 you can see code:

xmlEventWriter.close(); // Also closes any open Element(s) and the document
xmlEventWriter = openOutputFileAndWriteHeader(++fileNumber); // Continue with next file
dataRepetitions = 0;

To add footer, you need add something before closing file:

writeFooter(footer);
xmlEventWriter.close();
xmlEventWriter = openOutputFileAndWriteHeader(++fileNumber);
dataRepetitions = 0;

Please note that creating instance of FooterType for each file may be superfluous. It could be created outside loop, for example at 60 line