« first day (3155 days earlier)      last day (1784 days later) » 

1:01 PM
A girlfriend I had in college thought that a plane had to flip upside down when it flew passed the equator so that people inside would not fall to the top of the plane.
 
talk about a red flag
 
tell me about it
 
Even if you believe that gravity in the south hemisphere pulls things towards the sky, that wouldn't make sense. If you're flying due south and cross over the equator, then you'd be moving in the direction of gravity and effectively be in freefall. The passengers would be weightless. Certainly a "please fasten seatbelts" situation, but there's no danger of them slamming into anything.
 
it's from the plane having to pull up to avoid from falling off the earth
like a pendulum
 
My favorite was a video where some guy used a globe and a toy airplane to prove the earth can't be round. He put the plane above the northern hemisphere, then moved it down to the southern one and said "As you can see, the plane started right side up but now it's upside-down." I was like "uh-huh, I'm following you so far", and then I waited for him to continue speaking... but he didn't. That was the entirety of his argument.
 
1:07 PM
but gravity is always applied towards the centre of earth, will in this case the gravity be towards the north pole? @piRSquared
 
Yeah... she has a phd now and I don't know in what. But I do know it's an insult to those who earned a phd
 
I suppose the plane would eventually need to corkscrew by 180 degrees so its bottom still faces the direction of gravity (and thus the earth would be overhead) but it's not a particularly tight maneuver. It could do it over the course of like an hour.
 
how do you land an plane upside-down anyways?
 
@DeveshKumarSingh I really do appreciate that you guys are trying to concoct a workable theory.
 
I'm imagining runways suspended by cables from the earth overhead.
 
1:10 PM
@MisterMiyagi they install elevated platforms that they ... ^ /kevin'd
 
how about magnets?
 
OOOh
 
perhaps that antigravity guy is right...
 
Alternately, something like that scene from The Color Of Magic where the dragon riders land their mounts on the ceiling of a tremendous cavern
You would need VTOL capability for that though
 
and a dragon
 
1:12 PM
well we can assume there is a upside down runway just above the normal runway?
 
what good would a normal runway be.
 
@Kevin is the movie any good? only ever read the books
 
Hey I'm thirsty... where's the water down on this side of the planet?
 
and a nicely moulded gap between the two runways facing each other, where the plane fits snugly when it lands upside down
 
@piRSquared it's to keep those gravity nutters happy winks
 
1:13 PM
Here's a model that might make more sense. Suppose the earth is a flat disc. What popular media calls the "equator" is the edge, and each side of the disc corresponds to a "hemisphere". (this is not the model most popularly used by Flat Earthers -- they think both hemispheres are on the same side, and there's nothing on the other side)
There's no silly "all Australians dangle from tethers attached to the ground" logic this time. Gravity points towards the ground on both sides.
 
so what happens when you stand exactly on the equator?
 
assuming the gravity points towards the centre of that disc, won't people walk tilted towards the centre on that 2D disc, assuming the gravitational pull on that disc is not as high as in the atmosphere
 
@MisterMiyagi I think Kevin was talking about the scene in the book.
 
@PM2Ring happened to me just recently after graduation. Although I'd dreamt I'd messed up the dates for two exams and accidentally studied for the wrong one.
exhales deeply
 
There is a sharp discontinuity in gravity on the plane of the disc. If you stand on the edge, then half of you will be pulled in exactly the opposite direction as your other half.
It can't be the case that there is a smooth gradient of direction of gravity pointing towards the axis of the disc, because then everyone in Australia would be pulled at like a forty five degree angle, rather than straight down.
 
1:17 PM
OR We all live on one flat "Earth" but our simulation programs change our perspective as we "move".
 
now that's a story twist
 
haha let's not mix up conspiracy theories :)
 
If gravity instantly changes from "down" to "up" as the plane crosses the plane, then it would have to corkscrew 180 degrees quite quickly to correct the chaos in the cabin.
 
rbrb coffee
 
That is, assuming it descends by flying out into empty space and circling around in a gradual descent. I suppose if it moves slightly beyond the edge and nosedives, then the cabin will experience freefall that gradually returns to ordinary 1g as it levels out after it crosses the plane.
 
1:19 PM
although where would the moon go in this case? will it be still revolving around us, given the gravitational pull differs now
 
I guess the gradient is smoother at cruising altitude
 
Or, hmm, maybe it would feel like freefall abruptly changing into 1g as you cross the discontinuity
 
also how will the earth's rotation and revolution be affected around the sun
 
there is probably a pinch of quantum involved
 
I am thinking how when you roll a coin around on a flat table it wobbles towards the centre and then falls flat on it's face, perhaps that happens in this model, and half the life is wiped out, much like Thanos' snap
 
1:25 PM
The moon still goes around the earth and the earth still goes around the sun. There are two independent forces of gravity in this universe, called "Gravity classic" and "Gravity 2". Gravity Classic attracts objects towards one another in the way we are accustomed, but the gravitational constant is weaker and the exponent is smaller; this means that we can't feel the Gravity Classic exerted on us by the disc earth, but the disc earth feels the Gravity Classic exerted on it by the sun.
 
so only the earth is flat, all other celestial bodies are round?
 
On the other hand, Gravity 2 only operates along the inherent axis of the universe, which the disc earth also happens to be aligned along. Gravity 2's constant and exponent is larger, so it only really influences things that are close together.
@DeveshKumarSingh Yeah. We can tell that other planets and the sun are round because they look round. (some flat earthers will say this with a straight face)
 
interesting, and there are forces at play apart from gravity, like what happens to the sunlight, how is weather patterns/ day and night patterns changes, what happens to the tides at sea
 
It's unclear to me why only the Earth would be a disc in this model... I'm inclined to say "because of magnets"
 
quantum
since earth is the only planet with humans on it, our quantum observation weight is higher
 
1:31 PM
also if the earth is flat, it's pretty hard to explain the tectonic forces which bring earthquakes to play, or form mountains
also how long a hole do I need to drill in the surface to reach the other side
 
If I could abandon the pretense of logical thought, I'd blame the lizard people for intentionally making the Earth flatter and flatter over the course of eons, in order to bring about some sinister new world order
 
We haven't really explored the question of how thin.
 
@Kevin So is there some Diet Gravity as well? When is Gravity 3: The Reconning coming to theatres?
 
@DeveshKumarSingh Like Euler's Disk
 
@DeveshKumarSingh Depends on where you are. Earth experiences some amount of Gravity Classic, so the disc would really be more like a biconvex lens. It would be razor thin at the edge and thickest at the axis.
 
1:34 PM
@Kevin :) And here I thought we were flat, and we turned to biconvex like a UFO saucer :) if we push in from the edges more, we might become round
@PM2Ring yes exactly!
 
This still does not address exactly how thick it is at the axis. That would require like actual math and stuff.
 
well then won't people just slip of the highest point of the lens into outer space
 
That's about as likely as slipping into space while you're at the top of Mount Everest on our Earth.
 
yes, you are correct, I overthought it. the axis however thin still pulls people towards the center ever so slightly
 
cbg
 
1:42 PM
I didn't know they had a forum
 
:D
 
Just veering off the topic slightly for a moment, I remember reading an old scifi story set on a world with such extreme gravity that the people had no word or concept for falling. Stuff falls so quickly in that gravity field that their nervous system can't register it. If you let go of something, it's instantly on the ground.
 
that's one hell of a day at the gym
 
@PM2Ring what if someone jumped from a decent height, wouldn't the impact be too high?
@MisterMiyagi like the fitness gym?
 
@Aqua4 Well, yeah. :)
 
1:45 PM
I think you could reasonably have tectonic plates on Disc Lens Earth, but you might expect the layout of the north plates to be a mirror image of the layout of the south plates, since they're the same plates viewed from opposite sides. I don't think you'd necessarily see exactly symmetrical land masses; it would be possible for a mountain on one side to have an oceanic trench on the other side. It depends on how the plates interact.
 
@Aqua4 yeah, lifting anything in that kind of gravity would be practically impossible
including yourself...
 
then I would not be hitting my parkour or kick-boxing gym :p since no jumps
 
@PM2Ring Reminiscent of the scifi story about the life forms that live on the surface of a star. Their society is basically two dimensional. I think @JonClements has spoken of it once or twice.
 
but that would affect Bollywood movies a lot, :p as they don't obey the law of physics anywhere :D
would not*
 
A couple of weeks ago, I did some calculations of falling speed on a neutron star, but I forgot to write down the results. But it was something like a 10 metre drop in a couple of milliseconds. When stuff falls onto a neutron star from a decent height, it tends to cause a nuclear explosion.
 
1:49 PM
So two tectonic plates , one for the north and one for the south?
One just one big fragmented plate
 
"one big fragmented plate" is closer to what I'm thinking
Although since it's fragmented, I wouldn't call it "one plate"
 
@PM2Ring what if i throw nuclear bomb, would the impact multiply?
 
In other words, there are many plates, but there's only one layer of them.
 
@Aqua4 it would just get smashed before having time to detonate
 
@MisterMiyagi but then he also said that if stuff falls from decent height!
 
1:53 PM
@Kevin like salami on a pizza?
 
stuff falls -> nuked
nuke falls -> ???
 
If you toss an object up and let it hit the ground, it will have more kinetic energy than if you had limply dropped it from your hand. This is true whether you're on a planet or a neutron star. So perhaps the explosion would have slightly more energy. But I doubt it would be very noticeable
 
I'm no nuclear physicist but I'm willing to guess that what's meant is that there is an amount of energy that would be required to start a nuclear reaction somewhere but not necessarily on that neutron start.
 
Or, hmm, I think I misread the question. You weren't asking "if I throw an ordinary object upwards on a neutron star, will it explode more forcefully than if I had let it drop?", you were asking "if an ordinary object causes a nuclear explosion, would an actual nuclear bomb cause some sort of super explosion?". I'm going to say "yes" because that's the more fun answer.
 
kinda like starting a fire in a vacuum
 
1:57 PM
@piRSquared i have never tried that... is it more dangerous?
 
Combustion usually requires oxygen so you'd need to be burning some funky stuff if you wanted it to ignite in a vacuum
 
it is perfectly safe... but you need to hold your breath before you go in.
or change your definition of "burn"
 
@piRSquared why would I go myself, I'd just send a bot
 
^ yes, that
and perfectly safe for the bot... at least physically. emotionally, the bot might be disappointed by the results
 
@piRSquared in any case I would like to know the direction of the fire please
 
1:59 PM
can i remove a line at line number 'n' in a file using python
 
@pythonRcpp Sure. Read the lines into a list using readlines(), then delete the line you don't like, then write those lines back into the file.
 
@pythonRcpp txt file?
 
@Aqua4 It wouldn't make much difference. But to be fair, the stuff we normally see falling onto neutron stars is standard stellar gas: a mixture of hydrogen & helium. And hydrogen is your main ingredient in a hydrogen bomb. Chucking heavy stuff onto a neutron star is still pretty spectacular, though.
 
@Aqua4 yes
 
@pythonRcpp yes
 
2:01 PM
@Kevin you should use this if you don't have a lot of lines in the original file
 
are you absolutely sure that's not even a duplicate on SO main?
 
SO?
 
Stack Overflow
 
embarrasing
 
90% of questions of the form "can I do [thing] to a file?" can be solved by reading the file contents into a list, then asking "can I do [thing] to a list?", then writing the list to a file.
 
2:02 PM
i already have the line number i need to delete , in sed its just a one liner... was looking for something same in python
 
Or asking "can I do [thing] to an iterable of lines?" if you're worried about memory usage.
 
@pythonRcpp again: have you actually tried googling the problem?
 
@pythonRcpp maybe see also the diatribe at stackoverflow.com/questions/2112469/…
 
@pythonRcpp you can filter out the line in-between reading and writing
(line for line_no, line in enumerate(file, 1) if line_no != n)
 
or, we can all just keep feeding them, even without any response from them, I guess that works too
 
2:04 PM
for line in fileinput.input(): if fileinput.lineno() != n: print(line, end=None)
 
open('text2.txt', 'w').write((lambda f, n: ''.join(f[:n] + f[n+1:]))([*open('text.txt')], 3))
 
os.system("insert sed command here") # don't try this at home
 
^ only at work
 
@cs95 Flamethrower().throw("no no no, use subprocess, not os.system()")
 
@cs95 i was about to do this, but then googled , then came here
 
2:07 PM
How did googling lead here?
 
no googling did not help ... they all were telling me how to read file then fetch the line i want to delete and print the rest
 
@pythonRcpp OK, we're getting somewhere (not far but its a start)
now explain what about that link with code to do exactly what you want didn't help you
 
# Problem solving priority Q
1. Think about what to try
2. Google possible solutions
3. Ignore google and go to room 6
 
@Aqua4 What I'm hearing is "that approach has O(N) runtime so think twice about using it on huge files". This is true, but any approach will also be O(N) unless your file system is doing something clever that lets it store files in noncontiguous blocks of memory, and if you have access to that level of abstraction. So it's no worse than the sed approach.
 
granted, many Python solutions you find by googling will read all the lines into memory, and only then write all but one back out
(haven't googled this particular problem, but it's a hobby horse of mine which pops up basically every time somebody reads and writes something)
 
2:10 PM
<attempting prior joke but this time it's funny>
That's what she `sed`
 
@tripleee be glad if it's just a hobby for you :/
 
btw Andras, thanks for handling the garlic back then, I appreciate it
 
Hey guys! Do you happen to know if I want to run geckodriver in headless mode if I also need to have Firefox installed on my Linux machine?
 
@MisterMiyagi you have a parse error idioms.thefreedictionary.com/hobbyhorse
 
Is it even possible to do this iteratively with O(1)* memory? You'd need to write to a file while reading from it. I know "+" mode exists, but I don't know what it's capable of exactly.
 
2:13 PM
@Jewlanu what's geckodriver?
 
(*Or rather, O(length of longest line) memory)
 
@AndrasDeak I'm guessing they are trying to ask about Selenium
 
@Kevin you can read/write bytes and count \n
 
@tripleee I give it 50% chance
 
@AndrasDeak it's a binary filed used for writting web scrappers or web automation tests or even bots for buying sneakers
 
2:16 PM
I was more interested to know if it has anything to do with python but I've found your question since, thanks.
 
Hey guys! Do you happen to know if I want to run geckodriver in headless mode if I also need to have Firefox installed on my Linux machine? EDIT: With Selenium 3.11.0 and Firefox 57
 
Where is the documentation for the various modes of open? I'm looking at docs.python.org/3/library/functions.html#open and the only thing I can find about "+" is the table that says "open a disk file for updating (reading and writing)". Is that all they have to say?
 
mm, sneakers
 
Yep, it's about python, I wouldn't ask it here if it wasn't
 
@Jewlanu no need to repost the same message, you can remove the redundant bit
@Jewlanu yeah, thanks, unfortunately a lot of people disagree with this strategy ;)
 
2:18 PM
@pythonRcpp Why don't you want to do it using sed? It's probably much faster than any pure Python solution.
 
I might naively assume that the correct usage of "+" is open(filename, "+"), but this crashes with ValueError: Must have exactly one of create/read/write/append mode and at most one plus. Where does it say in the docs that I should be doing open(filename, "r+")? Is it in the tutorial somewhere...?
Zero points awarded for a reply like "it doesn't need to be in the docs because you can figure it out from the error message". It ought to be possible in principle to write a correct program on the first try without having to deduce critical interface information via guesswork
 
@PM2Ring Nice, you found it: Add a '+' to the mode to allow simultaneous reading and writing.
 
I notice that there is an additional sentence in the 3.x open docs that mentions "+" in the context of w+b and r+b. Neither of which are exactly what I was interested in, so these crazy eyes of mine filtered them out.
Whenever I make an outrageous claim that the documentation doesn't document something important, assume what I'm actually saying is "my reading comprehension is too poor to find this thing that is definitely documented, please help me"
 
2:35 PM
@Kevin The docs maintainers tricked you. In Python 2, the docs for open did have info about all the modes, but they removed it in 3, since it was duplicated in io.
 
is this a no-repro case? they're using the wrong variable name: stackoverflow.com/q/56479688/4909087
 
The 3.X open docs do link to docs.python.org/3/library/io.html#io-overview, but I couldn't find the information I desired among the various classes listed within.
 
@cs95 yes, his error just does not matter when there is no branching
in that case, top == i
 
@cs95 It's reproducible for me: print(isBalanced("{{([])}}")) prints YES as claimed, and print(isBalanced("{(([])[])[]}")) prints NO as claimed.
I'm trying to decide whether to point out that stackoverflow.com/q/56450268/953482 had a similar question yesterday.
For some reason OPs have a tendency to self-delete when I imply that I know that they're working on an assignment for a class and not just asking a question about a problem that they came up with all on their own. How strange -- it's not as if we have an official ban on homework questions, or anything :^)
 
huh, the spec for df.pop says a Series is returned but
 
2:45 PM
my goodness, that's a lot of answers
 
There might be a brigade of people that downvote homework questions, but they're renegades and I wag my finger at them in the strongest fashion
 
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list('ABA'))
df
Out[779]:
   A  B  A
0  1  2  3
1  4  5  6
2  7  8  9

df.pop('A')
Out[780]:
   A  A
0  1  3
1  4  6
2  7  9
viola, a dataframe
 
viola... abusing the system (-;
 
viola, a stringed instrument of the violin family, somewhat larger than a violin, played under the chin, and having a deeper tone.
 
Dumb and Dumber?
 
2:47 PM
My first PR will be an edit to the documentation "Returns a Series unless you act like a donkey"
@cs95 what does del df['A'] do
 
cue background music from the world's tiniest viola while merging that PR
 
it gets both columns
 
@piRSquared both columns drop like flies
 
that is interesting. Would you want an indexing uniqueness error?
 
there is probably someone out there relying on this to keep the world from turning into a lens-shaped thing
 
2:51 PM
I'm having a heck of a time finding out how to change the grey color on the axis planes of a 3d matplotlib plot. I may have to ask a question soon
 
> There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. There is another theory which states that this has already happened.
 
I would rather it raised a NotImplementedError: rename your columns first, noob
 
^^ that's fair but "nūb"
 
@piRSquared hmm?
Ah!
 
@AndrasDeak yeah, didn't work as planned
 
3:03 PM
Background colour?
 
trying
that does work
There was a small pebcak
 
3:23 PM
On the subject of variable naming, I was reminded the other day of a code base I inherited many years ago that kept track of the first and last line of a window scroll buffer using variables l_1 and l_l (representing the first and last lines). Now picture that with a Courier-style font, they are pretty much indistinguishable. I strongly suspect that the original dev did the work using more reasonable names (like first_line and last_line) and then in a moment of pique renamed them.
 
PEP8 recommends against using "lowercase l" for exactly that reason
 
Another historical tidbit - old Royal typewriters didn't even have a "1" key, lower-case L was used.
 
Copy/paste got this into my code range(0,360,1)! Not only was it ridiculously redundant (hyperbole) it also isn't PEP8 compliant.
 
@PaulMcG practicality beats purity!
 
rbrb early lunch
 
4:08 PM
@piRSquared thanks for the inverse recommendation :)
PS can you think of a more searchable/useful title for that post?
 
Style poll: type(x)() or x.__class__()? (question prompted by method for returning a new instance of a class)
 
type() 💯%
 
@cs95 lol, groupby mean on a 2d array pretending its a 1d array?
 
Using single argument type for anything other than logging purposes sets off one million alarms in my head, but I am loathe to call a dunder directly
And anyway x.__class__() should probably also raise the same million alarms and the only reason it doesn't is because I don't use __class__ nearly as much as I use type()
 
@AaronHall citation
 
4:21 PM
the difference in "favor" of .__class__ is it supports class assignment and type does not.
Since I don't support class assignment in the semantic sense, I don't see why I should support it in the API sense...
 
@piRSquared "GroupBy operation using an entire dataframe to group values" > inspired by what you said
 
Yes, that'll do. I just hate that question. I wanted to ask OP why did you have it in a dataframe in the first place? The 2d structure was pointless. How did you pick how many rows and/or columns? Then I told myself "No one cares about your peeves."
 
wim
4:38 PM
@AndrasDeak The examples it gives under the "No:" case are both better than the examples it gives under the "Yes:" case.
 
It's still under "No", right?
PEP 8 doesn't say to use return None, although you might still disagree with it
 
Doesn't PEP8 provide the silver standard?
 
what about the Black standard?
 
Sometimes I don't like how my variable names line up when I assign values to them.
left = 'This '
right = 'That'
So because PEP8 haunts me, I can't do this
left  = 'This '
right = 'That'
Instead, I misspell the variables
 
4:48 PM
left = 'This '
rght = 'That'
 
I line up my variables all the time. Fie upon pep 8! Fie I say!
 
we don't have a salad word for disgust, an equivalent for "fie"
May I suggest onion, mushroom(shroom), or chard
 
Developers gotta commit.
 
5:01 PM
NO! new entrant... Fig
Mushroom was taken anyway
 
A shame, since I dislike eating mushrooms the most out of those options
 
That's why I put it out there
 
Fungi skeeze me out. I think we should put all of them on a rocket ship and fire them off to another planet so the animals and plants can have earth to themselves*
 
english has words that have different meaning based on the context, so why not salad?
 
(*Protists and algae and such will still be here, but I can safely ignore them since they're not frequently served on my cheeseburgers)
 
5:05 PM
... do you like beer? (I don't but just sayin)
 
i vote garlic or mushroom
 
wim
@Kevin note: they are not always equivalent
 
I don't drink regularly, so even the much-loved yeast has been a net negative in my life
 
vinegar is usually produced with a yeast as well. Did you mean to include all fungi?
 
I'm ambivalent about vinegar as a condiment. I would need to take a census to determine if there are any foods I like that require vinegar during the cooking process.
 
wim
5:09 PM
maybe that will make a good puzzle actually (when are type(x) and x.__class__ not equivalent)
 
Hmm, vinegar is an ingredient of ketchup. This is a problem.
 
Ketchup is a vegetable, though, right?
 
Ok, we'll only put mushrooms specifically on the rocket ship. And slime molds while we're at it.
 
>>> (1).__class__ = bool
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __class__ assignment only supported for heap types or ModuleType subclasses
... What the heck is a heap type
 
5:18 PM
this is blatant stackism
 
wim
class A(object):
    def hello(self):
        print("A")

class B(object):
    __class__ = A

    def hello(self):
        print("B")

obj = B()

print(type(obj).__name__)
print(obj.__class__.__name__)
print(isinstance(obj, A))
print(isinstance(obj, B))
obj.hello()
puzzle: guess the output
and award yourself a score 0/5 to 5/5
 
2/5. The correctness of my guesses were [wrong, right, right, wrong, wrong] respectively.
I don't really know how __class__ works at all so I'm happy to get better than 0/5
 
wim
I give you an "A" for effort
 
whoah, 4/5
 
wim
(but you still have to repeat Python Datamodel fundamentals in 2020)
 
5:30 PM
I also don't know how __class__ works so I'm just luckier than Kevin
 
4/5 by basically ignoring everything about class
 
this is why cargo cult programming works :D
 
haha, and now i know a new phrase that so aptly describes something i've seen fairly often in new questions on SO without ever realising there was a phrase for it
 
@WindowsUsers any recommendations on a window manager like slant.co/topics/1249/viewpoints/1/…
 
@roganjosh I'll excuse you when those sausage rolls are sitting on my (won't be long before it's empty) plate darn you! :)
 
wim
5:47 PM
O.P. wants a regex to forbid "\u0061" but allow "a". good luck with that!
 
@wim 3/5 :(
 
this might be an inverse proficiency test
let's see if one of the inquisitive visitors get 5/5 ;D
 
There more I dig into it the more confused I get
my conclusion so far: __class__ is magic
 
6:08 PM
@Kevin I have a category table like this:

Model:

class Category(models.Model):
parentId = models.ForeignKey('self',on_delete=models.CASCADE,null=True)
name = models.CharField(max_length = 200, db_index = True)


categoryId parentId name
1 NULL 'Vehicle'
2 1 'Car'
3 1 'Bike'
4 NULL 'Wood'
5 4 'Table'

In the template I want to show the parent categories(categories with parentId as NULL)
and the sub categories(categories with parentId as one of the category ids) as dropdown items of the parent category
 
@chiragsoni may I ask why you're pinging Kevin with that?
 
Hmm, can't help you there. I don't know much about database ORMs and/or template frameworks.
 
Simply
@Kevin not a problem
Guys Sorry for any mistake
 
you can just put your question here, and if someone has any inputs for you on it, they will respond, you do not need to @ anyone :)
 
Can any one give the better answer
 
6:11 PM
this is one long full moon
 
@DeveshKumarSingh Ok I got
 
also seems like you already have a solution, why don't you try that
 
I can try that but see the last line of my question I need more optimized answer
As you only can thing that for each iteration of the outer for loop entire inner for loop will execute
 
There are more efficient ways to find the common elements between two collections than by iterating over both of them in a double for loop. For instance, create a dictionary with categoryIds as keys, and lists of items as values. You populate it with list_1's items in O(N) time, then iterate through list_2 in O(N) time and check if its categortyIds are in the dict.
That sentence got away from me a little bit. Maybe some code would be more illustrative.
from collections import defaultdict
d = defaultdict(list)
for item in list_1:
    d[item.categoryId].append(item)

for item in list_2:
    for matching_item in d[item.categoryId]:
        print("{item} and {matching_item} have identical categoryIds")
If you're thinking "great, but how do I do all of this using only the operations available to me in the template framework?", I have no idea. Maybe you can define this function on the Python side and call it from the template?
 
@Kevin I did a little mistake while posting the question here see again I am posting it. The mistake was just at on line: the if condition of the inner for loop
I have a category table like this:

Model:

class Category(models.Model):
parentId = models.ForeignKey('self',on_delete=models.CASCADE,null=True)
name = models.CharField(max_length = 200, db_index = True)


categoryId parentId name
1 NULL 'Vehicle'
2 1 'Car'
3 1 'Bike'
4 NULL 'Wood'
5 4 'Table'

In the template I want to show the parent categories(categories with parentId as NULL)
and the sub categories(categories with parentId as one of the category ids) as dropdown items of the parent category
 
6:21 PM
You'd only need to tweak my above code to change the dict indexing in the second-to-last line:
from collections import defaultdict
d = defaultdict(list)
for item in list_1:
    d[item.categoryId].append(item)

for item in list_2:
    for matching_item in d[item.parentId]:
        print("{item}'s parentId is the same as {matching_item}'s categoryId")
Is categoryId unique? you could do it with one less explicit for in that case.
d = {item.categoryId: item for item in list_1}
for item in list_2:
    if item.parentId in d:
        parent = d[item.parentId]
        print(f"{item}'s parentId is the same as {parent}'s categoryId")
    else:
        print(f"Couldn't find parent for {item}")
 
wim
@Aran-Fey that's why it's called a magic method
 
but it's even more magical than usual though
 
@Kevin yes categoryId is primary key
 
Oops, I forgot to put an f in front of all my f strings for every one of my code samples except that last one.
 
just f it
 
6:25 PM
Oh well, they all still run, they just have worthless print statements that give no useful information.
 
6:36 PM
At least you get to check out the variable names
 
4/5 because I could have guess that the one I missed was the other way around because why else would you ask the question but I really think that I should be right.
 
4/5, would have needed just a little more luck
 
wim
6:53 PM
@Aran-Fey yes. perhaps you should update your answer ;)
 
4/5, missed isinstance(obj, A). Can we have more of these? :D
 
wim
@piRSquared haha, meta-problem solving.
I remember a puzzle on puzzling stack when the solution somehow relied upon the assumption that the puzzle has a solution. Mind bending!
 
There was an actual Q&A about that. Let me find it.
 
wim
SO search broken for everyone or just me?
 
yeah, can't find anything right now
 
7:03 PM
It's my stackaversary!
 
on imgur it's called a cake day, so I guess happy 💩 day
 
wim
How did you notice? Does anyone use the search anyway? — CodeCaster Apr 6 '18 at 10:55
productivity in tech industry plummets
 
as in, the search bar? Works ok for me
 
it does now, albeit slowly
heeey, I think duckduckgo implemented the "search duckduckgo for SO" bang which i think I suggested to them a while back. They could've told me...
 
7:18 PM
@wim Uh, I'm not sure which part of it needs to be updated
To be honest I think I've been looking at __class__ the wrong way - it's probably not more magical than other dunders, it's likely less magical.
I thought it was some kind of descriptor magic implemented in type, but in reality it's probably just a regular ol' attribute
a regular ol' attribute that has special treatment in a couple of situations, but still
 
I think if isinstance is going to check __class__ then that's broken
or at least __class__ shouldn't be setable in the normal way
 
@AndrasDeak You mean !so?
 
No, that uses useless SO search. I mean !ddso
 
oh, neat. I actually made a feature request like that, too
 
could be that's why I didn't get notified, probably neither of us was the first one
 
7:25 PM
I can't even remember where/how I submitted that. Might've been reddit
 
Perhaps the official submission form at !bang?
 
Nope, that definitely wasn't it. Was some kind of forum-like thing
 
I see
 
7:46 PM
I don't understand why I'm struggling so much with trying to answer this pandas question. I first thought about get_dummies but all schools are missing "History". I've also tried different joins. This seems pretty fundamental; any pandas guys have a dupe or a question to shove me in the right direction?
I kinda thought an outer join of some kind would leave some NaNs to work out which schools were missing which classes, but it doesn't expand out for all school/course combinations
 
wim
@piRSquared by design
this feature allows an object to imitate another type
 
I don't follow. assume the modified version of what you posted:
class A(object):
    def hello(self):
        print("A")

class B(object):
    __class__ = A

obj = B()
Then I'd expect obj.hello() to work as it is imitating A... but it doesn't
So I guess what I didn't get is, In what context does it enable imitation?
 
wim
heh, that's funny, because hello is listed in the dir(obj) but you can't access it
 
8:03 PM
obj.__class__.hello(obj)
 
wim
@piRSquared do it like this instead
class A(object):
    def hello(self):
        print("A")

class B(object):
    pass

obj = B()
obj.__class__ = A
@Aran-Fey good point, the edge-cases that are glossed over here are not really relevant to the question.
and the question is one of those annoying ones like "I'm trying to do this really weird/dumb thing. I'm not going to explain why I'm doing it like this".
> The problem here is that all objects in python have a __class__ attribute that stores the type of the object
 
ohhh, we were assigning something to the __class__ attribute of the class itself.
 
I just realized I was looking for a __class__ descriptor in the wrong place... it's obviously in object, why was I looking in type?!
 
Do other classes have that defined
 
wim
this quote from your answer is oversimplifying things, but it's not really relevant to the question
 
8:07 PM
int.__class__ isn't int its type
 
wim
maybe __class__ stores the type of the object. usually, even. but maybe it has some other type.
 
So how does that work anyway? If an attribute can't be found the usual way, python then tries to look it up on the class that's stored in __class__?
 
wim
@piRSquared (1).__class__ should be int. and int.__class__ should be the metaclass (type). nothing to see here.
 
yeah, duh on me... I didn't think on that one
 
8:31 PM
@Kevin SUCH a good documentary
 
8:42 PM
Should a new answers duplicating an existing high voted one under the same question, only be flagged for moderator attention or additionally be downvoted?
 
<shrug> what kind of mood are you in?
 
rage
but what's correct?
 
If you think it really needed flagging then that's well beyond the impact of upvotes/downvotes so the main job has been done
 
@Darkonaut easily (I mean easily OK to downvote)
that plus a comment often leads to self-delete
Even if the mod declines you wouldn't want blatant dupe answers to thrive
 
I always imagined isin to represent somewhere.isin(something) but I realise it's actually something.isin(somewhere) (or more accurately, somethings.isin(somewhere)). I've been thinking about this backwards
 
8:51 PM
Ok thx, wasn't sure about downvoting a technically correct dupe. I somehow remember that it should facilitate deletion if you downvote.
 
this maps cleanly to python's something in somewhere
 
@Darkonaut yup, negative-score answers can be 20k-deleted
 
ah that's it, thx
 
wim
> wasn't sure about downvoting a technically correct dupe
downvote hover is like "this is not useful". if it's duplicating content from other answer it's not useful.
 

« first day (3155 days earlier)      last day (1784 days later) »