Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How to make good reproducible pandas examples?
The Good: Do include a small example DataFrame, either as runnable code: In [1]: df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B']) or make it "copy and pasteable" using pd.read_clipboard(sep=r'\s\s+'). In [2]: df Out[2]: A B 0 1 2 1 1 3 2 4 6 Test it yourself to make sure it works andRead more
The Good:
or make it “copy and pasteable” using
pd.read_clipboard(sep=r'\s\s+')
.Test it yourself to make sure it works and reproduces the issue.
df = df.head()
? If not, fiddle around to see if you can make up a small DataFrame which exhibits the issue you are facing.But every rule has an exception, the obvious one being for performance issues (in which case definitely use
%timeit
and possibly%prun
to profile your code), where you should generate:Consider using
np.random.seed
so we have the exact same frame. Having said that, “make this code fast for me” is not strictly on topic for the site.df.to_dict
is often useful, with the differentorient
options for different cases. In the example above, I could have grabbed the data and columns fromdf.to_dict('split')
.Explain where the numbers come from:
But say what’s incorrect:
Aside: the answer here is to use
df.groupby('A', as_index=False).sum()
.pd.to_datetime
to them for good measure.Sometimes this is the issue itself: they were strings.
The Bad:
The correct way is to include an ordinary DataFrame with a
set_index
call:Be specific about how you got the numbers (what are they)… double check they’re correct.
On that note, you might also want to include the version of Python, your OS, and any other libraries. You could use
pd.show_versions()
or thesession_info
package (which shows loaded libraries and Jupyter/IPython environment).The Ugly:
Most data is proprietary, we get that. Make up similar data and see if you can reproduce the problem (something small).
Essays are bad; it’s easier with small examples.
Please, we see enough of this in our day jobs. We want to help, but not like this…. Cut the intro, and just show the relevant DataFrames (or small versions of them) in the step which is causing you trouble.
How Slicing in Python works?
The syntax is: a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array There is also the step value, which can be used with any of the above: a[start:stop:step] # start througRead more
The syntax is:
There is also the
step
value, which can be used with any of the above:The key point to remember is that the
:stop
value represents the first value that is not in the selected slice. So, the difference betweenstop
andstart
is the number of elements selected (ifstep
is 1, the default).The other feature is that
start
orstop
may be a negative number, which means it counts from the end of the array instead of the beginning. So:Similarly,
step
may be a negative number:Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for
a[:-2]
anda
only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.Relationship with the
slice
objectA
slice
object can represent a slicing operation, i.e.:is equivalent to:
Slice objects also behave slightly differently depending on the number of arguments, similar to
range()
, i.e. bothslice(stop)
andslice(start, stop[, step])
are supported. To skip specifying a given argument, one might useNone
, so that e.g.a[start:]
is equivalent toa[slice(start, None)]
ora[::-1]
is equivalent toa[slice(None, None, -1)]
.While the
See less:
-based notation is very helpful for simple slicing, the explicit use ofslice()
objects simplifies the programmatic generation of slicing.How to create pivot table in mysql?
Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this. But... this wasn't the question, and it might even lead to some disadvantages, like how to get theRead more
Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this.
But… this wasn’t the question, and it might even lead to some disadvantages, like how to get the data into the spreadsheet, problematic scaling and so on.
The SQL way…
Given his table looks something like this:
Now look into his/her desired table:
The rows (
EMAIL
,PRINT x pages
) resemble conditions. The main grouping is bycompany_name
.In order to set up the conditions this rather shouts for using the
CASE
-statement. In order to group by something, well, use …GROUP BY
.The basic SQL providing this pivot can look something like this:
This should provide the desired result very fast. The major downside for this approach, the more rows you want in your pivot table, the more conditions you need to define in your SQL statement.
This can be dealt with, too, therefore people tend to use prepared statements, routines, counters and such.
Some additional links about this topic:
How to prevent SQL injection in PHP?
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fulRead more
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Since PHP 8.2+ we can make use of
execute_query()
which prepares, binds parameters, and executes SQL statement in one method:Up to PHP8.1:
If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example,
pg_prepare()
andpg_execute()
for PostgreSQL). PDO is the universal option.Correctly setting up the connection
PDO
Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
In the above example, the error mode isn’t strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the
PDOException
.What is mandatory, however, is the first
setAttribute()
line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).Although you can set the
charset
in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.Mysqli
For mysqli we have to follow the same routine:
Explanation
The SQL statement you pass to
prepare
is parsed and compiled by the database server. By specifying parameters (either a?
or a named parameter like:name
in the example above) you tell the database engine where you want to filter on. Then when you callexecute
, the prepared statement is combined with the parameter values you specify.The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.
Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the
$name
variable contains'Sarah'; DELETE FROM employees
the result would simply be a search for the string"'Sarah'; DELETE FROM employees"
, and you will not end up with an empty table.Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):
Can prepared statements be used for dynamic queries?
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
What is a NullPointerException?
According To Java Docs: Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying theRead more
According To Java Docs:
It is also the case that if you attempt to use a null reference with
synchronized
, that will also throw this exception.Otherwise, if the value of the Expression is null, a
NullPointerException
is thrown.There are two overarching types of variables in Java:
int
orchar
are primitives.Object
i.e. variables that refer to anObject
. If you want to manipulate theObject
that a reference variable refers to you must dereference it. Dereferencing usually entails using.
to access a method or field, or using[
to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of typeObject
are references.Consider the following code where you declare a variable of primitive type
int
and don’t initialize it:These two lines will crash the program because no value is specified for
x
and we are trying to usex
‘s value to specifyy
. All primitives have to be initialized to a usable value before they are manipulated.Now here is where things get interesting. Reference variables can be set to
null
which means “I am referencing nothing“. You can get anull
value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable tonull
).If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a
NullPointerException
.The
NullPointerException
(NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.Take the following code:
The first line declares a variable named
num
, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it tonull
.In the second line, the
new
keyword is used to instantiate (or create) an object of typeInteger
, and the reference variablenum
is assigned to thatInteger
object.If you attempt to dereference
num
before creating the object you get aNullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that “num may not have been initialized
,” but sometimes you may write code that does not directly create the object.For instance, you may have a method as follows:
In which case, you are not creating the object
obj
, but rather assuming that it was created before thedoSomething()
method was called. Note, it is possible to call the method like this:In which case,
obj
isnull
, and the statementobj.myMethod()
will throw aNullPointerException
.If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the
NullPointerException
because it’s a programmer error and the programmer will need that information for debugging purposes.In addition to
NullPointerException
s thrown as a result of the method’s logic, you can also check the method arguments fornull
values and throw NPEs explicitly by adding something like the following near the beginning of a method:Note that it’s helpful to say in your error message clearly which object cannot be
null
. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unlessobj
is reassigned, it is not null and can be dereferenced safely.Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example,
doSomething()
could be written as:Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.
In Java 14, the following is a sample NullPointerException Exception message:
List of situations that cause a
NullPointerException
to occurHere are all the situations in which a
NullPointerException
occurs, that are directly* mentioned by the Java Language Specification:throw null;
synchronized (someNullReference) { ... }
NullPointerException
if one of its operands is a boxed null referenceNullPointerException
if the boxed value is null.super
on a null reference throws aNullPointerException
. If you are confused, this is talking about qualified superclass constructor invocations:for (element : iterable)
loop to loop through a null collection/array.switch (foo) { ... }
(whether its an expression or statement) can throw aNullPointerException
whenfoo
is null.foo.new SomeInnerClass()
throws aNullPointerException
whenfoo
is null.name1::name2
orprimaryExpression::name
throws aNullPointerException
when evaluated whenname1
orprimaryExpression
evaluates to null.A note from the JLS here says that,
See lesssomeInstance.someStaticMethod()
doesn’t throw an NPE, becausesomeStaticMethod
is static, butsomeInstance::someStaticMethod
still throw an NPE!