问:
How to position TopLevel Window in Tkinter?
I want to position my Top Level Window just to the right of my Root Window.

Something like this → ❏❏

This is the code for my root window

```<code>root = Tk()
root.geometry("+100+100")
root.update()
root_width = root.winfo_width()
root_height = root.winfo_height()
root_xoffset = root.winfo_x()
root_yoffset = root.winfo_y()
</code>```

And this the code for my TopLevel window

```<code>newWindow = Toplevel(pady=10)
newWindow.geometry(f"+{root_width+root_xoffset}+{root_yoffset}")
</code>```

答:
You could use .winfo_x() and .winfo_width() to get the offsetx of the toplevel window.
Like:

```<code>import tkinter as tk

root = tk.Tk()

root.update() # to get the height and the offset of Tk window
toplevel = tk.Toplevel()
toplevel_offsetx, toplevel_offsety = root.winfo_x() + root.winfo_width(), root.winfo_y()
padx = 0 # the padding you need.
pady = 0
toplevel.geometry(f"+{toplevel_offsetx + padx}+{toplevel_offsety + pady}")
root.mainloop()
</code>```

OwnerDisplayName: anon

Body:
I want to position my Top Level Window just to the right of my Root Window.

Something like this → ❏❏

This is the code for my root window

root = Tk()
root.geometry("+100+100")
root.update()
root_width = root.winfo_width()
root_height = root.winfo_height()
root_xoffset = root.winfo_x()
root_yoffset = root.winfo_y()

And this the code for my TopLevel window

newWindow = Toplevel(pady=10)
newWindow.geometry(f"+{root_width+root_xoffset}+{root_yoffset}")

Body:
You could use .winfo_x() and .winfo_width() to get the offsetx of the toplevel window.
Like:

import tkinter as tk

root = tk.Tk()

root.update() # to get the height and the offset of Tk window
toplevel = tk.Toplevel()
toplevel_offsetx, toplevel_offsety = root.winfo_x() + root.winfo_width(), root.winfo_y()
padx = 0 # the padding you need.
pady = 0
toplevel.geometry(f"+{toplevel_offsetx + padx}+{toplevel_offsety + pady}")
root.mainloop()


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: How to remove one of two consecutive duplicate strings in list?

Body:
I have a list that has duplicated 'STRING' elements and looks like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', 'STRING', '90', '84', '82', '85', '86', 'STRING', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', 'STRING', '86', '89', '88', '66', '70', 'STRING', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

One of every two consecuitive 'STRING' elements has to be in its place. I need to remove every second of the consecutive STRINGelements. And the list should look like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

This is what I tried:

    for i in reversed(range(len(a)-1)):
        if (list1[i] == list1[i-1]) & (list1[i] == 'STRING'):
            list1.remove(list1[i-1])

but it doesn't work. When it's not reversed I get the IndexError.

Body:
Here's a (complex) list comprehension that uses [Python 3.Docs]: itertools.groupby(iterable, key=None).

Note that it's generic, but also highly customizable. For example, if you also want to eliminate duplicates (apply the same logic to):

Others (selectively: e.g. '45'): add them in the list at the end

All: eliminate the if clause at the end

>>> import itertools as it
>>>
>>> initial = ['32', '55', '74', '58', 'STRING', 'STRING','STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', 'STRING', '90', '84', '82', '85', '86', 'STRING', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', 'STRING', '86', '89', '88', '66', '70', 'STRING', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']  # Initial
>>>
>>> ref = ['32', '55', '74', '58', 'STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']  # Desired
>>>
>>> final = [k1 for k1, gl1 in ((k0, len(list(g0))) for k0, g0 in it.groupby(initial)) for factor in range(max(gl1 // 2, 1) if k1 in ["STRING"] else gl1)]
>>>
>>> print(final)
['32', '55', '74', '58', 'STRING', 'STRING', '56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']
>>>
>>> final == ref
True

Note: Modifying a sequence while iterating over it is not recommended, and doing so might yield unexpected results (for example for an initial list like ["STRING"]). The fact that it works in this particular case, might be purely coincidental.


问:
How do I write a Prometheus query that returns the value of a label?
I'm making a Grafana dashboard and want a panel that reports the latest version of our app. The version is reported as a label in the app_version (say) metric like so:

```<code>app_version_updated{instance="eu99",version="1.5.0-abcdefg"}
</code>```

I've tried a number of Prometheus queries to extract the version label as a string from the latest member of this time series, to no effect.

For example, the query

```<code>count(app_version_updated) by (version)
</code>```

returns a {version="1.5.0-abcdefg"} element with a value of 1. When put in a Grafana dashboard in a single value panel, this doesn't display the version string but instead the count value (1).

How can I construct a Prometheus query that returns the version string?

答:
While most of @marcus-rickert's answer is still valid in Grafana 7, there is some change.
The 'Stat' 'Name' field seems to be gone, instead in the 'Field' panel, you can set the 'Display name' to the label you want to show.

ContentLicense: CC BY-SA 3.0

Body:
I'm making a Grafana dashboard and want a panel that reports the latest version of our app. The version is reported as a label in the app_version (say) metric like so:

app_version_updated{instance="eu99",version="1.5.0-abcdefg"}

I've tried a number of Prometheus queries to extract the version label as a string from the latest member of this time series, to no effect.

For example, the query

count(app_version_updated) by (version)

returns a {version="1.5.0-abcdefg"} element with a value of 1. When put in a Grafana dashboard in a single value panel, this doesn't display the version string but instead the count value (1).

How can I construct a Prometheus query that returns the version string?


问:
Calculate first number in a list like BlackJack card game
I am just a newbie to python and my teacher tell me to create BlackJack game.And i stuck at the stage is count the total number of card.Here is what i got now, i need general solution for this one so i create a new python for this stage(just for testing)

```<code>list=["20","10","30"]
###I want to check first character of the number and add it together so i do this.

i = 0
while i < len(list):
      first_letter=list[i][0]
      i=i+1
      second_letter=list[i][0]
      total = first_letter+second_letter
      print(total)
####This is just an example for testing.
</code>```

And when i run the code it work somehow but also have this message :

```<code>
Traceback (most recent call last):

  File "D:\PYTHON BLACKJACK\00.py", line 9, in <module>

    second_letter=int(movie[i][0])

IndexError: list index out of range
</code>```

i can not understand this one. can someone help me with this???

答:
Try using enumerate() and a for loop. Also it's best to not override python builtin functions like list()

list = ["20", "10", "30"]
###I want to check first character of the number and add it together so i do this.

for i, item in enumerate(list):
      first_letter = int(item[0])
      second_letter = int(item[1])
      total = first_letter + second_letter
      print(total)
```

Body:
I am just a newbie to python and my teacher tell me to create BlackJack game.And i stuck at the stage is count the total number of card.Here is what i got now, i need general solution for this one so i create a new python for this stage(just for testing)

list=["20","10","30"]
###I want to check first character of the number and add it together so i do this.

i = 0
while i < len(list):
      first_letter=list[i][0]
      i=i+1
      second_letter=list[i][0]
      total = first_letter+second_letter
      print(total)
####This is just an example for testing.

And when i run the code it work somehow but also have this message :

Traceback (most recent call last):

  File "D:\PYTHON BLACKJACK\00.py", line 9, in <module>

    second_letter=int(movie[i][0])

IndexError: list index out of range

i can not understand this one. can someone help me with this???


问:
Zend action helper redirector
How to redirect in models or not in contrroler? use standart zend redirector helper</p>

```<code>$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl('/');
</code>```

答: You should never redirect from a model, redirection should only occur in controllers.  Models should be designed in a black box mannor, independant of the controller.</p>

Title: Zend action helper redirector

Body:
How to redirect in models or not in contrroler? use standart zend redirector helper

$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl('/');


问:
How to create a dictionary from 2 lists and other dictionary in Python?
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

```<code>POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

</code>```

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

```<code>gandalf_wins=0
saruman_wins=0
</code>```

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

```<code>gandalf_power=[]
saruman_power=[]
</code>```

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!

答:
Finally, I did this and worked for me: </p>

```<code>for spell in gandalf:
    gandalf_power.append(POWER[spell])

for spell in saruman:
    saruman_power.append(POWER[spell])

winner = ""

for g, s in zip(gandalf_power, saruman_power):
    if g > s:
        gandalf_wins+=1
        saruman_wins=0
    elif s > g:
        saruman_wins+=1
        gandalf_wins=0

    if gandalf_wins==3:
        winner="Gandalf"
        break
    elif saruman_wins==3:
        winner="Saruman"
        break

if gandalf_wins < 3 and saruman_wins < 3:
    print("Tie.")
else:
    print(f"The winner is {winner}!")
</code>```

Body:
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

gandalf_wins=0
saruman_wins=0

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

gandalf_power=[]
saruman_power=[]

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!

Body:
Finally, I did this and worked for me:

for spell in gandalf:
    gandalf_power.append(POWER[spell])

for spell in saruman:
    saruman_power.append(POWER[spell])

winner = ""

for g, s in zip(gandalf_power, saruman_power):
    if g > s:
        gandalf_wins+=1
        saruman_wins=0
    elif s > g:
        saruman_wins+=1
        gandalf_wins=0

    if gandalf_wins==3:
        winner="Gandalf"
        break
    elif saruman_wins==3:
        winner="Saruman"
        break

if gandalf_wins < 3 and saruman_wins < 3:
    print("Tie.")
else:
    print(f"The winner is {winner}!")


问:
Adode Flash Player offline?
Did anyone tried an offline Flash install? I have a Windows Server 2008 VM with no internet access.
Do you know how to do this? Is there any particular .exe for this, or the usual one?

I tried some Google suggestions, but no luck so far...

答:
You can find the "standalone" distribution of the flash player here:
https://www.adobe.com/support/flashplayer/debug_downloads.html

Choose from the "projector" releases for your matching OS/architecture.

Title: Adode Flash Player offline?


问:
Android Room Foreign Key onDelte = Cascade has no effect
I have a one-to-many relationship between two tables. The parent table is "People", the child table is "Pets". A person can have many pets. A pet can have only one Person.

I create the relation between the two tables in PersonWithPets.java using @Relation. In Pets.java, I am using ForeignKey with onDelete = CASCADE. But if I delete a Person, the corresponding Pets remain in the database, and I can't figure out why. I almost seems as if onDelte = CASCADE has no effect.
Maybe I am not using the right id's, but I have been over this many times and just can't seem to figure out why the pets of a person are not deleted with the person.

Of course I could use the personId of the pets to iterate and delete all Pets sharing the same personId, but that just seems like defying the purpose of the @ForeignKey annotation.

What could I be missing?
Sorry, if this is obvious. I am new to Android.

Person.java

```<code>@Entity(tableName = "person")
public class Person {
    @PrimaryKey(autoGenerate = true)
    private Integer id;

    String name;

    @Ignore
    private List<Pet> pets = null;

    public Person(){
        // empty constructor for serialization
    }

    @Ignore
    public Person(String name, List<Pet> pets) {
        this.name = name;
        this.pets = pets;
    }

    public Person(PersonWithPets personWithPets) {
        this.id = personWithPets.getPerson().getId();
        this.name = personWithPets.getPerson().getName();
        this.pets = this.getPets(personWithPets);
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setPet(Pet pet) {
        if (this.pets == null) {
            this.pets = new ArrayList<>();
        }
        this.pets.add(pet);
    }

    public List<Pet> getPets() {
        return this.pets;
    }

    private List<Pet> getPets(PersonWithPets personWithPets) {
        return personWithPets.getPets();
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

Pet.java

```<code>@Entity(tableName = "pet")
public class Pet {
    @PrimaryKey(autoGenerate = true)
    private Integer id;

    String name;

    public Pet() {
    }

    /**
     * @param name
     */
    @Ignore
    public Pet(String name) {
        this.name = name;
    }

    @ForeignKey
            (entity = Person.class,
                    parentColumns = "id",
                    childColumns = "personId",
                    onDelete = CASCADE,
                    onUpdate = CASCADE)
    private Integer personId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPersonId() {
        return personId;
    }

    public void setPersonId(Integer personId) {
        this.personId = personId;
    }
}
</code>```

PersonWithPets.java

```<code>public class PersonWithPets {
    @Embedded public Person person;

    @Relation(
            parentColumn = "id",
            entityColumn = "personId",
            entity = Pet.class
    )
    public List<Pet> pets;

    public Person getPerson() {
        return person;
    }

    public List<Pet> getPets() {
        return pets;
    }
}
</code>```

PersonRepository

```<code>public class PersonRepository {
    private static final String TAG = "RecipeRepository";
    private PersonDao personDao;
    private LiveData<List<Person>> people;
    private LiveData<List<PersonWithPets>> peopleWithPets;
    private LiveData<List<Pet>> pets;

    public PersonRepository (Application application) {
        PersonDatabase db = PersonDatabase.getInstance(application);
        personDao = db.personDao();
        people = personDao.getAllPeople();
        peopleWithPets = personDao.getAllPeopleWithPets();
        pets = personDao.getAllPets();
    }

    // Get all people with pets
    public LiveData<List<PersonWithPets>> getAllPeopleWithPets() {
        return peopleWithPets;
    }

    // Delete
    public void delete(Person person) {
        new DeletePersonAsyncTask(personDao).execute(person);
    }

    // Delete All People
    private static class DeleteAllPeopleAsyncTask extends AsyncTask<Void, Void, Void> {
        private PersonDao personDao;
        private DeleteAllPeopleAsyncTask(PersonDao personDao) {
            this.personDao = personDao;
        }
        @Override
        protected Void doInBackground(Void... voids) {
            personDao.deleteAllPeople();
            //personDao.deleteAllPets();
            return null;
        }
    }
 }
</code>```

Database

```<code>@Database(entities = {Person.class, Pet.class}, version = 5, exportSchema = false)
public abstract class PersonDatabase extends RoomDatabase {

    private static final String TAG = "PersonDatabase";
    private static PersonDatabase instance;
    public abstract PersonDao personDao();

    public static synchronized PersonDatabase getInstance(Context context) {
        if(instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    PersonDatabase.class, "person_database")
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallback)
                    .build();
        }
        return instance;
    }

    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            new PopulateDbAsyncTask(instance).execute();
        }
    };

    private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
        private PersonDao personDao;
        private PopulateDbAsyncTask(PersonDatabase db){
            personDao = db.personDao();
        }
        @Override
        protected Void doInBackground(Void... voids) {
            Person adam = new Person();
            adam.setName("Adam");
            Pet dog = new Pet();
            dog.setName("Dog");
            adam.setPet(dog);
            Long personId = personDao.insertPerson(adam);
            for (Pet pet : adam.getPets()) {
                pet.setPersonId(personId.intValue());
                personDao.insertPet(pet);
            }
            return null;
        }
    }
}
</code>```

DAO

```<code>@Dao
public interface PersonDao {
    @Transaction
    @Insert
    Long insertPerson(Person person);

    @Transaction
    @Insert
    void insertPet(Pet pet);

    @Transaction
    @Update
    int updatePerson(Person person);

    @Transaction
    @Delete
    void deletePerson(Person person);

    @Transaction
    @Query("DELETE FROM person")
    void deleteAllPeople();

    @Transaction
    @Query("DELETE FROM pet")
    void deleteAllPets();

    @Transaction
    @Query("SELECT * FROM person")
    LiveData<List<Person>> getAllPeople();

    @Transaction
    @Query("SELECT * FROM person")
    LiveData<List<PersonWithPets>> getAllPeopleWithPets();

    @Transaction
    @Query("SELECT * FROM pet")
    LiveData<List<Pet>> getAllPets();
}
</code>```

MainActivity

```<code>viewModel.getAllPeopleWithPets().observe(this, new Observer<List<PersonWithPets>>() {
            @Override
            public void onChanged(@Nullable List<PersonWithPets> peopleWithPets) {
                Log.d(TAG, "onChanged: --------------------------------");
                Log.d(TAG, "onChanged: ALL PEOPLE WITH PETS");
                for (PersonWithPets personWithPets : peopleWithPets) {
                    Log.d(TAG, "onChanged: Name: " + personWithPets.getPerson().getName() + " ID: " + personWithPets.getPerson().getId());
                    Log.d(TAG, "onChanged: Pets: " + + personWithPets.getPets().size());
                    if (personWithPets.getPets().size() > 0) {
                        for (Pet pet : personWithPets.getPets()) {
                            Log.d(TAG, "onChanged: Name: " + pet.getName() + " ID: " + pet.getId() + " PersonID: " + pet.getPersonId());
                        }
                    } else {
                        Log.d(TAG, "onChanged: No pets.");
                    }
                }
                Log.d(TAG, "onChanged: --------------------------------");
                setTitle("People: " + peopleWithPets.size() + " Pets: " + viewModel.getAllPets().getValue().size());
            }
        });
</code>```

答:
Try to remove ForeignKey annotation from the field declaration to the top of the entity:

```<code>@Entity(tableName = "pet", foreignKeys = @ForeignKey
    (entity = Person.class,
            parentColumns = "id",
            childColumns = "personId",
            onDelete = CASCADE,
            onUpdate = CASCADE))
public class Pet {
    @PrimaryKey(autoGenerate = true)
    private Integer id;
.......................
</code>```

It seems that @ForeignKey put above the field has no effect on creating foreign keys at all. You can see it both in the autogenerated Database Java class and checking the structure of table with any SQLite browser.

Body:
I have a one-to-many relationship between two tables. The parent table is "People", the child table is "Pets". A person can have many pets. A pet can have only one Person.

I create the relation between the two tables in PersonWithPets.java using @Relation. In Pets.java, I am using ForeignKey with onDelete = CASCADE. But if I delete a Person, the corresponding Pets remain in the database, and I can't figure out why. I almost seems as if onDelte = CASCADE has no effect.
Maybe I am not using the right id's, but I have been over this many times and just can't seem to figure out why the pets of a person are not deleted with the person.

Of course I could use the personId of the pets to iterate and delete all Pets sharing the same personId, but that just seems like defying the purpose of the @ForeignKey annotation.

What could I be missing?
Sorry, if this is obvious. I am new to Android.

Person.java

@Entity(tableName = "person")
public class Person {
    @PrimaryKey(autoGenerate = true)
    private Integer id;

    String name;

    @Ignore
    private List<Pet> pets = null;

    public Person(){
        // empty constructor for serialization
    }

    @Ignore
    public Person(String name, List<Pet> pets) {
        this.name = name;
        this.pets = pets;
    }

    public Person(PersonWithPets personWithPets) {
        this.id = personWithPets.getPerson().getId();
        this.name = personWithPets.getPerson().getName();
        this.pets = this.getPets(personWithPets);
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setPet(Pet pet) {
        if (this.pets == null) {
            this.pets = new ArrayList<>();
        }
        this.pets.add(pet);
    }

    public List<Pet> getPets() {
        return this.pets;
    }

    private List<Pet> getPets(PersonWithPets personWithPets) {
        return personWithPets.getPets();
    }

    public void setName(String name) {
        this.name = name;
    }
}

Pet.java

@Entity(tableName = "pet")
public class Pet {
    @PrimaryKey(autoGenerate = true)
    private Integer id;

    String name;

    public Pet() {
    }

    /**
     * @param name
     */
    @Ignore
    public Pet(String name) {
        this.name = name;
    }

    @ForeignKey
            (entity = Person.class,
                    parentColumns = "id",
                    childColumns = "personId",
                    onDelete = CASCADE,
                    onUpdate = CASCADE)
    private Integer personId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPersonId() {
        return personId;
    }

    public void setPersonId(Integer personId) {
        this.personId = personId;
    }
}

PersonWithPets.java

public class PersonWithPets {
    @Embedded public Person person;

    @Relation(
            parentColumn = "id",
            entityColumn = "personId",
            entity = Pet.class
    )
    public List<Pet> pets;

    public Person getPerson() {
        return person;
    }

    public List<Pet> getPets() {
        return pets;
    }
}

PersonRepository

public class PersonRepository {
    private static final String TAG = "RecipeRepository";
    private PersonDao personDao;
    private LiveData<List<Person>> people;
    private LiveData<List<PersonWithPets>> peopleWithPets;
    private LiveData<List<Pet>> pets;

    public PersonRepository (Application application) {
        PersonDatabase db = PersonDatabase.getInstance(application);
        personDao = db.personDao();
        people = personDao.getAllPeople();
        peopleWithPets = personDao.getAllPeopleWithPets();
        pets = personDao.getAllPets();
    }

    // Get all people with pets
    public LiveData<List<PersonWithPets>> getAllPeopleWithPets() {
        return peopleWithPets;
    }

    // Delete
    public void delete(Person person) {
        new DeletePersonAsyncTask(personDao).execute(person);
    }

    // Delete All People
    private static class DeleteAllPeopleAsyncTask extends AsyncTask<Void, Void, Void> {
        private PersonDao personDao;
        private DeleteAllPeopleAsyncTask(PersonDao personDao) {
            this.personDao = personDao;
        }
        @Override
        protected Void doInBackground(Void... voids) {
            personDao.deleteAllPeople();
            //personDao.deleteAllPets();
            return null;
        }
    }
 }

Database

@Database(entities = {Person.class, Pet.class}, version = 5, exportSchema = false)
public abstract class PersonDatabase extends RoomDatabase {

    private static final String TAG = "PersonDatabase";
    private static PersonDatabase instance;
    public abstract PersonDao personDao();

    public static synchronized PersonDatabase getInstance(Context context) {
        if(instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    PersonDatabase.class, "person_database")
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallback)
                    .build();
        }
        return instance;
    }

    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            new PopulateDbAsyncTask(instance).execute();
        }
    };

    private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
        private PersonDao personDao;
        private PopulateDbAsyncTask(PersonDatabase db){
            personDao = db.personDao();
        }
        @Override
        protected Void doInBackground(Void... voids) {
            Person adam = new Person();
            adam.setName("Adam");
            Pet dog = new Pet();
            dog.setName("Dog");
            adam.setPet(dog);
            Long personId = personDao.insertPerson(adam);
            for (Pet pet : adam.getPets()) {
                pet.setPersonId(personId.intValue());
                personDao.insertPet(pet);
            }
            return null;
        }
    }
}

DAO

@Dao
public interface PersonDao {
    @Transaction
    @Insert
    Long insertPerson(Person person);

    @Transaction
    @Insert
    void insertPet(Pet pet);

    @Transaction
    @Update
    int updatePerson(Person person);

    @Transaction
    @Delete
    void deletePerson(Person person);

    @Transaction
    @Query("DELETE FROM person")
    void deleteAllPeople();

    @Transaction
    @Query("DELETE FROM pet")
    void deleteAllPets();

    @Transaction
    @Query("SELECT * FROM person")
    LiveData<List<Person>> getAllPeople();

    @Transaction
    @Query("SELECT * FROM person")
    LiveData<List<PersonWithPets>> getAllPeopleWithPets();

    @Transaction
    @Query("SELECT * FROM pet")
    LiveData<List<Pet>> getAllPets();
}

MainActivity

viewModel.getAllPeopleWithPets().observe(this, new Observer<List<PersonWithPets>>() {
            @Override
            public void onChanged(@Nullable List<PersonWithPets> peopleWithPets) {
                Log.d(TAG, "onChanged: --------------------------------");
                Log.d(TAG, "onChanged: ALL PEOPLE WITH PETS");
                for (PersonWithPets personWithPets : peopleWithPets) {
                    Log.d(TAG, "onChanged: Name: " + personWithPets.getPerson().getName() + " ID: " + personWithPets.getPerson().getId());
                    Log.d(TAG, "onChanged: Pets: " + + personWithPets.getPets().size());
                    if (personWithPets.getPets().size() > 0) {
                        for (Pet pet : personWithPets.getPets()) {
                            Log.d(TAG, "onChanged: Name: " + pet.getName() + " ID: " + pet.getId() + " PersonID: " + pet.getPersonId());
                        }
                    } else {
                        Log.d(TAG, "onChanged: No pets.");
                    }
                }
                Log.d(TAG, "onChanged: --------------------------------");
                setTitle("People: " + peopleWithPets.size() + " Pets: " + viewModel.getAllPets().getValue().size());
            }
        });

Body:
Try to remove ForeignKey annotation from the field declaration to the top of the entity:

@Entity(tableName = "pet", foreignKeys = @ForeignKey
    (entity = Person.class,
            parentColumns = "id",
            childColumns = "personId",
            onDelete = CASCADE,
            onUpdate = CASCADE))
public class Pet {
    @PrimaryKey(autoGenerate = true)
    private Integer id;
.......................

It seems that @ForeignKey put above the field has no effect on creating foreign keys at all. You can see it both in the autogenerated Database Java class and checking the structure of table with any SQLite browser.


问:
Pandas - rearrange columns if column exists
I have a dataframes that are in jumbled order how can I rearrange the columns if they exits.

```<code>One      Two       Three  Six    Four     Five
1         2         3      6      4         5
1         2         3      6      4         5
...
</code>```

How can I arrange this columns in order? The issue here is that all six column might not be there in all occasions. So I need a simple line that can arrange it in order of One Two  Three  Four  Five  Six if that column exits. I mean if Two is not in df then it should be One Three Four Five Six

答:
That depends on the columns' names. If they are numbers, it's easy: just capture the columns, use the built-in sorted() function to put them in order and them change the column attribute of the data-frame. This is a one-liner:

df.columns = sorted(df.columns)
```

<p>If the columns' names are words, than it's a little more complex. You need to make a map that will associate numbers and their values in order. For example:</p>

<pre class="lang-py prettyprint-override"><code>def word_to_number(word):
    map = {
        "one": 1
        "two" : 2
        ...
    }
    return map[word.lower()]

df.columns = sorted(df.columns, key=word_to_number)
</code>```

See here for more information on sorted(): https://docs.python.org/3/howto/sorting.html.

Instead of writing the map itself (maybe that's difficult if your DF has too many columns or if you are not sure which columns you will be working on), you can use a library that does that for you, such as: https://pypi.org/project/word2number/

Body:
I have a dataframes that are in jumbled order how can I rearrange the columns if they exits.

One      Two       Three  Six    Four     Five
1         2         3      6      4         5
1         2         3      6      4         5
...

How can I arrange this columns in order? The issue here is that all six column might not be there in all occasions. So I need a simple line that can arrange it in order of One Two  Three  Four  Five  Six if that column exits. I mean if Two is not in df then it should be One Three Four Five Six

Body:
That depends on the columns' names. If they are numbers, it's easy: just capture the columns, use the built-in sorted() function to put them in order and them change the column attribute of the data-frame. This is a one-liner:

df.columns = sorted(df.columns)

If the columns' names are words, than it's a little more complex. You need to make a map that will associate numbers and their values in order. For example:

def word_to_number(word):
    map = {
        "one": 1
        "two" : 2
        ...
    }
    return map[word.lower()]

df.columns = sorted(df.columns, key=word_to_number)

See here for more information on sorted(): https://docs.python.org/3/howto/sorting.html.

Instead of writing the map itself (maybe that's difficult if your DF has too many columns or if you are not sure which columns you will be working on), you can use a library that does that for you, such as: https://pypi.org/project/word2number/


问:
python timezone problem with the same timezone
Why I get different result timezone in the one file with the almost same datetime constructions?</p>

```<code>print(datetime.datetime.now(pytz.timezone('Europe/Moscow')))
>>> 2020-05-31 12:55:04.778210+03:00

print(datetime.datetime(2020, 5, 31, 12, 54, 0, 0,  pytz.timezone('Europe/Moscow')))
>>> 2020-05-31 12:54:00+02:30
</code>```

答:
the problem lies within the fact that pytz uses a different time zone model than the Python standard lib. Here's a blog post by Paul Ganssle explaining the issue.

The correct way to do this with pytz would be to use the localize method of its timezone class:

```<code>import datetime
import pytz
print(datetime.datetime.now(pytz.timezone('Europe/Moscow')))
>>> 2020-05-31 15:15:45.559007+03:00

print(pytz.timezone('Europe/Moscow').localize(datetime.datetime(2020, 5, 31, 15, 16, 0, 0)))
>>> 2020-05-31 15:16:00+03:00
</code>```

While datetime.datetime.now(pytz.timezone('Europe/Moscow')) correctly creates a datetime object with the defined timezone, datetime.datetime(2020, 5, 31, 12, 54, 0, 0,  pytz.timezone('Europe/Moscow')) creates a naive datetime object first and then replace the timezone. Avoid replace when working with pytz, use localize instead.

An alternative to pytz is dateutil. Here, the above operation is more straight forward since dateutil uses the standard lib's time zone model:

```<code>import dateutil

print(datetime.datetime.now(dateutil.tz.gettz('Europe/Moscow')))
>>> 2020-05-31 15:13:55.967773+03:00

print(datetime.datetime(2020, 5, 31, 15, 14, 0, 0,  dateutil.tz.gettz('Europe/Moscow')))
>>> 2020-05-31 15:14:00+03:00
</code>```

Body:
Why I get different result timezone in the one file with the almost same datetime constructions?

print(datetime.datetime.now(pytz.timezone('Europe/Moscow')))
>>> 2020-05-31 12:55:04.778210+03:00

print(datetime.datetime(2020, 5, 31, 12, 54, 0, 0,  pytz.timezone('Europe/Moscow')))
>>> 2020-05-31 12:54:00+02:30

Body:
the problem lies within the fact that pytz uses a different time zone model than the Python standard lib. Here's a blog post by Paul Ganssle explaining the issue.

The correct way to do this with pytz would be to use the localize method of its timezone class:

import datetime
import pytz
print(datetime.datetime.now(pytz.timezone('Europe/Moscow')))
>>> 2020-05-31 15:15:45.559007+03:00

print(pytz.timezone('Europe/Moscow').localize(datetime.datetime(2020, 5, 31, 15, 16, 0, 0)))
>>> 2020-05-31 15:16:00+03:00

While datetime.datetime.now(pytz.timezone('Europe/Moscow')) correctly creates a datetime object with the defined timezone, datetime.datetime(2020, 5, 31, 12, 54, 0, 0,  pytz.timezone('Europe/Moscow')) creates a naive datetime object first and then replace the timezone. Avoid replace when working with pytz, use localize instead.

An alternative to pytz is dateutil. Here, the above operation is more straight forward since dateutil uses the standard lib's time zone model:

import dateutil

print(datetime.datetime.now(dateutil.tz.gettz('Europe/Moscow')))
>>> 2020-05-31 15:13:55.967773+03:00

print(datetime.datetime(2020, 5, 31, 15, 14, 0, 0,  dateutil.tz.gettz('Europe/Moscow')))
>>> 2020-05-31 15:14:00+03:00


问:
Combined form input values in component state
Need help for combining two inputs values at one state key.
When make change at Arrival date input can read the new value at data.arrivalDate and respectively when make change to Arrival time input can read it's value from data.arrivalTime.

What I want to do is, when click on the Submit button - before send the data - to combine results from both inputs in a single state field arrivesAt so to recieve string like 2020-01-01/09:05, so I don't need the old state keys data.fromDate & data.fromTime in my data object at all.

Here goes my code:
https://codesandbox.io/s/blue-tdd-xesmm?file=/src/App.js

答:
Try using the .toUTCString() function to turn your Date objects into strings and use things like .split() and .slice() to cut them up.

You can then add them together to create the string that you want before submitting it to where you want it to go.


问:
How to get latest offset for a partition for a kafka topic?
I am using the Python high level consumer for Kafka and want to know the latest offsets for each partition of a topic. However I cannot get it to work.

```<code>from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

con = KafkaConsumer(bootstrap_servers = brokers)
ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)]

con.assign(ps)
for p in ps:
    print "For partition %s highwater is %s"%(p.partition,con.highwater(p))

print "Subscription = %s"%con.subscription()
print "con.seek_to_beginning() = %s"%con.seek_to_beginning()
</code>```

But the output I get is

```<code>For partition 0 highwater is None
For partition 1 highwater is None
For partition 2 highwater is None
For partition 3 highwater is None
For partition 4 highwater is None
For partition 5 highwater is None
....
For partition 96 highwater is None
For partition 97 highwater is None
For partition 98 highwater is None
For partition 99 highwater is None
Subscription = None
con.seek_to_beginning() = None
con.seek_to_end() = None
</code>```

I have an alternate approach using assign but the result is the same

```<code>con = KafkaConsumer(bootstrap_servers = brokers)
ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)]

con.assign(ps)
for p in ps:
    print "For partition %s highwater is %s"%(p.partition,con.highwater(p))

print "Subscription = %s"%con.subscription()
print "con.seek_to_beginning() = %s"%con.seek_to_beginning()
print "con.seek_to_end() = %s"%con.seek_to_end()
</code>```

It seems from some of the documentation that I might get this behaviour if a fetch has not been issued. But I cannot find a way to force that. What am I doing wrong?

Or is there a different/simpler way to get the latest offsets for a topic?

答:
Using confluent-kafka-python

You can use position:

Retrieve current positions (offsets) for the list of partitions.

```<code>from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

offset_per_partition = consumer.position(partitions)
</code>```

Alternatively, you can also use get_watermark_offsets but you'd have to pass one partition at a time and thus it requires multiple calls:

Retrieve low and high offsets for partition.

```<code>from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

for p in partitions:
    low_offset, high_offset = consumer.get_watermark_offsets(p)
    print(f"Latest offset for partition {p}: {high_offset}")
</code>```

Using kafka-python

You can use end_offsets:

Get the last offset for the given partitions. The last offset of a
partition is the offset of the upcoming message, i.e. the offset of
the last available message + 1.

This method does not change the current consumer position of the
partitions.

```<code>from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

consumer = KafkaConsumer(bootstrap_servers = "localhost:9092" )
partitions= = [TopicPartition('myTopic', p) for p in consumer.partitions_for_topic('myTopic')]
last_offset_per_partition = consumer.end_offsets(partitions)
</code>```

Body:
I am using the Python high level consumer for Kafka and want to know the latest offsets for each partition of a topic. However I cannot get it to work.

from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

con = KafkaConsumer(bootstrap_servers = brokers)
ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)]

con.assign(ps)
for p in ps:
    print "For partition %s highwater is %s"%(p.partition,con.highwater(p))

print "Subscription = %s"%con.subscription()
print "con.seek_to_beginning() = %s"%con.seek_to_beginning()

But the output I get is

For partition 0 highwater is None
For partition 1 highwater is None
For partition 2 highwater is None
For partition 3 highwater is None
For partition 4 highwater is None
For partition 5 highwater is None
....
For partition 96 highwater is None
For partition 97 highwater is None
For partition 98 highwater is None
For partition 99 highwater is None
Subscription = None
con.seek_to_beginning() = None
con.seek_to_end() = None

I have an alternate approach using assign but the result is the same

con = KafkaConsumer(bootstrap_servers = brokers)
ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)]

con.assign(ps)
for p in ps:
    print "For partition %s highwater is %s"%(p.partition,con.highwater(p))

print "Subscription = %s"%con.subscription()
print "con.seek_to_beginning() = %s"%con.seek_to_beginning()
print "con.seek_to_end() = %s"%con.seek_to_end()

It seems from some of the documentation that I might get this behaviour if a fetch has not been issued. But I cannot find a way to force that. What am I doing wrong?

Or is there a different/simpler way to get the latest offsets for a topic?

Body:
Using confluent-kafka-python

You can use position:

Retrieve current positions (offsets) for the list of partitions.

from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

offset_per_partition = consumer.position(partitions)

Alternatively, you can also use get_watermark_offsets but you'd have to pass one partition at a time and thus it requires multiple calls:

Retrieve low and high offsets for partition.

from confluent_kafka import Consumer, TopicPartition

consumer = Consumer({"bootstrap.servers": "localhost:9092"})
topic = consumer.list_topics(topic='topicName')
partitions = [TopicPartition('topicName', partition) for partition in list(topic.topics['topicName'].partitions.keys())]

for p in partitions:
    low_offset, high_offset = consumer.get_watermark_offsets(p)
    print(f"Latest offset for partition {p}: {high_offset}")

Using kafka-python

You can use end_offsets:

Get the last offset for the given partitions. The last offset of a
partition is the offset of the upcoming message, i.e. the offset of
the last available message + 1.

This method does not change the current consumer position of the
partitions.

from kafka import TopicPartition
from kafka.consumer import KafkaConsumer

consumer = KafkaConsumer(bootstrap_servers = "localhost:9092" )
partitions= = [TopicPartition('myTopic', p) for p in consumer.partitions_for_topic('myTopic')]
last_offset_per_partition = consumer.end_offsets(partitions)


问:
Better option to create text bubble in chat app in android?
I have this style I want to implement in my chat app when user sends a message:

Should I use 9 patch or make it with XML? If XML is the better option how could I achieve this?

答:
You can make an XML for this, and you should make a bubble for incoming and outgoing messages.

This is one example for incoming chat bubble source.

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

<!--Shadow Layers-->

<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <padding
                android:bottom="1px"
                android:left="1px"
                android:right="1px"/>
            <solid android:color="#01000000" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <padding
            android:bottom="1px"
            android:left="1px"
            android:right="1px"/>
        <solid android:color="#01000000" />
        <corners android:radius="8dp" />
    </shape>
</item>

<!--===============-->
<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <padding
                android:bottom="1px" />
            <solid android:color="#09000000" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <padding
            android:bottom="1px" />
        <solid android:color="#09000000" />
        <corners android:radius="8dp" />
    </shape>
</item>

<!--===============-->

<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <padding
                android:bottom="1px"
                android:left="1px"
                android:right="1px"/>
            <solid android:color="#10000000" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <padding
            android:bottom="1px"
            android:left="1px"
            android:right="1px"/>
        <solid android:color="#10000000" />
        <corners android:radius="8dp" />
    </shape>
</item>

<!--ForeGround-->

<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <solid android:color="@color/colorWhite" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/colorWhite" />
        <corners android:radius="8dp" />
    </shape>
</item>

</layer-list>
</code>```

Body:
You can make an XML for this, and you should make a bubble for incoming and outgoing messages.

This is one example for incoming chat bubble source.

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

<!--Shadow Layers-->

<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <padding
                android:bottom="1px"
                android:left="1px"
                android:right="1px"/>
            <solid android:color="#01000000" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <padding
            android:bottom="1px"
            android:left="1px"
            android:right="1px"/>
        <solid android:color="#01000000" />
        <corners android:radius="8dp" />
    </shape>
</item>

<!--===============-->
<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <padding
                android:bottom="1px" />
            <solid android:color="#09000000" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <padding
            android:bottom="1px" />
        <solid android:color="#09000000" />
        <corners android:radius="8dp" />
    </shape>
</item>

<!--===============-->

<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <padding
                android:bottom="1px"
                android:left="1px"
                android:right="1px"/>
            <solid android:color="#10000000" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <padding
            android:bottom="1px"
            android:left="1px"
            android:right="1px"/>
        <solid android:color="#10000000" />
        <corners android:radius="8dp" />
    </shape>
</item>

<!--ForeGround-->

<item>
    <rotate
        android:fromDegrees="-35"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toDegrees="0">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <solid android:color="@color/colorWhite" />
        </shape>
    </rotate>
</item>
<item android:left="8dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/colorWhite" />
        <corners android:radius="8dp" />
    </shape>
</item>

</layer-list>


问:
Extra output outputted
In this code I want the output as a b c, but at the end there is another a outputting. So, how can I do it?

window.onload = function() {
  for (let i = 0; i < 3; i++) {
    var story = document.getElementsByClassName('story')[0];

    let clone = story.cloneNode(true);

    let usr = ["a", "b", "c"];

    document.getElementsByClassName('story')[i].innerHTML = usr[i];

    document.getElementById("story").appendChild(clone);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story">
  <p class="story"></p>
</div></code>```

答:
You already have a "P" node inside the "DIV" node. Then, you create another three. All together you get four "P" nodes.

Use the following codes to solve your problem.

```<code>window.onload = function() {

        let usr = ["a", "b", "c"];

          for (let i = 0; i < 3; i++) {

            let newP = document.createElement("p");
            newP.setAttribute("class", "story");
            newP.innerHTML = usr[i];

            document.getElementById("story").appendChild(newP);
          }
        }
</code>```

Title: Extra output outputted

Body:
You already have a "P" node inside the "DIV" node. Then, you create another three. All together you get four "P" nodes.

Use the following codes to solve your problem.

window.onload = function() {

        let usr = ["a", "b", "c"];

          for (let i = 0; i < 3; i++) {

            let newP = document.createElement("p");
            newP.setAttribute("class", "story");
            newP.innerHTML = usr[i];

            document.getElementById("story").appendChild(newP);
          }
        }


问:
Scheduling different notifications on each day Flutter
I am a newbie on Flutter. I am developing an app with notifications where notifications will be shown in different parts of the day.

For instance: (3:25 AM, 12:24 PM, 17:22 PM, 19:52 PM, 21:02 PM).

These times will differ based on the day. Times are stored on DB with their corresponding days. These notifications should be displayed even if the app is terminated and not being used.

Problems:

Get new data on around midnight for the new day. (For example around 00:00 AM my app should reschedule all yesterdays' notifications with new times to inform the user with correct data)

I am using flutter_local_notifications to schedule notification. Sometimes it will not fire a notification (if the scheduled time difference is more than 2 hours). That's is why I am going to schedule the soonest notification (for example if notifications should appear 3:25 AM then I want to schedule notifications 30 minutes before). But I am not sure if it is possible.

What I tried.

background_fetch for syncing time with DB but I could not make it work

flutter_local_notifications for showing notifications

Please consider the case that I want to show the notifications even my app is not running or in the background as well as I want to support both Android and iOS

Any help or suggestions are welcome. Thanks in advance

答:
For those who are facing the same issue, I managed to solve my problem by the following config

```<code>Future<void> initPlatformState() async {
    var config = BackgroundFetchConfig(
      minimumFetchInterval: 15,
      forceAlarmManager: true,
      stopOnTerminate: false,
      startOnBoot: true,
      enableHeadless: true,
      requiresBatteryNotLow: false,
      requiresCharging: false,
      requiresStorageNotLow: false,
      requiresDeviceIdle: false,
      requiredNetworkType: NetworkType.NONE,
    );
    BackgroundFetch.configure(config, _onBackgroundFetch);
  }
</code>```

Github repo to see the working code.
Do not forget to support, if the answer is helpful, upvoting the answer and give a star on github

Body:
For those who are facing the same issue, I managed to solve my problem by the following config

Future<void> initPlatformState() async {
    var config = BackgroundFetchConfig(
      minimumFetchInterval: 15,
      forceAlarmManager: true,
      stopOnTerminate: false,
      startOnBoot: true,
      enableHeadless: true,
      requiresBatteryNotLow: false,
      requiresCharging: false,
      requiresStorageNotLow: false,
      requiresDeviceIdle: false,
      requiredNetworkType: NetworkType.NONE,
    );
    BackgroundFetch.configure(config, _onBackgroundFetch);
  }

Github repo to see the working code.
Do not forget to support, if the answer is helpful, upvoting the answer and give a star on github


问:
Display an image from CoreData in SwiftUI
I have managed to save an image to CoreData using the following code:

```<code>let imageData = try Data(contentsOf: fileURL!)
let img = UIImage(data: imageData)
student.picture = img?.pngData()
</code>```

Of course, picture is of type Data.

Now, I would like to display this image in SwiftUI.

```<code>struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext
  @ObservedObject var student: Student

  var body: some View {
    VStack {
      Image(...student.picture...)
      Text("\(student.lastName)")
    }
  }
}
</code>```

But I cannot figure out what to put in place of ...student.picture....

Thanks for your help.

答:
If I correctly understood your model then the following should work</p>

```<code>Image(uiImage: UIImage(data: student.picture ?? Data()) ?? UIImage())
</code>```

Body:
I have managed to save an image to CoreData using the following code:

let imageData = try Data(contentsOf: fileURL!)
let img = UIImage(data: imageData)
student.picture = img?.pngData()

Of course, picture is of type Data.

Now, I would like to display this image in SwiftUI.

struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext
  @ObservedObject var student: Student

  var body: some View {
    VStack {
      Image(...student.picture...)
      Text("\(student.lastName)")
    }
  }
}

But I cannot figure out what to put in place of ...student.picture....

Thanks for your help.

Body:
If I correctly understood your model then the following should work

Image(uiImage: UIImage(data: student.picture ?? Data()) ?? UIImage())


问:
How can I sort the columns of a large data frame based on specific criteria?
I would like to sort the columns of a large dataframe (around 14000 variables) based on a specific rationale.

The column names have the following structure (Condition_Sleepstage_Parameter_Electrode_Nightpart):

```<code> [1] "Adapt_N2_negLengthLoc_C3_firstHour"          "Adapt_N3_negLengthLoc_C3_firstHour"
  [3] "Adapt_NREM_negLengthLoc_C3_firstHour"        "Book_N2_negLengthLoc_C3_firstHour"
  [5] "Book_N3_negLengthLoc_C3_firstHour"           "Book_NREM_negLengthLoc_C3_firstHour"
</code>```

R has the columns ordered in a purely alphabetical structure but I would like to have them in a logical order based on the following system:

First, variables should be presented in blocks per parameter. (order: "negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks", "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope", "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope", "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")

Within these blocks, the highest order hierarchy should be due to Condition. (order: "Adapt", "NoFilter", "Filter", "Book").

Thereafter, the next hierarchy should be defined by Electrode. (order: "F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2").

Thereafter by Nightpart (order:"firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight") and lastly by Sleepstage ("order: "N2", "N3", "NREM").

The resulting order should look like:

```<code>[1] "Adapt_N2_negLengthLoc_F3_firstHour"          "Adapt_N3_negLengthLoc_F3_firstHour"
[3] "Adapt_NREM_negLengthLoc_F3_firstHour"          "Adapt_N2_negLengthLoc_F3_firstQuarter"
[5] "Adapt_N3_negLengthLoc_F3_firstQuarter"          "Adapt_NREM_negLengthLoc_F3_firstQuarter"
[7] "Adapt_N2_negLengthLoc_F3_secondQuarter"          "Adapt_N3_negLengthLoc_F3_secondQuarter"
[9] "Adapt_NREM_negLengthLoc_F3_secondQuarter"          "Adapt_N2_negLengthLoc_F3_thirdQuarter"
[11] "Adapt_N3_negLengthLoc_F3_thirdQuarter"          "Adapt_NREM_negLengthLoc_F3_thirdQuarter"
[13] "Adapt_N2_negLengthLoc_F3_fourthQuarter"          "Adapt_N3_negLengthLoc_F3_fourthQuarter"
[15] "Adapt_NREM_negLengthLoc_F3_fourthQuarter"          "Adapt_N2_negLengthLoc_F3_wholeNight"
[17] "Adapt_N3_negLengthLoc_F3_wholeNight"           "Adapt_NREM_negLengthLoc_F3_wholeNight"
[19] "Adapt_N2_negLengthLoc_Fz_firstHour"           "Adapt_N3_negLengthLoc_Fz_firstHour"
...
</code>```

I hope that someone can help me, if there are any further questions then I am of course happy to provide more information!

Thanks in advance!

答:
You have to split the column name into the different parts that it consists of. That is done with str_split from the stringr package. It produces a list with an entry for every column name, every entry is a character vector with the different parts.
To create new columns with the different parts, I use map_chr from the purrr package to access the corresponding entry for every column name. Then, the columns are arranged. To achieve your desired order, convert the characters to factor and specify the order with the levels. The new order of the columns is represented by the column rowid:

```<code>old_order <- data.frame(col_names = c("Adapt_N2_negLengthLoc_C3_firstHour",          "Adapt_N3_negLengthLoc_C3_firstHour",
               "Adapt_NREM_negLengthLoc_C3_firstHour",        "Book_N2_negLengthLoc_C3_firstHour",
               "Book_N3_negLengthLoc_C3_firstHour",           "Book_NREM_negLengthLoc_C3_firstHour",
               "Adapt_N2_negLengthLoc_Fz_firstHour",           "Adapt_N3_negLengthLoc_Fz_firstHour"))

library(dplyr)
library(stringr)

splitted_names <- str_split(old_order$col_names, "_")

new_order <- old_order %>%
  tibble::rowid_to_column() %>%
  mutate(Condition = purrr::map_chr(splitted_names, `[`, 1),
         Sleepstage = purrr::map_chr(splitted_names, `[`, 2),
         Parameter = purrr::map_chr(splitted_names, `[`, 3),
         Electrode = purrr::map_chr(splitted_names, `[`, 4),
         Nightpart = purrr::map_chr(splitted_names, `[`, 5)) %>%
  arrange(factor(Parameter, levels = c("negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks", "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope", "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope", "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")),
          factor(Condition, levels = c("Adapt", "NoFilter", "Filter", "Book")),
          factor(Electrode, levels = c("F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2")),
          factor(Nightpart, levels = c("firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight")),
          factor(Sleepstage, levels = c("N2", "N3", "NREM"))) %>%
  pull(rowid)

old_order$col_names[new_order]
[1] Adapt_N2_negLengthLoc_Fz_firstHour   Adapt_N3_negLengthLoc_Fz_firstHour   Adapt_N2_negLengthLoc_C3_firstHour
[4] Adapt_N3_negLengthLoc_C3_firstHour   Adapt_NREM_negLengthLoc_C3_firstHour Book_N2_negLengthLoc_C3_firstHour
[7] Book_N3_negLengthLoc_C3_firstHour    Book_NREM_negLengthLoc_C3_firstHour
8 Levels: Adapt_N2_negLengthLoc_C3_firstHour ... Book_NREM_negLengthLoc_C3_firstHour
</code>```

Now that you already have the information separated into different columns, I recommend you to bring the complete data set into a tidy (long) format.

Body:
I would like to sort the columns of a large dataframe (around 14000 variables) based on a specific rationale.

The column names have the following structure (Condition_Sleepstage_Parameter_Electrode_Nightpart):

 [1] "Adapt_N2_negLengthLoc_C3_firstHour"          "Adapt_N3_negLengthLoc_C3_firstHour"
  [3] "Adapt_NREM_negLengthLoc_C3_firstHour"        "Book_N2_negLengthLoc_C3_firstHour"
  [5] "Book_N3_negLengthLoc_C3_firstHour"           "Book_NREM_negLengthLoc_C3_firstHour"

R has the columns ordered in a purely alphabetical structure but I would like to have them in a logical order based on the following system:

First, variables should be presented in blocks per parameter. (order: "negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks", "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope", "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope", "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")

Within these blocks, the highest order hierarchy should be due to Condition. (order: "Adapt", "NoFilter", "Filter", "Book").

Thereafter, the next hierarchy should be defined by Electrode. (order: "F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2").

Thereafter by Nightpart (order:"firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight") and lastly by Sleepstage ("order: "N2", "N3", "NREM").

The resulting order should look like:

[1] "Adapt_N2_negLengthLoc_F3_firstHour"          "Adapt_N3_negLengthLoc_F3_firstHour"
[3] "Adapt_NREM_negLengthLoc_F3_firstHour"          "Adapt_N2_negLengthLoc_F3_firstQuarter"
[5] "Adapt_N3_negLengthLoc_F3_firstQuarter"          "Adapt_NREM_negLengthLoc_F3_firstQuarter"
[7] "Adapt_N2_negLengthLoc_F3_secondQuarter"          "Adapt_N3_negLengthLoc_F3_secondQuarter"
[9] "Adapt_NREM_negLengthLoc_F3_secondQuarter"          "Adapt_N2_negLengthLoc_F3_thirdQuarter"
[11] "Adapt_N3_negLengthLoc_F3_thirdQuarter"          "Adapt_NREM_negLengthLoc_F3_thirdQuarter"
[13] "Adapt_N2_negLengthLoc_F3_fourthQuarter"          "Adapt_N3_negLengthLoc_F3_fourthQuarter"
[15] "Adapt_NREM_negLengthLoc_F3_fourthQuarter"          "Adapt_N2_negLengthLoc_F3_wholeNight"
[17] "Adapt_N3_negLengthLoc_F3_wholeNight"           "Adapt_NREM_negLengthLoc_F3_wholeNight"
[19] "Adapt_N2_negLengthLoc_Fz_firstHour"           "Adapt_N3_negLengthLoc_Fz_firstHour"
...

I hope that someone can help me, if there are any further questions then I am of course happy to provide more information!

Thanks in advance!

Body:
You have to split the column name into the different parts that it consists of. That is done with str_split from the stringr package. It produces a list with an entry for every column name, every entry is a character vector with the different parts.
To create new columns with the different parts, I use map_chr from the purrr package to access the corresponding entry for every column name. Then, the columns are arranged. To achieve your desired order, convert the characters to factor and specify the order with the levels. The new order of the columns is represented by the column rowid:

old_order <- data.frame(col_names = c("Adapt_N2_negLengthLoc_C3_firstHour",          "Adapt_N3_negLengthLoc_C3_firstHour",
               "Adapt_NREM_negLengthLoc_C3_firstHour",        "Book_N2_negLengthLoc_C3_firstHour",
               "Book_N3_negLengthLoc_C3_firstHour",           "Book_NREM_negLengthLoc_C3_firstHour",
               "Adapt_N2_negLengthLoc_Fz_firstHour",           "Adapt_N3_negLengthLoc_Fz_firstHour"))

library(dplyr)
library(stringr)

splitted_names <- str_split(old_order$col_names, "_")

new_order <- old_order %>%
  tibble::rowid_to_column() %>%
  mutate(Condition = purrr::map_chr(splitted_names, `[`, 1),
         Sleepstage = purrr::map_chr(splitted_names, `[`, 2),
         Parameter = purrr::map_chr(splitted_names, `[`, 3),
         Electrode = purrr::map_chr(splitted_names, `[`, 4),
         Nightpart = purrr::map_chr(splitted_names, `[`, 5)) %>%
  arrange(factor(Parameter, levels = c("negLengthLoc", "posLength", "wholeLength", "negPeak", "nbnegPeaks", "initialMeannegSlope", "finalMeannegSlope", "initialMaxnegslope", "finalMaxnegslope", "posPeak", "nbposPeaks", "initialMeannposSlope", "finalMeanposSlope", "initialMaxposSlope", "PeaktoPeak", "Number", "Density")),
          factor(Condition, levels = c("Adapt", "NoFilter", "Filter", "Book")),
          factor(Electrode, levels = c("F3", "Fz", "F4", "C3", "Cz", "C4", "P3", "Pz", "P4", "O1", "O2")),
          factor(Nightpart, levels = c("firstHour", "firstQuarter", "secondQuarter", "thirdQuarter", "fourthQuarter", "wholeNight")),
          factor(Sleepstage, levels = c("N2", "N3", "NREM"))) %>%
  pull(rowid)

old_order$col_names[new_order]
[1] Adapt_N2_negLengthLoc_Fz_firstHour   Adapt_N3_negLengthLoc_Fz_firstHour   Adapt_N2_negLengthLoc_C3_firstHour
[4] Adapt_N3_negLengthLoc_C3_firstHour   Adapt_NREM_negLengthLoc_C3_firstHour Book_N2_negLengthLoc_C3_firstHour
[7] Book_N3_negLengthLoc_C3_firstHour    Book_NREM_negLengthLoc_C3_firstHour
8 Levels: Adapt_N2_negLengthLoc_C3_firstHour ... Book_NREM_negLengthLoc_C3_firstHour

Now that you already have the information separated into different columns, I recommend you to bring the complete data set into a tidy (long) format.


问:
From where can i get libmp3lame.so file?
can anybody give me links to dowlnload libmp3lame.so file.I want to convert mp3 stream to pcm.
I want to do it using android ndk.</p>

答: Google tells me you can get it here on their official site, which was the first result for lame mp3.</p>


问:
Showdown doesn't parse inside html block
I am using Showdown.

When I run this code:

const showdown = require("showdown")

converter = new showdown.Converter()
const myMarkdownText = '## Some important text'
const myHtmlText = converter.makeHtml(myMarkdownText)
```

<p>I get</p>

<pre class="lang-html prettyprint-override"><code><h2 id="someimportanttext">Some important text</h2>
</code>```

which is the expected result.

But when I run this code:

const showdown = require("showdown")

converter = new showdown.Converter()
const myMarkdownText = '
 ## Some important text
'
const myHtmlText = converter.makeHtml(myMarkdownText)
```

<p>I get</p>

<pre class="lang-html prettyprint-override"><code><div markdown = "1"><p>## Some important text </p></div>
</code>```

Which means that Showdown didn't parse the stuff inside the html div.

Any help on how to make it work?

答: After reading the Showdown documentation (https://github.com/showdownjs/showdown#valid-options) my conclusion is that you should probably enable the backslashEscapesHTMLTags option and backslash the html tags.

Body:
I am using Showdown.

When I run this code:

const showdown = require("showdown")

converter = new showdown.Converter()
const myMarkdownText = '## Some important text'
const myHtmlText = converter.makeHtml(myMarkdownText)

I get

Some important text

which is the expected result.

But when I run this code:

const showdown = require("showdown")

converter = new showdown.Converter()
const myMarkdownText = '
 ## Some important text
'
const myHtmlText = converter.makeHtml(myMarkdownText)

I get

## Some important text

Which means that Showdown didn't parse the stuff inside the html div.

Any help on how to make it work?


问:
build.gradle.kts:10:28: Unresolved reference: settings
I have seen examples for using "by settings" delegation in build.gradle.kts scripts, but no matter what I have tried to do, Gradle complains that settings is an unresolved reference.  If I change 'settings' to 'project', Gradle is happy.  Has the use of 'by settings' been deprecated?  I looked in the Gradle 6.4.1 manual and it shows this delegation.  I've attached an image showing a simple Spring Boot app generated by Initializr with the only changes being the addition of the gradle.properties file and the delegation in the build.gradle.kts file.  I'd really appreciate any hints about this issue...  I know that I can use 'extra' properties or finding the property against the project object, but, frankly, this issue has annoyed me to the point that I need to know what is wrong! :P. Thank you for any help...

答:
The project delegate is defined in the class ProjectDelegate. Your build script is evaluated against an instance of KotlinBuildScript which extends Project, so the delegate is available.

However, when settings.gradle is evaluated, projects aren't configured yet, so there's no instance of KotlinBuildScript. Instead, the script is evaluated against an instance of KotlinSettingsScript which extends Settings, which has the settings delegate. I don't think this delegate was ever available to project build scripts.

In both cases the delegate is provided by an extension function, because both Project and Settings are Java files part of the Gradle core API.

I hope that answers your question.


问:
Angular - How to apply [ngStyle] conditions
I have a div that I want to style based on a condition.

If styleOne is true I want a background colour of red. If StyleTwo is true, I want the background colour to be blue. I've got half of it working with the below code.

```
<p>Is it possible to add a condition to say:</p>
<ul>
<li>if styleOne is true, do this</li>
<li>if styleTwo is true, do this?</li>
</ul>
<p><strong>Edit</strong></p>
<p>I think i've resolved it. It works. Not sure if it's the best way:</p>
<pre class="lang-html prettyprint-override"><code><div id="div" [ngStyle]="styleOne && {'background-color': 'red'} || styleTwo && {'background-color': 'blue'}">
</code>```

答:
```<code><ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>
</code>```

Body:
I have a div that I want to style based on a condition.

If styleOne is true I want a background colour of red. If StyleTwo is true, I want the background colour to be blue. I've got half of it working with the below code.

Is it possible to add a condition to say:

if styleOne is true, do this

if styleTwo is true, do this?

Edit

I think i've resolved it. It works. Not sure if it's the best way:


问:
How to install the "google/apiclient" package in a openclient 3 project with composer?
I don't have much experience with php, as i usually work with .net c# and windows environments.
However, I have now an opencart 3 installation on my local windows machine running on Apache2.
Opencart is working fine. I also have the same opencart on a live production server, also running fine.

I want to do an implementation of google signin on the site, and i would prefer to use the backend for this and not the javascript frontend provided by google.

To implement it I need the google-api-php-client library which I can download from here:
https://github.com/googleapis/google-api-php-client, or use composer to install it.

I installed composer for windows on my local machine.

As far as i see, all the libraries are in 'system\storage\vendor' folder.

I opened a command window by clicking on the project folder (htdocs) and ran the command: composer require google/apiclient:"^2.4.1".

After the installation, i can not see the library in the vendor folder, but i can see two new files: composer.json and composer.lock.

Also in the system\storage\vendor\composer folder, there is a file called installed.json and in it i can see all the old libraries there, but not the new one.

So, what am I missing?

In the docs for the library it says to include the 'system\storage\vendor\' autoload.php file in the new page, but opencart does that much before in the flow on startup.

So, in the new page i called $gClient = new Google_Client();, but ofcourse it is not recognized.

Any help would be appreciated!

Thanks in advance :)

答:
The composer.json file for opencart is located in the top-level root directory of the project (one level above upload/ holding the .htaccess) file.

The dependencies are stored under upload/system/storage/vendor/ (See the project's composer.json).

You need to invoke the command:

```<code>composer require google/apiclient:"^2.4.1"
</code>```

inside the top-level directory to install the google/apiclient package.

Body:
The composer.json file for opencart is located in the top-level root directory of the project (one level above upload/ holding the .htaccess) file.

The dependencies are stored under upload/system/storage/vendor/ (See the project's composer.json).

You need to invoke the command:

composer require google/apiclient:"^2.4.1"

inside the top-level directory to install the google/apiclient package.


问:
How to switch namespace in kubernetes
Say, I have two namespaces k8s-app1 and k8s-app2

I can list all pods from specific namespace using the below command

```<code>kubectl get pods -n <namespace>
</code>```

We need to append namespace to all commands to list objects from the respective namespaces. Is there a way to set specific namespace and list objects without including the namespace explicitly?

答:
I created a function in .zshrc

```<code>ksns() { kubectl config set-context --current --namespace="$1" }
</code>```

Then I call ksns default

Title: How to switch namespace in kubernetes

Body:
Say, I have two namespaces k8s-app1 and k8s-app2

I can list all pods from specific namespace using the below command

kubectl get pods -n <namespace>

We need to append namespace to all commands to list objects from the respective namespaces. Is there a way to set specific namespace and list objects without including the namespace explicitly?

Body:
I created a function in .zshrc

ksns() { kubectl config set-context --current --namespace="$1" }

Then I call ksns default


问:
Bokeh: ValueError: Out of range float values are not JSON compliant
I came across this discussion (from a year ago): https://github.com/bokeh/bokeh/issues/2392

I also saw the white screen without any errors..and then i tried to take a small subset of 2 columns and tried the below:

Since pandas just gets a bunch of rows with empty data in there as well, I tried dropna.. this resulted in there being no data at all. So instead I just specified the rows that should go into the df (hence the df = df.head(n=19) line)

```<code>import pandas as pd
from bokeh.plotting import figure, output_file, show

df = pd.read_excel(path,sheetname,parse_cols="A:B")
df = df.head(n=19)
print(df)
rtngs = ['iAAA','iAA+','iAA','iAA-','iA+','iA','iA-','iBBB+','iBBB','iBBB-','iBB+','iBB','iBB-','iB+','iB','iB-','NR','iCCC+']
x= df['Score']
output_file("line.html")

p = figure(plot_width=400, plot_height=400, x_range=(0,100),y_range=rtngs)

# add a circle renderer with a size, color, and alpha
p.circle(df['Score'], df['Rating'], size=20, color="navy", alpha=0.5)

# show the results
#output_notebook()
show(p)
</code>```

df:

```<code>   Rating  Score
0    iAAA   64.0
1    iAA+   33.0
2     iAA    7.0
3    iAA-   28.0
4     iA+   36.0
5      iA   62.0
6     iA-   99.0
7   iBBB+   10.0
8    iBBB   93.0
9   iBBB-   91.0
10   iBB+   79.0
11    iBB   19.0
12   iBB-   95.0
13    iB+   26.0
14     iB    9.0
15    iB-   26.0
16     NR   49.0
17  iCCC+   51.0
18   iAAA   18.0
</code>```

The above is showing me an output within the notebook, but still throws : ValueError: Out of range float values are not JSON compliant

And also it doesn't (hence?) produce the output file as well. How do I get rid of this error for this small subset? Is it related to NaN values? Would that also solve the 'white screen of death' issue for the larger dataset?

Thanks vm for taking a look!

In case you would like to see the entire error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-4fa6b88aa415> in <module>()
     16 # show the results
     17 #output_notebook()
---> 18 show(p)

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in show(obj, browser, new)
    300     if obj not in _state.document.roots:
    301         _state.document.add_root(obj)
--> 302     return _show_with_state(obj, _state, browser, new)
    303
    304

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in _show_with_state(obj, state, browser, new)
    310
    311     if state.notebook:
--> 312         comms_handle = _show_notebook_with_state(obj, state)
    313         shown = True
    314

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in _show_notebook_with_state(obj, state)
    334         comms_target = make_id()
    335         publish_display_data({'text/html': notebook_div(obj, comms_target)})
--> 336         handle = _CommsHandle(get_comms(comms_target), state.document, state.document.to_json())
    337         state.last_comms_handle = handle
    338         return handle

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in to_json(self)
    792         # this is a total hack to go via a string, needed because
    793         # our BokehJSONEncoder goes straight to a string.
--> 794         doc_json = self.to_json_string()
    795         return loads(doc_json)
    796

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in to_json_string(self, indent)
    785         }
    786
--> 787         return serialize_json(json, indent=indent)
    788
    789     def to_json(self):

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\core\json_encoder.py in serialize_json(obj, encoder, indent, **kwargs)
     97         indent = 2
     98
---> 99     return json.dumps(obj, cls=encoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs)

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\json\__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    235         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    236         separators=separators, default=default, sort_keys=sort_keys,
--> 237         **kw).encode(obj)
    238
    239

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\json\encoder.py in encode(self, o)
    197         # exceptions aren't as detailed.  The list call should be roughly
    198         # equivalent to the PySequence_Fast that ''.join() would do.
--> 199         chunks = self.iterencode(o, _one_shot=True)
    200         if not isinstance(chunks, (list, tuple)):
    201             chunks = list(chunks)

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\json\encoder.py in iterencode(self, o, _one_shot)
    255                 self.key_separator, self.item_separator, self.sort_keys,
    256                 self.skipkeys, _one_shot)
--> 257         return _iterencode(o, 0)
    258
    259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

ValueError: Out of range float values are not JSON compliant
</code>```

答:
I had this error in this line:

```<code>save(plot_lda, 'tsne_lda_viz_{}_{}_{}_{}_{}_{}_{}.html'.format(
    num_qualified_tweet, n_topics, threshold, n_iter, num_example, n_top_words, end_date))
</code>```

I worked use this repo as baseline: https://github.com/ShuaiW/twitter-analysis/blob/master/topic_tweets.py (mine)

And, i solved this with this code (hope this will useful for others):

```<code>  for i in range(X_topics.shape[1]):
    topic_coord[i, 0] = 0 if np.isnan(topic_coord[i, 0]) else topic_coord[i, 0]
    topic_coord[i, 1] = 0 if np.isnan(topic_coord[i, 1]) else topic_coord[i, 1]
    plot_lda.text(topic_coord[i, 0], topic_coord[i, 1], [topic_summaries[i]])
</code>```

The key is:

```<code>var = 0 if np.isnan(number) else number
</code>```

Body:
I came across this discussion (from a year ago): https://github.com/bokeh/bokeh/issues/2392

I also saw the white screen without any errors..and then i tried to take a small subset of 2 columns and tried the below:

Since pandas just gets a bunch of rows with empty data in there as well, I tried dropna.. this resulted in there being no data at all. So instead I just specified the rows that should go into the df (hence the df = df.head(n=19) line)

import pandas as pd
from bokeh.plotting import figure, output_file, show

df = pd.read_excel(path,sheetname,parse_cols="A:B")
df = df.head(n=19)
print(df)
rtngs = ['iAAA','iAA+','iAA','iAA-','iA+','iA','iA-','iBBB+','iBBB','iBBB-','iBB+','iBB','iBB-','iB+','iB','iB-','NR','iCCC+']
x= df['Score']
output_file("line.html")

p = figure(plot_width=400, plot_height=400, x_range=(0,100),y_range=rtngs)

# add a circle renderer with a size, color, and alpha
p.circle(df['Score'], df['Rating'], size=20, color="navy", alpha=0.5)

# show the results
#output_notebook()
show(p)

df:

   Rating  Score
0    iAAA   64.0
1    iAA+   33.0
2     iAA    7.0
3    iAA-   28.0
4     iA+   36.0
5      iA   62.0
6     iA-   99.0
7   iBBB+   10.0
8    iBBB   93.0
9   iBBB-   91.0
10   iBB+   79.0
11    iBB   19.0
12   iBB-   95.0
13    iB+   26.0
14     iB    9.0
15    iB-   26.0
16     NR   49.0
17  iCCC+   51.0
18   iAAA   18.0

The above is showing me an output within the notebook, but still throws : ValueError: Out of range float values are not JSON compliant

And also it doesn't (hence?) produce the output file as well. How do I get rid of this error for this small subset? Is it related to NaN values? Would that also solve the 'white screen of death' issue for the larger dataset?

Thanks vm for taking a look!

In case you would like to see the entire error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-4fa6b88aa415> in <module>()
     16 # show the results
     17 #output_notebook()
---> 18 show(p)

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in show(obj, browser, new)
    300     if obj not in _state.document.roots:
    301         _state.document.add_root(obj)
--> 302     return _show_with_state(obj, _state, browser, new)
    303
    304

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in _show_with_state(obj, state, browser, new)
    310
    311     if state.notebook:
--> 312         comms_handle = _show_notebook_with_state(obj, state)
    313         shown = True
    314

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in _show_notebook_with_state(obj, state)
    334         comms_target = make_id()
    335         publish_display_data({'text/html': notebook_div(obj, comms_target)})
--> 336         handle = _CommsHandle(get_comms(comms_target), state.document, state.document.to_json())
    337         state.last_comms_handle = handle
    338         return handle

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in to_json(self)
    792         # this is a total hack to go via a string, needed because
    793         # our BokehJSONEncoder goes straight to a string.
--> 794         doc_json = self.to_json_string()
    795         return loads(doc_json)
    796

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in to_json_string(self, indent)
    785         }
    786
--> 787         return serialize_json(json, indent=indent)
    788
    789     def to_json(self):

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\core\json_encoder.py in serialize_json(obj, encoder, indent, **kwargs)
     97         indent = 2
     98
---> 99     return json.dumps(obj, cls=encoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs)

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\json\__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    235         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    236         separators=separators, default=default, sort_keys=sort_keys,
--> 237         **kw).encode(obj)
    238
    239

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\json\encoder.py in encode(self, o)
    197         # exceptions aren't as detailed.  The list call should be roughly
    198         # equivalent to the PySequence_Fast that ''.join() would do.
--> 199         chunks = self.iterencode(o, _one_shot=True)
    200         if not isinstance(chunks, (list, tuple)):
    201             chunks = list(chunks)

C:\Users\x\AppData\Local\Continuum\Anaconda3\lib\json\encoder.py in iterencode(self, o, _one_shot)
    255                 self.key_separator, self.item_separator, self.sort_keys,
    256                 self.skipkeys, _one_shot)
--> 257         return _iterencode(o, 0)
    258
    259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

ValueError: Out of range float values are not JSON compliant

Body:
I had this error in this line:

save(plot_lda, 'tsne_lda_viz_{}_{}_{}_{}_{}_{}_{}.html'.format(
    num_qualified_tweet, n_topics, threshold, n_iter, num_example, n_top_words, end_date))

I worked use this repo as baseline: https://github.com/ShuaiW/twitter-analysis/blob/master/topic_tweets.py (mine)

And, i solved this with this code (hope this will useful for others):

  for i in range(X_topics.shape[1]):
    topic_coord[i, 0] = 0 if np.isnan(topic_coord[i, 0]) else topic_coord[i, 0]
    topic_coord[i, 1] = 0 if np.isnan(topic_coord[i, 1]) else topic_coord[i, 1]
    plot_lda.text(topic_coord[i, 0], topic_coord[i, 1], [topic_summaries[i]])

The key is:

var = 0 if np.isnan(number) else number


问:
match exact item of array or only exact the combination of array items _ MongoDB
suppose we have an array of some string. there is a use case It has to be done.

```<code>let myArray = ['a', 'g', 'd', 'e']

let collections = [

    {items:['a', 'b']},  ==> false

    {items:['a', 'g']}, ==> true

    {items:['d', 'f']},  ==> false

    {items:['a', 'g', 'd', 'e']}, ==> true

    {items:['a', 'g', 'd', 'e', 'o']}, ==> false

    {items:['a', 'g','e']}, ==> true

    {items:['g']}, ==> true

    {items:['g', 'k']}, ==> false
]
</code>```

my goals:

only exact match with one item.

match the only combination of these items.

first of all, I know this query is so expensive cause for every item of this array we have factorial of that query match.

if we have 2 elements in our array we have 2 possible queries. if we have 4 elements we have 4 * 3 * 2 * 1 possible queries.

my second question is: is this relevant? beside of the use case.

答:
You can easily achieve this using $setIsSubset

```<code>db.collection.aggregate([
    {
        $addFields: {
            filteredCollections: {
                $filter: {
                    input: "$collections",
                    as: "collection",
                    cond: {
                       $setIsSubset: [
                          ["$$collection.items"],
                          ["a", "g", "d", "e"]
                       ]
                   }
                }
            }
        }
    },
    {
        $match: {
            "filteredCollections.0": {$exists: true}
        }
    }
])
</code>```

For exact match you can use $all combined with $setIsSubset.

Body:
suppose we have an array of some string. there is a use case It has to be done.

let myArray = ['a', 'g', 'd', 'e']

let collections = [

    {items:['a', 'b']},  ==> false

    {items:['a', 'g']}, ==> true

    {items:['d', 'f']},  ==> false

    {items:['a', 'g', 'd', 'e']}, ==> true

    {items:['a', 'g', 'd', 'e', 'o']}, ==> false

    {items:['a', 'g','e']}, ==> true

    {items:['g']}, ==> true

    {items:['g', 'k']}, ==> false
]

my goals:

only exact match with one item.

match the only combination of these items.

first of all, I know this query is so expensive cause for every item of this array we have factorial of that query match.

if we have 2 elements in our array we have 2 possible queries. if we have 4 elements we have 4 * 3 * 2 * 1 possible queries.

my second question is: is this relevant? beside of the use case.

Body:
You can easily achieve this using $setIsSubset

db.collection.aggregate([
    {
        $addFields: {
            filteredCollections: {
                $filter: {
                    input: "$collections",
                    as: "collection",
                    cond: {
                       $setIsSubset: [
                          ["$$collection.items"],
                          ["a", "g", "d", "e"]
                       ]
                   }
                }
            }
        }
    },
    {
        $match: {
            "filteredCollections.0": {$exists: true}
        }
    }
])

For exact match you can use $all combined with $setIsSubset.


问:
Why do I get a warning every time I use malloc?
If I use malloc in my code:

```<code>int *x = malloc(sizeof(int));
</code>```

I get this warning from gcc:

```<code>new.c:7: warning: implicit declaration of function ‘malloc’
new.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’
</code>```

答:
Beside the other very good answers, I would like to do a little nitpick and cover something what is not discussed yet in the other answers.

When you are at Linux, To use malloc() in your code,

You don´t actually have  to #include <stdlib.h>.

(Although the use of stdlib.h is very common and probably every non-toy-program should include it either way because it provides a wide range of useful C standard library functions and macros)

You could also #include <malloc.h> instead.

But please note that the use of malloc.h is deprecated and it makes your code non-portable. If you want to use malloc() you should always and ever (except for explicit reasons to do otherwise) #include <stdlib.h>.

The reasons why, are best explained in the answers to this question:

difference between <stdlib.h> and <malloc.h>

Body:
If I use malloc in my code:

int *x = malloc(sizeof(int));

I get this warning from gcc:

new.c:7: warning: implicit declaration of function ‘malloc’
new.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’


问:
ValueError facing in implementing one hot encoding
Below is the implemention of one hot encoding with many categories under each column.

```<code>Ttop_10_LMR = [x for x in tdata.Loan_Amount_Requested.value_counts().sort_values(ascending=False).head(10).index]
</code>```

Ttop_10_LMR  variable gives the top 10 frequent values in Loan_Amount_Requested column.

```<code>def one_hot_top_x(df, variable, top_x_labels):
    for label in top_x_labels:
        df[variable+'_'+str(label)] = np.where(data[variable]==label, 1, 0)
</code>```

one_hot_top_x func will add new columns to tdata Dataframe by replacing top_x_labels with 1 and 0.

But when i run the below code,

```<code>one_hot_top_x(tdata, 'Loan_Amount_Requested', Ttop_10_LMR)
</code>```

Getting as ValueError: Length of values does not match length of index

Thanks.

答:
```<code>df[variable+'_'+str(label)] = np.where(tdata[variable]==label, 1, 0)
</code>```

instead of tdata given as data :)

Body:
Below is the implemention of one hot encoding with many categories under each column.

Ttop_10_LMR = [x for x in tdata.Loan_Amount_Requested.value_counts().sort_values(ascending=False).head(10).index]

Ttop_10_LMR  variable gives the top 10 frequent values in Loan_Amount_Requested column.

def one_hot_top_x(df, variable, top_x_labels):
    for label in top_x_labels:
        df[variable+'_'+str(label)] = np.where(data[variable]==label, 1, 0)

one_hot_top_x func will add new columns to tdata Dataframe by replacing top_x_labels with 1 and 0.

But when i run the below code,

one_hot_top_x(tdata, 'Loan_Amount_Requested', Ttop_10_LMR)

Getting as ValueError: Length of values does not match length of index

Thanks.

Body:
df[variable+'_'+str(label)] = np.where(tdata[variable]==label, 1, 0)

instead of tdata given as data :)


问:
Vuejs app showing Invalid host header error loop
I was running a vuejs app on its own dev server, now I can access the site by public IP of machine, But after pointing it with a domain using nginx its showing an error loop in console

error in console

Invalid Host header
[WDS] Disconnected!

Due to this the script,style injection and auto reload not working.

config of dev server

```<code>dev: {
  assetsSubDirectory: "static",
  assetsPublicPath: "/",
  disableHostCheck: true,
  host: "0.0.0.0", // '192.168.2.39',//can be overwritten by
  process.env.HOST
  port: 8080,
  autoOpenBrowser: false,
  errorOverlay: false,
  notifyOnErrors: false,
  poll: true,
  devtool: "cheap-module-source-map",
  cacheBusting: true,
  cssSourceMap: true
},
</code>```

nginx config for the domain

```<code>server
{
  listen 80 ;
  listen [::]:80;
  server_name prajin.prakash.com;
  location / {
        proxy_pass http://localhost:8081;
  }
}
</code>```

答:
Generally it is not recommended to disableHostCheck: true (as it may result in security issues), unless you understand and accept the risks.

Please instead try setting webpack config as follows:

In app root in vue.config.js add

```<code>module.exports = {
  devServer: {
    public: 'subdomain.domain.ext:port'
  }
};
</code>```

NB: for apps running on vuejs + nginx

Body:
I was running a vuejs app on its own dev server, now I can access the site by public IP of machine, But after pointing it with a domain using nginx its showing an error loop in console

error in console

Invalid Host header
[WDS] Disconnected!

Due to this the script,style injection and auto reload not working.

config of dev server

dev: {
  assetsSubDirectory: "static",
  assetsPublicPath: "/",
  disableHostCheck: true,
  host: "0.0.0.0", // '192.168.2.39',//can be overwritten by
  process.env.HOST
  port: 8080,
  autoOpenBrowser: false,
  errorOverlay: false,
  notifyOnErrors: false,
  poll: true,
  devtool: "cheap-module-source-map",
  cacheBusting: true,
  cssSourceMap: true
},

nginx config for the domain

server
{
  listen 80 ;
  listen [::]:80;
  server_name prajin.prakash.com;
  location / {
        proxy_pass http://localhost:8081;
  }
}

Body:
Generally it is not recommended to disableHostCheck: true (as it may result in security issues), unless you understand and accept the risks.

Please instead try setting webpack config as follows:

In app root in vue.config.js add

module.exports = {
  devServer: {
    public: 'subdomain.domain.ext:port'
  }
};

NB: for apps running on vuejs + nginx