« first day (2925 days earlier)      last day (2249 days later) » 
01:00 - 18:0018:00 - 00:00

01:55
How would i get this 2018-10-19T00:23:31Z into a datetime object for comparison ?
d1 = datetime.datetime.strptime("2018-10-19T00:23:31Z","%Y-%m-%dT%H:%M:%SZ")
 
2 hours later…
 
1 hour later…
04:52
@ex080 use iso8601.py
 
2 hours later…
07:00
what's the difference between these two??
a or b in c
(a or b) in c
the other is a or (b in c)
I do not know what you want to do but probably neither is correct.
07:21
@Self the difference is that one clearly defines the order of operations by using parentheses and the other relies on python's definition of the relative precedence of or and in.
07:34
@Self This table sums up the operator precedences in python, in case you want to know the specifics
@Self If a, b, and c are variable names, it is highly unlikely that either is what you really want
07:59
Anyone have a duplicate for this "my random value is always the same" question or do I have to answer it?
08:23
@Aran-Fey I decided to just answer it. But now comments from the OP lead me to believe this is an XY problem with some deep misunderstanding about how python executes code.
I don't think it's a deep misunderstanding, I think they just don't want to rewrite the "tons of variables like this" and are looking for another solution
Maybe you could expand your answer with a function that always returns a random value? That'd probably make for the most minimal change - they'd just have to write random_value() instead of random_value. Might be enough to make them happy.
^
def myTest(): random.choice(["test1","test2","test3"])
cabbage!
cabbage
cabbage
@Aran-Fey Maybe. But it's hard to be sure. And the more info the OP adds, the harder it's becoming to know how to answer them. It's a horrible chameleon XY question, and I'm tempted to VTC as no MCVE.
@Aran-Fey Kill it with fire!
08:38
The OP is a bit of a vampire, but the question itself is fine
From his latest comment, it looks like you were right.
Maybe they got confused by the word "variable" and thought it changes every time it's accessed?
Queue the updated improved question title: Why are variables static and not variable?
08:58
Do we have a duplicate for for i in lst: print(lst[i]) kind of problems?
Hello
I have to develop an REST api in python. I have python script and I want to integrate it to a web application so that I can trigger the script on calling an API.
I am trying to achieve it using flask. Is there any other options available ?
My script if run manually it takes around 5 minutes. So I am afraid that HTTP request may get timed out before completion of my script. How do I overcome it ?
09:13
@Aran-Fey No, we don't. But we should, since it's a pretty common error. I guess the reason we don't have one in our collection is that it's hard to find a dupe target that's sufficiently generic.
Alright, who wants to volunteer to write a boring self-answered Q&A?
Eg, this answer is ok, but the question isn't a MCVE, and the other stuff is a distraction. stackoverflow.com/a/31354671/4014959
Yeah, that's not nearly minimal enough for a good canonical
09:46
hello All,
I am trying to run a command with with output location via subprocess using POPEN but it gives as error that no such file or directory even if output directory is present
on linux system
on windows it is running fine
cbg
stackoverflow.com/questions/52888918/… too broad. OP not willing to explain what the issue is.
@AmanJaiswal My crystal ball tells me that there's a bug in your code. I don't know where, or what it is, though. For increased accuracy, it would probably help if we could see your code.
pObj = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
for line in iter(pObj.stdout.readline, b''): # replace '' with b'' for Python 3
sys.stdout.write(line.decode('utf-8'))
logger.info(line.decode('utf-8'))
pObj.wait()
cmd = ' axel -n 20 -q http:xyz....hsahk -o /home/amanj/runPTXTest/temp/'
> On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.
Use cmd = ['axel', '-n', '20', '-q', ...] instead
thats means all filds will be in a list
can you please give me a breafe summery about this why this is like this
10:01
From an OS viewpoint: When you start a process, you can pass it a list of command line arguments. Not a string. A list. That's why it's recommended to pass a list of arguments to Popen. If you pass a string, Popen doesn't know what to do with it.
COOL
thanks Aran
thanks a lot
What Aran said. And from a more holistic point of view: It's just safer. bash uses whitespace to separate arguments, but whitespace may also occur within arguments. In python, you can just make all arguments different elements in a list and use whitespace freely without having to think about unintended consequences.
Design question. I have a project where I collect global values in a file. Usually, those values are static stuff, like VERSION or SOME_THRESHOLD. But there is also one PATH_TO_ARTIFACTS that is different in test runs and an actual deployment. It's more of a command line option that is convenient to share globally because every component needs it. What do? Is just changing the value on program start a good idea / a safe thing to do?
10:20
I won't say I have a lot of experience in that, but I'd ask myself how accurate the path would be if it was generated at program start. If there is no risk of it going where it shouldn't be going, then I'd go ahead and generate it at program start (with the proper documentation of assumptions and considerations). Otherwise, I'd ask the users to bear with it and supply that path when running the program because the program won't know where to do and thus won't work properly
10:33
I think I focused the question badly. The path not working is completely fine, the users would know best what value to put. I really only mean if the following is safe:
#1importing a file (that wasn't imported anywhere else yet)
#2 changing a value in it
#3 importing said value from the file in many other places, expecting it to yield the updated value
Like, as long as I do my best not to call importlib.reload(my_settings), would it be ok?
As long as you're sure the value will be updated before it's imported anywhere else, it should be fine
Alright, I'll just comment it inline with "no imports before this line", surely everybody will respect it and understand why it's there :p
thanks for the input
10:57
Hi folks. I have a design question also. I am building a pyramid web app with sqlalchemy ORM and can't decide on the best strategy for handling session management. One way of course is to tie the session to the request but that means I will have to pass the session around in my code to the various layers which I don't want. Instead I am using a contextmanager that takes care of rolling back, committing and closing etc.
Was wondering if anyone has any thoughts on this, or knows of a better approach?
For context, yesterday I had a discussion on this following a question I had: stackoverflow.com/questions/52881309/…
11:12
@AndrewWinterbotham A boon to passing request or a session around that was not mentioned yesterday is that it makes your code easier to test. If your functions create their own internal sessions, you will have to patch/mock those somehow.
jpp
jpp
stackoverflow.com/questions/52891059/… unclear on many levels (array vs list), dataframe (pandas, or something else?), bad tagging, etc.
closed
11:29
@IljaEverilä true. How about having a decorator that takes cares of rolling back, committing etc like this: gist.github.com/xkal36/d6f00f8249ce48c5c4c867696ebc92fd
Which allows for easy testing in that the session is passed to the lower level model functions, without the facade layer I have knowing anything about it
11:46
Just trying to see if I can find an approach that gives me the best of both worlds
Although for testing, I would still have to patch the decorator ¯_(ツ)_/¯
So this cbg thing is alive and real, huh
A minor nit: that whole if flush: is a bit redundant, since Session.commit() always flushes.
@AndrewWinterbotham I guess you're familiar with pyramid_tm?
12:10
cbg
Not too familiar with pyramid_tm frankly, still new to pyramid
Sorry, but what is cbg?
@AndrewWinterbotham sopython.com/salad
    when = []
    for i in range(len(ids)):
    	when.append((ids[i], i))
    return cls.query.filter(cls.id.in_(ids)).order_by(
    		db.case(when, value=cls.id)), total
What's going on with the `case` part? the `ids` are the result of an elasticsearch query, and I'm pretty sure this method orders them by their score, but I don't see _how_. What does each tuple in `when` do in `db.case`?
Thought: if the ids are already in order of their score-(highest first), then... No, I'm still not seeing it.
12:25
Hi, what is the best way in Python to go from a dict like {'1':{'a':'b'},'2':{'a':'c'},'3':{'a','d'}} to {'1':'b','2':'c','3':'d'}?
This feels a bit dirty: {k: list(v.values())[0] for k,v in master_dict.items()}
Is the 'a' always there? And are you only creating the dict from the value for those 'a' keys?
jpp
jpp
Possibly: {k: next(iter(v.values())) for k,v in master_dict.items()}
{k: x for k, v in d.items() for x in v.values()}
@isquared-KeepitReal sets in python aren't ordered
list({2,1})
[1, 2]
@Arne that's in a reply to vaultah?
12:30
to you :p
@isquared-KeepitReal there's a typo or your dict is malformed? (2 of those have dicts in them, the third one is a set)
@Arne oh. I do not care about the order
Well, if you do something[0], you do
do you not care which of the values is pulled from your set?
@Arne the value of the key is a single value, it's not a lit
ahh
{'a','d'} -> {'a':'d'}
12:32
yes.. mistyped. sorry
>>> given = {'1':{'a':'b'},'2':{'a':'c'},'3':{'a':'d'}}
>>> {k: v['a'] for k,v in given.items()}
{'1': 'b', '2': 'c', '3': 'd'}
Then vaultah's dict comprehension looks fine
Yes, it does
@shad0w_wa1k3r thanks
Oh, the name of the key is guaranteed to be the same in all dictionaries?
13:10
Friday cabbage!
What I thought would be a simple geometry problem, turns out to require solving a polynomial -_- It's no fun doing math unless I can do it with only a compass and a straightedge.
doesn't the compass have a pencil on one side? Do the math with that.
I tried, but then the pokey bit on the other side kept poking me.
Can't blame a pokey thing for being pokey.
\o cbg
13:20
Fish gotta swim, birds gotta fly, pokies gotta poke
Man got to wonder why why why are bandages so expensive as he clutches the poke wounds on his hand while in line for the register at CVS
13:35
I'm confused what's the poke jokes going on
It's not, like, an obscure reference or anything. I just thought it was humorous that the sharp end of a compass would stab you if you tried to use it as a writing implement.
(compass as in the thing that draws circles, not the thing that tells you which direction north is)
Unfortunately, Wikipedia does not explain why the circle-drawing compass is called a compass, something I have been curious about all my life
Quick math/stats question. When calculating standard deviation or chi square value the process requires calculating the sum of squares. The raw deviations are squared so that the total sum of squares is not reduced by negative numbers. This makes sense to me, but when working with raw deviations that are floats between -1 and 1 the act of squaring the values reduces the value and therefore reduces the sum of squares. Does anyone know a key term I could google that relates to this concept?
I guess because it encompasses a circle?
13:46
Well that explains it well. So a compass is a "pace together"
...
Sometimes old world etymologies are so strange
> From Middle English compas (“a circle, circuit, limit, form, a mathematical instrument”), from Old French compas, from Medieval Latin compassus (“a circle, a circuit”), from Latin com- (“together”) + passus (“a pace, step, later a pass, way, route”); see pass, pace.
Two out of three mentions circles so I guess that justifies it
Although how you get from Latin's "together-step" to Medieval Latin's "a circle", I'm not sure
@Kevin That and the points "come together" was my thought.
This was a thing with Ancient Greek I remember: they had so many words that were built up from so many small words that it was hard to put together the original conception
"come together" makes sense
I would be surprised if the more modern word for a navigational compass didn't at some point inherit something or relate to the use of compasses used with maps in navigation in the middle ages or earlier. I vaguely remember learning about compasses/dividers being used to measure how many of a unit distance one point was from another by kinda stepping them across a map - that rotating would be a circular motion...
13:54
That's hilarious
Lost at C would be a great name for a Learn C Tutorial
Cbg
Could one of you, Python gurus, take a look at my question? I’m sure I’m missing something stupid but I can’t figure it out : stackoverflow.com/questions/52830583/…
Hmm, can't say I know anything about py2exe unfortunately
Why can't python be compiled to machine code?
No problem!
14:01
(context: I just googled compile python to machine code)
In principle, there's no reason it couldn't. But AFAIK py2exe and friends just bundle python.exe plus your script into a single executable file, rather than compiling your script directly to machine code.
Probably because that's a lot easier.
@AlanB. Try being specific about the libraries as seen here: stackoverflow.com/a/20930146/7384740
Just eval by itself would introduce a lot of bloat to a true Python compiler, since any program that could potentially call eval would have to compile the compiler into itself so it could compile strings passed to eval at runtime
Ourobouros-like
14:08
@W.Dodge already tried it, without success
And if you fire up your interpreter you can import unicodecsv no problem, right?
The py2exe FAQ says there's a debug flag you can supply, in order to get more information about what modules it's bundling. Have you tried that?
"if you fire up your interpreter", you mean if I run my code? (Sorry English is not my native language)
I didn't @Kevin, i'll check it out, thank you
"Fire up interpreter" means "run python interactively, so that you get a '>>>' prompt"
As in, can you do this:
C:\Users\Kevin\Desktop>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import unicodecsv
>>>
And not get an exception
14:13
Just to make sure it is there
I can import unicodecsv without problem
Good, good
I used to have a similar problem with matplotlib, but adding
data_files=matplotlib.get_py2exe_datafiles()
fixed the problem
I have to go, thank you for your help!
14:30
Gah! I got bit by Py2 old-style class using an (object)-less class definition in code that is supposed to be Py2/Py3 compatible. I'm getting so used to Py3 style that I just left it off. When the cls.__name__ returned "instance" should been the tip-off.
@ThiefMaster lol, did you add a tag just for telling people not to spam hacktoberfest commits?
There's probably a few we can backfill.
14:47
@Aran-Fey Nice mind reading! You guessed what the OP needed with the random.choice() question
Yesterday I saw a question where the OP was generating random numbers with a homespun LCG and I got the impression that he was doing it not because it was a fun exercise, but because he didn't know that Python had a random module.
@davidism yes, because adding actually prevents it from counting for hacktoberfest
i haven't seen any other malicious/nonsense PRs this year
(i don't want to exclude people who just sent a PR that we disagreed with without the PR being bad per se)
but look at the history of this particular dude - tons of PRs, all nonsense
Huh, didn't know that. I looked at their site and it didn't mention it, it just said they validated the PRs before counting them.
recbg
: http://stackoverflow.com/questions/tagged/c
I want to make a variant of C with significant indentation
I wonder what a straight 1:1 replacement of curly brackets with INDENT and DEDENT tokens would look like
14:58
could we do a canonical duplicate for "Can anyone help me?" with accepted answer "No!"
or at least bring back "Too localized: problem not in code but in the asker's mind"
int main(int argc, char *argv[])
    ...
    while (x == y)
        something();
        somethingelse();

        if (some_error)
            do_correct();
        else
            continue_as_usual();
    finalthing();
Now we just need to remove the semicolons and incorporate dynamic typing, and we'll have a nice language ;-)
user4396006
Hello guys I have here this nested list comprehension its returning NameError cant tell why
user4396006
paths = [os.path.join(dirpath, filename) for filename in filenames for dirpath, dirnames, filenames in os.walk(os.path.dirname(os.path.realpath(__file__)))]
What message?
Try flipping the order of the fors
paths = [os.path.join(dirpath, filename) for dirpath, dirnames, filenames in os.walk(os.path.dirname(os.path.realpath(__file__))) for filename in filenames]
user4396006
15:05
it gives a NameError: name 'filenames' is not defined
user4396006
Why is that? I thought that would be the logical order
user4396006
oh great man it works
user4396006
why is that the correct order? is it not counter-intuitive?
I think there are arguments for both sides of the "which order should multiple for loops in a comprehension be evaluated in?" argument
Same order as if you wrote in nested for loops
15:07
Most expressions in Python evaluate left-to-right, so it makes sense that the loop that creates filenames has to be on the left of the loop that iterates over filenames
On the other hand, the way you were trying to do it feels intuitive to me as well
user4396006
yeah that makes sense however i thought comprehensions would evaluate from inside out
user4396006
yeah idk i guess its just the way it is
user4396006
thank you anyway that was most helpful
comprehensions already violate the left-to-right intuition anyway, since [x+1 for x in range(10)] has x in an expression before x is created by for x in range(10)
It kind of makes logical sense thought because the assignation is to the left, isn't it? So the variable x is closest to the operating procedure?
path = [os.path.join(dirpath, filename)...
not
path = dirpath, dirnames, filenames in ...
user4396006
15:16
yeah i believe that list comprehensions to me should work in the reversed order
hmmm... is it "acceptable" to put multiple from .Package import Module inside __init__.pys? Or rather, at what point (number of imports) is it not acceptable anymore?
user4396006
this is since we put the instruction before definitions, for loops should also be nested in reversed order
I would mildly prefer to live in the parallel universe where list comps are evaluated inside out, but it's not a hill I want to die on
@FélixGagnon-Grenier I'd expect one for each subpackage/module
Is it possible to nest an if statement inside a list comprehension?
15:18
Ok. That sounds logical indeed
sure. [x for x in range(10) if x > 5]
I'd think the question is what you want to put into the package namespace
@Kevin Alright, now that ordering is really screwing with my head
Or perhaps you want a ternary, not a filter? [x if x > 5 else x*100 for x in range(10)]
Yeah, the ternary makes more sense
15:19
@AndrasDeak Well, this was prompted by me not liking an import like from Package.Module import Module (as silly as this might be)
Especially if you were doing a double for loop with a ternary
[x for x in range(10) if x > 5 if x % 2]
@FélixGagnon-Grenier namespaces are one honking great idea; let's have more of those :P
Which is evaluated first?
if x is greater than 5 or if x is even?
Are we going to have the "why does Python allow multiple consecutive ifs?" fight again? I'll get the popcorn :>
adding the import into the __init__ seems to allow the (much) more elegant from Package import Module :D
15:20
@FélixGagnon-Grenier that's fine I think. You'll very often want to separate your functionality into multiple .py files while wanting to keep the one package namespace for all
Hmm, just got an odd error in my REPL:
>>> def f(x):
... Readline internal error
Traceback (most recent call last):
  File "C:\Programming\Python 3.6\lib\site-packages\pyreadline\console\console.py", line 768, in hook_wrapper_23
    res = ensure_str(readline_hook(prompt))
  File "C:\Programming\Python 3.6\lib\site-packages\pyreadline\rlmain.py", line 571, in readline
    self._readline_from_keyboard()
  File "C:\Programming\Python 3.6\lib\site-packages\pyreadline\rlmain.py", line 536, in _readline_from_keyboard
    if self._readline_from_keyboard_poll():
@AndrasDeak sounds good
It's showing up every time I hit the tab key.
you borkeded it!
File "C:\Programming\Python 3.6\lib\site-packages\pyreadline\modes\ emacs.py", line 243, in process_keyevent
15:22
I just hit "a" followed by tab and it displayed and as assert abs( all( any( ascii(. Has the REPL had function name hinting for all this time and I didn't know it?
clearly emacs is at fault
@Kevin it does, usually
@Kevin in python 3: yes, in python 2: no
I've had half-baked installs of 3 which didn't, but it usually does
Restarting the REPL doesn't help. The 2.7 REPL works fine though. Most curious.
Is this because I tried to make a tuple that contains itself yesterday, and I caused a segfault
probably not, although windows
15:26
stackoverflow.com/questions/51250796/… suggests this is a fairly common issue
... Why is abandonware in charge of reading information from my REPL?
@malan x>5 first, then x%2. You can test this yourself by using methods that print to stdout as a side-effect:
>>> def f(x):
...     print(x)
...     return True
...
>>> [x for x in range(1) if f("first") if f("second")]
first
second
[0]
I don't recall ever installing pyreadline... Maybe it was a dependency of something I installed yesterday.
Anyway, I've uninstalled it, and the problem went away.
works for windows too
brb gonna sell all my physical possessions and by doing so transcend mortal concerns
just use ipython :p
prompt_toolkit > pyreadline anyway
15:37
[can't reply, because I'm in the awkward intermediary period between "sold my computer" and "can connect to Wifi directly with my pineal gland"]
Kevin if you can hear us, use this ouija board to tell us where we can find your secret stash of sick references
l o o s e b r i c k
f i r e p l a c e
pbfcomics! :P
:-)
15:42
... damnit. I just broke my no failed audits in 18 months streak on this review. I would not go to war over it, but it does seem that it was reopen worthy after they add their code, samples and desired outcome.
... actually said code seem to have been there from the start...
15:55
SO is 10 years old. Here is python's first question on SO :)
65
Q: XML Processing in Python

saalonI am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the ...

Putting "in python" at the end of your question even though it's already tagged Python... Some things never change
16:47
this meta thread should be required reading for every newbie on SO
17:06
>criminals or terrorists building something evil
How could you even tell?
@Aran-Fey ^delveeable
Amateur malware authors are surprisingly forthcoming about it. "I have a problem with my keylogger, steal_credit_cards.py..."
lol
Maybe once a month I see questions about programs that are definitely viruses
Actually I don't mind answering questions about keyloggers if there's no indication that they plan to use them for evil. I've written a keylogger myself because I wanted custom hotkeys that worked regardless of what window had keyboard focus.
Flask has this annoying habit when I'm in debug mode of spontaneously claiming I haven't created a user_loader
I have to restart the app
I think it happens when I make significant changes to the models
But I can't be sure
My dog has the annoying habit of pressing the button on the surge protector and causing my laptop to run out of battery and me lose all putty connection in the middle of my work with no warning, but that's easier to debug
wim
wim
17:20
does the dog do it on purpose?
probably
dogs and kids can learn stuff like that if they feel neglected (or just being jerks :P)
wim
wim
"time for walkies.. <push>"
I don't think so; more to the point, who the hell designed this surge protector with a giant easy-to-push button at floor level?
Is it possible to create a virtualenv programmatically?
Like with bash?
17:29
Like within Python
Python can do anything that a command prompt can do, thanks to subprocess
So I know I can run pip like: stackoverflow.com/a/35120690/974407
I was thinking I could use subprocess but would pip.main(['list']) run in that virtual env?
My baseless guess is "no"
Once the script is executing I would imagine even calling subprocess.call(["source", "./venv/bin/activate"]) wouldn't hoist the script into a new execution environment
wim
wim
@malan it's a surge protector, not a doge protector
17:39
I guess I can find out with which deactivate
wim
wim
there's a reason virtualenv activate is written in bash, not python
@wim Still, a little inaccessibility for the off switch on a critical power source doesn't seem like too much to ask for.
morning cabbage
wim
wim
already inside the runtime it's too late for setting up the environment
Couldn't you fork a new process though by calling the script with python?
with subprocess*
wim
wim
17:44
I recommend you look at pew github.com/berdario/pew
subprocess may be possible. but that will not be fun.
It seems many people misunderstand what a virtual environment actually is and how it works. It's a really cheap and fragile hack.
It's just changing your executable path to a different collection of python executables so that you don't install a bunch of dependencies in your global python stuff, isn't it?
recbg
@malan sort of. venv isnt as much of a kludge as virtualenv
venv itself shouldn't break that easily
How does pyenv fit into this group?
it doesn't
What is pyenv
17:53
it is another kludge for mainly macosx which makes it possible to install a non-obsolete python in mac.
Sorry I was thinking of pipenv
This question has a pretty good answer on this subject: stackoverflow.com/questions/41573587/…
@PaulMcG pipenv "fits"
it doesn't fit my brain. My neural pathways are fundamentally incompatible with Kenneth Reitz's :d
I use pyenv on Linux also, not just Mac, to test pyparsing changes on different Python versions locally
I've got enough python versions installed side-by-side from ubuntu repos
01:00 - 18:0018:00 - 00:00

« first day (2925 days earlier)      last day (2249 days later) »