« first day (3886 days earlier)      last day (1062 days later) » 

1:33 AM
Hi, I've been having a small doubt regarding filtering in pandas:
I want to save the date where the GHI number is the maximum:
e = df.Date[df.GHI == max(df.GHI)]
and then filter out the df for only those days:
df[df.Date == e]
but I get the ValueError: Can only compare identically-labeled Series objects
I searched the previous answers to this which included sort index and reset index, but neither helped
 
1:48 AM
Nevermind, I was able to find the fix by using:
df[df.Date.isin(e)]
But I still don't understand why

df[df.Date == e]

doesn't work..
 
 
1 hour later…
2:53 AM
hi
in django, when I do python manage.py migrate or python manage.py runserver I get errors like this prnt.sc/14aqal9
any solution?
 
 
1 hour later…
4:09 AM
@python_user I mean, building a list of tuples is not novel. Dupe target needed...
 
4:28 AM
any reason to dupe vote a 2 year old question? I dont know pandas so I didnt go ahead with that
 
5:03 AM
@cmk101010 Because e is of type Series not a scalar value.
 
 
3 hours later…
8:09 AM
Hi, I have a question regarding the pd.grouper function...
This is the code where I finding the mean of a scalar value recorded in minutes to the hour value:
df1['GHI'] = df.groupby(pd.Grouper(key='Datetime',freq='H'))['GHI'].mean()
Is there a way instead of hourly to get it done for the hour long interval between say: 12:30 to 1:30 so that it can bias towards the 1:00 time
 
8:41 AM
cabbage
 
9:05 AM
cbg
 
 
2 hours later…
PCM
11:21 AM
Hey, who wants to look at old tkinter model
 
11:48 AM
cbg
 
 
2 hours later…
1:43 PM
why python not restricted guys any code you write will run even if you don't expect this result
 
That's how all programming languages work
 
In what programming language do you write code that doesn't run?
 
I can think of three ways to interpret the statement:
1. Because Python isn't compiled, it will run your code even if it is syntactically incorrect.
2. The Python process has all the privileges of the user running it, so it might be able to do bad things like delete your files.
3. Sometimes Python programs produce output you don't expect, for example if you make a mistake while writing it.
1 is simply incorrect. For example, the program print("Hello" crashes with SyntaxError: unexpected EOF while parsing before running any code.
2 is how 99% of languages work. Language designers have to go out of their way to design a sandbox that the language can't escape from. Javascript in browsers comes to mind.
 
c# is restricted you can't type anything ex dict["0"]="A" and it run it will raise error in python it will add new value
 
3 is how 100% of languages work. A computer can't guess what output you expect the program to have, and it can't verify that your algorithm will produce that output. This is literally mathematically impossible because of the halting problem.
@MohamedFathallah That looks like valid C# code to me, assuming you've declared dict to be a type that allows that kind of indexing.
 
1:54 PM
@Kevin in c# error will raise key 0 doesn't exist
 
I think you're wrong.
 
So suddenly we've narrowed down the issue from "python" to "dicts in python" :|
So how do you add keys/values to a dict in C#?
 
ideone.com/5o8UeC verifies that dict["0"] = "A"; is valid C# syntax
You might now be thinking "what I meant was, if you use dict["0"] in an expression without assigning a value to that key first, then you'll get a KeyError". Well, that's how it works in Python too.
>>> d = {1:2}
>>> print(d["0"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '0'
 
I have a feeling we'll soon move on to talking about arrays instead of dicts
 
2:00 PM
it interesting talk thou
 
I thought of another interpretation, which I think does have some merit: 4. Python is not explicitly typed, so you can't easily declare that a dict can only have strings as keys, and can only have floats as values. It's impossible to stop the programmer from doing x = {1: "foo", 2.0: set()}
Allowing collection types to store non-homogeneous data can lead to some truly gnarly and error-prone code. I've seen it happen plenty of times.
C# doesn't have this problem because generic collections like Dictionary will promptly raise a compilation error complaining of incompatible types if you try to do dict[1.0] = 2 on a Dictionary<string, string>. (unless it tries to get clever with implicit type conversion)
 
this what i meant i do write c# but I didn't really know that dict in c# can add a new key, value pair if it doesn't exist because I still think this still error-prone if I try to access an item with a key that doesn't exist for (change it's value) it should warn me
 
All that said, I think duck typing / strong implicit typing is still worthwhile, just for the amount of boilerplate it cuts out. Why do Dictionary<string, string> dict = new Dictionary<string, string>(); when I can just do d = {}? Sure, I'm increasing my risk of type-based logic error, but I can minimize that by employing sensible design practices, and maybe make even use the optional type annotation system.
 
thanks, Kevin and Aran-Fey I really benefit from talking with you guys, I am new to python if you can recommend resources i would appreciate this
 
@MohamedFathallah I do like the idea of a stricter dictionary-like type that you can't add new keys to. Or at least, you can only add new keys to it by using different syntax.
class StrictMapping(dict):
    """like dict, but doesn't let you add new keys with indexed assignment (e.g. `d[a] = b`)"""
    def __setitem__(self, key, value):
        if key not in self:
            raise KeyError(key)
        super().__setitem__(key, value)

    def new_pair(self, key, value):
        if key in self:
            raise KeyError(key)
        super().__setitem__(key, value)

d = StrictMapping({1: 2, 3: 4})
d[1] = 23           #ok
d[3] = 99           #ok
d[5] = 0            #bad; 5 is not an existing key
Something like this
Wacky syntactical bodge proposal: use sliced assignment for key insertion
class StrictMapping(dict):
    """like dict, but doesn't let you add new keys with indexed assignment (e.g. `d[a] = b`)"""
    def __setitem__(self, key, value):
        if isinstance(key, slice):  #user used `d[:a] = b` syntax
            key = key.stop
            if key in self:
                raise KeyError(key)
        else:                       #user used `d[a] = b` syntax
            if key not in self:
                raise KeyError(key)
        super().__setitem__(key, value)

d = StrictMapping({1: 2, 3: 4})
 
2:42 PM
Pfft. Adding new items should obviously be done with d[key:value]
 
3:12 PM
Hi everyone I want to generate frequency counts for n_gram lists I have
For unigrams it was pretty straightforward but for bigrams the method is taking a lot of time
unigram_dict = {}
for gram in unigrams:
    current_gram = ''.join(gram)
    if current_gram in unigram_dict:
        unigram_dict[current_gram] += 1
    else:
        unigram_dict[current_gram] = 0
Can anyone help me optimize the way I am doing this or suggest resources for the same?
Background information: unigrams is a list of lists containing single words and the end purpose is to store the word or words (in case of bigrams or trigrams) and their frequencies in a dict for visualization
Similarly bigrams is a list of lists containing two words in each list and trigrams three words in each list
 
collections.Counter is very good for concisely constructing histograms
 
[['when', 'the'],
['the', 'young'],
['young', 'people'],
['people', 'returned']] -> sample format for bigrams
 
>>> import collections
>>> collections.Counter("I've got a lovely bunch of coconuts, here they are standing in a row")
Counter({' ': 13, 'e': 6, 'o': 6, 'n': 5, 't': 4, 'a': 4, 'c': 3, 'h': 3, 'r': 3, 'v': 2, 'g': 2, 'l': 2, 'y': 2, 'u': 2, 's': 2, 'i': 2, 'I': 1, "'": 1, 'b': 1, 'f': 1, ',': 1, 'd': 1, 'w': 1})
It should be able to do bigrams too, although they have to be hashable
>>> collections.Counter(tuple(bigram) for bigram in seq)
Counter({('when', 'the'): 1, ('the', 'young'): 1, ('young', 'people'): 1, ('people', 'returned'): 1})
 
ok so do I need to convert them to tuples?
 
Yeah.
But perhaps you can cut down on some steps if you're generating that list from the initial input. No point doing "convert string to list of lists of strings, then convert to list of tuples of strings, then pass to Counter" when you can just do "convert string to list of tuples of strings, then pass to Counter"
 
3:23 PM
thanks! @Kevin
 
For example here's an approach that doesn't permanently store the data in any kind of intermediary form, it goes straight from plain string to histogram
from collections import Counter
def iter_grams(seq, n):
    for i in range(len(seq)-n):
        yield tuple(seq[i:i+n])

s = "when the young people returned"
c = Counter(iter_grams(s.split(), 2))
print(c)
#result: `Counter({('when', 'the'): 1, ('the', 'young'): 1, ('young', 'people'): 1})`
Of course behind the scenes it goes from string to list of strings to generator of tuples of strings to Counter, but none of the intermediary objects are bound to a name, so they're not cluttering up our namespace
Oops, I just noticed the off-by-one error. That should be for i in range(len(seq)-n+1):
Final thought: I bet there's a third party NLP library that does a lot of this work for you, in addition to nice sanitization of input with inconsistent capitalization and punctuation etc
 
Thank you so much! I was able to put together everything and improve the code :)
So I found out about nltk and its ngram funtion which returns a tuple as you showed above
Then I just combined both (your approach and nltk's function)
bigrams_counter = Counter(ngrams(text.split(), 2))
ngrams is the function available in nltk which does the same
 
👍
nltk may indeed be the library I was thinking of
 
3:39 PM
Hey, folks!
I need help with getting the content of this link
{"msg":"OK","server_time":"2021-06-06 17:37:56","status":200,"result":{"files":[{"link":"https://sbembed1.com/1j66d2r1nmrc.html","thumbnail":"https://i.sbcdn21.com/1j66d2r1nmrc_t.jpg","file_code":"1j66d2r1nmrc","canplay":1,"views":"0","length":"5","uploaded":"2021-06-06 16:15:10","public":"1","title":"test","fld_id":"0"}],"results_total":"1","results":1}}
Thank you in advance!!!
 
If you're trying to get 'https://sbembed1.com/1j66d2r1nmrc.html', then try d["result"]["files"][0]["link"]
Assuming that d contains the object you just posted, and assuming it's a dict. And not, say, a string that just looks like a dict.
If it is a string, there are ways around that
 
I changed d to soup and it didn't work.
input:
`soup = BeautifulSoup(res.content, 'html.parser')

print(soup["result"]["files"][0]["link"])`
I got a KeyError that stemmed from 'result'
 
Makes sense. soup is not a dictionary, so my dictionary-based solution wouldn't work.
 
Yeah, I figured. What do you suggest, Omni man?
 
I'm a little confused now. Where did the object you showed us come from? Is that the result of print(res.content), or print(BeautifulSoup(res.content)), or print(res), or something else?
 
3:48 PM
I used requests to get this API information. Then, I thought I'd use BeautifulSoup to arrange it and get one part of it.
 
AFAIK BeautifulSoup does not know anything about HTTP response codes, so I wouldn't expect "status":200 to show up in a soup's output unless the page is doing something very weird
 
hmm yeah BeautifulSoup would be trollling
you have a point
 
@Dannie I think you would have to use the requests module to handle status code too afaik
 
I'm certain the information needs to be in a dictionary in order to get a key value.
But how do I convert the requests information into one?
@NordineLotfi It works perfectly but I get this:
 
How about import json; d = json.loads(res.content); print(d["result"]["files"][0]["link"])
 
3:51 PM
{"msg":"OK","server_time":"2021-06-06 17:37:56","status":200,"result":{"files":[{"link":"https://sbembed1.com/1j66d2r1nmrc.html","thumbnail":"https://i.sbcdn21.com/1j66d2r1nmrc_t.jpg","file_code":"1j66d2r1nmrc","canplay":1,"views":"0","length":"5","uploaded":"2021-06-06 16:15:10","public":"1","title":"test","fld_id":"0"}],"results_total":"1","results":1}}
 
Assuming that res.content is a string that exactly matches the output you just posted
 
Yeah, I'm sure it's a string.
I woulda bet my house during the 2008 crisis on it
 
Rule of thumb: 99% of the time, BeautifulSoup is only useful if your string is HTML. {"msg": "OK", blah blah blah} is not HTML.
 
True.
 
Anyway. Did my json suggestion work?
 
3:53 PM
Ya know Kevin
I'm gonna end up kissing you one day
 
:-)
 
Could you explain why you added the index before ["link"]
there's one link, so shouldn't that have substituted?
 
the value associated with the "files" key is a list, so you have to index the list to get its contents. This is true even if the list contains only one element.
That's not specific to http responses or json, that's how lists work in basically any language too
 
Right. That escaped my mind. Damn it, Kevin! You're an American hero!
 
Incidentally, many HTTP fetching libraries have a helper method that converts response content into a json-like data structure without you having to do anything manually. For example, requests has response.json(): docs.python-requests.org/en/master/user/quickstart/…
 
3:58 PM
I'll def look into this. Thank you!
May the FBI never knock on your door!
 
I accept this blessing with grattitude
 
 
2 hours later…
6:10 PM
Btw I found the formal name for the concept we discussed a while ago with andras about discussion and iron manning and rationality. en.wikipedia.org/wiki/Aumann%27s_agreement_theorem That's what I had formulated in my mind and now found it
also readthesequence.com is awesome :)
 
Ah, I heard of the concept but didn't know the term
 
6:33 PM
I disagree with you guys all the time which is handy proof that you can be smart and motivated and knowledgeable, and still not rational
But perhaps the theorem is still useful when two regular humans disagree, since it can give hints about why they disagree. Are we missing common knowledge? Are our priors different? Do we have a goal more important than being right? Did I forget to carry the one when I did the formula for Bayesian updating?
I don't actually understand conditional probability... I tried doing the math on simple examples and I got weird results. Scenarios like "you find a quarter on the ground, and flip it once. It lands with heads facing up. What are the odds it will be heads if you flip it again?"
 
Conditional probability took away my approx 10 marks todays on maths exam :/
 
@Kevin Probably because there's no conditional probability there :P The last coin flip has no effect on the outcome of the next flip.
 
@Aran-Fey So they are independent events?
 
Yes
 
What if I have an additional prior: "thanks to the efforts of a mad counterfeiter, the ground around town is littered with unfair coins that come up heads with probability P. You estimate that there is a probability Q of any particular quarter on the ground being unfair"
 
6:47 PM
So that would mean P(A/B) would be same as P(A)?, I guess
 
There's certainly no conditional probability if you have absolute faith in the fairness of the coin. i.e. Q=0. But it is said that Bayesians don't believe in probability zero.
 
@Kevin Yup, in that case it would be conditional probability. Flipping the coin gives you information about how likely it is to be an unfair coin
 
@Kevin this is true :)
 
Ok, I'm glad I'm on the right track conceptually. Maybe I'll take another crack at the math.
 
otherwhise you are stuck and can't update anymore
 
6:51 PM
Intuitively, I expect my beliefs to update a little bit after observing one flip, and to update a lot after, say, getting 100 heads in a row
 
anyone have a recommended thought process for deciding when/when not to use dot notation?
I know it's probably a question of preference, but I always forget when/when not to use it...
 
The alternative to dot notation being what?
 
If it makes your life easier, use it :-)
 
@Aran-Fey parentheses?
 
I don't follow. You're asking when to use foo.bar instead of foo(bar)?
 
6:56 PM
I meant, doing something like this func(something) instead of func.something
@Aran-Fey yeah, essentially :)
or if there other possible notation beside dot and parentheses (but I don't think there is right?)
 
If I understand your question, I'd say there are others.
 
@Kevin it does! but sometimes I'm unsure if it work with a particular thing, so I just try-and-fail or check code template example on a particular thing
@Kevin oh, interesting
 
@NordineLotfi Those are completely different things though. In func.something, func is an object andsomething is the name of an attribute/quality/whatchamacallit that func possesses. In func(something), func is a function and something is the input to that function.
 
@Aran-Fey :o so I guess that's where stem some of my confusion about this
 
For example, pandas can employ some truly strange (IMO) syntax involving square brackets
 
6:58 PM
@Kevin yeah, I noticed this too (but since I never really used pandas seriously, I just thought they were weird list)
 
In other words, foo.bar means "give me foo's bar", whereas foo(bar) means "do foo with bar"
 
Here's one I picked randomly out of the pandas docs: df1.loc[:, df1.loc['a'] > 0]
 
@Aran-Fey gotcha, this does make more sense when it's said like this :D Thanks, I'll keep that in mind
 
"pandas' datatypes are basically weird lists": true
This might be too technical, but the primaries of Python may be what you're wondering about. They describe the basic things you can do directly with a variable (and also more complex expressions)
 
@Kevin Thanks! I'll check this out :)
I don't mind if it's technical since I think this probably was closer to a technical question anyway
 
7:03 PM
So for some variable x, you have a choice of atom (essentially leaving it alone, e.g. x), attributeref (e.g. x.y), subscription (e.g. x[y]), slicing (e.g. x[y:z:w]), and call (e.g. x(y))
 
is there any way to know in advance if a specific thing (eg: function, classes, etc) support dot notation/parentheses/etc or not? something like type() but for this specific usage?
 
The documentation? :P
 
XD
Yeah, but I meant, so I could do it interactively in ipython without having to check the doc
 
Why would you ever go out of your way to not read the docs? Sounds like a bad idea
 
so I would just do magicfunc(function) and it would show me if it support dot notation or other
@Aran-Fey sometimes I don't have internet...
although I guess I could get them offline hmm
 
7:06 PM
There's always the help function
 
facepalm
yeah, should work
 
Virtually all objects have at least one attribute, so x.y is almost always possible if you know what "y" to use. subscription and slicing might be supported if the object's class defines __setitem__, and calling is supported if its class defines __call__.
 
@Kevin I see :o the term "atom" is a clever one to use in this instance (didn't know it but it does make sense when used here)
 
atoms are 100% supported by all objects no matter what, if you haven't guessed that
There is no value that will crash your program just by writing the name of the variable it's bound to
... I think.
 
@Kevin I see. I guess that's one more thing I discovered today! Thanks :D
 
7:10 PM
The only way for an atom to crash your program is the absence of an object
...Y'know, just in case this whole thing wasn't confusing enough yet
 
When you get as deeply philosophical as "but what can you do with an object, really?", then things automatically become confusing :-P
 
Time to reset the counter once again
 
@Aran-Fey didn't know :o
 
Beware thinking too deeply... First, you'll start to see everything as zeroes and ones. Then, those too vanish, and you'll find that the lowest foundations of logic are completely empty
 
@Kevin I didn't think there was anything lower than binary...very much appreciated for this
 
 
2 hours later…
9:03 PM
Ok, 90 minutes into conditional probability and I've almost proven that P*Q + R*(1-Q) is in the range of [0,1], given that P and Q and R are all in the range of [0,1]
 
9:25 PM
Hmm, it's obvious just from looking at it, but I have no idea how to translate that into a formal proof
 
First I need to prove that X-Y is in [0,1] given that X is in [0,1] and Y is in [0,1] and X >= Y
I have 90% of a proof but I'm assuming that X < Y is equivalent to -Y < -X, which feels just a little "draw the rest of the owl" to me
 
Hmm, multiplying by a negative number and flipping the comparison operator is a pretty standard operation IMO
 
Yeah. looking at en.wikipedia.org/wiki/Inequality_(mathematics), it's very easy to prove if the converse and additive inverse properties are guaranteed axioms.
I suspect they're not "bare metal" axioms, if you're willing to strip off some abstraction layers and think about the properties of total orderings over the set of reals. But I'm not super interested in that right now.
 
Folks, how to avoid horizontal scrolling when loading documentation in VS Code?
 
View -> Toggle Word Wrap?
 
9:35 PM
@Aran-Fey: Thank you very much. You saved my life and time!
 
Yes, I also suggest word wrap. Refer to stackoverflow.com/questions/31025502/… for far too much information.
 
OK @Kevin: I set it in the global setting.json. Thank you!
 
X >= Y              #given
X - Y >= Y - Y      #subtract
X - Y >= 0          #simplify

X <= 1              #given
Y >= 0              #given
-Y <= 0             #additive inverse + converse
X - Y <= 1          #addition

0 <= X-Y <= 1       #the "move some stuff around" property
∎
 
Oh, smart
 
It's interesting to me that this is provable with only three givens, even though the problem statement seemingly gives us five facts about the system. Perhaps X >= 0 and Y <= 1 can't be considered "independent facts" because they can be derived from the other three facts. X >= Y and Y >= 0 implies X >= 0, for example.
 
10:07 PM
@Kevin that looks like a linear combination of P and R, which will always fall between P and R, hence also between 0 and 1
The values of P*Q + R*(1-Q) are situated on the line between (0, P) and (1, R) where Q is basically your scale from P to R.
 
Yeah, earlier I was thinking "looks like a lerp", and from experience I know that doesn't stray past its endpoints.
 
Correction: convex combination
 
Some easings do spring past their endpoints, but it's bayesian probability time, not cool animation techniques time
Convex combination -- another fine addition to my collection of mathy terms
 
10:30 PM
Folks, is print("\n"*50) the only way to clear screen in python?
class MyObject:
    def __init__(self, name="Rune"):
        self.name = name

    def get_name(self):
        return self.name

    def print(self):
        print(self.get_name())


print("\n" * 50)
obj = MyObject()
obj.print()
This trick sounds too weird. :-)
 
@Kevin: Thank you very much!!!!!!!!!
 
IMO there isn't a "clean" way of doing this, that works the same on all OSes and isn't doing something silly with newlines. I suspect this is the case because 1) there isn't much demand among professional devs for console screen clearing; 2) The Python design team doesn't want to assume that the user's output device is capable of clearing itself.
 
@TheShortestMustacheTheorem there is really no need to be creating getter methods here
Just access the attribute directly. If you want to change how an object is displayed in the console, then set a __str__ or __repr__ method to fit with the Python data model. I know this wasn't what you were asking about, but it's (IMO) worth raising. This isn't Java/C#
 
@roganjosh I am watching a tutorial at udemy. Maybe I will understand why it is not necessary later. :-)
 
10:38 PM
if they showed you such a getter they won't tell you why it's bad form
 
Or perhaps it's more concise to say "operating systems make very few guarantees about the stdout standard stream" and "For the sake of compatibility, the Python dev team assumes nothing about stdout other than what is guaranteed"
 
the people telling you that's bad form won't show you code like that as a good example
 
Do you mean I should write like this?
    def print(self):
        print(self.name)
 
I wish there was a stable floor to hold my opinion of these courses, but the subsidence is apparently chronic
 
yes
 
10:39 PM
As a concrete example, some old computers use a physical ink-on-paper printer as their stdout device. Can't clear that without whiteout.
 
OK. Thank you all!
Continue watching the tutorial .... :-)
 
What you might want to do is use a @property to prevent the attribute from being overwritten, but that's another matter
 
oh ok. Thank you!!
 
@TheShortestMustacheTheorem I know you "can't be bothered to read documentation even after wrong things have happened" but you really should consider reading the official tutorial
(instead, or first, rather than in addition to)
 
@AndrasDeak Yes. Ideally I should read the official. I am in hurry to master opencv that is taught in python now. :-)
 
10:43 PM
If "continue watching the tutorial" means "later in the tutorial, they explain that their sample code from earlier was intentionally bad, and show you how to correct it to make it good", that doesn't totally convince me that the tutorial is good. It demonstrates that they have good technical ability, but raises a red flag about their grasp of the philosophy of education.
 
@Kevin: Totally agree with you. Thank you!
 
I don't think it's a good idea to teach someone the wrong way to do something, without indicating that it's wrong, and only later teach them the right way. Especially in one-way mediums like this where the listener might close the window halfway through the video, and never discover that get_name was a ruse
 
Fortunately 95% of the time it's just the authors being genuinely bad coders, rather than being merely crucially misqualified to teach.
 
To be honest the second method in the following is my creation:


def get_name(self):
return self.name

def print(self):
print(self.get_name())
 
Now, if they said "here's a sample class that demonstrates how to assign and access attributes. It doesn't completely follow best practices of class design -- We'll get into that later -- but it's good enough for our purposes now"... That's another story, IMO
 
10:47 PM
I expect the course will do nothing of the sort
 
Now little Joey WindowCloser at least knows that there is something wrong with the code, even if he never learns what. So he won't put complete blind faith in the design pattern.
 
I paused the video, and do some modification based on my creativities that might be wrong. :-)
 
@Kevin LPTHW vibes
 
If you're saying "the tutorial doesn't actually recommend get_name, that's just something I came up with as an experiment", then that's fine. I write bad code experimentally all the time.
 
@TheShortestMustacheTheorem just ask yourself what point there would be for such a getter in a language where you can freely access attributes
 
10:50 PM
@AndrasDeak: the get_name() is needed if I want to print the name of the instance of the class. :-)
 
No, you can just do self.name
you can even omit parentheses that way
 
I see you asked earlier if print(self.name) was a valid approach, and it is. Did you have trouble integrating it into your code?
 
Yes, really
 
@TheShortestMustacheTheorem that's what get_name() does, and it's not special at all
 
10:51 PM
obj = MyObject()
obj.get_Name()
I want to do this.
 
Yes, but we're telling you we don't do that in python.
 
Why do you want to do that?
 
OK. I will make it private with __.
 
But why?
 
because C#-flavoured python is best python
 
10:54 PM
import subprocess as sp


class MyObject:
    def __init__(self, name="Rune"):
        self.__name = name

    def get_name(self):
        return self.__name

    def print(self):
        print(self.__name)


sp.call("cls", shell=True)
obj = MyObject()
obj.print()

#  the following cannot be compiled!
# print(obj.__name)
 
So
 
get_name is needed
 
That doesn't give me a reason as to why name needs to be mangled
 
that's how you sell first-aid kits: "perfect for shot wounds in your feet"
oh well
 
OK. I am reading at random orders. I will come back again later. Thank you folks, sorry for my bad codes. :-)
 
10:56 PM
ideone.com/39FoQi demonstrates that ordinary attributes are perfectly accessible both inside and outside a class, without requiring a getter
 
Is it bad to make the name private?
 
Not necessarily. That feature exists in the language for a reason. But if you can't think of a very good reason to use it, you shouldn't use it.
 
@roganjosh To make the name field private so get_name() becomes crucial or needed. :-)
 
I think perhaps two things are being argued here: the regulars are saying "it's very rare that it's necessary to define a getter for an attribute", and Shortest Mustache Theorem is saying "sometimes, it's necessary to define a getter for an attribute"
 
Again, why? You can't have proper private variables in Python, even if you invoke name mangling. If you want some function to run before a property is set then you can imply the attribute is private by having a single leading _ in the name and then use @property as a getter/setter
 
11:02 PM
@roganjosh OK. I took a note for this. And I will review later because I have not reached such a feature yet. Thank you very much!
 
If the regulars assume mustache is saying "getters are frequently useful, actually", and mustache thinks the regulars are saying "getters are never useful, actually", then nobody is going to be able to convince anyone of anything, because our actual arguments are already compatible.
 
I think it's clear to them that a paradigm has been lifted from one language and plonked into Python, and it doesn't hold water in the same way
 
@Kevin: I believe in the regulars' for sure because they have more experience in Python. :-)
Just follow the expert to be safe. :-)
Thank you very much for our discussion. I have to continue watching the tutorial, the deadline is approaching... :-)
 
FWIW, I wasn't just nitpicking. Your codebase will balloon totally unnecessarily if you keep following that approach. I just wanted to call it out :)
 
I'm tempted to bring up the @property decorator, because it eliminates one of the common justifications for getters in other languages, in particular "I want getting/setting to trigger some kind of side effect, and I can't do that with a plain attribute"
On the other hand, descriptors are not exactly newbie-friendly, so I think it may only confuse things further. Therefore I will not bring up descriptors or @property at all.
 
11:30 PM
Out of topic: I have an old question here: https://tex.stackexchange.com/q/549836/87876


I want to know whether there is any python package that can be used easily to draw stereometry problems? How about blender+python?

Is blender+python promising solution?
 
Blender has a robust command line interface, right? If all else fails, you can communicate with it via the subprocess module.
 
@Kevin I am not familiar with Blender actually.
 
Ok. I guess I'm saying that, in general, if you have a functioning solution in some other language or platform, then you can probably send those results to a Python front-end.
 
@Kevin: OK. I have no solution from other languages so I need to create from zero with the tool I am looking.
By the way, how to solve the following dependency issue?
The conflict is caused by:
pyvista 0.30.1 depends on vtk
I tried invoke
pip instlal vtk but it produces other errrors.
It seems vtk is not a package that I can install from virtual environment.
 
11:50 PM
Rendering 3d wireframes or solid shapes in Python is relatively easy, since OpenGL has Python bindings, and IIRC there are a handful of libraries that build on top of OpenGL to provide a nicer interface. Drawing labels for points and line segments may be more challenging, if they don't provide a way to examine the 2d screen coordinates of a 3d logical coordinate, without actually drawing it.
And even more challenging if you want some kind of force-directed logic that nudges labels around so they position themselves in empty space instead of obstructing an important part of the shape
 
@Kevin: OK. How about rendering LaTeX for the labels?
 
All of this assumes that you already know ahead of time the logical numerical coordinates of the shapes you want to draw. Deriving those coordinates from 3d geometry problems such as "project point X onto line segment Y" is a whole other can of worms... I don't know of any Python libraries that will do that math for you.
projections and cross products and such are fairly easy to implement yourself, using simple vector classes. But I imagine there are problems that you can't just find the formula for on Wikipedia. Such as, I don't know, "find the intersection of these two hyperboloids"
 
MOst the objects I want to draw are cubes. I am teaching high school students. :-)
 
Even "find the intersection of these two cubes" can be very difficult, if you're sufficiently determined :-)
 
I am trying to invoke the following code:
import pyvista as pv
from pyvista import examples

unstructured = examples.load_hexbeam()
poly = examples.load_ant()
poly.points /= 10
poly.points += [0, 2, 3]

plotter = pv.Plotter()
plotter.add_mesh(unstructured, color=[0.6, 0.2, 0.1], label='beamy')
plotter.add_mesh(poly, color=[0.1, 0.6, 0.6], label='anty')

plotter.add_legend()
plotter.show()
 
11:59 PM
First, rotate cube A along axis X by pi radians... Then rotate cube B along axis Z by e radians... Multiply B's volume by sqrt(2). Now find their intersection
 

« first day (3886 days earlier)      last day (1062 days later) »