210
Points
Questions
40
Answers
54
-
Asked on July 16, 2020 in Mysql.
In MySQL a table can have only one auto_increment column and this column must be a part of the primary key. See details here.
Technical workaround for your task would be creating of a table with a single auto_increment column, and you can obtain auto_increment value by inserting a record into this table and immediately calling standard MySQL function last_inser_id(). When time comes you should truncate the table – in this case the auto_increment count will be reset.
- 445 views
- 2 answers
- 0 votes
-
Asked on July 16, 2020 in Java Script.
Here are the steps:
- transform the object to list of key-value pairs (
_.toPairs()
or built-in’sObject.entries()
) - sort the list
- transform list of key-value pairs back to object (
_.fromPairs()
or built-in’sObject.fromEntries()
)
Below snippet could help you. I use
_.chain()
for better readabilityconst data = { "Inventory Creation": [ { id: 150, reading: "12345", readingDate: "2020-07-14", }, ], "Inventory & Check-in": [ { id: 151, reading: "12345", readingDate: "2020-11-14", }, ], "Check-in": [ { id: 152, reading: "12345", readingDate: "2020-08-14", }, ], } const res = _.chain(data) .toPairs() .sortBy((p) => p[1][0].readingDate) .reverse() .fromPairs() .value() console.log(res)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
- 363 views
- 3 answers
- 0 votes
- transform the object to list of key-value pairs (
-
Asked on July 16, 2020 in Python.
You have to initialize your Student object and pass root to it. Add this to the end of your code for it to run:
app=Student(root) root.mainloop()
Your current code as is includes a lot of syntax errors that need to be fixed before running. The following should run, albeit with some visual errors:
from tkinter import * from tkinter import ttk class Student: def __init__(self,root): self.root=root self.root.title("student management system") self.root.geometry("1350x700") title=Label(self.root,text="Student Management System",bd=10,relief=GROOVE,font=("time new roman",40,"bold"),bg="yellow",fg="red") title.pack(side=TOP,fill=X) Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson") Manage_Frame.place(x=20,y=70,width=450,height=560) #========Massage Frame=============================== Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson") Manage_Frame.place(x=20,y=100,width=450,height=560) m_title=Label(Manage_Frame,text="Manage Students",bg="crimson",fg="white",font=("time new roman",30,"bold")) m_title.grid(row=0,columnspan=2,pady=10) lbl_roll = Label(Manage_Frame, text="Roll No.", bg="crimson", fg="white",font=("time new roman", 20, "bold")) lbl_roll.grid(row=1, column=0, pady=10,padx=20,sticky="w") txt_roll = Entry(Manage_Frame,font=("time new roman", 15, "bold"),bd=5,relief=GROOVE) txt_roll.grid(row=1, column=2, pady=10, padx=20, sticky="w") lbl_name = Label(Manage_Frame, text="Name", bg="crimson", fg="white", font=("time new roman", 20, "bold")) lbl_name.grid(row=1, column=0, pady=10, padx=20, sticky="w") txt_name = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE) txt_name.grid(row=2, column=1, pady=10, padx=20, sticky="w") lbl_Email = Label(Manage_Frame, text="Email", bg="crimson", fg="white", font=("time new roman", 20, "bold")) lbl_Email.grid(row=1, column=0, pady=10, padx=20, sticky="w") txt_Email = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE) txt_Email.grid(row=3, column=0, pady=10, padx=20, sticky="w") lbl_Gender = Label(Manage_Frame, text="Gender", bg="crimson", fg="white", font=("time new roman", 20, "bold")) lbl_Gender.grid(row=4, column=0, pady=10, padx=20, sticky="w") combo_Gender=ttk.Combobox(Manage_Frame,font=("times new roman",20,"bold")) combo_Gender['values']=("Male","Female","other") combo_Gender.grid(row=4,column=1,padx=20,pady=10) lbl_Contact = Label(Manage_Frame, text="Contact", bg="crimson", fg="white", font=("time new roman", 20, "bold")) lbl_Contact.grid(row=5, column=0, pady=10, padx=20, sticky="w") txt_Contact = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE) txt_Contact.grid(row=5, column=1, pady=10, padx=20, sticky="w") lbl_DOB = Label(Manage_Frame, text="DOB", bg="crimson", fg="white",font=("time new roman", 20, "bold")) lbl_DOB.grid(row=6, column=0, pady=10, padx=20, sticky="w") txt_Contact = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE) txt_Contact.grid(row=6, column=1, pady=10, padx=20, sticky="w") lbl_address = Label(Manage_Frame, text="Address", bg="crimson", fg="white", font=("time new roman", 20, "bold")) lbl_address.grid(row=6, column=0, pady=10, padx=20, sticky="w") txt_address = Entry(Manage_Frame, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE) txt_address.grid(row=6, column=1, pady=10, padx=20, sticky="w") #=========Button Frame========= btn_Frame=Frame(Manage_Frame,bd=4,relief=RIDGE,bg="crimson") btn_Frame.place(x=15, y=500, width=420) Addbtn = Button(btn_Frame,text="add",width=10).grid(row=0,column=0,padx=10,pady=10) Updatebtn = Button(btn_Frame, text="update", width=10).grid(row=0, column=1, padx=10, pady=10) Deletebtn = Button(btn_Frame, text="delete", width=10).grid(row=0, column=2, padx=10, pady=10) Clearbtn = Button(btn_Frame, text="clear", width=10).grid(row=0, column=3, padx=10, pady=10) #=========Detail Frame========= Detail_Frame = Frame(self.root, bd=4, relief=RIDGE, bg="crimson") Detail_Frame.place(x=500, y=100, width=800, height=580) lbl_search = Label(Detail_Frame, text="Search By", bg="crimson", fg="white", font=("time new roman", 20, "bold")) lbl_search.grid(row=0, column=0, pady=10, padx=20, sticky="w") combo_search = ttk.Combobox(Manage_Frame,width=10,font=("times new roman", 13, "bold"),state="readonly") combo_search['values'] = ("Roll", "Name", "contact") combo_search.grid(row=0, column=1, padx=20, pady=10) txt_Search = Entry(Manage_Frame,width=15, font=("time new roman", 15, "bold"), bd=5, relief=GROOVE) txt_Search.grid(row=6, column=1, pady=10, padx=20, sticky="w") searchbtn = Button(btn_Frame, text="Search", width=10).grid(row=0, column=3, padx=10, pady=10) showallbtn = Button(btn_Frame, text="Show All", width=10).grid(row=0, column=4, padx=10, pady=10) #=========Table Frame========= Table_Frame = Frame(Detail_Frame, bd=4, relief=RIDGE, bg="crimson") Table_Frame.place(x=10, y=70, width=760, height=500) scroll_x=Scrollbar(Table_Frame,orient=HORIZONTAL) scroll_y = Scrollbar(Table_Frame, orient=VERTICAL) Student_table=ttk.Treeview(Table_Frame,columns=("roll","name","email","gender","contact","dob","Address"),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set) scroll_x.pack(side=BOTTOM,fill=X) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.config(command=Student_table.xview) scroll_y.config(command=Student_table.xview) Student_table.heading("roll",text="Roll") Student_table.heading("name", text="Name") Student_table.heading("email", text="Email") Student_table.heading("gender", text="Gender") Student_table.heading("contact", text="Contact") Student_table.heading("dob", text="D.O.B") Student_table.heading("Address", text="Address") Student_table['show']='headings' Student_table.pack() root=Tk() app=Student(root) root.mainloop()
- 374 views
- 1 answers
- 0 votes
-
Asked on July 16, 2020 in Python.
While I agree that Michameis answer, I want to add another thing: You can use
np.seterr(all="raise")
to raise all numpy warnings as exceptions. This way, you don’t have to filter the values beforehand and can justtry
out if the operations work:import scipy.stats import numpy as np x=[1,4,4,7,11,13,15,15,17,18,19,19,20,20,22,23,28,29,31,32,36,37,47,48,49,50,54,54,55,59,59,61,61,66,72,72,75,78,78,81,93,96,99,108,113,114,120,120,120,123,124,129,131,137,145,151,156,171,176,182,188,189,195,203,208,215,217,217,217,224,228,233,255,271,275,275,275,286,291,312,312,312,315,326,326,329,330,336,338,345,348,354,361,364,369,378,390,457,467,498,517,566,644,745,871,1312,1357,1613,1630] np.seterr(all='raise') temp = 0 for k in x: try: temp += np.log(scipy.stats.gamma.pdf(k, 2, 1)).sum() except FloatingPointError: pass
- 348 views
- 4 answers
- 0 votes
-
Asked on July 16, 2020 in Python.
How to deal with
SettingWithCopyWarning
in Pandas?This post is meant for readers who,
- Would like to understand what this warning means
- Would like to understand different ways of suppressing this warning
- Would like to understand how to improve their code and follow good practices to avoid this warning in the future.
Setup
np.random.seed(0) df = pd.DataFrame(np.random.choice(10, (3, 5)), columns=list('ABCDE')) df A B C D E 0 5 0 3 3 7 1 9 3 5 2 4 2 7 6 8 8 1
What is the
SettingWithCopyWarning
?To know how to deal with this warning, it is important to understand what it means and why it is raised in the first place.
When filtering DataFrames, it is possible slice/index a frame to return either a view, or a copy, depending on the internal layout and various implementation details. A “view” is, as the term suggests, a view into the original data, so modifying the view may modify the original object. On the other hand, a “copy” is a replication of data from the original, and modifying the copy has no effect on the original.
As mentioned by other answers, the
SettingWithCopyWarning
was created to flag “chained assignment” operations. Considerdf
in the setup above. Suppose you would like to select all values in column “B” where values in column “A” is > 5. Pandas allows you to do this in different ways, some more correct than others. For example,df[df.A > 5]['B'] 1 3 2 6 Name: B, dtype: int64
And,
df.loc[df.A > 5, 'B'] 1 3 2 6 Name: B, dtype: int64
These return the same result, so if you are only reading these values, it makes no difference. So, what is the issue? The problem with chained assignment, is that it is generally difficult to predict whether a view or a copy is returned, so this largely becomes an issue when you are attempting to assign values back. To build on the earlier example, consider how this code is executed by the interpreter:
df.loc[df.A > 5, 'B'] = 4 # becomes df.__setitem__((df.A > 5, 'B'), 4)
With a single
__setitem__
call todf
. OTOH, consider this code:df[df.A > 5]['B'] = 4 # becomes df.__getitem__(df.A > 5).__setitem__('B", 4)
Now, depending on whether
__getitem__
returned a view or a copy, the__setitem__
operation may not work.In general, you should use
loc
for label-based assignment, andiloc
for integer/positional based assignment, as the spec guarantees that they always operate on the original. Additionally, for setting a single cell, you should useat
andiat
.More can be found in the documentation.
Note
All boolean indexing operations done withloc
can also be done withiloc
. The only difference is thatiloc
expects either integers/positions for index or a numpy array of boolean values, and integer/position indexes for the columns.For example,
df.loc[df.A > 5, 'B'] = 4
Can be written nas
df.iloc[(df.A > 5).values, 1] = 4
And,
df.loc[1, 'A'] = 100
Can be written as
df.iloc[1, 0] = 100
And so on.
Just tell me how to suppress the warning!
Consider a simple operation on the “A” column of
df
. Selecting “A” and dividing by 2 will raise the warning, but the operation will work.df2 = df[['A']] df2['A'] /= 2 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/__main__.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead df2 A 0 2.5 1 4.5 2 3.5
There are a couple ways of directly silencing this warning:
-
Make a
deepcopy
df2 = df[['A']].copy(deep=True) df2['A'] /= 2
-
Change
pd.options.mode.chained_assignment
Can be set toNone
,"warn"
, or"raise"
."warn"
is the default.None
will suppress the warning entirely, and"raise"
will throw aSettingWithCopyError
, preventing the operation from going through.pd.options.mode.chained_assignment = None df2['A'] /= 2
@Peter Cotton in the comments, came up with a nice way of non-intrusively changing the mode (modified from this gist) using a context manager, to set the mode only as long as it is required, and the reset it back to the original state when finished.
class ChainedAssignent: def __init__(self, chained=None): acceptable = [None, 'warn', 'raise'] assert chained in acceptable, "chained must be in " + str(acceptable) self.swcw = chained def __enter__(self): self.saved_swcw = pd.options.mode.chained_assignment pd.options.mode.chained_assignment = self.swcw return self def __exit__(self, *args): pd.options.mode.chained_assignment = self.saved_swcw
The usage is as follows:
# some code here with ChainedAssignent(): df2['A'] /= 2 # more code follows
Or, to raise the exception
with ChainedAssignent(chained='raise'): df2['A'] /= 2 SettingWithCopyError: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
The “XY Problem”: What am I doing wrong?
A lot of the time, users attempt to look for ways of suppressing this exception without fully understanding why it was raised in the first place. This is a good example of an XY problem, where users attempt to solve a problem “Y” that is actually a symptom of a deeper rooted problem “X”. Questions will be raised based on common problems that encounter this warning, and solutions will then be presented.
Question 1
I have a DataFramedf A B C D E 0 5 0 3 3 7 1 9 3 5 2 4 2 7 6 8 8 1
I want to assign values in col “A” > 5 to 1000. My expected output is
A B C D E 0 5 0 3 3 7 1 1000 3 5 2 4 2 1000 6 8 8 1
Wrong way to do this:
df.A[df.A > 5] = 1000 # works, because df.A returns a view df[df.A > 5]['A'] = 1000 # does not work df.loc[df.A 5]['A'] = 1000 # does not work
Right way using
loc
:df.loc[df.A > 5, 'A'] = 1000
Question 21
I am trying to set the value in cell (1, ‘D’) to 12345. My expected output isA B C D E 0 5 0 3 3 7 1 9 3 5 12345 4 2 7 6 8 8 1
I have tried different ways of accessing this cell, such as
df['D'][1]
. What is the best way to do this?1. This question isn’t specifically related to the warning, but it is good to understand how to do this particular operation correctly so as to avoid situations where the warning could potentially arise in future.
You can use any of the following methods to do this.
df.loc[1, 'D'] = 12345 df.iloc[1, 3] = 12345 df.at[1, 'D'] = 12345 df.iat[1, 3] = 12345
Question 3
I am trying to subset values based on some condition. I have a DataFrameA B C D E 1 9 3 5 2 4 2 7 6 8 8 1
I would like to assign values in “D” to 123 such that “C” == 5. I tried
df2.loc[df2.C == 5, 'D'] = 123
Which seems fine but I am still getting the
SettingWithCopyWarning
! How do I fix this?This is actually probably because of code higher up in your pipeline. Did you create
df2
from something larger, likedf2 = df[df.A > 5]
? In this case, boolean indexing will return a view, so
df2
will reference the original. What you’d need to do is assigndf2
to a copy:df2 = df[df.A > 5].copy() # Or, # df2 = df.loc[df.A > 5, :]
Question 4
I’m trying to drop column “C” in-place fromA B C D E 1 9 3 5 2 4 2 7 6 8 8 1
But using
df2.drop('C', axis=1, inplace=True)
Throws
SettingWithCopyWarning
. Why is this happening?This is because
df2
must have been created as a view from some other slicing operation, such asdf2 = df[df.A > 5]
The solution here is to either make a
copy()
ofdf
, or useloc
, as before.- 772 views
- 15 answers
- 0 votes
-
Asked on July 16, 2020 in php.
you must use prepared statement to solve this problem
- 337 views
- 1 answers
- 0 votes
-
Asked on July 16, 2020 in AngularJS.
Off the top of my head there is no one function that will do this for you as you are dealing with an array of objects and also there is no rule for which duplicate would be removed as duplicate.
In your example you remove the one with
size: small
but if you were to implement this using a loop you’d most likely include the first and exclude the last as you loop through your array.It may very well be worth taking a look at a library such as lodash and creating a function that uses a combination of it’s API methods to get the desired behaviour you want.
Here is a possible solution you could use making use of basic Arrays and a filter expression to check whether a new item would be considered a duplicate before being attached to a return result.
var arrayWithDuplicates = [ {"color":"red", "size": "small"}, {"color":"green", "size": "small"}, {"color":"blue", "size": "medium"}, {"color":"red", "size": "large"} ]; var reduce = function(arr, prop) { var result = [], filterVal, filters, filterByVal = function(n) { if (n[prop] === filterVal) return true; }; for (var i = 0; i < arr.length; i++) { filterVal = arr[i][prop]; filters = result.filter(filterByVal); if (filters.length === 0) result.push(arr[i]); } return result; }; console.info(reduce(arrayWithDuplicates, 'color'));
You can check out some literature on Array filtering here If you need to provide a preference on which item to remove you could define extra parameters and logic that will make extra property checks before adding to a return value.
Hope that helps!
- 729 views
- 12 answers
- 0 votes
-
Asked on July 16, 2020 in HTML.
Console.log as you said is use for the development , to check our variables’ values but it has no impact on the DOM (page).
document.getElementById thing will change directly the DOM which allows you to change the actual page and values of elements you decided.
Hope it helps you 🙂
- 293 views
- 3 answers
- 0 votes
-
Asked on July 16, 2020 in HTML.
You can do it trough the route! with something like this:
href={"/checkin?EventId=" + event.id }
or
href={`/checkin?EventId=${event.id}`}
And when /checkin load just use this line of code to get the value:
new URLSearchParams(window.location.search).get('EventId')
I hope it helps!
- 278 views
- 2 answers
- 0 votes
-
Asked on July 16, 2020 in HTML.
First and foremost,
delete
is a reserved keyword you cannot use it for a function name.Secondly, you must pass a reference of the element being clicked. This can be achieved by passing the
this
argument to your onclick handler:<button onclick="deleteParent(this)"> delete</button>
This will result in the following
<div id="parent"> <div> <input type="text" placeholder="name"> <button onclick="deleteParent(this)"> delete</button> </div> <div> <input type="text" placeholder="age"> <button onclick="deleteParent(this)"> delete</button> </div> </div> <script> function deleteParent(btn){ btn.parentNode.remove(); } </script>
You should also not use the same
id
on multiple elements.- 372 views
- 5 answers
- 0 votes