« first day (3124 days earlier)      last day (1825 days later) » 

12:41 AM
close / simple typo SyntaxError on filename when trying to read file?. OP tried to use ... (backticks) instead of quotes ('...' or "...") around the filename. It has nothing to do with PSVs or files, specifically.
 
 
5 hours later…
5:32 AM
cbg
@smci Closed, little late tho...
Funny that when making a package, running __init__.py throws an error, but calling it outside works, the error (when running __init__.py) is the problem with . when importing..
 
6:00 AM
yeah, you're not supposed to run any files inside a package
if you wanna execute a package, give it a __main__.py
 
Exactly :-) i am trying to create a new python module...
@Aran-Fey I don't think i need that, i just have a habit of F5 + Enter in idle for running it
 
6:17 AM
Morning cbg
 
cbg =)
 
I need some help from MSeifert as i know he created iteration_utilities module/library, he must know...
I wanna do the same
 
@Darkonaut The most effective thing that can happen to change attention is if OP changes their accept from the current answer to your own. I once stalked someones twitter from a question they'd asked to alert them about a better answer and asked them to consider their vote.
They didn't change their vote, but at that point I had felt that I did what could reasonably be expected.
 
6:39 AM
And that awarded you a restraining order :P
 
@Arne Not likely to happen. OP pretended interest but I think he was the downvoter after some days. Since he linked to this answer in later answers he gave himself, I suspect he has some conflict of interest here ^^
 
ahh, too bad
@AndrasDeak The best ones get framed and glued to the fridge :p
 
6:59 AM
rbrb
 
Good noon peeps
Any Django devs here ?
 
maybe, maybe not. but you'll probably have a better chance of getting a response by just speaking what's on your mind.
 
7:14 AM
Need an advice, My Django views file has lots of code in it, Should I create a separate .py file(say Utils.py) and create appropriate functions and call them from the views.py ?
In Java we can create numerous classes and packages so will following the same architecture for python will be relevant ?
I am trying hard to search a Django project on GitHub and learn the code style/architecture from it but not getting any...
 
yeah, you dont really need a dev to answer that question. Your code structure should make sense to you, and the people who'll maintain it.
if it will help you keep it cleaner, then definitely go for it. Especially if the functions being moved to a separate file "belong" together, it makes it a lot easier to follow what's going on while reviewing code
 
Say if you are parsing a REST API request, in Hibernate and Spring , we create a request object class that maps to the core db object class and then this is passed on as a function to a JAR which will validate and provide appropriate response.
Can we achieve the same in Django ?
 
@GeekDroid that's a standard practice, you can split into multiple files if the code gets long. See this for an example - github.com/mirumee/saleor/tree/master/saleor/checkout
You can do similar stuff with the models.py as well.
 
sure, why not. Though if i may add, java is a bit...excessive when it comes to classes. Python traditionally when making packages is perfectly happy with making packages/sub packages, instead of explicitly defining classes. Classes are used when they make sense, and are important to tie functionality together in an object that needs to be either directly used or passed around. when it comes to just "operations", just a module or package with functions can suffice.
 
@GeekDroid yes, you'll be importing stuff from the relevant utils.py (or whatever other way you name your files) into the corresponding views.py file(s). Basically, views.py need only handle the request processing logic at a broad level, other fine details / routines can go into other .py modules (e.g. utils.py or forms.py or tasks.py)
 
7:33 AM
I am trying to compare two dates to see if the date is greater than todays date, but when I put it in a function it fails to execute the if. if I just do it as a few lines it works though.
import datetime

def adjust_date(newdate):
    try:
        print(1,newdate)
        strdate = datetime.datetime.strptime(str(newdate), "%Y-%m-%d 00:00:00")

        strdate = strdate.date()
        print(2,strdate)

        nowdate = datetime.datetime.now()
        nowdate = nowdate.date()
        print(3,nowdate)

        if newdate > nowdate:
            print("broken")
            return strdate.replace(year=strdate.year-100)
    except:
        return newdate
    return strdate

adjust_date('2065-01-24 00:00:00')
output is :
1 2065-01-24 00:00:00
2 2065-01-24
3 2019-05-06
'2065-01-24 00:00:00'
 
@ThelurkerLurker It looks like newdate is already some kind of date object (perhaps a daretime.date), so why are you converting it to a string & then converting that back to a datetime? Also, please don't use bare except, use named exceptions.
 
@PM2Ring Thank you, will look at that
 
7:53 AM
@shad0w_wa1k3r Thank you
@ParitoshSingh Thank you.
 
8:47 AM
i have a fairly large dataframe and i have 2 date columns and an ID column. is it possible to create a 3rd date column that checks to see if this is the first instance of the ID and if so use date1 else use date2?
first instance as in earliest of date column 2
 
9:00 AM
if that makes sense
 
9:14 AM
Hey no one has replied to my question , probably because someone have down voted it stackoverflow.com/questions/55987726/…
Could you guys check it out and let me know where is problem or up vote it if there's none
 
@U9-Forward Thanks. In fact turns out they were Unicode quotes U+2018,9, which are also illegal for quoting a string. You can see this with [ '{:02x}'.format(ord(c)) for c in "‘training.psv’" ] from this answer
but not much point in reopening the question to say that, so I left a comment.
...for which an existing duplicate question-and-answer is this one from MartijnP
I plan to nominate Print a string as hex bytes? to the canon. Anyone got any updates for 3.6/3.7/f-string ? Note that Unicode hex sequences longer than 2 bytes get correctly rendered: [ '{:02x}'.format(ord(c)) for c in "‘fancy Unicode U+2018,9 quotes’" ] Are there any other, more general questions and answers? e.g. octal? other bases?
 
9:52 AM
Hello I have installed anaconda
and I am trying to run a python file from vs code
when I start it, it is not recognizing the conda command
 
10:03 AM
@za001a the room's rules ask you to not bring up a question here until it's 48 hours old; see sopython.com/chatroom
also, asking for upvotes is not considered good style
> when i tried print( x['test1']) i got Syntax Error
if that's what you are trying to troubleshoot, the question needs to contain the actual code, in context -- the print on its own is valid syntax, as you can easily verify, but the syntax error might come from a missing close parenthesis on an earlier code line
 
10:34 AM
Heya o/
Is there anyway to parse a json which key has special characters like "$" ? Reference question: stackoverflow.com/q/55461576/1944896
 
>>> json.loads('{"A":"33","$C":"12"}')
{'A': '33', '$C': '12'}
works fine
 
btw which json module you used ?
I am using flask.json
 
import json
 
Oh okay, lemme check
Found the issue
Some commented line I had copied as well as part of json which was causing the issue
 
I want to form a json from rows coming from an XLSX file
I am using openpyxl
which will be the best way to?
 
10:45 AM
@tripleee i thought its 24h only ... it was 24h if i'm not wrong
i agree with u about the upvote i'm only looking forward to solve an issue and downvoteing it makes it less likely to be solved ... not sure why i got down voted tho
and yes that is the actual code ...
i just added a comment between them
to explain
 
@AndrasDeak I used used a lambda myself and got things to work like i wanted
 
@TheLittleNaruto Which room are you most active in ?
 
11:03 AM
@QuicoLlinaresLlorens if you happen to have pandas installed, you can cheat slightly... json_string = pd.read_excel('your_excel.xlsx', sheet_name='whatever').to_json(orient='records')
 
ok this is weird
x = {'test1': Table('test1', MetaData(bind=None), Column('id', INTEGER(), table=<test1>, nullable=False, server_default=DefaultClause(<sqlalchemy.sql.elements.TextClause object at 0x000001F83BCAEC50>, for_update=False)), Column('name', VARCHAR(), table=<test1>, nullable=False), schema=None), 'test2': Table('test2', MetaData(bind=None), Column('id2', INTEGER(), table=<test2>, nullable=False, server_default=DefaultClause(<sqlalchemy.sql.elements.TextClause object at 0x000001F83BCCEA58>, for_update=False)), Column('name2', VARCHAR(length=200), table=<test2>, nullable=False), schema=None)}
 
11:25 AM
@kauray glad to hear that
 
@za001a 48 hours is spelled out very clearly in the room policy I linked to
 
22 hours ago, by Andras Deak
@za001a we ask that you don't ask for help with fresh questions you've asked on main. Regarding your question, you should edit it and add the actual error message you get, especially since it's not a syntax error.
22 hours ago, by Andras Deak
Given our history I don't believe you without a full traceback. And anyway this info should go in your question, not here
That's two things that tripleee had to reiterate for you.
 
@GeekDroid On SO ? Mostly Python.
 
@za001a that's not weird, Python has no way to know that a single quote does not end the string started by your previous single quote; so you are saying print('stuff' otherstuff 'morestuff') where I added spaces to hopefully show you more clearly where the problem is
 
@TheLittleNaruto I thought java
 
11:34 AM
@tripleee I mean, 99% of languages with format strings can figure it out... why can't python?
It's not unreasonable to expect that to work
 
@AndrasDeak My most time is devoted to Python Nowadays.
 
@TheLittleNaruto On MSE ?
 
@Aran-Fey they can?
 
@TheLittleNaruto Python has plenty of syntax to allow you to use different quotes; I don't think a DWIM layer would add more value than confusion
 
@triplee @Aran-Fey well... stuff like print('stuff' 'otherstuff' 'morestuff') will work :p
 
11:35 AM
I am confused whether to learn Python,Kotlin or DS & Algo or improve problem solving on Hackerrank/leetcode ?
 
@JonClements absolutely
 
@GeekDroid Shadow's den. But I am not an active user on these sites. I am mostly active on Hinduism.SE
 
@GeekDroid it's hard to imagine you would get "not Python" from this room, but it's really up to what you want to achieve and what you currently understand and like
 
Oh are you an orthodox religious dude ?
@TheLittleNaruto
 
@GeekDroid Dude don't jump here and there. Just stick to Java , solve problems.
 
11:37 AM
those are two different and partially opposing pieces of advice
 
In India, careers are not smooth due to the dynamic nature of the software companies demanding skillsets
 
not just India, mind
 
You can find people here running for money based on skillsets..For eg if Python can earn you more, people would run behind and learn it..
 
some skills are less likely to remain in demand and/or allow you to pivot to new skill sets than others
 
I am an Android developer..don't know when Google would say "Java is gone ! Use Kotlin"
 
11:40 AM
The fact that one can also earn a living using programming is a marginal side-effect. We're here for the fun ;)
 
@tripleee I am working on one company internal project which is being developed using Python. Hence is my devotion. ;-)
 
And learning Python for self my life is hectic...9 AM to 7 PM job life remaining you have hardly 3 hours to spend time for dinner.yourself and friends,family..
 
@GeekDroid A software developer doesn't have a life outside his IDE
 
@TheLittleNaruto M-x butterfly
 
Within this 3 hours Python + Kotlin + DS + Algorithm + problem solving on hackerrank/leetcode...Pretty occupied and messed up...
@TheLittleNaruto True man..No time for friends/family.
 
11:42 AM
@tripleee :D
@GeekDroid Ok bye
 
Bye
 
@AndrasDeak Absolutely. Kotlin example:
>>> println("${if(true) "foo" else "bar"}")
foo
 
huh, I'd never expect that
and bash doesn't do that
 
bash
pfffft
 
but they also only have the one string I guess
@Aran-Fey I used to know perl but I no longer do and these are the two languages I know that have string interpolation
it took me a while to understand what f-strings were even about when people kept telling me it's for string interpolation
scratch that, bash can do that too
 
11:53 AM
bash better than python confirmed?
 
I wouldn't go that far :P
 
iex(1)> "Hello #{if nil, do: "There", else: "World!"}"
"Hello World!"
Been drinking the Elixir cool-aid lately.
 
bash: can nest quotes in string interpolation
python: doesn't make me want to hit my head against a wall if I use it for more than 5 minutes
tough call, but I think python wins by a small margin
 
is this db url correct for pymongo?
DB_URL = f"mongodb://{DB_USERNAME}:{DB_PASSWORD}@ds137596.mlab.com:37596/"
I am getting this:
pymongo.errors.OperationFailure: Authentication failed.
 
12:24 PM
The clue's in the message? :p
 
@Aran-Fey erm how do you mean nest quotes in string interpolation? Bash lets you nest quotes in command substitutions but that's quite separate
 
that's probably what I saw and meant
declare -A aa
aa[hello]=world

echo "${aa["hello"]}"
 
I'm not too familiar with bash, so just mentally substitute "string interpolation" for whatever makes sense :p
 
@Aran-Fey Bash has string interpolation alright, echo "this is the value of $HOME" but you can't nest quotes there
what you can do is echo "this is $(echo "command substitition")" but that's the command substitution putting a boundary between the nested quotes, not the quotes themselves nesting
@AndrasDeak that's not really properly nesting, though it's true that ${variable} in curlies allows for a nested expression inside the curlies, somewhat similarly to how a command substitution puts a boundary between the outer and the inner quotes
 
I'll take your word for it :P
 
12:38 PM
but that's only one level of nesting really anyway (though you could abuse it if you know some variables are undefined)
 
that just means I was right twice, when I said nesting is not allowed and when I said it is
 
exactly! (-:
 
12:52 PM
A recent question asks, 'I am trying to convert a string which is a = "2019-04-22 00:00" to a datetime'. I suspect a Whos On First skit will ensue until it's revealed that the string is actually 'a = "2019-04-22 00:00"'
 
@tripleee sorry i was in a meeting
i tried to make the question as clear as possible
can u take a look at it ?
 
@za001a what indications do we have that you understand written English?
you have received multiple rounds of feedback and meta-feedback and so far it seems you have not been able to understand what we tried to tell you
 
1:07 PM
@tripleee yeah honstly i didn't get it
u said something about the spaces and i have tried to eleminate the spaces it didnt work
i am still at the office and too many meetings happening today
 
So give it some rest, start with a fresh mind later. You're only wasting your time (and quite frankly, ours as well) if you try figuring this out without being able to give it the attention it needs.
reread later the things you've been told so far
 
@AndrasDeak actually only @tripleee gave me feedback no one else did lol ... i've noticed that my question is keep getting ranked down so no one will ever solve it , thanks
 
Perhaps the moral of the story is "make sure your question is as clear as it can possibly be when you first submit it, because 99% of the userbase won't notice if you edit an unclear question after the fact"
 
@Kevin that's kinda tricky because it's always way too clear for us but we are evolved in the issue and that is why we see it that clear , for external point of view they might see something that we don't so we can't
if u can see it now can u tell me if it's clear enough ?
 
1:23 PM
It's not particularly clear, although maybe that's because I don't know anything about Flask or SQLAlchemy. I do think it's a little odd that half of the length of the question is dedicated to the problem of the SyntaxError caused by your malformed f-string, since you already know that the solution is to write it as print(f'\n\n test1 = { x["test1"] } \n\n') instead.
 
@za001a lol.
 
If it were my question I would be inclined to edit out all references to the SyntaxError and ask only about the problem of dynamically supporting databases of unknown type
If you aren't yet clear on why print(f'\n\n test1 = { x["test1"] } \n\n') works and print(f'\n\n test1 = { x['test1'] } \n\n') does not work, it's because a string literal surrounded by apostrophes can't have unescaped apostrophes inside it. This isn't specific to f-strings: x = 'I'm cool' is the same kind of syntax error.
 
cbg-noon
is there any django specialists here by any chance...?
 
cabbage
 
@Kevin "is it though?" :P
 
1:38 PM
As said, I plan to nominate Print a string as hex bytes? to the canon. Anyone got any updates for 3.6/3.7/f-string ? Note that Unicode hex sequences longer than 2 bytes get correctly rendered: [ '{:02x}'.format(ord(c)) for c in "‘fancy Unicode U+2018,9 quotes’" ] Are there any other, more general questions and answers? e.g. octal? other bases?
soliciting your comments...
 
1:51 PM
I'm 70% sure that .format-style arguments also work in f-strings, so that's an easy addition. [I duck to avoid lightning strikes from any gods listening for statements like "how hard could it possibly be?"]
>>> [ '{:02x}'.format(ord(c)) for c in "‘fancy Unicode U+2018,9 quotes’" ]
['2018', '66', '61', '6e', '63', '79', '20', '55', '6e', '69', '63', '6f', '64', '65', '20', '55', '2b', '32', '30', '31', '38', '2c', '39', '20', '71', '75', '6f', '74', '65', '73', '2019']
>>> [ f'{ord(c):02x}' for c in "‘fancy Unicode U+2018,9 quotes’" ]
['2018', '66', '61', '6e', '63', '79', '20', '55', '6e', '69', '63', '6f', '64', '65', '20', '55', '2b', '32', '30', '31', '38', '2c', '39', '20', '71', '75', '6f', '74', '65', '73', '2019']
 
those whitespaces hurt me
 
user7437554
def smina_score(mol, orig_mol='first.pdbqt', prot='second.pdbqt'):
  out = shell('''./smina.static -r {} -l {} --autobox_ligand
{} --autobox_add 8 --exhaustiveness 8 -o {}-{}-redock.pdbqt'''
.format(prot,mol,orig_mol,prot.split('-')[0],mol.split('.')[0]),shell=False)
 
Just repeat to yourself "whitespace can't hurt me, it's insignificant"
 
user7437554
Please, if any of you can help me to improve the notation with .format
 
there's something ironic about shell(..., shell=False)
 
user7437554
1:55 PM
I've done it but I guess it's a mess
 
user7437554
Yes it is, but I have no idea who did it
 
How do you feel about... F strings
 
user7437554
Is it wrong?
 
f-strings would replace the .format, and it would be much easier to read, probably
 
don't use .format or any other kind of string formatting. If you set shell=False, you're supposed to pass a list of arguments, not a string.
 
1:56 PM
and that ^ too I guess, I didn't think further
 
As in, "is it wrong to specify shell=False when calling shell?". If it was wrong, then it wouldn't be an option
 
I'd also bind prot.split('-')[0] etc to separate names first, for readability
 
user7437554
what
 
user7437554
too many things ha
 
out = shell(['smina.static', '-r', prot, '-l', mol, ...], shell=False)
 
user7437554
1:59 PM
I see
 
user7437554
But is it important?
 
So, something like:
def smina_score(mol, orig_mol='first.pdbqt', prot='second.pdbqt'):
    phase_of_moon = prot.split('-')[0]
    blood_type = mol.split('.')[0]
    #todo: pick descriptive names for these ^^^
    output_filename = "{}-{}-redock.pdbqt".format(phase_of_moon, blood_type)
    out = shell(['./smina.static', '-r', prot, '-l', mol, '--autobox_ligand', orig_mol, '--autobox_add', '8', '--exhaustiveness', '8', '-o', output_filename], shell=False)
 
@santimirandarp If you want your code to work on Windows, then yes
 
user7437554
Fine, I didn't know about that @Aran-Fey
 
Anyway, what is this shell function? Did subprocess add some new aliases when I wasn't looking?
 
2:01 PM
Apr 19 at 14:50, by Andras Deak
what's shell??
Apr 19 at 14:50, by santimirandarp
oh, yes, i'm sorry. It is just a link to the shell command line
 
pretty sure it's just aliased subprocess.run
 
"a link to the shell command line" is entirely too vague so I'll go ahead and assume it's the same as subprocess.run.
 
user7437554
haha yes, you're right, but I didn't write it! @AndrasDeak
 
def smina_score(mol, orig_mol='first.pdbqt', prot='second.pdbqt'):
    phase_of_moon = prot.split('-')[0]
    blood_type = mol.split('.')[0]
    #todo: pick descriptive names for these ^^^
    output_filename = "{}-{}-redock.pdbqt".format(phase_of_moon, blood_type)
    out = shell([
        './smina.static',
        '-r', prot,
        '-l', mol,
        '--autobox_ligand', orig_mol,
        '--autobox_add', '8',
        '--exhaustiveness', '8',
        '-o', output_filename
    ], shell=False)
Now with gratuitious newlines
 
@santimirandarp whether you wrote it or not you could look at the code you're using and give a straight answer, you know
 
2:04 PM
@santimirandarp Sorry, I was wrong. Passing a string with shell=False works fine on Windows, but not on linux:
>>> subprocess.run('echo 5', shell=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'echo 5': 'echo 5'
 
user7437554
@AndrasDeak yes, I can even paste it here, but there are many things I don't understand there
 
user7437554
I'm not lazy, believe me please
 
Anecdote: I'm on Windows, and in the past, my attempts to call subprocess.run have failed if I supplied a string instead of a list. I don't remember what value the shell parameter had at the time.
 
I believe you. You only need to find import shell or shell = ... in the code. Don't paste it here.
 
I believe Windows has trouble with shell=True if you pass a list of arguments... because shlex is too dumb to correctly escape things for the Windows shell
 
user7437554
2:07 PM
Np, so should I leave the function as it is?
 
>>> print(shlex.quote("hello world"))
'hello world'
^ uses yammin' single quotes
 
user7437554
@AndrasDeak I'll take this
 
@santimirandarp If you're asking "so should I continue to call shell with a string, to make sure my code works in Windows?", no. If Aran-Fey is correct, then passing a list is only a problem when shell=True. Your code has shell=False so you should pass a list.
It's not like changing it to use a list is particularly hard, since I already did it for you, and incorporated Andras' name binding suggestion to boot
 
@Aran-Fey Why is that a problem? black? json?
 
Windows doesn't use single quotes to escape stuff, it parses that as two arguments like ["'hello", "world'"]
 
2:12 PM
I'm not entirely convinced that "You can't call run with a list when shell=True in Windows" is actually true, since e.g. subprocess.run(["echo", "blah"], shell=True) works on my machine
 
user7437554
@Kevin fine I was just a little puzzled
 
@Kevin Can you try subprocess.run(['python.exe', '-c', 'print("hello world")'], shell=True)?
 
If the proposed mechanism of borkness is "arguments with spaces in them get incorrectly quoted with apostrophes and not quote marks", then I do not observe that behavior: subprocess.run(["echo", "foo bar"], shell=True) outputs "foo bar", which implies to me that apostrophes are not involved
@Aran-Fey Ok.
>>> subprocess.run(['python.exe', '-c', 'print("hello world")'], shell=True)
hello world
CompletedProcess(args=['python.exe', '-c', 'print("hello world")'], returncode=0)
 
hmm, guess I was wrong
but entering python.exe -c 'print("hello world")' into a terminal doesn't work, right?
 
It (seemingly) executes, but produces no output:
C:\Users\Kevin\Desktop>python.exe -c 'print("hello world")'

C:\Users\Kevin\Desktop>
python.exe -c "print('hello world')" prints hello world as may be expected
 
2:18 PM
huh, no output is weird
I expected a crash like
aran-fey@Starlight ~> python -c \'print\(\"hello world\"\)\'
  File "<string>", line 1
    'print("hello
                ^
SyntaxError: EOL while scanning string literal
 
Maybe it's behaving as though it's executing a program whose entire text is the single string literal 'print("hello world")'. This does not jive with my understanding of Windows command line quote handling, but [shrug]
 
Aha!
aran-fey@Starlight ~> python -c \'print\(\"hello\ world\"\)\'
aran-fey@Starlight ~>
forgot to escape the space
so basically it's treated as one single argument, but surrounded by single quotes
which is valid python code that doesn't do anything (it's a string literal)
 
My understanding of Windows command line quote handling is "it's garbage, which is why you should almost always use pathnames that don't have spaces", so it's not particularly hard to not jive.
IOW it's easy to surprise me thanks to my overly simplistic mental model
 
m8_
Hey guys, having an issue using a lambda to divide by 100 if values are ints: pastebin.com/5XTXDmUf. Can anyone take a look please?
 
not sure what the problem is, but comparing floats with == looks like a bad idea to me
 
m8_
2:27 PM
It's dividing some of them but not others
I also tried isinstance(x, float)
 
Isn't that the point of the lambda? divide by 100 if it's divisible by 3, don't divide otherwise
 
try math.isclose instead of ==
 
m8_
right, but some values are divisible by 3 and it's not dividing
 
Can you give a specific example of a number that should divide, and which isn't dividing?
 
m8_
50
 
2:29 PM
But 50 isn't divisible by 3 :-)
 
m8_
if you run the dict and load into a df, you'll see some whole numbers it's not dividing but others it is
So the first value, 90, it divides and returns 0.9
 
If you want to divide every whole number regardless of whether it's divisible by 3, then checking x % 3 == 0.0 isn't a very effective way of doing that
 
m8_
so what's a more effective way?
 
151
Q: How to check if a float value is a whole number

chopper draw lion4I am trying to find the largest cube root that is a whole number, that is less than 12,000. processing = True n = 12000 while processing: n -= 1 if n ** (1/3) == #checks to see if this has decimals or not I am not sure how to check if it is a whole number or not though! I could conver...

TLDR: df.loc[:, 'Initial Percent'] = df.loc[:, 'Initial Percent'].apply(lambda x: x/100 if x.is_integer() else x)
 
m8_
jeez, I see. Thanks
Still confused why isinstance wasn't working though
 
2:34 PM
Wild guess: dataframes like to ensure that every value in a column is the same type, so if you feed it both floats and ints, it will convert the ints to floats.
 
indeed it does
 
m8_
gotcha, thanks
 
I suspect there is an XY problem here and the real problem is "I need a list of percentages, but half of them are numbers in the range [0, 100] and the other half are numbers in the range [0, 1]. How do I normalize these values so they all have the same range?". In which case trying to detect the range based on their type may or may not work depending on what other guarantees you can make about the input
The code works OK on your input now, but what if someone enters 50.7% as 50.7? You should divide it by a hundred but any logic based on checking integerness will fail to divide it.
Perhaps you could do lambda x: x/100 if x > 1 else x, and this works for almost all cases...
But ultimately it's completely impossible to know whether an input of 1 means 100% or 1%
 
m8_
hmm, ok that makes sense. I guess I'll have to rethink this
 
sounds like one of those cases where you have to climb up the pipeline with a big wrench in one hand
(the wrench is not for the pipes)
 
2:40 PM
"Demand (using a spiked bat if necessary) that your client supply you input with consistent formatting" is the solution I had in mind, too
Alternatively, "acquire (in writing) an agreement from the client that you're allowed to completely mangle the input in case of unresolvable ambiguity"
 
Haha, the only other way to check is that you have a set of integers or percentages in several columns that add to one or one hundred respectively. (Assuming no one is giving a 110%)
And that the reporting style is consistent from each source
 
If one of the unspoken guarantees is "all of the numbers with the range [0,100] are always integers, and all of the numbers with the range [0,1] are always floats", then an unambiguous solution does exist, but you need to implement it before you convert to a dataframe, since that obliterates useful type data
Something like data["Initial Percent"] = {k: v/100.0 if isinstance(v, int) else v for k,v in data["Initial Percent"].items()}
 
m8_
So we receive these data via Excel files. Sometimes we get Not Applicable, 90%, 90 or .9. We've never received anything over 100%, or never received a 1 intended to be 100%
 
If I've made a class Pbj and it has methods like get_bread() and put_jelly_on_bread(), is it fine to write in a method that calls all of the methods successively to create the end result like make_sandwich(). That's a normal thing to do right?
 
m8_
so I think your suggestion of if x > 1 might do the trick @Kevin
 
2:52 PM
"nobody ever sent us a 1 that was supposed to be a 100%" is a good sign, and might mean that you can ignore the ambiguity. As long as you're not writing MRI software or an insulin pump controller or something.
 
m8_
ha no, this is tumor content data collection. Still needs to be accurate but no risk to the patient
thanks for your help everyone
 
If the user wants 100% of something, and you give them 1%, will somebody die? Will you get fired? The answer to these will inform your design
 
m8_
no deaths, probably won't get fired...probably is good enough for me
 
Ok, I thought that might be the case. If the process really required a rigorous quality control, then you wouldn't be getting heterogeneous data in the first place
 
m8_
Exactly...our contracts with our clients were written by third graders, so there is no accountable.
 
2:56 PM
If/when heads start rolling, the person that sent you this data will be first against the wall, not you.
(hmm, mixed metaphor there, since walls are used for firing squads, not beheadings. "The person that sent you this data will be at the front of the guillotine line" doesn't roll off the tongue as well)
 
m8_
ha, makes perfect sense..especially for those who served ncoer.com/wall.htm
 
@Kevin first at the gallows?
 
lol
 
Afternoon. I'm building a web with flask and flask_socketio. Until now we have started the web using the socketio.run command (we also use eventlet through monkypatch). In the web I have a database connection and upon a change it will trigger an update on the websocket.
 
If your head is rolling around on the ground after a trip to the gallows, that means your hangman used the incorrect amount of rope. Leave him a bad Yelp review.
 
3:02 PM
However, we are now trying to start with gnuicorn instead... and now when the database triggers, the websocket is closed for some reason...
any ideas (please ping)?
 
Mine would be rolling for sure this year end, I made an API in python2.7
 
did you have to use 2.7?
 
I did not know that Python2.7 is about to retire :(
 
@Markus Hmm, curious. I wonder if some kind of resource cleanup is happening and closing your websocket prematurely.
I briefly wondered if maybe the web socket was going out of scope and getting garbage collected by Python, but that doesn't seem likely if the variable name is still accessible
 
3:08 PM
@lmao Great time to port your API, then :-)
 
well, if it helps, you already wrote the code once. porting would be much easier than starting from scratch. The thing though is this: the code you're writing an API for, that's entirely under your control?
 
Put some parens around your prints, apply a fresh coat of paint over your unicode strings, and bob's your uncle
 
Who's Bob?
 
@Kevin : I hope uncle bob saves me from hangman :)
 
He is the mythical uncle of all people that have successfully carried out an ostensibly simple task
 
3:10 PM
@ParitoshSingh: Yeah, that's entirely under my control...
 
Not to be confused with one's Uncle that Works at Nintendo, who sends you cheat codes every month that never seem to work on your friend's game boys
 
If my last name was 'mao' I'd name my kid 'larry'
 
perfect, the ball's in your court then so to speak ^^
 
@piRSquared Larry Mao!
 
yes, lmao could be his screen name (-:
 
3:12 PM
It works on yours and you definitely were able to capture Yoshi after pushing the truck next to the SS Anne. Your friends probably just didn't defeat the Elite Four 100 times like you told them to.
 
There are many Larry Mao's in China...:)
 
I knew of a Chinese person named Humberto... so it could happen
I debated taking my wife's maiden name which would have been socially confusing for some.
 
@piRSquared: LMAO!!
With your permission, I would like to know her maiden name
 
hoang
I'd have been Sean Hoang
 
has a nice ring to it
 
3:16 PM
Nice that you did not keep that name, lol
Pari = fairy, @ParitoshSingh
 
@piRSquared Xian Hoang =D
 
@Arne ha... that would work
 
That's intelligent @Arne
So uncle Bob, is porting 100% reliable, I would be following this tutorial- digitalocean.com/community/tutorials/…
 
"String formatting syntax has changed from Python 2 to Python 3" -- No it wasn't
 
Yeah, .format exists in 2.7 too.
I support the eternal struggle to get everyone everywhere to stop using percent-style formatting, but a misinformation campaign isn't the way to go
 
3:26 PM
those are the woooooorst.
 
(Today's vicarious pet peeve: the fact that you can't have a quote block and regular text in the same multiline message)
 
Python was born directly into version 3.6
 
@lmao Porting is as reliable as the human that's doing the porting :-)
 
and the quality of the underlying code...
 
You can make your 3.X code work exactly the way it did in 2.7, and you can even prove that it works exactly the same... If you're willing to put in the work
 
3:28 PM
@kevin: Ok then, I am Superman!
@WayneWerner: Quality of underlying code- Improper, Inefficient data structures?
 
Hmm. Was .format backported from 3.X? Then it kind of makes sense to say that .format is a 3.X feature.
 
@lmao Especially if you're assuming the world is ASCII
 
To call it a 3.X only feature rather requires us to throw 2.7 under the bus as a sort of freak of nature that isn't part of the true Python 2 line
2.6 spits on the ground and says "A version that supports from __future__ import print_function is no brother of mine"
 
@WayneWerner: Never thought of that
 
4:03 PM
anyone have a link to wim's un-nest an arbitrary nested iterable post?
hmm that was for including depth as well. There is another one. no matter I modified the code to suit my purposes anyway
 
I still love my ast.literal_eval(f'[{repr(mylist).replace("[", "").replace("]")}]') hack
Geeze that italics font is garbage for inline coding with weird nesting
(granted that only handles nested lists, you'd have to strip some other characters & whatnot)
 
Semi-relatedly, I'm surprised that ast.literal_eval("["*94 + "]"*94) crashes on my machine with a MemoryError. It's not all that much memory, surely
ast.literal_eval("[" + "1,"*100000 + "]") runs OK so it's not as if I'm short on RAM
 
94 embedded lists
uhhh [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] is now crashing on my system.
 
4:19 PM
>>> [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
s_push: parser stack overflow
MemoryError
Interesting
 
So it works for 93, but not for 94
 
> It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.
 
I knew there was a limit to the size of literals, but I didn't know it was 94
 
>>> ast.literal_eval("("*93 + ")"*93)
()
>>> ast.literal_eval("("*94 + ")"*94)
s_push: parser stack overflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/lib/python3.7/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
MemoryError
Okay, the parser doesn't like parentheses/brackets
 
I bet there's a very good reason that the stack can't grow as large as it needs to, but I have no idea what that reason could be
 
4:23 PM
l = []
m = l
for i in range(94):
    m.append([])
    m = m[0]

l
seems ok
 
I think I'll go with "allocating memory dynamically for this purpose makes things hilariously slow"
 
There is nothing funnier than wasting cpu cycles so that I can't get any work done.
 
"model is training"
goes off to swordfight
 
The stack overflow triggers when if (s->s_top == s->s_base) { evaluates to True. Looks to me like they're using a circular buffer as a stack.
Circular buffers necessarily have a maximum size, so necessarily the stack can't grow without limit. The question remains as to why they're using a circular buffer.
On the other hand, github.com/python/cpython/blob/… doesn't look particularly circular. stackentry s_base[MAXSTACK] is a regular old array.
I guess /* NB The stack grows down */ implies that the stack is full when s_top points to the first address in the array.
A bit confusing since when I imagine memory laid out spatially I think of larger addresses as being farther down than lower addresses. From that perspective, the stack grows up
 
4:46 PM
@Kevin: Sorry to interrupt you, do answer me when you are free - How could I increase my knowledge like you guys? Tell me books/sites/resources, I'd religiously follow them.
All of you here are just fabulous.
 
Start with empty array of size 4

+---------+--------------+
| address | value        |
+---------+--------------+
| 0       | junk         | < s_base points here
| 1       | junk         |
| 2       | junk         |
| 3       | junk         |
| 4       | out of range | < s_top points here
+---------+--------------+

call s_push with argument 99

+---------+--------------+
| address | value        |
+---------+--------------+
| 0       | junk         | < s_base points here
| 1       | junk         |
This looks like growing up, right? I'm not having a stroke?
@lmao Here is the response I gave the last time this topic came up
 

« first day (3124 days earlier)      last day (1825 days later) »