How to decrypt hash get from this function

Question: we are encrypting our password in the app using this function.How to decrypt them when we need actual string.var crypto = require('crypto');
function encryptPassword(password) {
    var salt = new Buffer('priotzen', 'base64');
    return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64');
}

Thanks :)
Comment: It's a one-way hash. It's not possible to decrypt.
Answer: The code you've provided generates a one-way hash. If you use this, then you validate passwords by comparing hashed values. There is no way to decrypt the existing password. If the user forgets their password, then you do a password reset.
If you really want to have retrievable passwords, then you need to look at encryption rather than hashing algorithms. For this type of application, symmetric key encryption, such as AES may be suitable.
Keep in mind that encryption is computationally much more expensive than hashing, and less secure. Hashing is nearly always preferred for passwords. Unless there is some extremely compelling reason to have retrievable passwords, you should steer your client towards one-way hash passwords.
Comment: 1. Encryption should not be used when password verification is the goal. 2. Encryption may not be more expensive than hashing given that CPUs with AES-NI instructions are commonly available and many platforms have fast crypto engines available. 3. PBKDF2 is a NIST recommended method for password verifiers. Hashing, actually **iterated cryptographic hashing**, is the preferred method for creating password verifiers used for password verification. 4. Encryption of passwords can lead to the exposing of the passwords to attackers and admin personal.


django comment: how to specify the sort direction?

Question: I am using comment app in django, but currently the sort direction is by date(from old to new), I want the comments are displayed by date from new to old, how to change it?
Comment: Are you trying to order in a view or on the model as a whole? Is this an app you made yourself or is it third-party?
Answer: you can do:
{% get_comment_list for event as comment_list %}
{% for comment in comment_list reversed %}
    ...
{% endfor %}

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
Answer: You can use the minus sign to inverse the ordering.
t = Theme.objects.order_by('-pub_date')
Avoid using business logic in the templates as much as possible.
the django documentation


Where and how do the ViewLocator-generated Views get their DataContexts assigned (in Avalonia's Todo tutorial application)?

Question: In the completed Avalonia tutorial Todo application --- where and how do TodoListView and AddItemView acquire their  DataContexts to be equal to TodoListViewModel and AddItemViewModel  respectively ???
I mean their parent control MainWindow's DataContext is a MainWindowViewModel instance (as assigned in App.xaml.cs file) --- while MainWindow's Content attribute is bound to MainWindowViewModel's Content property (which does get assigned instances of the viewmodels during execution). I just cannot trace the source wherefrom TodoListView and AddItemView acquire their DataContexts. Do they get it while:

Being created by the ViewLocator at runtime ?  --  but that's not possible as the DataContext property of the newly instantiated View is still NULL just before the ViewLocator returns the View instance -- as shown by the output of following code in the completed application (the code in the if block is modified by me to produce required output):

public IControl Build(object data)
        {
            var name = data.GetType().FullName.Replace("ViewModel", "View");
            var type = Type.GetType(name);

            if (type != null)
            {
                var viewInstance = (Control)Activator.CreateInstance(type);

                // the following always evaluates to true --- i.e. DataContext is always NULL before viewInstance is returned.
                if(viewInstance.DataContext == null)
Console.WriteLine($"DataContext property of the newly created View instance of {name} in ViewLocator is NULL just before returning! ");

                return  viewInstance ;
            }
            else
            {
                return new TextBlock { Text = "Not Found: " + name };
            }
        }

OR they get their DataContext assigned by the parent Window ? --- but the parent window's own DataContext is MainWindowViewModel -----  how do we get to TodoListViewModel or AddItemViewModel  from   MainWindowViewModel ???

In short , I am unclear about where the Views generated at runtime via ViewLocator are getting their DataContext properties assigned.

Summarizing what I understood from the answer and some search and play:

If a ContentControl's (in this case Window's) Content property is a Control then the Control simply inherits the DataContext from the parent ContentControl. But if  the ContentControl's Content property is a non-Control then the ContentPresenter of the ContentControl first finds a data template for the non-Control  so that a child View can be generated and then sets its own DataContext to the non-Control. This newly assigned DataContext then gets inherited by the newly generated child View. Phewwwwww!
Answer: DataContext is inherited from ContentPresenter which is asking IDataTemplate.Build for a new view instance. When Content isn't a control, ContentPresenter sets its own DataContext to the value of Content which gets inherited by the child view.
ContentPresenter is used internally by the Window to display its Content property.
Same happens with ListBox items.
Comment: Wow -- thanks --- that was quick and to the point. Brilliant!


i want to use assetmanager for an image

Question: MyGdxGame.java
 public void print(){
    manager=new AssetManager();
    manager.load("selectlevel.png",Texture.class);
    manager.finishLoading();
    }

select level screen
 public void image(){
    Image img1=game.manager().get(("selectlevel.png"));
    }

what i get(

Exception in thread "LWJGL Application" java.lang.ClassCastException:
  com.badlogic.gdx.graphics.Texture cannot be cast to
  com.badlogic.gdx.scenes.scene2d.ui.Image

i dont want to change image type to Texture.
Comment: You are trying to set a Texture to the variable img1(which is an Image) . Try using Image img1= new Image(game.manager().get(("selectlevel.png")));
Comment: does not work aswell
Comment: @dfour cannot resolve constructor 'Image(java.lang.Object)'
Comment: You will have to cast the Object to a texture like this
Image img1= new Image((Texture)game.manager().get(("selectlevel.png")));
or call the get method with the class parameter like this
Image img1= new Image(game.manager().get(("selectlevel.png",Texture.class)));
Comment: @dfour thank you sir
Answer: Based on your error message:

Exception in thread "LWJGL Application" java.lang.ClassCastException: com.badlogic.gdx.graphics.Texture cannot be cast to com.badlogic.gdx.scenes.scene2d.ui.Image

You are trying to place a Texture in a variable that is made for an scene2d.ui.Image. This will not work because a Texture and a scene2d.ui.Image are very different.
The scene2d.ui.Image has a constructor that takes a Texture so should be called like this:
Image imgVariable = new Image(i_am_a_Texture);

In the comments you mentioned you recieved an error

cannot resolve constructor 'Image(java.lang.Object)'

This is saying that when you used the new Image constructor you passed it an Object and not a Texture which it was expecting.
In order to make the Object a Texture you could cast it to a Texture by adding (Texture) in from of the object you want cast like this:
 Texture textureVariable = (Texture) game.manager().get(("selectlevel.png"));

However the assetManager already has a way of saying what class the object returned should be and that is to add the class as the 2nd parameter like below
Texture textureVariable = game.manager().get(("selectlevel.png",Texture.class))

i want to use assetmanager for an image


how to bind/ unbind a Date type attribute to a DatePicker object

Question: i have the following code:
@FXML
private DatePicker birthday;
//other code
private final ChangeListener<Person> personListener = (value, oldValue, newValue) -> {
//other code
birthday.valueProperty().unbindBidirectional(oldValue.getBirthday());
//other code
};

birthday property is of type java.time.LocalDate, and belongs to a class Person. because I use JPA, I want do not to use JavaFX properties.
The above code fails to compile. The compiler's error message is:
error: no suitable method found for unbindBidirectional(LocalDate)
       birthDayPicker.valueProperty().unbindBidirectional(oldV.getBirthday());
method Property.unbindBidirectional(Property<LocalDate>) is not applicable
  (argument mismatch; LocalDate cannot be converted to Property<LocalDate>)
method ObjectProperty.unbindBidirectional(Property<LocalDate>) is not applicable
  (argument mismatch; LocalDate cannot be converted to Property<LocalDate>)

How can i solve this problem?
Update:
My person class has the followin code:
@Entity
@Table(name = "PERSON")
@NamedQueries({
    @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
    @NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p WHERE p.id = :id"),
    @NamedQuery(name = "Person.findByFirstname", query = "SELECT p FROM Person p WHERE p.firstname = :firstname"),
    @NamedQuery(name = "Person.findByLastname", query = "SELECT p FROM Person p WHERE p.lastname = :lastname"),
    @NamedQuery(name = "Person.findByMail", query = "SELECT p FROM Person p WHERE p.mail = :mail"),
    @NamedQuery(name = "Person.findByBirthday", query = "SELECT p FROM Person p WHERE p.birthday = :birthday")})
public class Person implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "FIRSTNAME")
    private String firstname;
    @Column(name = "LASTNAME")
    private String lastname;
    @Column(name = "MAIL")
    private String mail;
    @Column(name = "BIRTHDAY")
    @Temporal(TemporalType.DATE)
    private LocalDate birthday;

    public Person() {
    }

    public Person(Integer id) {
        this.id = id;
    }

    public Person(Integer id, String firstname) {
        this.id = id;
        this.firstname = firstname;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        Integer oldId = this.id;
        this.id = id;
         listenerList.firePropertyChange("id", oldId, id);
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        String oldFirstName = this.firstname;
        this.firstname = firstname;
         listenerList.firePropertyChange("firstname", oldFirstName, firstname);
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        String oldLastName = this.lastname;
        this.lastname = lastname;
          listenerList.firePropertyChange("mail", oldLastName, lastname);
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        String oldMail = this.mail;
        this.mail = mail;
        listenerList.firePropertyChange("mail", oldMail, mail);
    }

    public LocalDate getBirthday() {
        return birthday;
    }

    public void setBirthday(LocalDate birthday) {
        LocalDate oldBirthDay = this.birthday;
        this.birthday = birthday;
        listenerList.firePropertyChange("birthday", id, birthday);
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Person)) {
            return false;
        }
        Person other = (Person) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "jpa.entities.Person[ id=" + id + " ]";
    }

    @Transient
    final private PropertyChangeSupport listenerList = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        listenerList.addPropertyChangeListener(listener);

    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        listenerList.removePropertyChangeListener(listener);

    }

}

the controller class:
public class PersonController implements Initializable {

@FXML
private TableView<Person> personsTable;
@FXML
private TableColumn<Person, Integer> idColumn;
@FXML
private TableColumn<Person, String> firstColumn;
@FXML
private TableColumn<Person, String> lastColumn;
@FXML
private TableColumn<Person, LocalDate> birthdayColumn;
@FXML
private TableColumn<Person, String> mailColumn;
@FXML
private TextField id;
@FXML
private TextField firstName;
@FXML
private TextField lastName;
@FXML
private TextField mail;
@FXML
private DatePicker birthDayPicker;
private EntityManagerFactory emf;
private EntityManager em;
private ObservableList<Person> data;
private LocalDate birthday;

/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    emf = Persistence.createEntityManagerFactory("persistenceTest");
    em = emf.createEntityManager();
    data = FXCollections.observableArrayList();
    birthDayPicker.setOnAction((ActionEvent evnt) -> {
        birthday = birthDayPicker.getValue();

    });
    personsTable.getSelectionModel().selectedItemProperty().addListener(personListener);
    configureColumn();
    populate();
}

@FXML
private void addPerson(ActionEvent event) {
    em.getTransaction().begin();
    Person p = new Person(Integer.parseInt(id.getText()), firstName.getText());
    p.setLastname(lastName.getText());
    p.setBirthday(birthDayPicker.getValue());
    p.setMail(mail.getText());
    em.persist(p);
    data.add(p);
    em.getTransaction().commit();
}

@FXML
private void savePerson(ActionEvent event) {

}

@FXML
private void deletePerson(ActionEvent event) {
    em.getTransaction().begin();
    Person p = personsTable.getSelectionModel().selectedItemProperty().getValue();
    data.remove(p);
    em.remove(p);
    em.getTransaction().commit();
}

private void populate() {
    TypedQuery<Person> query = em.createQuery(
            "SELECT e FROM Person e", jpa.entities.Person.class);
    List<Person> list = query.getResultList();
    data.addAll(list);
    personsTable.setItems(data);
}

private void configureColumn() {
    idColumn.setCellValueFactory(new PropertyValueFactory<Person, Integer>("id"));
    firstColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("firstname"));
    lastColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("lastname"));
    birthdayColumn.setCellValueFactory(new PropertyValueFactory<Person, LocalDate>("birthday"));
    birthdayColumn.setCellFactory(p -> {
        return new TableCell<Person, LocalDate>() {
            @Override
            protected void updateItem(LocalDate item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    final DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                    setText(item.format(format));

                }
            }
        };
    });
    mailColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("mail"));

}

private final ChangeListener<Person> personListener = (value, oldV, newV) -> {
    if (oldV != null) {
        id.textProperty().unbindBidirectional(oldV.getId());
        firstName.textProperty().unbindBidirectional(oldV.getFirstname());
        lastName.textProperty().unbindBidirectional(oldV.getLastname());
        birthDayPicker.valueProperty().unbindBidirectional(oldV.getBirthday()); // error
        mail.textProperty().unbindBidirectional(oldV.getMail());

    }
    if (newV != null) {
        try {
            id.textProperty().bindBidirectional(JavaBeanIntegerPropertyBuilder.create().bean(newV).name("id").build(), new NumberStringConverter());
            firstName.textProperty().bindBidirectional(JavaBeanStringPropertyBuilder.create().bean(newV).name("firstname").build());
            lastName.textProperty().bindBidirectional(JavaBeanStringPropertyBuilder.create().bean(newV).name("lastname").build());
            birthDayPicker.valueProperty().bindBidirectional(); // error
            mail.textProperty().bindBidirectional(JavaBeanStringPropertyBuilder.create().bean(newV).name("mail").build());

        } catch (NoSuchMethodException e) {
            System.out.println("erreur : " + e.getMessage());
        }

    }

};

}

Comment: Again, you have to bind to a JavaBeanPropertyAdapter if you are not going to use JavaFX properties. I will post an answer when I am back at a computer.
Comment: You need to keep a reference to the adapter. See posted answer. I still think it's better to use JavaFX properties in the entity class, though.
Comment: See if http://stackoverflow.com/questions/26959392/javafx-bind-not-property-member-to-control/ helps. You should at least use a `java.time.LocalDate`, even if you don't want to use JavaFX properties (using properties, which you can do with JPA, will make your life easier).
Comment: @ James_D That doesn't really help me. i changed the type to LocalDate.  JPA recognize it (i added a class that  implements AttributeConverter). what is next?
Comment: Either use JavaFX properties and bind to the `ObjectProperty`, or add `PropertyChangeSupport` and bind to a `JavaBeanPropertyAdapter`, as in the linked question.
Comment: @James_D see the update, the problem persists
Comment: thanks very much.  for binding, i used: birthDayPicker.valueProperty().bindBidirectional(JavaBeanObjectPropertyBuilder.create().bean(newV).name("birthday").build()); it works. but How about unbinding. i must use the method unbind with no argument?
Answer: The easiest thing to do is simply to use JavaFX properties in your Person class. This works with JPA as long as you use "property access" instead of "field access". I.e.:
public class Person {

    private final StringProperty firstname = new SimpleStringProperty();

    public StringProperty firstnameProperty() {
        return firstname ;
    }

    @Basic(optional = false)
    @Column(name = "FIRSTNAME")
    public final String getFirstname() {
        return firstnameProperty().get();
    }

    public final void setFirstname(String firstname) {
        firstnameProperty().set(firstname);
    }

    private final ObjectProperty<LocalDate> birthday = new SimpleObjectProperty<>();
    public ObjectProperty<LocalDate> birthdayProperty() {
        return birthday ;
    }

    @Column(name="BIRTHDAY")
    @Temporal(TemporalType.DATE)
    public LocalDate getBirthday() {
        return birthdayProperty().get();
    }
    public void setBirthday(LocalDate birthday) {
        birthdayProperty().set(birthday);
    }

    // etc
}

(Note that Hibernate still objects to final get and set methods, so you would have to make those methods non-final if you use Hibernate, which is slightly less than ideal. If you use a JPA-compliant ORM this shouldn't cause a problem.)
If you cannot use JavaFX properties in your entity for some reason, you can manage the binding with a JavaBeanObjectProperty. Code along the following lines should work:
public class PersonController {

    private JavaBeanObjectProperty birthdayPropertyAdapter ;

    // ...

private final ChangeListener<Person> personListener = (value, oldV, newV) -> {
    if (oldV != null) {
        id.textProperty().unbindBidirectional(oldV.getId());
        firstName.textProperty().unbindBidirectional(oldV.getFirstname());
        lastName.textProperty().unbindBidirectional(oldV.getLastname());
        mail.textProperty().unbindBidirectional(oldV.getMail());

    }

    if (birthdayPropertyAdapter != null) {
            birthdayPicker.valueProperty().unbindBidirectional(birthdayPropertyAdapter);
    }

    if (newV != null) {
        try {
            id.textProperty().bindBidirectional(JavaBeanIntegerPropertyBuilder.create().bean(newV).name("id").build(), new NumberStringConverter());
            firstName.textProperty().bindBidirectional(JavaBeanStringPropertyBuilder.create().bean(newV).name("firstname").build());
            lastName.textProperty().bindBidirectional(JavaBeanStringPropertyBuilder.create().bean(newV).name("lastname").build());
            mail.textProperty().bindBidirectional(JavaBeanStringPropertyBuilder.create().bean(newV).name("mail").build());

    birthdayPropertyAdapter = JavaBeanObjectPropertyBuilder.create()
    .bean(newV)
    .name("birthday")
    .build();

    birthdayPicker.valueProperty().bindBidirectional(birthdayPropertyAdapter);

        } catch (NoSuchMethodException e) {
            System.out.println("erreur : " + e.getMessage());
        }

    }

};

Answer: Change the type of date in your Person class, then add and use appropriate accessors.
public class Person {
    final private ObjectProperty<LocalDate> birthday;

    public Person(LocalDate birthday) {
        this.birthday = new SimpleObjectProperty<LocalDate>(birthday);
    }

    public LocalDate getBirthday() {
        return birthday.get();
    }

    public void setBirthday(LocalDate birthday) {
        this.birthday.set(birthday);
    }

    public ObjectProperty<LocalDate> birthdayProperty() {
        return birthday;
    }
}

. . .

@FXML
private DatePicker birthday;
//other code
private final ChangeListener<Person> personListener = (value, oldValue, newValue) -> {
    //other code
    birthday.valueProperty().unbindBidirectional(oldValue.birthdayProperty());
    //other code
};

Comment: Adding constraints like this to your question is always a good idea.
Comment: i want do not to use javafx properties. I use JPA.


Continuity of this function though the distance

Question: Our professor taught us this way to prove the continuity of a function at a point: we have to find a suitable "distance" function $h$. Then $f$ is continuous at $x_0$ if there exists $h$ such that
$$|f(x) - f(x_0)| \leq h(||x-x_0||)$$
And this $h$ can be written as $h(d)$ and $h(d) \to 0$ for $d \to 0$.
I'm having problems in applying this for the function
$$
f(x, y) =
\begin{cases}
\frac{2x^2 y}{x^4+y^2} & (x, y) \neq (0, 0)\\
0 & (x, y) = (0, 0)
\end{cases}
$$
I already proved in many ways that the function is not continuous (example: using parabolas, straigh lines and sequences). I cannot manage to prove it with this method though.
I thought of
$$\bigg|\frac{2x^2y}{x^4+y^2}\bigg| \leq \frac{2x^2|y|}{x^4+y^2} \leq \frac{2x^2y^2}{x^4+y^2} \leq \frac{2x^2y^2}{x^2+y^2}$$
But then I always obtain some function that goes to $0$. For example if I say
$$x^2y^2 \leq (x^2+y^2)^2$$
or using AM/GM inequality...
Comment: Yes, the trick with $h$ is used to prove continuity, and the trick with curves to prove discontinuity. But I am trying to build a more precise answer to the present post.
Comment: @AnneBauval I really appreciate that! Thank you in advance (and for all!)
Comment: Your post is unclear: the method you were taught is used to prove the continuity, but your function is [not continuous](https://math.stackexchange.com/questions/1616669) (as yourself claim having "proved in many ways").
Comment: For $0y^2$ and $x^4<x^2$ hence your two inequalities $\frac{2x^2|y|}{x^4+y^2} \leq \frac{2x^2y^2}{x^4+y^2} \leq \frac{2x^2y^2}{x^2+y^2}$ are false.
Comment: @AnneBauval Yes, indeed! I was trying to prove, with the same method, that the function is not contnuous. Like maybe obtaining a distance that does not go to zero...
Comment: That would be of no help. There are *always* functions $h$ such that $\lim_0h\ne0$ and (for $x$ close to $x_0$) $|f(x)-f(x_0)|\le h(||x-x_0||):$ just take $h$ big enough.
Comment: @AnneBauval Oh, so I could indeed prove that my function is $\leq$ of certain $h(d)$ which goes to zero, even if $f$ is not continuous? I then have to rely on paths... Thank you!
Answer: As mentionned in the comments, the trick with $h$ you have been taught is used to prove continuity, hence is not adapted here to prove discontinuity.
Whatever the function $f$ (continuous or not at $x_0$), you will always find some function $h$ such that $\lim_0h\ne0$ and $|f(x)-f(x_0)|\le h(\|x-x_0\|)$ for $x$ close to $x_0$ (just take $h$ big enough) and that will be of no help.
On the opposite, since your function $f$ here is discontinuous at $(0,0),$ your claim having bounded it and "always obtain some function that goes to $0$" cannot be true. In fact, as explained in the comments, your inequalities $\frac{2x^2|y|}{x^4+y^2} \leq \frac{2x^2y^2}{x^4+y^2} \leq \frac{2x^2y^2}{x^2+y^2}$ were wrong.
However, the "trick whith $h$" can be used to prove discontinuity if you calculate the least upper bound $h$ and prove that this bound does not tend to $0.$ I.e. if you prove that
$$h(R):=\sup_{\|x-x_0\|\le R}|f(x)-f(x_0)|\not\to0\text{ as }R\to0.$$
(This is nothing more than a reformulation of the discontinuity of $f$ at $x_0$.)
For your function $f(r\cos t,r\sin t)=\frac{2r(1-s^2)s}{r^2(1-s^2)^2+s^2}$ where $s=\sin t,$ you will easily find that for $r$ fixed, the maximum of $|f|$ is attained when $|s|=r(1-s^2)$ and is therefore equal to $1.$ So in your example, the lub is the constant function $h(R)=1.$ But this way of proving discontinuity is much more expensive than the usual one with a well-chosen curve, which does not require to compute the lub explicitely.
Incidentally, the same ideas may be used when you want to apply the dominated convergence theorem but you don't know whether there is some integrable dominating function: simply calculate (if possible) the least dominating function, and look if it is integrable or not.
Comment: You can be sure if (useless theorem) and *only if* (unrealistic dream) you studied *all* the (continuous) paths, or equivalently: all the sequences in $\Bbb R^2$ converging to $(0,0).$
Comment: Oh, but the "distance method" is as good as the epsilon-delta for proving continuity! What is not good is the "curves method", which should be used only to prove discontinuity. This was my answer to your "rapid question".
Comment: That was awesome, thank you so much!! I just have a rapid question: suppose I have some $f(x, y)$ such that the limit while approaching the origin trhough different paths (like $y = mx$ or $y = \alpha x^2$ or $x = \sqrt{|y|}$ and so on) is the same (say I studied three different paths).
How can I be sure from this, that $f(x, y)$ is continuous at the origin? I mean, I did not studied "all" the paths...
Comment: Haha ok! Then how are people really sure about those limits?
Comment: Well: not by studying sublimits on curves, but by direct global $\epsilon-\delta$-proofs.
Comment: Then I wonder why our professor taught us the "distance method" instead of the epsilon-delta method, which for what I could understand, it's 101% safe in any case...


How Can Inline IMG SRC data:image Be Transferred With JavaScript to PHP?

Question: Below is an element that contains inline base64 image data (abbreviated to fit here). How can JavaScript get the inline data and send it to PHP? It would be good if an intermediate canvas can be avoided, since the raw data is already available.
In the page:

The JavaScript I'm currently using to click on the  element to trigger the transfer to PHP, which saves a 0 byte .png file to disk:
$("#photo").click(function() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'uploadPhoto.php', true);
  xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  var data = 'image=' + this.src;
  xhr.send(data);
});

uploadPhoto.php, which receives the data and writes it to disk:
<?php
  if ($_POST) {
    define('UPLOAD_DIR', '/photos/');
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
  } else {
    print 'Unable to save ' . $_POST['image'];
  }
?>

What's missing?
SOLUTION UPDATE
Per @EhsanT, the png format of the raw data was not matched in the php, so this line in the php now has png where jpeg used to be:
str_replace('data:image/png;base64,', '', $img);

Comment: Duplicated http://stackoverflow.com/questions/15709515/save-base64-encoded-image-with-ajax-request-in-php
Answer: The only thing you are doing wrong in this particular sample code you have provided is that you have a PNG base64 image data, and in your uploadPhoto.php file you are expecting a JPG file.
So in the uploadPhoto.php file just change this line:
$img = str_replace('data:image/jpeg;base64,', '', $img);

to this:
$img = str_replace('data:image/png;base64,', '', $img);

and you are good to go


Cloning only a subdirectory with Git

Question: I have a Git repository that includes subdirectories. Example dirA/dirB.
Is there a way to do a git clone on a Unix server to pull only files from a subdirectory (dirB)?
Is there some other Git command other than clone that will do this?
How do I Git a specific file?
Comment: http://stackoverflow.com/questions/600079/is-there-any-way-to-clone-a-git-repositorys-sub-directory-only
Comment: [Simple answer here](http://stackoverflow.com/a/2466755/287948)
Comment: Already answered. Updated 2022 answer https://stackoverflow.com/a/73254328/4184651
Answer: Suppose your project is in a dir called project, and you want only those commits which touch project/dirB.
Then:
git clone project/ subproject/
cd subproject
git filter-branch --prune-empty --subdirectory-filter dirB HEAD

subproject will now contain the git history which touches dirB.
Comment: this worked great to grab only the initial sub-directory content, but when I executed a subsequent `pull` it merged with the original branch...
Comment: If you don't want the git history as a whole, add the `--depth 0` flag.
Answer: Cf git-archive(1) Manual Page.
With a shell command:
git archive --remote=<repo_url> <branch> <path> | tar xvf -

Answer: I would like to share a workaround. You can clone the entire repo, and then create a symulink for subdirectory:
mkdir <repo_dir>
cd <repo_dir>
git clone <repo_url>
ln -s <sub_dir> <your_location_where_you_want_to_checkout_sub_dir>

Again, this is not a solution - just a workaround. You will still clone the whole repo, and you can pull the changes only from . However, this was useful in some case of mine.
Answer: It's not really cloning, but if you just want a part of a project to start a new repo with, go into your repo and
git archive master <subdir> | tar -x -C /somewhere/else

Then go /somewhere/else and start a new repo there.
Answer: Git works on the repository level. You will not be able to select only a subdirectory. If the repository that you are interested in has a web interface, you might be able to navigate to your subdirectory and grab it.
Comment: Yes, git works on a repository, however, the desire to have a light checkout is high due to data mobility challenges.
Answer: If you want to clone only parts of your repository, you should look at git submodules.
The subdirectory is managed by a specific git repository and is referenced in the main repository as a submodule.
When you clone the main repository, the submodules are not automatically cloned.
Comment: This does not answer the question. It basically says: "I don't have an answer for your question, so I'll answer another question, because that's what I think you should do instead."
Comment: When you clone the main repository, the submodules are not automatically cloned? why? it absurd:(
Comment: @EduardoBezerra Exactly. I would prefer an answer and then a comment on alternatives. Check Bruno Thomas answer
Comment: `Git sparse` might be a better option. Have a look at this (http://stackoverflow.com/a/13738951/431967) answer.

Cloning only a subdirectory with Git


How to use ngClass on many elements with variable in ts

Question: I have a variable in my ts file that toggles when a button is clicked:
expanded: boolean = false;

  expandStuff() {
    this.expanded = !this.expanded;
    }

I have a few divs that I want this toggle to affect and change the class of the div. So I thought I could use ngClass:
[ngClass]="{'max-stuff' : expanded}"

I added only this to the divs I want to be affected. But I have been unable to get it to work. Literally nothing happens. What am I doing wrong? Do I need to add something else? Is my syntax incorrect?
Comment: Looks okay with the code. Anyway, can you create a Minimal Reproducible Example on [Stackblitz](https://stackblitz.com)? So we can know the structure of your code and the root cause.
Comment: As Yong stated, this should work fine. Probably something else going on. Either create a stackblitz or post more surrounding code.
Comment: I discovered it won't work if I have a style the class would affect set inline already. makes sense really :)
Answer: If it's a root component, have you imported BrowserModule?
If it's a child component, have you imported CommonModule?
As an example
import {BrowserModule} from "@angular/platform-browser"

@NgModule({
    imports: [BrowserModule]
})
export class SomeModule {}


Discover Whether A Program Is Installed From Python3 Script

Question: Within my python3 software I need to check to see if git is installed. I know that from the terminal I can type:
dpkg --get-selections > filename

to find what programs are installed and then put that into a file.
From there, how would I get python to see if git is installed? Or is there an easier way?
Comment: Using the terminal command and putting it into a file doesn't work, as if you uninstall a program the file is still there but just has the word "deinstalled" on the same line instead of "installed".
Comment: To stick with a terminal command but do it a lot easier, you can do: "dpkg -s git". You'll get the package details if it's installed or "Package `git' is not installed and no info is available" if it's not installed.
Answer: You may use the python apt module, but it only checks if the package is installed. It will fail non-deb distributions or if installed outside the package manager:
import apt
cache = apt.Cache()
cache.open()
 cache["git-core"].is_installed# Evaluates true if git is installed

Try to run git and handle the exception if it fails:
import subprocess

try:
    # pipe output to /dev/null for silence
    null = open("/dev/null", "w")
    subprocess.Popen("git", stdout=null, stderr=null)
    null.close()

except OSError:
    print("git not found")

A third option would be to try all the paths in $PATH and test if you have exec permission on path/git.
Comment: If you use `subprocess.DEVNULL` instead of the dev device, this answer works on Windows CPython too.

`git_found = subprocess.call(['git', '--version'], stdout=subprocess.DEVNULL) != 0
`
Answer: Look for installed files
Assuming we know where the application's launcher or binary is installed by default an easy to do approach would be to just check for it's existence like:
#! /usr/bin/env python3
#
# Query package state by installation path

import os.path
path = '/usr/bin/git'

def query_package(path):
    if os.path.exists(path):
        print('Git is ready to use')
    else:
        print('please install Git')

Consult DPKG
Another way to query installed packages however is to consult the package management, in our case dpkg:
#! /usr/bin/env python3
#
# Query package state by dpkg status

import subprocess
package = 'git'

def query_package(package):
    status = subprocess.getstatusoutput("dpkg-query -W -f='${Status}' " + package)
    if not status[0]:
        print(status[1]) # package is installed
    else:
        print(status[1])

Answer: If you wanted to do it that way you could do something like:
checkvar = 0
for line in open("filename"):
    if "git" in line:
        checkvar = checkvar + 1
print "Phrase git found ", checkvar, " times"
Answer: I would take a different approach. In order to check whether Git is available on a given system, either check if the git binary exist in user's PATH, or just try to execute git --version. This check will be more reliable, and it supports people who (for any reason) install Git from source in /usr/local/bin, or even ~/bin.
This is not a direct answer to your question, but I hope it helps anyway. If you need a help in coding that in Python, let me know and I'll provide more details.
Comment: Seems reasonable, but how would I go about getting python to register whether or not git is actually there?
Comment: Try to run it with subprocess.Popen() and handle the exception if it fails. I have updated my answer.
Answer: You could also try checking the output of which.
(Maybe that won't work as no one else has suggested it?)
Comment: `which` is a shell built-in, so you would have to spawn a shell first.
Comment: `/usr/bin/which` isn't a shell built-in, unless I'm mistaken.
Comment: Right, it's a built-in only in Zsh (which I use). Sorry about that.
Answer: TLDR: As of 2022, use the subprocess module (which is awesome)! And here's the onliner:
import subprocess; subprocess.run(["git", "--version"], stdout=subprocess.DEVNULL, check=True)

The subprocess Module:
The subprocess module is the epitome of all reasons why Python is an amazing scripting language! I use it for everything where a Shell script might end up being too unmaintainable & cluttered.
On that note, here's the update code snippet you should be using right now for Python v3.5+:
import subprocess

subprocess.run(["git", "--version"], stdout=subprocess.DEVNULL, check=True)

The subprocess.run() Function is All You'll Ever Need:
Introduced in Python v3.5, the run() function is all you'll ever need to invoke a tool from a Python script. And in addition, it's check parameter will throw a CalledProcessError in case the process(es) exits with a non-zero code. Hence, you can easily check if a tool is installed or simply by passing True to the check parameter of the run() function.


How to make a sound bug on Focal Fossa to be fixed

Question: During the Focal Fossa testing week I found a bug related to internal sound not working on Bay Trail, sound card chtmax98090, I reported it(#1871306).
My communication exchange happened to be only with automated procedures, I provided all the details and reports requested.
After that no communication at all, the status of the bug remains unchanged.
Recently, because of an improvement in alsa-project, I tested a fix for the bug and I added a comment to the bug report to explain it.
What I am expected to do to make the fix evaluated and used to fix the bug?
I noted that on the same architecture/sound card similar bugs have been ignored and they are still open.
Comment: Have you tested the issue occurs in *groovy*, it's more likely to be fixed in later releases unless it's a security flaw, or impacting a lot of users. You're the only person impacted by that bug, so it's unlikely to justify a SRU (*stable release update*) to fix for already *stable* releases such as 20.04/focal.
Comment: As i wrote, I filed the bug before Focal release. And, sorry, I'm not the only one, but just one in the few that filed the issue: the same issue has been filed over time a number of times against different releases.
Answer: It's not about bugs being ignored. It's about limited number of volunteers triaging those bugs.
Fundamentally, what the Kernel developers need to know is:

The priority of the bug. Issues that crash systems and lose data come first.
Which project should be responsible for fixing the bug. If the next release of Alsa has already fixed the bug, Ubuntu won't waste effort re-fixing it.
Where in the kernel code the bug is likely to be located.

To get to that point, bugs must be triaged. When a Kernel Team bug triager looks at the bug report, there are still a lot of questions. The more of these you can answer in the bug report, the more likely the bug will be triaged quickly. If the triager has to do all this research themself, the bug will wait until they feel like doing it (remember: volunteer). If the triager cannot reproduce the problem or lacks the correct hardware, the bug will wait until somebody else comes along.

Does this bug affect lots of people? Does it crash systems or lose data? Or is it merely annoying?

Has the bug been reported upstream (debian, alsa, kernel)? Have they made progress upon it?

Is this new hardware that has never worked? Or did it work in the past (regression)? Can it be duplicated on similar hardware (reproducible)? If a regression, has it been bisected?

Is the proposed fix a mere workaround? Or a real fix? Is the bug really a code problem? Or is it a design problem?

Now let's apply this to the Ubuntu-specific kernel development workflow:
Kernel developers are generally focused on the next release of Ubuntu (20.10). They can backport some features to older kernels...but that's generally unnecessary since most LTS users should be using HWE to get newer kernels.

This means that you should always test the bug in the pre-release version of Ubuntu. If it's not fixed, then it's a valid bug report against the pre-release version of Ubuntu (and more likely to get triaged sooner).

If it is broken in an older kernel, but fixed in a newer kernel, then somebody has already fixed the bug. It's a stable release update request or a backport request. Developers might reject low-priority requests, since that newer (fixed) kernel will show up in the LTS with the next point release anyway.

Release cycle deadlines: Ubuntu 20.10 Kernel Freeze will be in a couple weeks. If it's not fixed by then, you must re-test the bug with 21.04 in November as the Kernel Team moves on to the next pre-release version of Ubuntu.

If you are interested in becoming a volunteer bug triager, we always welcome new participants!
Comment: Thank you for taking the time for your long explanation. Unfortunately it is not answering my question: it's alsa and not an obscure component of the system. The fix is simply bringing in an alsa project GitHub repository as it is, or in other words to update it in Ubuntu. It is not requiring any special effort, the openSUSE devteam did it and contributed to the alsa projectI, I did it yet as a tester with them . I'm going to check 20.10 as you suggest.
Comment: Btw in my opinion it does make no sense to check 20.10: it will last few months by far less than 20.04. Furthermore, yes I'm the only one that filed that bug but out there is plenty of Chromebooks same architecture out of ChromeOS support, all potential Linux machines. If you think that I'm the only one concerned, it's non sense to go ahead: I worked the bug around  on my machine, therefore issue fixed, next problem.
Comment: In my comment I was  neither teaching which is the best workflow nor criticizing anyone, sorry if it sounded arrogant. Ok let's say that I test 20.10 before the release/freeze/whatever and I find the same bug and the same fix works: what's the next step? To file again the bug against 20.10 to provide all the reports? It will be again myself the only one affected, score 6. The testing is done and the fix has been accepted upstream by alsa-project: Arch is using it, openSUSE Tumbleweed is using it, I guess it is in some stage in Debian (unstable or testing).
Comment: it's a set of config files affecting nothing else than the specific sound card I use. Who is the person or the team I need to get in touch with to explain the story after I have filed the bug against 20.10? Can you provide me a link or some directions about where to find the team that maintains alsa or the kernel and how can I get in touch with them? Thank you in advance.
Comment: Just did a quick search:
1. the package that should brings the missing configuration is alsa-ucm-conf
2. alsa-ucm-conf in groovy is version 1.2.2, the same as focal and it is missing the pieces of configuration that are fixing the issue
3. alsa-ucm-conf in Debian Sid is version 1.2.3, which is brignign the configuration files that are fixing the issue

What do you suggest me to do now?

Thank you.
Comment: Wow, that's great! 1. Update the bug header (different package) and edit the description (or add a comment).  2. Jump into IRC #ubuntu-bugs and request triage and help with 3 and 4 below. Be patient - the chatroom's busy hours depend upon where folks live.  3. Your September goal should be merging the 1.2.3 package into Ubuntu 20.10 before Debian Import Freeze.  4. Your November goal should be an SRU to backport the package (or just the files) the 20.04.
Comment: Additional tip: If you browse the Launchpad pages for the [alsa-ucm-conf package,](https://code.launchpad.net/ubuntu/+source/alsa-ucm-conf), you should see your bug in there. But you will also see the folks who touch that package often, and do code commits. Subscribe them to the bug, and reach out to them. Some might be dead-ends, but some might be able to help.
Comment: That's the kind of guidance  I was looking for! Thank you, let's see if I can make it.
Comment: It worked: now the bug has priority "high" and it is assigned.


Order of html title attribute

Question: Anyone else find it a bit weird that tags are placed first in the html title attribute. for example I've seen quite a few start:

6 - Some question here
7 - Another question here

When I have a load of tabs open gathering resources on my macbook I often see tabs with just 6/7 then a few more random tags in them which isn't very helpful.
Can the tags be appended to the title instead of prepended?
Comment: No idea why someone would vote this down, it was a legitimate question...
Comment: On meta sites down-votes mean somebody disagrees with what implied in the question; in this case, somebody disagrees with the necessity of appending the tags to the title, instead of prepending them.
Answer: For SEO purposes, the Stack Exchange engine adds in the most used tag on the question that hasn't already been organically worked into the title. This makes sense for many use cases, and is an automated substitute for "In X, How do I...?"
For example, let's say on Stack Overflow your question was about sorting arrays in PHP. You might title your question How do I sort this array? and tag it php. The question, on Google's SERP, might then appear as php - How do I sort this array? which is more useful, when you're looking for PHP solutions.
Note that you aren't the only one to find it weird and this isn't a Drupal Answers specific problem. See https://gaming.meta.stackexchange.com/questions/2266/allow-tags-to-be-blacklisted-specifically-from-appearing-in-the-html-page-title, a question opened on a different meta site.
Comment: I certainly think we are losing out on using drupal 6/7 as a tag in this case.

Order of html title attribute


How to count total selected files on AjaxFileUpload on change java script

Question: Greetings!!
I am trying to count total numbers of files have been selected or dropped in file dropbox in AjaxFileUpload controller. It shows on number of files in Queue. I need to access the numbers of files in queue. How could I do that. I am trying to write onchange event for AjaxFileUpload but it's not working which works for ASP File Uploder.
It will be helpful if I get the number of files have been selected on AjaxFileUpload change.
Thanks
Comment: In code behind....I want to get the count of all images in the queue waiting to be uploaded....protected void ajaxUploadImage_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
Comment: @john wat actually you need on upload complete
Comment: @Sultan can you share the code that you tried. so we can get clear idea what are you trying to do !
Answer: You can count number of file uploaded successfully from JavaScript by using OnClientUploadComplete event. Please check below:
AjaxFileUpload Code:
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" OnClientUploadComplete="uploadcomplete" OnUploadComplete="AjaxFileUpload1_UploadComplete" Mode="Auto" runat="server" />

JavaScript Ccode:

For more details about this, please check AJAX Control Toolkit Tutorial: AjaxFileUpload.
Answer: As for my understanding:
AjaxFileUpload.js library doesn't support multiple uploads by itself. So you have to implement the multi-file upload by yourself. There are others libraries that support multiple files upload out of the box: Fine Uploader 5 seen to be a nice one.
If you need to use AjaxFileUpload you can follow this stackoverflow question that is related of what you want to do upload multiple files with ajaxFileUpload with different file ids
. Then you can add a counter for as many times as you call the function.
Answer: you can use "UploadComplete"  event to do this
   protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
                {
                   HttpFileCollection uploads = HttpContext.Current.Request.Files;
                    int NoOfFiles = uploads.Count
    }


Is there any way to check if a player drank a specific potion?

Question: I tried something like this:
scoreboard objectives add potion minecraft.used:minecraft.potion 0
But that went up every time I drank any type of potion. And this isn't a command:
scoreboard objectives add potion potion{CustomPotionEffects:[{Id:1b,Amplifier:0b,Duration:2400}]} 0
So I would like some help with this.
Answer: You can use the minecraft.used:minecraft.potion criteria in combination with a tag to do this. The criteria would be used to detect when the player drinks a potion and the tag would serve as an indicator that the player is holding the correct potion.
I put together a simple example of this concept. Just create this scoreboard objective:
/scoreboard objectives add potion minecraft.used:minecraft.potion

and paste the following commands into a chain of command blocks (repeating command block and some chain command blocks attached to it).
/tag @a[nbt={SelectedItem:{id:"minecraft:potion",tag:{CustomPotionEffects:[{Id:1b,Amplifier:0b,Duration:2400}]}}},tag=!correctPotion] add correctPotion
/execute as @a[scores={potion=1..},tag=correctPotion] run say drank healing potion
/tag @a[nbt=!{SelectedItem:{id:"minecraft:potion",tag:{CustomPotionEffects:[{Id:1b,Amplifier:0b,Duration:2400}]}}},tag=correctPotion] remove correctPotion
/scoreboard players reset @a[scores={potion=1..}] potion

Just replace the NBT data in SelectedItem with the data your potion has. I used the example you provided in your post.


"Password for root" prompt on a sudoer

Question: On an Ubuntu 14.04 LTS system, I get a prompt of "Password for root" when logged in as a remote directory user (sssd). My user account is configured as a sudoer, both directly and via a group (from the directory):
fred:~$ sudo egrep -v '^(#|$)' /etc/sudoers
[sudo] password for brett:
...
%sudoers    ALL=(ALL) ALL
fred        ALL=(ALL) ALL
fred:~$ getent group | grep sudoers
sudoers:*:00000000:joe,fred,peter
fred:~$ getent passwd | grep fred
fred:*:00000:11111111:Fred:/home/fred

Both passwd and group come from the directory (kerberos). I am able to sudo in console, but the UI prompts for root passwd (root has no password, which I'd like to keep that way) - on other systems, I've always been prompted for my own password, for sudo things in the background.
gksu was previously not installed, not sure if this is required, but have installed it and am still getting the same thing.
Is is possible to configure GUI to prompt for current user password instead of root password if current user is a sudoer?
edit 1
It seems that polkit is also involved in this. I tried changing the "sudoers" group name in the remote directory to "sudo", but not sure if having 2 groups with the same name but different ids is a great idea. I've added sudoers group to AdminIdentities by editing /etc/polkit-1/localauthority.conf.d/51-ubuntu-admin.conf. There was no immediate success, but am rebooting now to see if it fixes it.
Answer: Add a user as a sudoer is not enough for the GUI - the user / group also needs to be configured as an admin in polkit. For example, if you want to allow all members of the non-standard / custom sudocustom group to run sudo graphically, assuming they're configured as sudoers, you could modify /etc/polkit-1/localauthority.conf.d/51-ubuntu-admin.conf from:
AdminIdentities=unix-group:sudo;unix-group:admin

to
AdminIdentities=unix-group:sudo;unix-group:admin;unix-group:sudocustom

This should give you a selection of users from the list of groups to elevate as (i.e. all members of sudo, admin and sudoers above).

"Password for root" prompt on a sudoer


What is 'one turn' in Bravely Default?

Question: I know the how Brave and Default work. But something I have not quite paid attention to is what spells like Free Lunch that 'Make MP cost 0 for "two turns"' ACTUALLY mean.
If I Brave 3 times (so when I am up, I do 4 attacks) is that "four turns" so my fourth attack will cost normal MP?
Turn 1: (Free Lunch, Free Summon, Free Summon, 40 MP Summon)

Or is that "one turn" and the next time I get to go I have four more free spells again?
Turn 1: (Free Lunch, Free Summon x3) Turn 2: (Free Summon x4)

Or is it the more complicated, All effects for that turn pretend you are on your first turn and but since I actually spent 3 extra turns I am now down to total turns affected - 4 uses.
Turn 1: (Free Lunch, Free Summon x3) Turn '5': (40 MP Summon)

Answer: A turn is when you input your attacks/spells.
When you have negative BP you skip your turn for that character.
Eg:
turn 1:
Edea with 3bp free lunch and summon x3 free
Tiz with 1bp free lunch and summon x3 free
Ringabel with 3bp free lunch and summon x1 free

turn 2:
Edea with 0bp summon x4 free
Tiz with -1 no action
Ringabel with 2bp summon x1 free

turn 3:
Edea -2bp no action
Tiz with 0bp summon x4 not free
Ringabel with 2bp summon x1 not free

Answer: Brave lets you move multiple times in a turn.
If you do x4 Brave, you get to move 4 times in one turn, so:
Free Lunch -> Amp Strike -> Amp Strike -> Amp Strike
Will let you do x3 Amp Strike at 0 MP cost (even though Amp Strike is red, you have to select them manually).
If you can somehow move again the next turn, Free Lunch's effect would probably still be in effect.
For spells/abilities that don't have high costs like Amp Strike, you're probably better off just paying for the ability once and then using Mimic 3 times. This way you get to use it 4 times in a row, not have to Brave into -4 to get the most use out of Free Lunch.
Note: Mimic doesn't work for Specials, Rage, and Friend Summons.
Comment: !! Mimic works multiple times in a row?! I just discovered it I thought it only copied a real move once. (To do the same move 4 times you have to spend the price twice instead of four times.) The more you know.

What is 'one turn' in Bravely Default?


Create new Pandas columns based on conditional counts of all other columns

Question: I have a Pandas data frame with around ~360 columns.
I want to add another column to the other frame based on the count of whether in rest of the columns how many columns have a value greater than 0. Type of all my columns is float 64.
If this is my original dataframe
column A column B column C ...............Column Z
0          1.5      6.77                   3.33
3.5        4.5      0                       0
0           0       0.98                    0
.
.
.
2.35      4.32       0                      9.21

I want to add a column to it like this which have count of all non zero columns for each row:
column A column B column C ...............Column Z  Column New
0          1.5      6.77                   3.33        3
3.5        4.5      0                       0          2
0           0       0.98                    0          1
.                                                      .
.                                                      .
.                                                      .
2.35      4.32       0                      9.21       3

How can i add a column like this?
I was trying this but getting all NaNs.
df['column_new']=df.apply(lambda x: (x > 0).count())

Not sure if this is the correct way approach this.
Just to give an idea this is how values in my original data frame are like. So i want a count of columns in the new column which don`t have zero value.
Answer: You're on the right track. The comparison to zero returns series of bools, so you can sum rather than count. You also don't need to apply this since you can compare the entire dataframe and then sum along the correct axis:
df = df.assign(count_gt_zero=(df > 0).sum(axis='columns'))

Answer: Another option with gt:
df['new_column'] = df.gt(0, axis=1).sum(axis=1)


Find the n that is a positive integer makes the equation have a positive integer solution, if it has no solution, please prove it.

Question: $$\begin{cases}\frac{x}{6n}\in N\\
\frac{81n^5-n}{8x}\in N\end{cases},\frac{x}{6n}<\frac{81n^5-n}{8x},x,n∈N$$
I try to let $x=6nk$ ,then $\frac{81n^5-n}{8x}=\frac{81n^4-1}{48k}$,and
I think I can try to solve$\frac{81n^4-1}{48}∈N$ first, but I don't know what should I do next.
Comment: Welcome to Math.SE! ... The community prefers/expects a question to include something of what the asker knows about the problem. (*What have you tried? Where did you get stuck?* etc) This helps answerers tailor their responses to best serve you, without wasting time (theirs or yours) explaining things you already understand or using techniques beyond your skill level. (It also helps convince people that you aren't simply trying to get them to do your homework for you. An isolated problem statement with no evidence of personal effort makes a poor impression, attracting down- and close-votes.)
Comment: Hint: try denote integer quantities as $k$ and $l$ and compose equation for $n$ in terms of $k$ and $l$.
Answer: There must exist $R,S \in \Bbb{Z^+}$ such that

$x = 6nR$
$81n^5 - n = 8xS = 8(6nR)S$
$R < S$.

However, since you are given that $n$ must be a positive integer, you can assume that $n \neq 0.$  Therefore, you can divide the 2nd constraint above by $n$.
This implies that
$$81n^4 - 1 = 48RS. \tag1 $$
However, (1) above is impossible to satisfy, because the LHS is congruent to $-1 \pmod{3}$ and the RHS is congruent to $0 \pmod{3}.$
Answer: first, $81n^4-1$ can be written as $(3n-1)(3n+1)(9n^2+1)$ , and obviously,
three of them are not divisible by $3$, so $\frac{81n^4-1}{48}$ won't be a positive
integer.From the above, you can know for all k is a positive integer, $\frac{81n^4-1}{48k}$ won't be a positive integer, and no doubt, $\frac{x}{6n}$ won't be a positive
integer too.


Markov chains - Why is this a distribution?

Question: I read about markov chains here : https://www.cs.princeton.edu/courses/archive/fall05/cos521/markov.pdf .
There was something I didn't understand at the beginning of page 6,
the last inequality, with the $A_iE_i$ and $L_2$ norm.
From what I understand, they mean that $x - v_1 (\frac{1}{n})$ (where $v_1 $is the $(1,1,...,1)$ vector), is a distribution.  But how come? $x$ is a distribution and we deduct a vector whose coordinates sum to $1$.
Why is $x - v_1(\frac{1}{n})$ (or sum of  $A_iE_i$ from $i=2$ to $n$) , a distribution?
Answer: Since $x$ is a distribution, $Mx$ is too, since $M$ is a transition matrix.
Note that its stationary distribution is $s=(1/n)\vec{1}$. But $s$ is the first eigenvector of $M$ (by definition of stationary distribution given), with eigenvalue $1$ (so $Ms=s$). In other words $e_1=s$ and since the eigenvectors form a complete system, you can write:
$$
x = \sum_{i=1}^n \alpha_i e_i = s + \sum_{i=2}^n \alpha_i e_i
$$
using the observation (in the notes) that $\alpha_1=1$.
Now:
$$
Mx = M\left(s+\sum_{i=2}^n \alpha_i e_i\right)=
Ms+\sum_{i=2}^n \alpha_i M e_i
= s+\sum_{i=2}^n \alpha_i \lambda_i e_i
$$
is a distribution (since $Mx$ is one). So $M^tx$ is also one.
Repeatedly applying our rule above gives:
$$
M^tx = s + \sum_{i=2}^n \alpha_i \lambda_i^t e_i
$$
The author is interested in how fast $ M^tx $ converges to $s$. So he looks at and bounds
$$
||M^tx - s||_2 = ||s + \sum_{i=2}^n \alpha_i \lambda_i^t e_i - s||_2
= ||\sum_{i=2}^n \alpha_i \lambda_i^t e_i||_2
$$
which is the $\ell_2$ distance of the distribution $M^tx$ from $s$, for some $t$.
The quantity in the norm is not a distribution; rather, it is the distance between two discrete distributions.

Edit: it seems the asker's actual question is why
$||\sum_{i=2}^n \alpha_i e_i||_2 \leq 1$. I'll show that now:
\begin{align}
|| \sum_{i=2}^n \alpha_i e_i  ||_2^2
&=
||x - s||_2^2 \\
&=
\sum_i \left( x_i - \frac{1}{n} \right)^2 \\
&=
\sum_i x_i^2 - \frac{2x_i}{n} +\frac{1}{n^2}\\
&=
||x_i||_2^2 - \frac{2}{n}\sum_i x_i +\frac{1}{n}\\
&=
||x_i||_2^2 - \frac{1}{n}\\
&\leq
||x_i||_1^2 - \frac{1}{n}\\
&\leq
1 - \frac{1}{n}\\
&\leq 1
\end{align}
Comment: What I don't understand, is why the norm : $||\sum_{i=2}^n \alpha_i  e_i||_2$ less than / equal to 1. Suppose we have 2 vectors $(1,0,...,0)$ , $(0,1,...,0)$. Both are distributions but their L2 norm is the root of 2, which is larger than 1...
Comment: @Bar What do you mean? If $a_i(j)=\delta_{ij}$ is the unit vector with all zeroes except a 1 at the $i$ position, then $||a_i||_2=1$. $||a_i + a_k||_2=\sqrt{2}$ though. But in any case where is it claimed that $|| \sum_{i=2}^n\alpha_ie_i || \leq 1$? What is claimed/used is that $||x||_2 \leq ||x||_1=1$.
Comment: @Bar I think I understood your question; see the edits above.
Comment: Yes, that was it, thanks!


How to switch two rows in a matrix in scheme or haskell?

Question: I was trying to do this after I did the transpose  of a matrix using the map function but still can't figure out how to swap two rows in a matrix.
I'm a beginner in functional programming and trying to learn.
This is my code for transpose :
transpose ::[[Int]]->[[Int]]
transpose([]:_)=[]
transpose x = ((map head x):(transpose (map tail x)))

And I want to do something similiar to this:
Switch/swap two rows of a matrix
[[1,2,3]         [[4,5,6]
 [4,5,6]    =>    [1,2,3]
 [7,8,9]]         [7,8,9]]

Comment: You might wanna spend a couple more minutes to clarify your question; As it stands it's not very clear what exactly you're trying to do (of course it has something to do with matrices, but for example you didn't even mention how you define a matrix - and I'd be very interested to see how you defined transpose with map, that sounds kinda odd - transpose is a structural operation, wheras map only exposes contained values).
Comment: Welcome to StackOverflow. What have you tried so far? Please post some code from your best attempt. This will make your question a better fit for the site and you will be likely to get better answers in return.
Comment: i edited the question and included an example of what i want and code from transpose
Comment: You should definitely use the approach in mhwombat's answer, but another option would be to multiply by the appropriate [elementary matrix](http://en.wikipedia.org/wiki/Elementary_matrix).
Answer: Ah, you're making it more complicated than it needs to be. I'm going to assume you always want to swap the first two rows. How would you do it if it were a simple list, e.g....
[a, b, c, d]    => [b, a, c, d]

You'd probably write something like this:
swapFirstTwo (a:b:xs) = b:a:xs
swapFirstTwo xs = xs           -- if there are <2 elements

If we load this into GHCi, we can ask what the type signature of swapFirstTwo is.
λ> :t swapFirstTwo
swapFirstTwo :: [a] -> [a]

So swapFirstTwo can take a list of anything. Can it handle a list of lists?
λ> swapFirstTwo [[1,2,3], [4,5,6], [7,8,9]]
[[4,5,6],[1,2,3],[7,8,9]]

Yes it can!


$\sum_\limits{n=1}^{\infty}\frac{1}{n!x^n}$ and $\sum_\limits{n=1}^{\infty}\frac{1}{(2n-1)x^n}$ different convergence domains?

Question:
Exercise: Find the convergence domain of the series$\sum_\limits{n=1}^{\infty}\frac{1}{n!x^n}$ and $\sum_\limits{n=1}^{\infty}\frac{1}{(2n-1)x^n}$.

First series:
$\sum_\limits{n=1}^{\infty}\frac{1}{n!x^n}\leqslant\sum_\limits{n=1}^{\infty}\frac{1}{x^n}$ and now employing the Cauchy integral test:
$\int_\limits{1}^{\infty}\frac{1}{x^n}dn=\frac{1}{x\log(x)}$
So the series converge absolutely for $x\neq 0$.
Solution(book):"series converge absolutely for $x\neq 0$"
Second series:
$\sum_\limits{n=1}^{\infty}\frac{1}{(2n-1)x^n}\leqslant\sum_\limits{n=1}^{\infty}\frac{1}{x^n}$ since $2n-1>1$. So the series should converge absoulutely on $x\neq 0$.
Solution(book): $x>1\:\:,\:\:x\leqslant -1$.
Question:
Why does the solutions different? Am I doing something wrong?
Answer: Your approach to first series is wrong. Simply apply the quotient test and you'll see that it converges always. Your approach could not possibly work because $\sum_{n=1}^\infty\frac1{x^n}$ only converges when $|x|>1$.
Applying the quotiente test to the second series, you'll see that it converges if $|x|>1$ and that diverges if $|x|<1$. Finally, if $x=1$ it diverges (like the harmonic series) and if $x=-1$ it converges, by the Leibniz test.


Contact listener error

Question: When I use this code, I'm getting error.and the error line is which one is with "if". why?
<code>     private ContactListener contactListener()
    {
        ContactListener contactListener = new ContactListener()
        {
            @Override
            public void beginContact(Contact contact)
            {
                final Fixture x1 = contact.getFixtureA();
                final Fixture x2 = contact.getFixtureB();
                if(x1.getBody().getUserData().equals("player"))
                {

                }
           }

            @Override
            public void endContact(Contact contact)
            {
            }
         };
         return contactListener;
    }
</code>
Error
Comment: What error you occurred ?
Comment: http://s24.postimg.org/tdl4kqgp1/Capture.png
Answer: Try this -
<code>if (x1.getBody().getUserData()!=null && x1.getBody().getUserData().equals("player") ||
        x2.getBody().getUserData()!=null && x2.getBody().getUserData().equals("player"))
</code>

Contact listener error


Parsing XML with PowerShell with date comparison

Question: Could you please help me to debug my code.
I'm using a Powershell script to parse a large amount of XML files from one folder and create a monitoring report, to review who's modifying the XML and when.
So, the problem is in moment, when I try to compare date of the XML file modified and today's date ($filterDate).
Initially I've got a folder full of XML files and I need to get from inside of these files date modified, user, and name of file. I added example of XML code.
Right now, the part with Where-Object {$_.TimeModified.Date -GE $filterDate} didn't work with -GE, but if i try to put it -LE, it show me output from all files.
Example XML
<ModullarRule schema="3.2" id="2132135e" entrypoint="12321321321313ce2" design="118;51">
    <Name>AnyShit2Queue</Name>
    <Description/>
    <Comments/>
    <RuleAudit stamp="2132131237" version="firstname.lastname@example.com">
        <SrvModified date="2018.11.29 09:35:11" user="User1"/>
        <XmlModified date="2017.12.05 17:13:49" user="User2"/>
        <SrvCreated date="2017.12.05 10:07:36" user="User2"/>
        <XmlCreated date="2017.12.05 10:07:36" user="User2"/>
    </RuleAudit>
</ModullarRule>

I'm trying to take the <SrvModified> part from the XML.
$Path = "C:\Test"
$filterDate = Get-Date -format "yyyy.MM.dd hh:mm:ss"

Get-ChildItem -Path $Path -Filter '*.xml' -File -Recurse | ForEach-Object {
    [xml]$xml = Get-Content -Path $_.FullName | Where-Object {
        $_.TimeModified.Date -LE $filterDate
    }
    foreach ($item in $xml.ModullarRule.RuleAudit.SrvModified) {
        $Xml.ModullarRule.RuleAudit.SrvModified | Select date, user
    }
}

Thanks!
Comment: A time in the past is less than a time in the future. Since `$filterdate` is the time when the code runs, then any date in the past will be less than that.
Comment: When i use $filterDate like  $filterDate = (Get-Date).AddDays(-2).Date, i got same error. I need to convert it to format of TimeModified at first?
Comment: When doing comparisons of unlike types, the LHS (left-hand side) dictates the object types being compared. Since you did not cast either side, the `$_.TimeModified.Date` is considered a string and makes `$filterdate` a string as well. You need to cast it like `[datetime]$_.TimeModified.Date`.
Comment: What is `.TimeModified.Date` supposed to be anyway? None of the objects you are dealing with even has this property, as far as I can see.
Comment: I hope .TimeModified.Date it is last time what this file was modified, what you can see in file properties in Windows. Found it somethere in internet btw
Answer: As best as I have interpreted your question, you want to select @date and @user attributes of all <SrvModified> where the @date is greater than a given reference date, for example "two days ago", in all XML files in the target folder.
One could do it using Where-Object:
$path = "C:\Test"
$refDate = (Get-Date).AddDays(-2).ToString('yyyy.MM.dd HH:mm:ss')

Get-ChildItem -Path $Path -Filter '*.xml' -File -Recurse | ForEach-Object {
    $xmlPath = $_.FullName

    $xml = New-Object xml
    $xml.Load($xmlPath)

    $xml.ModullarRule.RuleAudit.SrvModified |
        Where-Object date -gt $refDate |
        Select-Object date, user, @{name="file"; expr={$xmlPath}}
}

Comment: So problem was that I initially decided not to compare with the value inside the xml, but took "modified date" from windows
Comment: Not really, because the modified date in Windows is called `.LastWriteTime`, not `.TimeModified`. Chances are that you compared against `null` because you accessed a property that does not exist.


Eclipse : Target "Unknown" in android device chooser

Question: I am using Samsung Galaxy SIV. When I try to select it in the 'Android device chooser', Eclipse recognize as a Samsung  Galaxy SIV but in target it does not recognize. It says target "unknown". Because of this problem, I can't choose the phone as the Android device.
How can I get Eclipse to recognize the target ?
Comment: Which OS u are using?
Comment: i am using windows 8.
Comment: You should install driver for that device. Did you?
Comment: did you enable debugging options in your phone?
Comment: well, i restarted phone and laptop and it works fine now. i dont know where it went wrong first.
Comment: Rebooting the phone worked for me
Answer: For Completeness: (Windows)
1) Enable USB debugging on your device.
On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development.
On Android 4.0 and newer, it's in Settings > Developer options.
Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.
2) Restart your Phone
When you have done this, still there will be "unknown" listed under target, from here, just restart your phone and as soon it is started, it will ask if you want to use this pc for debugging.
Answer: The first time your PC tries to connect with your device (after set up OEM USB driver), your device will ask if trust this pc or portal whatever. Make sure your answer yes on your device
Answer: In Eclipse, first check your project property. Go to ANDROID tab -> select proper target.
Second in your AndroidManifest.xml file change the "android:minSdkVersion" & "android:targetSdkVersion" to what your android phone supports.
Answer: For any future onlookers of this issue, I found that I needed to uncheck the debugger option and recheck it. After doing that, the popup showed for trusting my computer. I said always trust and hit okay and everything worked.


How to display large array of objects as a HTML table in a React app

Question: My task is to display array of objects as a table in my React app with some basic filters(date before/after etc..). Object has 5-6 fields(gender, email, status, date..). I don't want to render all objects at once, rather I want to create a virtualised table which displays 20-30 items at once and upon scrolling will display the next 20-30 items. I researched a lot about this and I found React-Virtualised, React-Table, React-Window to achieve this task.
What I don't understand is some examples suggest using React-table with react-window and some suggest React-Virtualised or react-window alone. And also React-Virtualised and React-window is built for lists and grids. But I want a table. I'm quite confused since last night as in which library is the right one for my use-case. Help me understand please.
Answer: I don't think you should immediately look for a library to do this for you.
You can easily do it yourself by for example putting 30 elements in a table and adding a scroll handler to the table element.
Then when the user has scrolled to the bottom, you just load more elements in.
If you want to make it even more efficient and advanced, you can re-use the 30 elements you've already created.
Comment: Thanks for the suggestion. But I can't afford so much time right now, so I'm looking for a quick solution to this. If you know any library please let me know


Find the subspace $S$ to maximize the function $J=\frac{Tr(P_{S}A)}{Tr(P_{S}B)}$

Question: Let $A$ and $B$ be two synmetric matrices, $B$ is positive and $A$ is non-negtive. Surpose a $k$ dimentional space $S\subset R^{n}$ , and let $P_S$ be its orthogonal projection matrix.
QUESTION: Find the subspace $S$ to maximize the function $J=\frac{Tr(P_{S}A)}{Tr(P_{S}B)}$
PS: Let $\lambda _1 \ge\lambda_2 \ge \cdots \ge \lambda _n $ be the generalized eigenvalues of $(A,B)$, and $p_1, p_2, \cdots ,p_n$ are the coresponding eigenvectors. I guess the space $span\{p_1,p_2, \cdots , p_k\}$ is the solution. But I cannot prove it.
Answer: A very partial answer. Of course, those who placed "on hold" your question on MO know the answer (at least, I hope so...).
Up to an orthonormal change of basis, $P_S=diag(I_k,0_{n-k}),A=\begin{pmatrix}K&L\\M&N\end{pmatrix}$; then $tr(P_SA)=tr(K)=\sum_{i=1}^ke_i^TAe_i$, where $(e_i)_i$ is the (orthonormal) canonical basis. Then $\sup_S\dfrac{tr(P_SA)}{tr(P_SB)}=\sup_{S}\dfrac{\sum_{i=1}^ku_i^TAu_i}{\sum_{i=1}^ku_i^TBu_i}$, where $(u_i)_i$ is an orthonormal basis of $S$.
If $k=1$, then $\sup_S\dfrac{tr(P_SA)}{tr(P_SB)}=\sup_{u\not=0}\dfrac{u^TAu}{u^TBu}=\lambda_1$ is reached when $u=p_1$.
If $k\geq 2$, then it is not clear because the $(p_i)_i$ are not orthogonal vectors.
Comment: This is my first time to ask a question onSE and you are the first one who answer my question. Thank you very much.


To convert month name into month number using CONVERT() in sql

Question: I know this is a repeated question but i couln't find answer to my problem.
I am trying to get 03-FEB-2014 as 03-02-2014 .I am using below query:
SELECT CONVERT(date,CREATED,105) from dbstatus

but its throwing following error:
Error starting at line 1 in command:
SELECT CONVERT(date,CREATED,105) from dbstatus
Error at Command Line:1 Column:15
Error report:
SQL Error: ORA-00936: missing expression
00936. 00000 -  "missing expression"
*Cause:
*Action:

"CREATED" is name of a column having dates as 03-FEB-2014
Comment: `CONVERT(date,CREATED,105)` would be the usage for T-SQL not MySQL
Comment: CONVERT() provides a way to convert data between different character sets. You will not achieve what you want with it.
Comment: I don't think convert does what you think it does...
Comment: try this `SELECT CONVERT(VARCHAR(10), GETDATE(), 110) AS [MM-DD-YYYY]`
Answer: First select to_date(date_column,'YYYY-MM-DD') then apply to_char(date_column,'YYYY-MM-DD')
--03-FEB-2014 as 03-02-2014
select to_char( to_date(sysdate,'dd-mon-yyyy'),'dd-mm-yyyy') from dual;

Comment: Thanks a lot.simple yet effective
Answer: Don't use convert. Convert it used for converting between character sets.
Instead use MONTHNAME for what you want: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_monthname
EDIT: Actually, I think what you're trying to do is turn FEB into 02. If that is the case you can use this to do so:
month(str_to_date('Feb','%b'))
This will return 2 which you can then CONCAT into your date.


Have to take ownership of USB port after each reboot

Question: I have a laser engraver. I was having issues getting Ubuntu to talk to it via USB.  I finally sorted that out, but now when I reboot, I have to run the command below every time, or I can't talk to the engraver.  What am I missing so it will stay permanently?  Thanks.
sudo chown [username] ttyUSB0

Comment: Does this answer your question? [How do I allow non-root access to /ttyUSB0?](https://askubuntu.com/a/133244/66509) .
Comment: To correct method is to add yourself to the group of ttyUSB0.
Answer: ttyUSB is a serial connection. It should be available. You might have to change the user rights:
sudo adduser <user> dialout

where your username should replace "< user >"


Use exploded variable in query without having to loop

Question: How can I run a query with multiple where clauses depending on an exploded variable (array)?
$original = "123,44,55,66";
$exploded = explode(",", $original);
foreach($exploded as $var)
{
    $query = $mysqli->query("SELECT name FROM my_table WHERE id = $var");
}

I don't want to use a foreach loop for the query itself because it uses a lot of resources and slows the loading time for the page by a lot, so how can this be accomplished?
Answer: You can check by in query so you will get result without foreach loop
Query:
$mysqli->query("SELECT name FROM my_table WHERE id in (123,44,55,66) ");

Answer: As per your code, every time your query gets overwrite and thus you'll get the last selected data. You can get the result by using IN operator.
Instead, try this :-
$original = "123,44,55,66";
$query = $mysqli->query("SELECT name FROM my_table WHERE id in ($original)");


jQuery: Checking for disabled attribute and adding/removing it?

Question: I select all input elements of a form like this:
var fields = $( form + " :input" ).not( "button" );

How do I check if any of these inputs has the disabled attribute set and remove it when present?
Also, I need to add it after is has been removed (and serialize the fields in between), is there an elegant way for this? Something like toggle but for attributes?
Answer: Assuming you are using jQuery 1.6 or above, the suggested method is to use .prop().
fields.prop("disabled", false);
If you need to have logic around each one, you could do something to the extent of
var fields = $( form + " :input" ).not( "button" );
fields.each(function(index, element) {
    var isDisabled = $(element).is(':disabled');
    if (isDisabled) {
        $(element).prop('disabled', false);
    } else {
        // Handle input is not disabled
    }
});

jsfiddle
Answer: You can use the disabled selector
$('input:disabled').attr('disabled', '');

See here
http://jsfiddle.net/JngR9/
Answer: use :disabled Selector`
try this
$('input:disabled').remove();

Answer: To Remove
$('input:disabled').removeProp('disabled');

or
$('input:disabled').prop('disabled', 'disabled');

To Add
$('input:disabled').prop('disabled', 'disabled');


How to restart listening Twitter straming Api Again?

Question: I'm using Twitter4j to get Tweets real time via. Twitter streaming API and it is working fine . Sometime it throws Exception due to network connecting issue(or some other reason) which is also OK to me however I'm not able to recover from this condition & it require server restart . Can someone please suggest how to restart  listening Twitter straming Api Again without server restart . We have TwitterStreamFactory & TwitterStream class in Twitter4j. Many thanks in advance .
Answer: You should create a handler for such exceptions and in it create a loop that tries to start listening a few times before erroring out.


drop duplicates by value in csv python

Question: I want to delete rows that have the same value (duplicate values) in specific column.
For example - I have the next df:
name, number, if_unique
1. name1, number1, unique
2. name2, number2, unique
3. name3, number3, not_unique

after removing duplicated by specific column (if_unique) the result will be:
3. name3, number 3, not_uniqe

I have tried so far:
df.drop_duplicates('git_url', keep=False)

Edit:
this line worked for me -
df.drop_duplicates(subset="if_unique", keep=False, inplace=True)

Comment: Does this answer your question? [drop\_duplicates not working in pandas?](https://stackoverflow.com/questions/46489695/drop-duplicates-not-working-in-pandas)
Comment: `df.drop_duplicates('if_unique',keep=False)`
Comment: tried it, didn't work :(
Comment: Please provide a small workable example with your desired output, instead of abstract variables. If you want to delete all duplicates, it should work without the ```keep=False``` argument.
Comment: Did you want to do that `inplace=True`?
Comment: I want to remove both first and second  line (duplicates)
Answer: This worked for me:
df.drop_duplicates(subset="if_unique", keep=False, inplace=True)

drop duplicates by value in csv python


How can I deal with repeat teamkillers in BFBC2 Hardcore mode on PS3?

Question: I've experienced that killing people in the own team becomes more and more common. Sometimes it's because they want to have the vehicle you're taking, sometimes I guess just for fun (I've even seen someone named "Teamkiller...") or as a revenge for being (possibly unintentionally) team-killed.
This is no fun at all and can turn the whole game around.
Losing a few points and having team kills in your record doesn't seem to scare many people off. For example, experienced players can easily compensate for -100 points for shooting a team mate before entering a helicopter, by then taking that helicopter and destroying tanks.
How can I remove teamkillers that are ruining a game from Battlefield Bad Company 2 Hardcore games?  How can I keep them from coming back?
Answer: This might be harsh but you can get TK'ers PSN accounts blocked
Comment: Although I'd prefer some automatic mechanism, that's good to know - thanks!
Comment: No, that's not possible. PSN accounts can't be blocked for gameplay (or lack thereof)


WPF Animation execute twice

Question: I faced an issue regarding the Animation execute twice, please check the code:

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>

        <ListView x:Name="lstHandled" Grid.Column="0" Visibility="Visible">
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListViewItem>Jimmy</ListViewItem>
            <ListView.Triggers>
                <EventTrigger RoutedEvent="ListView.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard>
                            <ThicknessAnimation
                                Storyboard.TargetName="spAll"
                                Storyboard.TargetProperty="(StackPanel.Margin)"
                                From="-100,0,0,0" To="0,0,0,0"
                                AutoReverse="False"
                                Duration="0:0:1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </ListView.Triggers>
        </ListView>

        <StackPanel x:Name="spAll" Grid.Column="0" Width="100" Margin="-100,0,0,0" Orientation="Horizontal">
            <ListView x:Name="Handled">
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
                <ListViewItem>Hello</ListViewItem>
            </ListView>
            <ListView x:Name="UnHandled">
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
                <ListViewItem>World</ListViewItem>
            </ListView>
            <StackPanel.Triggers>
                <EventTrigger RoutedEvent="StackPanel.MouseLeave">
                    <BeginStoryboard>
                        <Storyboard>
                            <ThicknessAnimation
                                Storyboard.TargetName="spAll"
                                Storyboard.TargetProperty="(StackPanel.Margin)"
                                From="0,0,0,0" To="-100,0,0,0"
                                AutoReverse="False"
                                Duration="0:0:1"/>

                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </StackPanel.Triggers>
        </StackPanel>
    </Grid>

When the mouse leave the "spAll" StackPanel. It fired the Mouse Enter event for the ListView. How to avoid this issue?
Thanks a lot!
Answer: They are both in the same grid column so they overlap and thus the enter/leave events :) Separate them in the UI.

WPF Animation execute twice


Google Map Navigation in Flutter

Question: I'm new to flutter.
I found Flutter doesn't support inline map, only a static map view.
I wanted to build an app which I need to show the driving directions on the map.
Is it possible to create the same in flutter?
Answer: you can use android_intent library in flutter for starting googlemaps and get diection in android.
library : https://pub.dartlang.org/packages/android_intent
and in ios you can use both google api like comgooglemaps or google map url {i choose this one} and maps.apple.com.
String origin="somestartLocationStringAddress or lat,long";  // lat,long like 123.34,68.56
String destination="someEndLocationStringAddress or lat,long";
if (new LocalPlatform().isAndroid) {
      final AndroidIntent intent = new AndroidIntent(
          action: 'action_view',
          data: Uri.encodeFull(
              "https://www.google.com/maps/dir/?api=1&origin=" +
                  origin + "&destination=" + destination + "&travelmode=driving&dir_action=navigate"),
          package: 'com.google.android.apps.maps');
      intent.launch();
    }
    else {
        String url = "https://www.google.com/maps/dir/?api=1&origin=" + origin + "&destination=" + destination + "&travelmode=driving&dir_action=navigate";
        if (await canLaunch(url)) {
              await launch(url);
       } else {
            throw 'Could not launch $url';
       }
    }

i hope it helps.
Comment: OP asked he wants to build an app which shows direction, your answer just opens Google Maps app with navigation.
Comment: Maybe not exactly what they asked, but the native view as far as I can tell won't navigate to a point so I will give you an upvote.  Useful information
Comment: thanks my friend :D , it was the just way which solved my problem :/
Comment: The package android intent is deprecated and replaced with android intent plus
[link](https://pub.dev/packages/android_intent_plus)
Comment: This way opens a Webview in the app, we need to open Google Maps app instead
Answer: At the time of writing this answer, the work on inline maps is still in progress. But since the guys at flutter have given others the ability to develop plugins, there are some alternatives.
You might want to check out :
https://firstname.lastname@example.com_66715/maps-in-flutter-a1ac49ab554b
If you just want to get the location of your user:
https://pub.dartlang.org/packages/location
If you want to keep a watch out for new updates, I found some interesting discussions going on here:
https://github.com/flutter/flutter/issues/73
Comment: I got everything from the links above except for one thing.

Is it possible to show the fastest route also?
Comment: @Jayadeep how did you get the route and make it colored like shown in picture?
Comment: That was just a screenshot for the question.
Comment: @Jayadeep i tried with the String origin =currentLocation(from the location plugin), and String destination = "6.873941599999999,79.88108439999999", but didnt work. any idea why ?
Comment: FYI the Mapview plugin is discontinued
Answer: Bit late, but might be helpful to someone.
As far as i know, Google currently does not have exposed API or package for flutter, which would allow you to create this Navigation easily. Best approach would be to get Directions data from DirectionsAPI from Google. With this data you could create polyline and you would also have data for duration, steps, or distance. You would need to redraw your custom marker, based on current user location and act like navigation.
Simplier approach might be via MapBox and their Navigation SDK. Take a look at this package https://pub.dev/packages/flutter_mapbox_navigation and their official documentation https://docs.mapbox.com/android/navigation/guides/.
Answer: Use Dependency - url_launcher: ^6.1.4
static Future<void> openMap(double latitude, double longitude) async {
String iosUrl = 'https://maps.apple.com/?q=$latitude,$longitude';
if (GetPlatform.isAndroid) {
  String googleUrl ='https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
  if (await canLaunch(googleUrl)) {
    await launch(googleUrl);
  } else {
    throw 'Could not launch $googleUrl';
  }
}else{
  if (await canLaunch(iosUrl)) {
    await launch(iosUrl);
  } else {
    throw 'Could not open the map.';
  }
}

}
This above code is Working Fine and Running properly for android and IOS
For Ios put this Code in Info.plist
 <key>LSApplicationQueriesSchemes</key>
<array>
 <string>googlechromes</string>
 <string>comgooglemaps</string>
 <string>iosamap</string>
</array>

For Android put in manifiest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 <queries>
    <package android:name="com.google.android.apps.maps" />
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:mimeType="text/plain" />
    </intent>
</queries>

Comment: can you give me the better solution
Answer: I was able to open google maps using only url_launcher (no other packages or native side changes)
Using the mode attribute you can choose how the URL should be handled, and using the externalApplication or externalNonBrowserApplication the device will open google maps
    Position currentPosition = await Geolocator.getCurrentPosition();
    String origin = '${currentPosition.latitude},${currentPosition.longitude}';
    String destination = '${currentPosition.latitude + 0.002},${currentPosition.longitude - 0.002}';

    final Uri _url = Uri.parse('https://www.google.com/maps/dir/?api=1&origin=$origin&destination=$destination&travelmode=driving&dir_action=navigate');

    await launchUrl(
        _url,
        mode: LaunchMode.externalApplication,
    );

Google Map Navigation in Flutter