答:
Here's a short way to do it without comprehensions:

```<code>set().union(*map(doubleIt, q))
</code>```

It calls doubleIt on every element of q and merges the resulting sets into one set with set().union.

If you want a comprehension, use a set comprehension with two for clauses:

```<code>ret = {new_elem for elem in q for new_elem in doubleIt(elem)}
</code>```

This iterates over q, calls doubleIt on each element, and iterates over the sets returned by doubleIt, putting the elements of those sets in the new set. It's equivalent to

```<code>ret = set()
for elem in q:
    for new_elem in doubleIt(elem):
        ret.add(new_elem)
</code>```

Title: Run a function returning a set on a set, and get back a larger set

Body:
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

Body:
Here's a short way to do it without comprehensions:

set().union(*map(doubleIt, q))

It calls doubleIt on every element of q and merges the resulting sets into one set with set().union.

If you want a comprehension, use a set comprehension with two for clauses:

ret = {new_elem for elem in q for new_elem in doubleIt(elem)}

This iterates over q, calls doubleIt on each element, and iterates over the sets returned by doubleIt, putting the elements of those sets in the new set. It's equivalent to

ret = set()
for elem in q:
    for new_elem in doubleIt(elem):
        ret.add(new_elem)


来源: stackexchange

问:
How do I create a query that list the name of students who took fewer than three classes or have a null value for class
I have a "database" with two tables a student,and enroll. The student table has stuid, lastname, firstname. The enroll table has stuid classnumber and grade.

I have to return a list that looks like this

Last Name

Burns
Jones
Lee
McCarthy
Rivera
Smith

First Name

Edward
Mary
Perry
Owen
Jane
Tom

I attempted to do a statement like this

Select lastname, firstname
Where Not exists (Select stuid from enroll e where e.stuid = s.stuid)
Having count(*) < 3
Group By lastname, firstname;

I understand that I need two merge the two tables basically so that I get the results of people who have classes < 3 and people who are also not currently enrolled in a class.

答:
Use LEFT JOIN and HAVING

```<code> SELECT st.stuid, lastname, firstname
 FROM student st
 LEFT JOIN enroll el ON st.stuid = el.stuid
 GROUP BY st.stuid
 HAVING count(el.stuid) < 3
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use LEFT JOIN and HAVING

 SELECT st.stuid, lastname, firstname
 FROM student st
 LEFT JOIN enroll el ON st.stuid = el.stuid
 GROUP BY st.stuid
 HAVING count(el.stuid) < 3


问:
Improving Login-Security through denial of Copy & Paste?
we have a common login form for an webapplication, nothing fancy, something like

...<input type="text" value="Username" /><input type="password" value="" />...

My co-worker argues that denying the user to copy & paste within the login form would improve the application security.
I think otherwise because the password input is already protected by the browser itself (You cannot copy the password from the input element).

However, we added the following JScripts to the input elements:

```<code>... onpaste="return false;" oncopy="return false;" ondrag="return false;" ondrop="return false;" ...
</code>```

A tester criticised that it is still possible to "drag" copy with the CRT key, of course it will only copy the * characters and not the password, but it still allowes to copy values from the form, and so the test case was returned as failed.

So much for the background.

My Question:

Is there any security improvement at all from denying any kind of copy & paste within the login form that is worth the extra effort?

Thanks you
Simon

答: I agree with the consensus here.  I don't see how removing copy-and-paste functionality could improve security, and all JavaScript can be disabled anyway.  It's not worth your time.</p>

ContentLicense: CC BY-SA 2.5

Body:
we have a common login form for an webapplication, nothing fancy, something like

...<input type="text" value="Username" /><input type="password" value="" />...

My co-worker argues that denying the user to copy & paste within the login form would improve the application security.
I think otherwise because the password input is already protected by the browser itself (You cannot copy the password from the input element).

However, we added the following JScripts to the input elements:

... onpaste="return false;" oncopy="return false;" ondrag="return false;" ondrop="return false;" ...

A tester criticised that it is still possible to "drag" copy with the CRT key, of course it will only copy the * characters and not the password, but it still allowes to copy values from the form, and so the test case was returned as failed.

So much for the background.

My Question:

Is there any security improvement at all from denying any kind of copy & paste within the login form that is worth the extra effort?

Thanks you
Simon


问:
'unlink', Permission denied error when executing function [exec]
This is the file test1.php:

```<code> <?php
    set_time_limit(0);
    for($i= 1;$i<5000 ;$i++){

        $comm_sjis = "echo 'test'";
        $result = exec($comm_sjis);

    }
    unset($result);
    echo 'ok';
</code>```

This is file test2.php:

```<code><?php

set_time_limit(0);

function write_txt($str)
{
    $filepath = 'E:/temp/test.xml';
    if (($fp = @fopen($filepath, "a")) === false) {
        return;
    }

    if (!flock($fp, LOCK_EX)) {
        @fclose($fp);
        return;
    }

    if (fwrite($fp, $str . "\n") === false) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!fflush($fp)) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!flock($fp, LOCK_UN)) {
        @fclose($fp);
        return;
    }

    if (!fclose($fp)) {
        return;
    }
}

for($i= 1;$i<100 ;$i++){

    write_txt('test');
    unlink('E:/temp/test.xml');
}
echo 'ok';
</code>```

If I run file test2.php while test1.php is running, an error will occur:

Warning: unlink(E:/temp/test.xml): Permission denied in C:\xampp\htdocs\test2.php on line 45

When I only run test2.php, without test1.php, this error does not occur.
Why does unlink give a Permission denied error when I execute the function?

I'm using XAMPP 3.2 vs php 5.6 with Windows 7.

答:
You're silencing errors in fopen which means that if, at any point, the file fails to open (perhaps because of a memory limit being reached in XAMPP, for example), you'd have no way of knowing in your script (you can view it in your logs).

From the PHP Manual:

bool unlink ( string $filename [, resource $context ] )

Deletes filename. Similar to the Unix C unlink() function. An
  E_WARNING level error will be generated on failure.

unlink deletes a file. That means that if your file fails to open using fopen, and you haven't created it already, it may well not exist. Trying to unlink a file that does not exist will result in an error.

An easy solution would be to silence errors on unlink as well.

```<code>@unlink('E:/temp/test.xml');
</code>```

That way it will fail gracefully if your function fails to write a file. Another option is to check if the file exists before trying to unlink.

```<code>$file = 'E:/temp/test.xml';
if (file_exists($file)) {
    error_log(‘could not write file’);
    unlink($file);
}
</code>```

My favored option in this case might be to use Exceptions. When you fail to open or fail to unlock a file, throw an Exception. You can catch it, log the issue and break the loop before you try to unlink.

That should help you debug what is going on.

Example:
    namespace Test;

```<code>class FileException extends \Exception { }
class UnlockFailedException extends FileException { }

function write_txt($str)
{
    $filepath = 'E:/temp/test.xml';
    if (($fp = @fopen($filepath, "a")) === false) {
        throw new FileException('Could not open file');
    }

    if (!flock($fp, LOCK_EX)) {
        @fclose($fp);
        return;
    }

    if (fwrite($fp, $str . "\n") === false) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!fflush($fp)) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!flock($fp, LOCK_UN)) {
        @fclose($fp);
        throw new UnlockFailedException('Unable to unlock file.');
    }
    /**
     * This doesn't do anything
     * if (!fclose($fp)) {
     *     return;
     * }
     */
    fclose($fp);
}
</code>```

Then:

```<code>$msg = 'ok';
for($i= 1;$i<100 ;$i++){
    try {
        write_txt('test');
        unlink('E:/temp/test.xml');
    } catch (FileException $e) {
        error_log($e->getMessage());
        $msg = 'errors detected';
    }
}
echo $msg;
</code>```

By adding exception handling, you can debug this kind of behavior for yourself and find the root cause of the issue.

A couple final notes:

I run Linux, so it’s not easy for me to test this behavior on a Windows 7 XAMPP machine. However, I suspect it is because the system is locking due to limited I/O resources. Note that, according to the manual, Windows places a madatory lock on the file (whereas in Linux the lock is advisory). Running flock in a massive loop and echo in a massive loop on a limited resources system can lead to resources failing. If you intend to run something like this in production you won’t run into it as often but you will still need to account for it. Exception handling and error logging can ensure that when the file doesn't work you will have enough data to debug.

Assuming unlink is the problem is not a safe assumption at all.

As stated, silencing unlink or checking to see if the file exists will silence this error.

Body:
This is the file test1.php:

 <?php
    set_time_limit(0);
    for($i= 1;$i<5000 ;$i++){

        $comm_sjis = "echo 'test'";
        $result = exec($comm_sjis);

    }
    unset($result);
    echo 'ok';

This is file test2.php:

<?php

set_time_limit(0);

function write_txt($str)
{
    $filepath = 'E:/temp/test.xml';
    if (($fp = @fopen($filepath, "a")) === false) {
        return;
    }

    if (!flock($fp, LOCK_EX)) {
        @fclose($fp);
        return;
    }

    if (fwrite($fp, $str . "\n") === false) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!fflush($fp)) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!flock($fp, LOCK_UN)) {
        @fclose($fp);
        return;
    }

    if (!fclose($fp)) {
        return;
    }
}

for($i= 1;$i<100 ;$i++){

    write_txt('test');
    unlink('E:/temp/test.xml');
}
echo 'ok';

If I run file test2.php while test1.php is running, an error will occur:

Warning: unlink(E:/temp/test.xml): Permission denied in C:\xampp\htdocs\test2.php on line 45

When I only run test2.php, without test1.php, this error does not occur.
Why does unlink give a Permission denied error when I execute the function?

I'm using XAMPP 3.2 vs php 5.6 with Windows 7.

Body:
You're silencing errors in fopen which means that if, at any point, the file fails to open (perhaps because of a memory limit being reached in XAMPP, for example), you'd have no way of knowing in your script (you can view it in your logs).

From the PHP Manual:

bool unlink ( string $filename [, resource $context ] )

Deletes filename. Similar to the Unix C unlink() function. An
  E_WARNING level error will be generated on failure.

unlink deletes a file. That means that if your file fails to open using fopen, and you haven't created it already, it may well not exist. Trying to unlink a file that does not exist will result in an error.

An easy solution would be to silence errors on unlink as well.

@unlink('E:/temp/test.xml');

That way it will fail gracefully if your function fails to write a file. Another option is to check if the file exists before trying to unlink.

$file = 'E:/temp/test.xml';
if (file_exists($file)) {
    error_log(‘could not write file’);
    unlink($file);
}

My favored option in this case might be to use Exceptions. When you fail to open or fail to unlock a file, throw an Exception. You can catch it, log the issue and break the loop before you try to unlink.

That should help you debug what is going on.

Example:
    namespace Test;

class FileException extends \Exception { }
class UnlockFailedException extends FileException { }

function write_txt($str)
{
    $filepath = 'E:/temp/test.xml';
    if (($fp = @fopen($filepath, "a")) === false) {
        throw new FileException('Could not open file');
    }

    if (!flock($fp, LOCK_EX)) {
        @fclose($fp);
        return;
    }

    if (fwrite($fp, $str . "\n") === false) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!fflush($fp)) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return;
    }

    if (!flock($fp, LOCK_UN)) {
        @fclose($fp);
        throw new UnlockFailedException('Unable to unlock file.');
    }
    /**
     * This doesn't do anything
     * if (!fclose($fp)) {
     *     return;
     * }
     */
    fclose($fp);
}

Then:

$msg = 'ok';
for($i= 1;$i<100 ;$i++){
    try {
        write_txt('test');
        unlink('E:/temp/test.xml');
    } catch (FileException $e) {
        error_log($e->getMessage());
        $msg = 'errors detected';
    }
}
echo $msg;

By adding exception handling, you can debug this kind of behavior for yourself and find the root cause of the issue.

A couple final notes:

I run Linux, so it’s not easy for me to test this behavior on a Windows 7 XAMPP machine. However, I suspect it is because the system is locking due to limited I/O resources. Note that, according to the manual, Windows places a madatory lock on the file (whereas in Linux the lock is advisory). Running flock in a massive loop and echo in a massive loop on a limited resources system can lead to resources failing. If you intend to run something like this in production you won’t run into it as often but you will still need to account for it. Exception handling and error logging can ensure that when the file doesn't work you will have enough data to debug.

Assuming unlink is the problem is not a safe assumption at all.

As stated, silencing unlink or checking to see if the file exists will silence this error.


问:
Creating a nested array with unspecified number of columns
I'm trying to create a nested array that takes the user's input and stores it in the sub arrays. The number of subarrays is given by the user. I need the columns to be unspecified, and any number of elements can go in.

Is there a way to achieve this?

I tried:

```<code>puts "How many groups do you want to create?"
number_of_teams = gets.chomp
team_array = [Array.new(number_of_teams.to_i){Array.new()}]
</code>```

答:
team_array = Array.new(number_of_teams.to_i) { [] }

So if input is 3 then team_array will have  [ [], [], [] ]

Body:
I'm trying to create a nested array that takes the user's input and stores it in the sub arrays. The number of subarrays is given by the user. I need the columns to be unspecified, and any number of elements can go in.

Is there a way to achieve this?

I tried:

puts "How many groups do you want to create?"
number_of_teams = gets.chomp
team_array = [Array.new(number_of_teams.to_i){Array.new()}]


问:
Where is logical error in the given code?
I am trying to add a new node to the linked list. Online tutorials(http://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/) uses a pointer to a pointer and I am not able to understand how it works. So I decided to write my own code but I am having a problem with the push() function. Here is the code.

```<code>#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0);
    printf("\n");
    print_list(head);

    return 0;
}
</code>```

It compiles without error. However, the expected node with value 0 does not get inserted in the beginning of my linked list.

Current Output
1->2->3->
Expected Output
0->1->2->3->

Please help me get the required output without using pointer to a pointer in push() function. Also, share a link to a source which has a good explanation of pointer to a pointer and it relates to the linked list.

答:
Everything in C is passed by value. Even the pointers
So
I have two pointers

```<code>void swap(char* first, char* second)
{
  //take temp var and swap
}

main(){
char *first, *second;
first = 0x1;
second = 0x2;

printf("%x, %x", first, second);
swap(first, second);
printf("%x, %x", first, second);

}
</code>```

this code will not swap the values, since in swap(), the locally created values on stack are being swapped.
Realize that pointers are behaving just like another normal variables there.
Yes but if you dereference them you can swap the values pointed by the pointers inside the swap().

Catch is: head you passed is passed by value, the push() function does its job but assignment to head is done LOCALLY.

Body:
I am trying to add a new node to the linked list. Online tutorials(http://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/) uses a pointer to a pointer and I am not able to understand how it works. So I decided to write my own code but I am having a problem with the push() function. Here is the code.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0);
    printf("\n");
    print_list(head);

    return 0;
}

It compiles without error. However, the expected node with value 0 does not get inserted in the beginning of my linked list.

Current Output
1->2->3->
Expected Output
0->1->2->3->

Please help me get the required output without using pointer to a pointer in push() function. Also, share a link to a source which has a good explanation of pointer to a pointer and it relates to the linked list.

Body:
Everything in C is passed by value. Even the pointers
So
I have two pointers

void swap(char* first, char* second)
{
  //take temp var and swap
}

main(){
char *first, *second;
first = 0x1;
second = 0x2;

printf("%x, %x", first, second);
swap(first, second);
printf("%x, %x", first, second);

}

this code will not swap the values, since in swap(), the locally created values on stack are being swapped.
Realize that pointers are behaving just like another normal variables there.
Yes but if you dereference them you can swap the values pointed by the pointers inside the swap().

Catch is: head you passed is passed by value, the push() function does its job but assignment to head is done LOCALLY.


问:
How to remove a branch locally?
I have a master and a dev branch in my repository. I want to remove the master branch from my computer so that I don't accidentally commit to it (it's happened..).

There are questions on here about how to delete branches locally and remotely, but I haven't been able to find out how to only delete a branch locally.

One answer said to use this:

```<code>git branch -d local_branch_name
</code>```

But I tried that and the branch still shows up in the GitHub application.

答:
To Force Delete a Local Branch:

```<code>$ git branch -D <branch-name>
</code>```

[NOTE]:

-D is a shortcut for --delete --force.

Title: How to remove a branch locally?

Body:
I have a master and a dev branch in my repository. I want to remove the master branch from my computer so that I don't accidentally commit to it (it's happened..).

There are questions on here about how to delete branches locally and remotely, but I haven't been able to find out how to only delete a branch locally.

One answer said to use this:

git branch -d local_branch_name

But I tried that and the branch still shows up in the GitHub application.

Body:
To Force Delete a Local Branch:

$ git branch -D <branch-name>

[NOTE]:

-D is a shortcut for --delete --force.

ContentLicense: CC BY-SA 4.0


问:
How to refresh listView after database operation
How do I update the data of my ListView after doing operations on it? In the onClick of the custom adapter? In the MainActivity OnResume? I saw a lot of posts on that, but every time they just gave a line of code but not where to put it.

My custom Adapter:

```<code>    class CustomAdapter extends ArrayAdapter {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Contact> arrayList; //Lui transmettre le tableau adapter
    private ContactDatabase db;

    public CustomAdapter(Context context, ArrayList<Contact> arrayList){
        super(context, R.layout.contact_list, arrayList);
        db = new ContactDatabase(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.arrayList = arrayList;
    }

    private class ViewHolder{
        TextView txtName, txtPhone;
        ImageView tete, dial;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;

        if(convertView == null){
            //Reglage general
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.contact_list, parent, false); //Layout du design

            //Recuperation des ID
            viewHolder.txtName = convertView.findViewById(R.id.clName);
            viewHolder.txtPhone = convertView.findViewById(R.id.clNumber);
            viewHolder.tete = convertView.findViewById(R.id.cl_icone);
            viewHolder.dial = convertView.findViewById(R.id.cl_dial);

            //Definition du tag
            convertView.setTag(viewHolder);

        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //Definition des changements
        final Contact contact = arrayList.get(position);
        //viewHolder.txtName.setText(db.dbToString(position + 1));
        viewHolder.txtName.setText(Integer.toString(contact.getId()));
        viewHolder.txtPhone.setText(contact.getPhone());
        viewHolder.tete.setImageResource(contact.getImage());

        //Change color
//        int backgroundColor = ContextCompat.getColor(context, contact.getColor());
//        viewHolder.txtPhone.setTextColor(backgroundColor);

        //OnClick sur l'icone telephone
        viewHolder.dial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("tel:" + contact.getPhone()));
                //context.startActivity(intent);
                db.delete(contact.getId());
            }
        });

//        //OnClick sur l'icone image
        viewHolder.tete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, AddContactActivity.class); //On creer l'intent de donnee
//                intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
//                intent.putExtra("index", position); //On place les donnes enregistrer dans l'intent quon fera passe
//                ((Activity) context).startActivityForResult(intent, 100);

            }
        });

        return convertView;
    }

}

My Main Activity:

public class MainActivity extends AppCompatActivity{

    private ListView listView;
    private FloatingActionButton btnAdd;
    private ArrayList<Contact> contacts;
    ContactDatabase db;

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

        //Definition des ID
        btnAdd = findViewById(R.id.btn_add);
        listView = findViewById(R.id.list_view); //Recheche du listView
        listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message

        //Listener pour le button ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //Creation de ladapter
        db = new ContactDatabase(this);
        contacts = db.getData();
        CustomAdapter adapter = new CustomAdapter(this, contacts);
        listView.setAdapter(adapter);
    }

}
</code>```

Can you give me the code to put and where to put it exactly, so that after each operation my listView refresh automatically

答:
after each operation my listView refresh automatically

Just call    adapter.notifyDataSetChanged(); when you need to refresh your listView

adapter.notifyDataSetChanged();

notifyDataSetChanged()

Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

Sample code

```<code>CustomAdapter adapter = new CustomAdapter(this, contacts);
adapter.notifyDataSetChanged();
</code>```

In Your Code

```<code>@Override
protected void onResume() {
   super.onResume();
   //Creation de ladapter
   contacts.clear();
   db = new ContactDatabase(this);
   contacts.addAll(db.getData());
   adapter.notifyDataSetChanged();
}
</code>```

Body:
How do I update the data of my ListView after doing operations on it? In the onClick of the custom adapter? In the MainActivity OnResume? I saw a lot of posts on that, but every time they just gave a line of code but not where to put it.

My custom Adapter:

    class CustomAdapter extends ArrayAdapter {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Contact> arrayList; //Lui transmettre le tableau adapter
    private ContactDatabase db;

    public CustomAdapter(Context context, ArrayList<Contact> arrayList){
        super(context, R.layout.contact_list, arrayList);
        db = new ContactDatabase(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.arrayList = arrayList;
    }

    private class ViewHolder{
        TextView txtName, txtPhone;
        ImageView tete, dial;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;

        if(convertView == null){
            //Reglage general
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.contact_list, parent, false); //Layout du design

            //Recuperation des ID
            viewHolder.txtName = convertView.findViewById(R.id.clName);
            viewHolder.txtPhone = convertView.findViewById(R.id.clNumber);
            viewHolder.tete = convertView.findViewById(R.id.cl_icone);
            viewHolder.dial = convertView.findViewById(R.id.cl_dial);

            //Definition du tag
            convertView.setTag(viewHolder);

        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //Definition des changements
        final Contact contact = arrayList.get(position);
        //viewHolder.txtName.setText(db.dbToString(position + 1));
        viewHolder.txtName.setText(Integer.toString(contact.getId()));
        viewHolder.txtPhone.setText(contact.getPhone());
        viewHolder.tete.setImageResource(contact.getImage());

        //Change color
//        int backgroundColor = ContextCompat.getColor(context, contact.getColor());
//        viewHolder.txtPhone.setTextColor(backgroundColor);

        //OnClick sur l'icone telephone
        viewHolder.dial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("tel:" + contact.getPhone()));
                //context.startActivity(intent);
                db.delete(contact.getId());
            }
        });

//        //OnClick sur l'icone image
        viewHolder.tete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, AddContactActivity.class); //On creer l'intent de donnee
//                intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
//                intent.putExtra("index", position); //On place les donnes enregistrer dans l'intent quon fera passe
//                ((Activity) context).startActivityForResult(intent, 100);

            }
        });

        return convertView;
    }

}

My Main Activity:

public class MainActivity extends AppCompatActivity{

    private ListView listView;
    private FloatingActionButton btnAdd;
    private ArrayList<Contact> contacts;
    ContactDatabase db;

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

        //Definition des ID
        btnAdd = findViewById(R.id.btn_add);
        listView = findViewById(R.id.list_view); //Recheche du listView
        listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message

        //Listener pour le button ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //Creation de ladapter
        db = new ContactDatabase(this);
        contacts = db.getData();
        CustomAdapter adapter = new CustomAdapter(this, contacts);
        listView.setAdapter(adapter);
    }

}

Can you give me the code to put and where to put it exactly, so that after each operation my listView refresh automatically

Body:
after each operation my listView refresh automatically

Just call    adapter.notifyDataSetChanged(); when you need to refresh your listView

adapter.notifyDataSetChanged();

notifyDataSetChanged()

Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

Sample code

CustomAdapter adapter = new CustomAdapter(this, contacts);
adapter.notifyDataSetChanged();

In Your Code

@Override
protected void onResume() {
   super.onResume();
   //Creation de ladapter
   contacts.clear();
   db = new ContactDatabase(this);
   contacts.addAll(db.getData());
   adapter.notifyDataSetChanged();
}


问:
Insert unique values in Array in Javascript
I have one array. The function gets called continuously from backend service.
I want to push unique values in one object. My code is

```<code>currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});
</code>```

Please guide me to enter only unique currentValue and seconds value in graphDataObject

答:
Use filter function along with || to avoid duplication

let graphDataObject = [{timestamp : 11, value : 11},{timestamp : 4, value : 44},{timestamp : 2, value : 22},{timestamp : 3, value : 24}]

let newObject = {timestamp : 11, value : 24}

let result = graphDataObject.filter((obj) => {
    return obj.timestamp == newObject["timestamp"] || obj.value == newObject["value"];
})

if(result.length > 1) {
  // already present.. do your logic
}```

Body:
I have one array. The function gets called continuously from backend service.
I want to push unique values in one object. My code is

currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});

Please guide me to enter only unique currentValue and seconds value in graphDataObject


问:
use of removeif for filtering list containing objects
I am stuck on using removeif java 8 and looking for some help

```<code>List<ACHTransaction> transactions = transactionDao.retrieveTransactions(getJobParameters();
</code>```

from transactions I want to remove those transactions based on checking property of object

if transaction.getFileHash is not null then I want to remove that transaction. if transaction.getFileHash is null I want to keep it.

so I am trying removeif

```<code>List<ACHTransaction> transactions = transactionDao.retrieveTransactions(getJobParameters().removeIf(t -> (Optional.ofNullable(t.getFileHash()).orElse(0).intValue() != 0));
</code>```

but I am getting errors. Is someone can explain how removeif work with object properties?

答:
I tested below piece of code and it worked as required. I hope this is what you were looking for.</p>

```<code>import java.util.ArrayList;
import java.util.List;

public class TestRemoveIf {

public static void main(String[] args) {

    Transaction myTrans1 = new Transaction("myTrans1");
    Transaction myTrans2 = new Transaction("myTrans2");
    Transaction myTrans3 = new Transaction("myTrans3");
    Transaction myTrans4 = new Transaction("myTrans4");

    myTrans1.setFileHash("not Null");
    myTrans3.setFileHash("not null");

    List<Transaction> trList = new ArrayList();
    trList.add(myTrans1);
    trList.add(myTrans2);
    trList.add(myTrans3);
    trList.add(myTrans4);

    trList.removeIf(t -> t.getFileHash()!=null);

    System.out.println(trList);

}

}

public class Transaction {

String fileHash;
String name;

public String getFileHash() {
    return fileHash;
}

public void setFileHash(String fileHash) {
    this.fileHash = fileHash;
}

public Transaction(String name) {
    super();
    this.name = name;
}

@Override
public String toString() {
    return "Transaction [fileHash=" + fileHash + ", name=" + name + "]";
}

}
</code>```

Body:
I am stuck on using removeif java 8 and looking for some help

List<ACHTransaction> transactions = transactionDao.retrieveTransactions(getJobParameters();

from transactions I want to remove those transactions based on checking property of object

if transaction.getFileHash is not null then I want to remove that transaction. if transaction.getFileHash is null I want to keep it.

so I am trying removeif

List<ACHTransaction> transactions = transactionDao.retrieveTransactions(getJobParameters().removeIf(t -> (Optional.ofNullable(t.getFileHash()).orElse(0).intValue() != 0));

but I am getting errors. Is someone can explain how removeif work with object properties?

Body:
I tested below piece of code and it worked as required. I hope this is what you were looking for.

import java.util.ArrayList;
import java.util.List;

public class TestRemoveIf {

public static void main(String[] args) {

    Transaction myTrans1 = new Transaction("myTrans1");
    Transaction myTrans2 = new Transaction("myTrans2");
    Transaction myTrans3 = new Transaction("myTrans3");
    Transaction myTrans4 = new Transaction("myTrans4");

    myTrans1.setFileHash("not Null");
    myTrans3.setFileHash("not null");

    List<Transaction> trList = new ArrayList();
    trList.add(myTrans1);
    trList.add(myTrans2);
    trList.add(myTrans3);
    trList.add(myTrans4);

    trList.removeIf(t -> t.getFileHash()!=null);

    System.out.println(trList);

}

}

public class Transaction {

String fileHash;
String name;

public String getFileHash() {
    return fileHash;
}

public void setFileHash(String fileHash) {
    this.fileHash = fileHash;
}

public Transaction(String name) {
    super();
    this.name = name;
}

@Override
public String toString() {
    return "Transaction [fileHash=" + fileHash + ", name=" + name + "]";
}

}


问:
UITextField adjusts Font Size To Fit height
I have a UITextField:

```<code>let promoTextField: UITextField = {
     let textField = UITextField()
     textField.font = UIFont.systemFont(ofSize: 32, weight: UIFont.Weight.light)
     textField.placeholder = NSLocalizedString("PromoCode", comment: "")
     textField.textAlignment = .center
     textField.translatesAutoresizingMaskIntoConstraints = false
     textField.minimumFontSize = 17
     textField.adjustsFontSizeToFitWidth = true

     return textField
    }()
</code>```

The UITextField height (only height) can be changed based device screen size. I need to automatically change font size based on UITextField hight. How to do this?

答:
```<code>label.minimumScaleFactor = 0.1    // your value
label.adjustsFontSizeToFitWidth = true
label.lineBreakMode = .byClipping
label.numberOfLines = 0
</code>```

Body:
I have a UITextField:

let promoTextField: UITextField = {
     let textField = UITextField()
     textField.font = UIFont.systemFont(ofSize: 32, weight: UIFont.Weight.light)
     textField.placeholder = NSLocalizedString("PromoCode", comment: "")
     textField.textAlignment = .center
     textField.translatesAutoresizingMaskIntoConstraints = false
     textField.minimumFontSize = 17
     textField.adjustsFontSizeToFitWidth = true

     return textField
    }()

The UITextField height (only height) can be changed based device screen size. I need to automatically change font size based on UITextField hight. How to do this?


答:
```<code>***SOLVED***

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val, ***struct node *new_node***)
{

    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));
    ***struct node *new_node = (struct node*)malloc(sizeof(struct node));***

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0,new_node);
    printf("\n");
    print_list(***new_node***);

    return 0;
}
</code>```

Title: Where is logical error in the given code?


问:
How do I remove local (untracked) files from the current Git working tree?
How do I delete untracked local files from the current working tree?</p>

答:
We can easily removed local untracked files from the current git working tree by using below git comments.

```<code>git reset [--soft | --mixed [-N] | --hard | --merge | --keep] [-q] [<commit>]
</code>```

Example:

```<code>git reset --hard HEAD
</code>```

Links :

https://git-scm.com/docs/git-reset

How do I use 'git reset --hard HEAD' to revert to a previous commit?

Reset local repository branch to be just like remote repository HEAD

https://jwiegley.github.io/git-from-the-bottom-up/3-Reset/4-doing-a-hard-reset.html

OwnerDisplayName: Tim

Body:
We can easily removed local untracked files from the current git working tree by using below git comments.

git reset [--soft | --mixed [-N] | --hard | --merge | --keep] [-q] [<commit>]

Example:

git reset --hard HEAD

Links :

https://git-scm.com/docs/git-reset

How do I use 'git reset --hard HEAD' to revert to a previous commit?

Reset local repository branch to be just like remote repository HEAD

https://jwiegley.github.io/git-from-the-bottom-up/3-Reset/4-doing-a-hard-reset.html


问:
Finding duplicates from multiple list in python
I want to find duplicates( not to remove these duplicates but extract those repeating values) from multiple lists which are in a single list for example : a have list called Chunks which has 13 lists inside it.

my data is as follows

```<code>[[@TestRun
    And user set text "#Surname" on textbox name "surname"
    And user validate message on screen "Switch to paperless"
    And user click on "Manage accounts" label
    And user click link with label "View all online services"
    And user waits for 10 seconds
    Then page is successfully launched
    And user click link with label "Go paperless for complete convenience"
    Then page is successfully launched
    And user validate message on screen "#EmailAddress"
    And user clicks on the button "Confirm"
    Then page is successfully launched
    And user validate message on screen "#MessageValidate"
    Then page is successfully launched
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And user validate "Switch to paperless" button is disabled
    And user validate message on screen "Online only"
    When user click on "Log out" label
    Then page is successfully launched]

[@TestRun
    And user click on link "Mobile site"
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user click on link "#Account"
    Then page is successfully launched
    And user verify message on screen "#Account"
    And user verify message on screen "Manage statements"
    And user verify message on screen "Step 1 of 3"
    Then page is successfully launched
    And user verify message on screen "Current format type"
    And user verify message on screen "Online"
    When user selects the radio button "Paper" ]

[@TestRun
 And user set text "#Surname" on textbox name "surname"
Then user wait for page load
And user click on button "Continue to Online Banking"
Then user wait for page load
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And page is successfully launched
    And user waits for 10 seconds ]
[ @TestRun
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user waits for 10 seconds
    And user click checkbox "Telephone"
    And user click checkbox "Post"
    And user clicks on the button "Save"
    Then page is successfully launched ]]
</code>```

I have extracted every testcases in one list i.e lines betwwen two @testrun as one list

```<code> import itertools as it
import more_itertools as mit
import pandas as pd
## got seperated all test case in seprate list i.e 13 test cases in 13 lists
with open('cust_pref.txt', "r") as f1:
    lines_1 = f1.readlines()

    pred_1 = lambda x: x.startswith("@TestRun")
    inv_pred_1 = lambda x: not pred_1(x)

    lines_1 = it.dropwhile(inv_pred_1, lines_1)
    chunks_1 = list(mit.split_before(lines_1, pred_1))
##print the list of testcases
print(chunks_1)
</code>```

Now I need to find out how to find common in all this lists and how can I know from which list which are common

I tried out following

```<code>def get_duplicated_element(array):
    global result, checked_elements
    checked_elements = []
    result = -1
    def array_recursive_check(array):
        global result, checked_elements
        if result != -1: return
        for i in array:
            if type(i) == list:
                if i in checked_elements:
                    result = i
                    return
                checked_elements.append(i)
                array_recursive_check(i)
    array_recursive_check(array)
    return result

get_duplicated_element(chunks_1) ## this gives the answer as -1 , which is not expected
</code>```

Expected output is: finding common values /lines(in my cases) and if possible which steps comes in which list number in python

Desired output is :

```<code>{
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
}
</code>```

AS these steps are repeated in every list  so these sholud be the output

I have used following to get duplicates

```<code>def find_dupe(lists, target):
    seen = set()
    for lst in lists:
        for item in lst:
            if item == target and item in seen:
                return True
            seen.add(item)

seen, dups = set(), set()
for l in chunks:
    dups = dups.union(seen.intersection(set(l)))
    seen = seen.union(set(l))
</code>```

I get some duplicates from this but now my problem is i dont know which line is from which list ? Is there any way to achieve this mapping which values corresponds to which list

答:
Not quite the desired output you want, but you can get a hint to process further on. Check this:</p>

```<code>>>> data = [['@TestRun',
  '    And user set text "#Surname" on textbox name "surname"',
  '    And user validate message on screen "Switch to paperless" ',
  '    And user click on "Manage accounts" label ',
  '    And user click link with label "View all online services" ',
  '    And user waits for 10 seconds ',
  '    Then page is successfully launched ',
  '    And user click link with label "Go paperless for complete convenience" ',
  '    Then page is successfully launched ',
  '    And user validate message on screen "#EmailAddress" ',
  '    And user clicks on the button "Confirm" ',
  '    Then page is successfully launched ',
  '    And user validate message on screen "#MessageValidate" ',
  '    Then page is successfully launched ',
  '    And user click on "menu open user preferences" label ',
  '    And user clicks on the link "Statement and letter preferences" ',
  '    Then page is successfully launched ',
  '    And user validate "Switch to paperless" button is disabled ',
  '    And user validate message on screen "Online only" ',
  '    When user click on "Log out" label ',
  '    Then page is successfully launched'],
 ['@TestRun ',
  '    And user click on link "Mobile site" ',
  '    And user set text "#Surname" on textbox name "surname" ',
  '    Then page is successfully launched ',
  '    And user click on link "#Account" ',
  '    Then page is successfully launched ',
  '    And user verify message on screen "#Account" ',
  '    And user verify message on screen "Manage statements" ',
  '    And user verify message on screen "Step 1 of 3" ',
  '    Then page is successfully launched ',
  '    And user verify message on screen "Current format type"  ',
  '    And user verify message on screen "Online" ',
  '    When user selects the radio button "Paper"'],
 ['@TestRun',
  ' And user set text "#Surname" on textbox name "surname"',
  'Then user wait for page load',
  'And user click on button "Continue to Online Banking"',
  'Then user wait for page load',
  '    And user click on "menu open user preferences" label ',
  '    And user clicks on the link "Statement and letter preferences" ',
  '    Then page is successfully launched ',
  '    And page is successfully launched ',
  '    And user waits for 10 seconds']]
>>> data = [[line.strip() for line in test_set] for test_set in data]
>>> linewise_counts = {}
>>> for list_index,test_set in enumerate(pdata):
        for line in test_set:
            linewise_counts.setdefault(line,set()).add(list_index)

>>> duplicates = ["{} -> {}".format(line, in_list) for line,in_list in linewise_counts.items() if len(in_list)>1]
>>> duplicates
['And user clicks on the link "Statement and letter preferences" -> set([0, 2])',
 'And user waits for 10 seconds -> set([0, 2])',
 'Then page is successfully launched -> set([0, 1, 2])',
 '@TestRun -> set([0, 1, 2])',
 'And user set text "#Surname" on textbox name "surname" -> set([0, 1, 2])',
 'And user click on "menu open user preferences" label -> set([0, 2])']
</code>```

Body:
I want to find duplicates( not to remove these duplicates but extract those repeating values) from multiple lists which are in a single list for example : a have list called Chunks which has 13 lists inside it.

my data is as follows

[[@TestRun
    And user set text "#Surname" on textbox name "surname"
    And user validate message on screen "Switch to paperless"
    And user click on "Manage accounts" label
    And user click link with label "View all online services"
    And user waits for 10 seconds
    Then page is successfully launched
    And user click link with label "Go paperless for complete convenience"
    Then page is successfully launched
    And user validate message on screen "#EmailAddress"
    And user clicks on the button "Confirm"
    Then page is successfully launched
    And user validate message on screen "#MessageValidate"
    Then page is successfully launched
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And user validate "Switch to paperless" button is disabled
    And user validate message on screen "Online only"
    When user click on "Log out" label
    Then page is successfully launched]

[@TestRun
    And user click on link "Mobile site"
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user click on link "#Account"
    Then page is successfully launched
    And user verify message on screen "#Account"
    And user verify message on screen "Manage statements"
    And user verify message on screen "Step 1 of 3"
    Then page is successfully launched
    And user verify message on screen "Current format type"
    And user verify message on screen "Online"
    When user selects the radio button "Paper" ]

[@TestRun
 And user set text "#Surname" on textbox name "surname"
Then user wait for page load
And user click on button "Continue to Online Banking"
Then user wait for page load
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And page is successfully launched
    And user waits for 10 seconds ]
[ @TestRun
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user waits for 10 seconds
    And user click checkbox "Telephone"
    And user click checkbox "Post"
    And user clicks on the button "Save"
    Then page is successfully launched ]]

I have extracted every testcases in one list i.e lines betwwen two @testrun as one list

 import itertools as it
import more_itertools as mit
import pandas as pd
## got seperated all test case in seprate list i.e 13 test cases in 13 lists
with open('cust_pref.txt', "r") as f1:
    lines_1 = f1.readlines()

    pred_1 = lambda x: x.startswith("@TestRun")
    inv_pred_1 = lambda x: not pred_1(x)

    lines_1 = it.dropwhile(inv_pred_1, lines_1)
    chunks_1 = list(mit.split_before(lines_1, pred_1))
##print the list of testcases
print(chunks_1)

Now I need to find out how to find common in all this lists and how can I know from which list which are common

I tried out following

def get_duplicated_element(array):
    global result, checked_elements
    checked_elements = []
    result = -1
    def array_recursive_check(array):
        global result, checked_elements
        if result != -1: return
        for i in array:
            if type(i) == list:
                if i in checked_elements:
                    result = i
                    return
                checked_elements.append(i)
                array_recursive_check(i)
    array_recursive_check(array)
    return result

get_duplicated_element(chunks_1) ## this gives the answer as -1 , which is not expected

Expected output is: finding common values /lines(in my cases) and if possible which steps comes in which list number in python

Desired output is :

{
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
}

AS these steps are repeated in every list  so these sholud be the output

I have used following to get duplicates

def find_dupe(lists, target):
    seen = set()
    for lst in lists:
        for item in lst:
            if item == target and item in seen:
                return True
            seen.add(item)

seen, dups = set(), set()
for l in chunks:
    dups = dups.union(seen.intersection(set(l)))
    seen = seen.union(set(l))

I get some duplicates from this but now my problem is i dont know which line is from which list ? Is there any way to achieve this mapping which values corresponds to which list

Body:
Not quite the desired output you want, but you can get a hint to process further on. Check this:

>>> data = [['@TestRun',
  '    And user set text "#Surname" on textbox name "surname"',
  '    And user validate message on screen "Switch to paperless" ',
  '    And user click on "Manage accounts" label ',
  '    And user click link with label "View all online services" ',
  '    And user waits for 10 seconds ',
  '    Then page is successfully launched ',
  '    And user click link with label "Go paperless for complete convenience" ',
  '    Then page is successfully launched ',
  '    And user validate message on screen "#EmailAddress" ',
  '    And user clicks on the button "Confirm" ',
  '    Then page is successfully launched ',
  '    And user validate message on screen "#MessageValidate" ',
  '    Then page is successfully launched ',
  '    And user click on "menu open user preferences" label ',
  '    And user clicks on the link "Statement and letter preferences" ',
  '    Then page is successfully launched ',
  '    And user validate "Switch to paperless" button is disabled ',
  '    And user validate message on screen "Online only" ',
  '    When user click on "Log out" label ',
  '    Then page is successfully launched'],
 ['@TestRun ',
  '    And user click on link "Mobile site" ',
  '    And user set text "#Surname" on textbox name "surname" ',
  '    Then page is successfully launched ',
  '    And user click on link "#Account" ',
  '    Then page is successfully launched ',
  '    And user verify message on screen "#Account" ',
  '    And user verify message on screen "Manage statements" ',
  '    And user verify message on screen "Step 1 of 3" ',
  '    Then page is successfully launched ',
  '    And user verify message on screen "Current format type"  ',
  '    And user verify message on screen "Online" ',
  '    When user selects the radio button "Paper"'],
 ['@TestRun',
  ' And user set text "#Surname" on textbox name "surname"',
  'Then user wait for page load',
  'And user click on button "Continue to Online Banking"',
  'Then user wait for page load',
  '    And user click on "menu open user preferences" label ',
  '    And user clicks on the link "Statement and letter preferences" ',
  '    Then page is successfully launched ',
  '    And page is successfully launched ',
  '    And user waits for 10 seconds']]
>>> data = [[line.strip() for line in test_set] for test_set in data]
>>> linewise_counts = {}
>>> for list_index,test_set in enumerate(pdata):
        for line in test_set:
            linewise_counts.setdefault(line,set()).add(list_index)

>>> duplicates = ["{} -> {}".format(line, in_list) for line,in_list in linewise_counts.items() if len(in_list)>1]
>>> duplicates
['And user clicks on the link "Statement and letter preferences" -> set([0, 2])',
 'And user waits for 10 seconds -> set([0, 2])',
 'Then page is successfully launched -> set([0, 1, 2])',
 '@TestRun -> set([0, 1, 2])',
 'And user set text "#Surname" on textbox name "surname" -> set([0, 1, 2])',
 'And user click on "menu open user preferences" label -> set([0, 2])']


问:
how to correctly modify integers with while loops
So basically, I'm just trying to return a GCD from two previous numbers,

```<code>public static String GCD( int Denominator,int Numerator) {
    int newNum=Numerator;
    int newDen=Denominator;
    int newWhole=Whole;
    int GCD=0;
    if (Numerator == 0) {
        GCD = Denominator;
    }

    while (Denominator != 0) {
        if (Numerator > Denominator) {
            Numerator = Numerator - Denominator;
        }else {
            Denominator = Denominator - Numerator;
        }
    }
    GCD = Denominator;
    System.out.println(GCD);
}
</code>```

You would think that since i declared GCD outside the loop that it would return just fine

but no, i just get 0 as an answer? almost every time..... thoughts?

答:
That's because your while loop is dependent on the value of Denominator as the loop ends when the value of Denominator is decreased to 0.

And right outside the while loop, you're storing the value of Denominator in 'GCD' which is obviously '0'.

So no matter what you do in the while loop, you would get 0 as the final result of your GCD.

I hope this solves your problem.

Body:
So basically, I'm just trying to return a GCD from two previous numbers,

public static String GCD( int Denominator,int Numerator) {
    int newNum=Numerator;
    int newDen=Denominator;
    int newWhole=Whole;
    int GCD=0;
    if (Numerator == 0) {
        GCD = Denominator;
    }

    while (Denominator != 0) {
        if (Numerator > Denominator) {
            Numerator = Numerator - Denominator;
        }else {
            Denominator = Denominator - Numerator;
        }
    }
    GCD = Denominator;
    System.out.println(GCD);
}

You would think that since i declared GCD outside the loop that it would return just fine

but no, i just get 0 as an answer? almost every time..... thoughts?


问:
How to check java version at linux (RedHat6)
 I am trying to check what java version I have installed in my linux machine, I have tried:

```<code>which java
</code>```

and I get:

```<code>/usr/bin/java
</code>```

but when I type:

```<code>java -version
</code>```

the console is returning nothing and getting stuck in a "java mode" , feels like the command called java and its waiting for my inputs, any thing I type then returns nothing... until I type crt+C it exits the mode...

答:
If your java version more than 1.6 then it should work

java -version

if version is not installed it returns error message

Please share some snapshot so i can rectify it

Body:
 I am trying to check what java version I have installed in my linux machine, I have tried:

which java

and I get:

/usr/bin/java

but when I type:

java -version

the console is returning nothing and getting stuck in a "java mode" , feels like the command called java and its waiting for my inputs, any thing I type then returns nothing... until I type crt+C it exits the mode...


答: You need a return statement somewhere in your code.  Probably at the end of the method, you need to write return GCD;.

Title: how to correctly modify integers with while loops


问:
I want to force the user to edit the value of the NumericStepper by using the arrows only so they cannot type a value directly into the value field
When using the NumericStepper I want to force the user to only be able to edit the value using the NumericStepper's up and down arrows. I do not want the user to be able to type in a value directly. How can i do this in flex 4? Can someone please provide an example?

Thanks

答:
Yo need to set the NumericStepper's textDisplay as non editable. You can do it once the component has been initialized:

```<code>    <fx:Script>
        <![CDATA[
            protected function init():void {
                nmStppr.textDisplay.editable = false;
            }
        ]]>
    </fx:Script>

    <s:NumericStepper id="nmStppr"
            horizontalCenter="0" verticalCenter="0"
            creationComplete="init();"/>
</code>```

or creating a custom skin as explained here

Body:
Yo need to set the NumericStepper's textDisplay as non editable. You can do it once the component has been initialized:

    <fx:Script>
        <![CDATA[
            protected function init():void {
                nmStppr.textDisplay.editable = false;
            }
        ]]>
    </fx:Script>

    <s:NumericStepper id="nmStppr"
            horizontalCenter="0" verticalCenter="0"
            creationComplete="init();"/>

or creating a custom skin as explained here