« first day (3120 days earlier)      last day (2053 days later) » 

13:03
does years not work for timedelta?
newdate -= timedelta(year=100)
gives an error
The docs would answer that
and days doesnt allow 100 years in timedelta meh 36525
"1 year away" is not a well-defined quantity
timedelta obeys the best-guess at actual dates and times. It is not based on these kind of approximations
i see
if newdate > datetime.now():
        for n in range(10):
            newdate -= timedelta(days=3652.5)
13:11
what do you mean "days doesn't allow 100 years"?
days=36525 gives an error
does it?
>>> datetime.datetime.now() - datetime.timedelta(days=36525)
datetime.datetime(1919, 5, 2, 15, 11, 58, 567226)
hmm i was getting an error
must be a python bug
strange its working now. im not sure what i did
13:13
that's why one should also read error messages and not just conclude that "it doesn't work" or "there's an error"
I don't think there are necessarily 36525 days in a single hundred year span. Keep in mind that leap year rules are more complicated than "once every four years"
I think 365.25 is not a bad approximation for a year
the next correction is every 100 years or so, right?
@ThelurkerLurker Are you sure that subtracting a non-integer number of days makes sense there?
Certainly you'd be pretty dang close. But if a margin of error of one day is too much, then you should consider an alternate approach.
that being said, "100 years earlier" is such a plastic notion that anything might work until the developer defines what they really want to do
13:15
well the problem is my function pd.to_datetime(dat, format='%d-%b-%y', errors='ignore') sometimes is returning from "68" -> "2068" instead of "1968"
>>> datetime.date(2119, 5, 2) - datetime.date.today()
datetime.timedelta(36524)
Knew it
me too :D
The problem is how you're telling pandas to read the date format
@AndrasDeak FWIW, the 365.25 day mean Julian year is what's used in the definition of a light year. A mean Gregorian year is 365.2425 days.
13:16
I'll leave you all to this glorious XY problem :P
(XYZ or more, actually)
@PM2Ring I see
>>> datetime.date.today() - datetime.timedelta(days=36525)
datetime.date(1919, 5, 2)
>>> datetime.date.today() + datetime.timedelta(days=36525)
datetime.date(2119, 5, 3)
Of course, if you want Excel compatibility, you have to use Julian years, not Gregorian. :)
Given that timedelta doesn't have a year attribute, how should one write an expression that takes a datetime and returns a datetime whose year attribute is one larger?
What is a year, though?
It's the value stored in the year attribute. (yes, I'm being deliberately obtuse.)
For the purposes of this thought experiment, the requirement passed down to me from on high is that I must increment the attribute and not think very hard about the consequences of Julian vs Gregorian vs Solar
13:22
Just take the year string and add 1 to it, I guess
x = datetime.datetime.now(); x.replace(year=x.year+1) does the needful but I don't very much like using an assignment statement for something that ought to be an expression
For the purposes of my programs, I treat a year as 365 days in terms of archiving stuff. It's pretty inconsequential to me, and I like it like that. I've had enough of datetimes. They are also deliberately obtuse :P
This looks like a very useful gem in the making, and I'm considering to offer a bounty to attract good answers - but only if it's not a duplicate. (I didn't find any, but that doesn't mean there aren't any.) Has anyone seen a question like this before?
You could always take PM's 365.2425 and convert to seconds and add it. I'm not sure any approach will give a satisfying answer
Perhaps (d:=datetime_expression_goes_here).replace(year=d.year+1) would do it
13:31
Ugh, an aphid flew in my eye as I was leaving, I had to re-enter campus to find a mirror
:-(
@Aran-Fey Surely that's an opinion question?
@Aran-Fey it's hard to believe that there isn't already a good "how to ship python code" answer
@toonarmycaptain Is it? I thought the answer would be "write a setup.py and/or a requirements.txt" (Though I admit I don't know jack about packaging)
@wim's been contemplating a packaging howto for a long while
13:33
@Aran-Fey there is also the "vendor everyhting" approach
Even if there are multiple approaches, it's not like the question is asking "which is the best?". People can post their approach and list advantages/disadvantages. It's a useful question.
and writing a setup.py isn't a good answer anymore, since pep518 introduces the more general pyproject.toml definition
setup.py is specific to distutils
@Aran-Fey the word 'proper' would be the hint to me, as there isn't a 'protocol'. I mean, the question really is - how do I package a project so that it will install with whatever it needs in whatever environment a user attempts to install it in.
@AndrasDeak The modern-day Odyssey is far less exciting
You leave my mother out of this
13:36
@Aran-Fey I absolutely agree it's useful. :)
Just be greatful that you don't have to deal with old dates from several centuries ago, when they did stuff like changing the year number on the 25th of March instead of the 1st of January. Or inserting the leap day before the 24th of February.
@toonarmycaptain I think it's a good QA target. There is a lot of confusion about the matter, and a couple of scenarious that require vastly different solutions
patience isn't my strong suit, but I suppose I'll wait an hour or two before I start a bounty, just in case
Julius Ceasar mandates a drastic change in timekeeping. Software developer Brutus is unamused.
The Mythical Man Month tells us that enlisting 60 men to stab Caesar doesn't mean you can kill him 60 times faster.
13:39
@Arne No argument there. I'd love a canonical pythonic solution, or handful of canonical solutions for different use cases. Yet I feel if I asked "what's the proper way of doing that" I'd have my question shut down as primarily opinoin based.
Twist, Brutus doesn't get his ISO 9001 accreditation
46 BC had 15 months. Make sure you account for this. Mwhaha.
NB If you wish to remain sane, do not try to assemble assemble chronologies with day granularity.
Beware the Ides of Sprint 44.3
@toonarmycaptain I guess "proper" is a word to avoid in a question on SO, but I also guess that python packaging is an exception
since there is so many ways to do it improper
(But wait, that's 44 BC, so it wouldn't make sense for the major version number to count up starting from 0 AD. It would either be Sprint Negative 44.3; or Sprint 709.3, if Sprint 1 was at the purported founding of Rome as depicted by the myth of Romulus and Remus)
13:48
@Kevin Home many days are in your years? 300, 331, 360? ;)
Unclear, which is why the hypothetical ancient roman sprint tracker only has granularity down to months. The only time you need days is when you're trying to figure out when the Ides are.
... Assuming that one calculates Ides by taking the total number of days in the month and dividing by two. I think the actual romans just declared by fiat which day the Ides were on, on a month-by-month basis
"Damn, what a month!" "Lemon, it's the ides..."
tfw you start working the fields on the Nones, toil for what feels like thirty days, and when you look at the calendar it's still only two days to the Ides
Yeah, cos the orbit was different then and the sun didn't do much
Am I having a stroke or does it make no sense that en.wikipedia.org/wiki/Roman_calendar#Months doesn't have a "The 2nd day before the Ides" row
13:57
I believe the general practice would be to read in the file and list that as install_requires. EG something like with open('requirements.txt', 'r') as f: deps=f.readlines() and then in setup() do install_requires=depsRSHAP 56 secs ago
kill me..
@Kevin The Romans used inclusive counting, which can cause a bit of confusion.
alright, I was planning to do something different this evening, but if this preposterous heresy continues I might have to write an answer instead
Someone is that wrong on the internet?
@Kevin Some years back then had 10, 12, 15 months, though.
That's fine. There's nothing wrong with the sprint going to <whatever>.15.
14:01
Eg, when the Julian calendar was introduced, they misunderstood the leap year rule that the Alexandrian mathematicians had devised for them, so for the first few leap year cycles they added a leap day every 3 years instead of every 4.
Sure the client may grumble that it's impossible to calculate how many sprints we've gone through just by looking at the version number, but he'll just have to take our word for it that we're billing him fairly 0:-)
Trying to correlate dates between different ancient calendars can be a real nightmare, unless you have access to dated astronomical records, like dates of eclipses.
Sol System v2.0 will solve this problem by being conveniently placed next to 64 pulsars that just happen to fluctuate in perfect powers-of-two synchronicity when viewed from Earth v2.0.
14:26
hello
Calendar system always reminds me of Mayan & Aztec calendars (nightmare for all us students that time!)
i'm trying to link database through out the front end , for example allow user to input his database link in an input filed and then connect him with his database , it's a CRM project and i'm using FLASK for it
i cant find any lead anywhere
Hey guys, anyone here good with Keras? I'm using the Conv2d layer to go over images and I'm hoping to spit out an image on the other side... the images going in are (500, 500, 3) (3 for RGB). but I'm getting (None,500, 500,3) shape out.
I'm wondering where the extra dimension is coming from?
Gen_Input = Conv2D(32, (6, 6), padding="same", name="generative", input_shape=(500,500, 3), data_format="channels_last")

Generative_Model = Sequential([

Gen_Input,

PReLU(alpha_initializer='zeros'),

Conv2D(3, (3, 3), padding="same"),
PReLU(alpha_initializer='zeros', name="outp1"),

Reshape((500, 500, 3), input_shape=(None, 500, 500, 3))

])
formatting tip: triple backticks don't work in here. For more information, check out sopython.com/wiki/…
thanks Kevin ... yeah I was struggling with them.
I don't know a dang thing about Keras, but I'm suspicious of that input_shape=(None, 500, 500, 3) parameter. Maybe this is where the extra dimension is coming from.
@za001a and it's a little hard to believe that you can't find any information when there's things like this
input_shape=(None, 500, 500, 3)?
Ah I see No it's not that
Indentation saves lives
14:40
@roganjosh thank you for the links i will go through them , and yes it's that rare mainly because i didn't what are the keywords to write in the search engine
@AndrasDeak sure I lost the indentation when I pasted it.
I presume the indentation is something like:
Gen_Input = Conv2D(32, (6, 6), padding="same", name="generative", input_shape=(500,500, 3), data_format="channels_last")

Generative_Model = Sequential([

    Gen_Input,

    PReLU(alpha_initializer='zeros'),

    Conv2D(3, (3, 3), padding="same"),
    PReLU(alpha_initializer='zeros', name="outp1"),

    Reshape((500, 500, 3), input_shape=(None, 500, 500, 3))
])
Not that it matters much because it would be syntactically valid with no indentation at all
@za001a "flask tutorial". But anyway, good luck :)
@PrimeByDesign None is the batch dimension as explained here
# as first layer in a Sequential model
    model = Sequential()
    model.add(Reshape((3, 4), input_shape=(12,)))
    # now: model.output_shape == (None, 3, 4)
    # note: `None` is the batch dimension

    # as intermediate layer in a Sequential model
    model.add(Reshape((6, 2)))
    # now: model.output_shape == (None, 6, 2)

    # also supports shape inference using `-1` as dimension
    model.add(Reshape((-1, 2, 2)))
    # now: model.output_shape == (None, 3, 2, 2)
From the docs
I expect the follow-up question is "ok, so it's by design that the shape becomes (None, 500, 500, 3). But I still don't want it like that. How do I make the shape into what I want after the fact?"
14:50
hi guys !
which is easier to guess a date format pandas or parser ?
What does that even mean?
Parser as in third party library dateparser? I've heard good things about it.
<can vouch for dateparser>
The sample code makes it look quite easy to use. Import and call and you're done
But it is slow
There's too much background info missing from your question. Are you suggesting you want to use pandas to parse a single date, or do you have a dataframe?
14:54
@Dodge - thank you!
Two date-guessing questions in the space of as many hours. Is there a Kaggle competition or something?
@PrimeByDesign As far as getting rid of that, maybe those outputs are built on numpy arrays (should be, it's an image right?). Someone like Andras could tell you how to drop a dimension from a numpy array, I'd need to Google that. Maybe those outputs are something else entirely...
i have a huge list of dates as strings i need to try and guess which is the most common format so i can apply to the list and it's fine if i have 'null' values
but i need to some how guess the format while or before it's being parsed
i tried applying some solutions you've already given me but i ended up with a huge list of format patterns and still was missing some formats while applying them to the datetime.strptime()
@Dodge yeah I can drop it no problem but the issue I have is that I'm creating an adverserial network so I need to put the output of this into the output of another. The easiest thing is to make a sequential of both generator and discriminator.
this means I have to reshape in the graph somehow
@HarvesterHaidar guessing which is the most common won't fix the issue, surely. It sounds like dateparser is the best way forwards
15:01
@Dodge... I did it!
@PrimeByDesign Nice!
@Dodge I simply moved the reshape into the adverserial network which is comprised of the generator and discriminator.
This seems a little roundabout to me. Using a format guessing library to inspect a bunch of datetime-looking strings so you can deduce the format necessary to parse them with strptime... Why not just use the guessing library to parse them once, and never use strptime at all?
Unless the use-case is "I want to run the guesser on a small representative sample of my data so I can determine the most common format, and then use strptime on my real data. Running the guesser on the entire data won't work because my data is huge and the guesser is much slower than strptime"
i can test a small portion of the huge list no problem , and even the ambiguity i can fix but if you have a look at the second answer please . .
https://stackoverflow.com/questions/44321601/how-to-determine-appropriate-strftime-format-from-a-date-string?answertab=active#tab-top
I'm missing something here. I don't think they suggested that but maybe I misread
15:06
it's missing the %y format and when there is 12h40m30s
By my reckoning, Cahit's answer is pretty close to the "guess on a representative sample, then strptime on the real data" use-case I described
Ok, it was insinuated. If you go with dateparser then you apply it to the whole dataset
what like about parser.parse is that it can ignore the separators and gives a single format to almost any string in the shape of date , there must be a way i can guess the date format before returning the date object
Sure, knock yourself out
that's why i'm here lol i can't do that
15:10
As far as I can tell neither dateparser nor dateutil have a function that takes a datetime-looking string and returns a format string suitable for passing into a strptime call.
@Dodge I've been trying to credit you in my answer but I can't seem to find a way to do that... stackoverflow.com/questions/55955044/…
Answer to my own questoin
question*
can you please suggest an solution without involving a list of format patters
... But you're kind of making it sound like there is such a function, since "parser.parse ... gives a single format"
@HarvesterHaidar I'm telling you that you're wrong, but in a nice way. Don't go down that hole; datetimes are Programmers Bane
so please guide me to a solution , i'm new to python
15:13
We already did. "there must be a way i can guess the date format before returning the date object" dateparser does this. It's costly and may be wrong, but the story kinda ends on applying that
Anyway, I'm out. Maybe there is a better way, but I don't know it
I interpret "there must be a way i can guess the date format before returning the date object" to mean "the datetime guesser library I'm using has a function that takes a datetime-looking string and returns a datetime object and a format string that could be used to parse it with strptime. But this is a waste of effort, because I only want the format string. Is there a similar function that only returns the format string? I expect that would be more efficient."
If this is the correct intpretation, I have two thoughts. First, I don't know if there's a function similar to the one you're using, because I don't know which one you're using, or even which library you're using. I suspect it's dateparser but I'm not sure because you haven't formally referred to it by name.
Second, I question the premise that a returns-only-format-string function would be particularly faster than one that returns both the datetime and the format string. Most likely the guesser library can only confidently return a format string if it tried to parse the datetime-looking string and succeeded, so it's doing the work of converting to datetime regardless of whether the datetime gets returned or not.
My second interpretation of your problem is "my datetime guesser library returns only the datetime object and not the format string. This is not useful to me, because my entire motivation for using a guesser is to determine the most common format of a representative sample of the data. Is there a function that gives me the format string? It's fine if it also returns the datetime"
If that is the correct interpretation, then I already answered that: I don't see a function in dateparser or dateutil that does this.
i'll give up on the dateparser , i will stop trying to guess the format from that but i really need a solution
Jan's answer basically boils down to "write your own guesser function from scratch that returns a format string. Here's one that I wrote that you could use"
i tried ignoring the separators and providing a list of format patters so i can use with datetime.strptime() but i ended up with a list of over 300 patter and didn't even cover most of the cases
So what do you hope to achieve by dropping dateparser?
15:23
I'm curious. Where did those 300 patterns come from? Did you write them yourself, or did you use a tool?
i was asked to do so but i will not listen i will follow your advise
yes i wrote them myself in fact i could share them if you're interested
Ok, sure. Put them in a pastebin or something.
thanks!
this is what i'm trying right now , but the %y is missing
not to sound all high-horsey or anything, but most of these problems are best solved by hitting the person who gives you undefined crap data until they stop
Correct
15:27
i totally agree
here's the date format patters list i told you about
https://pastebin.com/qeHQNwiJ
I notice that Jan's regex defines a year_short_def subpattern, but he never actually uses it in the "actually match them" section of the pattern. I suspect this is because you can't be completely certain that any particular number field is a short year field because much of the time it could also plausibly be a day or month field
"01/02/03" could be January 2 2003 or February 1 2003 or March 2 2001 or who knows what else
one last thing Jan please
how to fix this case of your solution given_sdate = '30/10/10 12h30m40s'
@HarvesterHaidar Did you come up with those using combinatorics? I would expect that a good heuristic needs fewer educated guesses
Perhaps Jan is aware of this shortcoming, but understood that it would take a lot of work to implement even rudimentary logic like "if it's bigger than 31, it's probably a short year", so he quietly submitted this not-quite-complete solution and hoped nobody would complain
An entirely reasonable course of action because there's only so much labor you can expect to extract from somebody in exchange for a handful of upvotes
@AndrasDeak yes that's exactly what happened but first i transformed every possible separator in the original date string then could apply that list
15:35
@HarvesterHaidar To be clear, I am not Jan and I did not write that answer.
@HarvesterHaidar it's probably faster if you decide about the separator in python and only apply the relevant one to your problem
Incidentally, "generate an enormous list of plausible patterns, run every one of them on the representative data, and select the one that succeeded most frequently" isn't a bad solution if you're fine with having a pattern that almost certainly won't work on every row or even most rows
my bad @Kevin
You mentioned that it's fine to have null values so maybe supplying the one most successful pattern is OK even if it chokes on 90% of your data??? idk
this solution was not good enough because there must be NO list of patters
15:39
Right. I'm suggesting writing a helper program that identifies the single pattern that works best, and then using only that single pattern in your actual program.
it would be great to have the %y , that solution was the closest so far , just need a little bit of work for the '12h12m12s'
If it's only a little bit of work, I have faith that you can figure it out :-)
Oh Kevin it's a little bit of work for a python expert not for me
i'm sorry did't mean to make it sound down
I understand. It may indeed be easy for an expert... My own assessment is that it would take a moderate amount of work. Possibly because I have only intermediate skill so I am not privy to the expert-level techniques required to solve the problem easily. Let us hope that a true expert comes along!
to be honest i tried to add %y to the formats but it was like learning mandarin
15:44
In the meantime I must BRB because my manager needs me to crawl through the Jeffries Tubes to access the central mainframe.
good luck @Kevin
i'll be waiting for a miracle
@roganjosh i read all of it even thought it says migration everywhere .. but as i expected it's not what iam looking for
i'm not trying to migrate database to another
@wim down a total of 10% this morning
i'm trying to instruct flask for each session to read certain database
user will input the database info in some front end inputs and flask should progress that details and read the database
16:00
I have no idea what your read, then
@za001a are you using flask-sqlalchemy?
@za001a "migrate" doesn't mean move one database to another. It means to make changes to the existing schema
Yes, it mentioned migration, but the vast majority of what I posted is not about migration
@WayneWerner yes
ok let me refrase what iam looking for because the biggiest problem i have is that i don't know how to address it or keywords for it to research it
So what's your problem? If you've configured it correctly...
16:04
so i'm trying to build CRM based on FLASK

where user can input his/her database details through the front end then flask should connect to the database inserted and return the database query back to the user.
Yeah, precisely what the tutorial I linked to does
@PrimeByDesign No worries, glad you got it sorted
@za001a You will need a central database to store all the other database configurations
Yes. You had a choice. Stop at that, or go to this.
You don't even need to follow those tutorials. Just import sqlite3 and run queries anywhere in your Flask app
16:09
@roganjosh i've read the whole thing and i couldn't find the part that allows me to read the database from external sorce
i think you didnt get it
No, I think you want to be fast-tracked
the user might have a database that could be postgress/orcle /mysql ... etc it's not binded with the code. it's a user input.
You mean it might need a connector that is in the arsenal of SQLAlchemy?
@za001a I suggest that you look at the SQLAlchemy documentation for connecting to a database
@roganjosh i'm not sure what you mean , i'm sory my english isn't not that good what do you mean by "connector that is in the arsenal of SQLAlchemy" ?
@Code-Apprentice i did read it .. all of them are similar to this

from datetime import datetime, timedelta
import unittest
from app import app, db
from app.models import User, Post

class UserModelCase(unittest.TestCase):
    def setUp(self):
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
16:15
Thanks, so, in here wiki.python.org/moin/TimeComplexity in the dict section, set item is said to be O(1). It is O(1) if we are setting a value to a key which has already been computed and had a value assigned, but if we have all the keys different and being computed the first time the time complexity is O(k) where k is the length of each string which could vary. Is that correct? — block-ch 1 hour ago
"umm ... no?"
I mean that SQLAlchemy can connect to a lot of databases. I did get your question, but you can't expect to immediately get a result here. I tried to point you in the right direction
i'm not looking for the result right away i'm looking for the right directio @roganjosh
It is fundamental to Flask that there is somewhere to store, query and change data
that's rather fundamental of web applications as opposed to web pages
@za001a in any case, let's not confuse the rather silly Flask- Sqlalchemy with SQLAlchemy proper.
@roganjosh i know it can change data but how can i instruct it to change the fundamental data itself such ass app.config() and only does that for certain sessions only
16:18
@za001a you need to use SQLAlchemy, not Flask-SQLAlchemy
?
On both comments
@roganjosh naturally.
@AnttiHaapala I'm curious on your thoughts on that last statement, though
@za001a Do you have a login?
@za001a so let me ask this: are there supposed to be multiple users with multiple databases at the same time on a single instance who pay to you?
@roganjosh yes the site should have a login then connect the user to the right database
16:21
So you have access to current_user
@AnttiHaapala not sure about the payment part but yes it should
well, if they aren't paying why would you bother
@roganjosh yea i'm planning to have it but it's still at the research station
@AnttiHaapala i don't know why you are asking but i'm helping multiple charities , i'm not looking for anything in return
@za001a yes. You can do something similar in your own code to build the connection string from user input.
16:25
Nothing stops you writing pure SQL from your Flask app if you don't want to go down the ORM route
I only have my prototypes handy
class ProductionTargets:

    def __init__(self, department):

        self.department = department
        self.all_targets = []
        today = dt.datetime.now().weekday()
        start_of_week = dt.datetime.now() - dt.timedelta(days=today+1)
        next_two_weeks = start_of_week + dt.timedelta(days=7*2)

        df = run_query("""
                       SELECT * FROM published_results
                       WHERE is_active = ?
                           AND department = ?
                           AND DATE(production_date) >= ?
@za001a You don't change app.config(). You likely need to keep that to connect to a central database that contains the user-entered configuration for their own personal database. Then you create a separate connect to that database using the input from the user.
run_query is a helper function that I have because I often want dataframes returned, but not always
But that is just a class in my Flask app, and it just connects to a sqlite3 db
@roganjosh thank you so much , ofcourse i wont just copy and paste it i will use this as a clue to where to reasearch and find the rest of this puzzle
@Code-Apprentice what that means is that you will do (mostly) as I said: forget the Flask-SQLAlchemy (forget the config)
The request from the front-end hits a view, that view loads that function, takes the data from it, and fires it back
16:29
@Code-Apprentice that is what i thought but how ?
@za001a what I posted is far from the complete picture, but there's nothing mythical about the web app over just regular python
Give it a database path, run the queries. But you would be much better using an ORM if you can
@AnttiHaapala yup, that sounds about right
14 mins ago, by Antti Haapala
@za001a you need to use SQLAlchemy, not Flask-SQLAlchemy
I still don't understand that
Why?
@roganjosh flask-sqlalchemy is a piece of "#¤ that does integration completely backwards from what za001a needs to do.
@roganjosh thank you for explaining that
@Code-Apprentice i don't mind , but yes why ? what i should be looking for ?
16:34
@za001a I suggest you step away from your current problem and build a simple application that connects to a database. It always helps to solve a simpler problem first then add the complexity later.
@AnttiHaapala It worries me slightly when it's you saying that...
You are not Zeus giving birth to Athena. Software never springs whole from a programmers head.
@roganjosh what worries?
@Code-Apprentice yea i dont mind it at all but iam here just get a clue to any tutorial / or a title to what iam trying to achieve
That you think it's "a piece of "#¤" because it makes me think I need to move out of it
16:36
@roganjosh you should look out of it
@roganjosh it isn't SQLAlchemy.
it is just "one way to configure SQLAlchemy for flask apps"
@za001a so start by using SQLAlchemy to connect to a database and create a table
But it's not broken, it just doesn't do what you want it to do?
@roganjosh mostly it is broken though.
the .querydoesn't belong to model classes, for example.
@Code-Apprentice sure then ?
ugh. I hoped you wouldn't say that :P
16:38
You start with Foo.query and... the question is what does it mean... "dark magic" and "usually not what you want."
sqlalchemy in itself does not provide the way to do Foo.query because it would be plain silly :D
So how do you handle the connection with Flask?
@roganjosh I don't, I don't use Flask.
Since there are multiple sessions. Did you write your own implementation?
But if I did, I did probably something like stackoverflow.com/a/43462162/918959
@za001a don't worry about the "then" until you finish that part
16:41
@Code-Apprentice i'm new to programmer but i'm not that new to programming .. i'm at the point where i need to make flow chart first and then follow it
i cant find any code or article about flask ORM that covers that part ...
that is why i am stuck
@za001a all of this discussion aside, I literally pointed you to a resource that builds a full app with quite a lot of the Flask library described.
@za001a Flow charts are a great tool, but I don't think it is appropriate here. It sounds like you are designing this system at a much higher level than flow charts allow.
@AnttiHaapala I think I've got too used to the plug-and-play
Sam
Sam
Anyone familiar with the following error when trying to use json.loads() with a string as its parameter: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
You should show a snippet of the JSON
Sam
Sam
16:47
{\'category_id\': \'1730823031\', \'leaf_category\': True, \'name\': \'Sweatshirts\'} is the result of dumps()
Which looks wrong
That isn't JSON
Sam
Sam
o
Correction: that's the result of repr(dumps(something))
Sam
Sam
{'category_id': '1730823031', 'leaf_category': True, 'name': 'Sweatshirts'} it looks like this when I make the request to my flask end point
I'd expect repr(dumps(...)) to look more like '\'{"foo": "bar"}\''
16:49
@roganjosh I have checked the toturial and flask-sqlachmy website , could you point me to which part or title you are talking about coz I couldn't find it
Crucially, all the keys would be quoted with quote marks and not apostrophes
Sam
Sam
Now I'm trying to pick it up in my flask end point and do something with it
@roganjosh it isn't plug and play. It is plug and bang your head against the wall then rip it off.
:P
@Sam So how do you serialize it?
Sam
Sam
When I use request.data inside my end point, it's a <class 'bytes'> so now I want to convert it back to a format I can pull things out of.
16:51
@Sam Very strange. {'category_id': '1730823031', 'leaf_category': True, 'name': 'Sweatshirts'} is not valid JSON because JSON strings must be delimited with quote marks, not apostrophes. Are you sure the code that creates this string is actually using json, and not something else? For example, maybe it's just doing return str(my_dict)?
either head or flask-sqlalchemy, depending on which one is easier server.
Or possibly just return my_dict and the framework is quietly converting it to a string without your explicit knowledge
Sam
Sam
So before I make the post request, the payload is a dict.. so I use json.dumps(dict) and then make the post request with that
So sorry the above is wrong where I said what the request body looked like. It looks like this:
{"category_id": "1730823031", "leaf_category": true, "name": "Sweatshirts"}
Ok. You should be able to succesfully call loads on that, whether it's a string or a bytes.
>>> json.loads(b'{"category_id": "1730823031", "leaf_category": true, "name": "Sweatshirts"}')
{'category_id': '1730823031', 'leaf_category': True, 'name': 'Sweatshirts'}
>>> json.loads('{"category_id": "1730823031", "leaf_category": true, "name": "Sweatshirts"}')
{'category_id': '1730823031', 'leaf_category': True, 'name': 'Sweatshirts'}
All of your property names are correctly enclosed in double quotes, so the json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes error should not occur
plus response.json() should know that, right?
I mean if he's using requests that should be preferred
17:00
Sure. If one's framework has a way to abstract away this kind of work, one should use it.
Sam
Sam
@AndrasDeak what is this?
@Sam the requests library
Ugh, python 3 docs for requests is nowhere on google
is there a way removing all decimals using .format() ? I tried "{:.0f}".format(1.6197433) but it returns 2?
I'm gonna say, we need an MCVE here because I don't know how you can json.dumps() an object and get a decode error on the other side. JSON is pretty reliable.
17:02
btw I know I can simply use int(n) but I don't know for the other way.
What was the final solution for za001?
Sam
Sam
I'll check it out now. thanks
I don't think there was one. I linked them to a chapter in a tutorial
@roganjosh; Ok.
17:09
@Sam that means the string you are trying to parse is not valid JSON. JSON requires keys to be surrounded by double quotes
@skyline33 I don't think there's a way to control the rounding that happens when format turns a float into a string.
Sam
Sam
@Code-Apprentice Yup I think the payload is off
Style poll. True or False: x = list() and x = [] are equally valid style choices.
Personally I am inclined to say that x = [] is always preferable over x = list().
The Admiral Ackbar in me is screaming.
17:24
Err... well x = [] will always be an empty list... x = list() will be whatever list() happens to be at the time :)
list = set; x = list()... :p
Not to mention the number of errors people get from: list = [1, 2, 3]; new_list = list()...
That screws up my potential argument that x = list() is more explicit than x = [] and therefore correct
The rebinding of the name list is indeed a concern. But let's assume that the program is nice and never overwrites the name list with anything else.
Using an empty list literal is more efficient than calling the list constructor. The same goes for all the built-in types that have literals.
I prefer []... it's always going to be an empty list - it's shorter, perfectly clear what it's supposed to do etc... and you don't have to worry about not having mucked up list somewhere...
Plus... it can be managed at compile time... rather than run time...
@Kevin agreed
17:29
Indeed!
I ask because I was looking at Difference between foo=list, foo=[], and foo=list() and I was trying to decide how much to bash foo=list() compared to foo=[]. My instinct was to bash it a lot, but I didn't want to introduce personal bias WRT style when PEP8 doesn't back me up
plus changing it to include some actual items is simpler than list((1, 2)) or heaven forbid... writing that as list([1, 2])! :p
It seems the consensus is that foo=[] is better for various reasons, so I guess my original slam-filled formulation would have been fine.
Not that I'm going to write an answer now, since there are already some present.
If there's a list() call inside my_function, then that call will happen every time my_function is called, whereas the [] literal is evaluated once, at function definition time. And it's really fast, since the CPython interpreter has all the empty literal objects built in.
Immutable empty literals, right?
assuming you mean caching
or what does "built in" mean in this context?
17:35
Hmm, interesting. In its original revision, one of the answers implied that foo = [] would fetch a singleton-ish empty list, and only change it to a "real" list after calling append. If CPython has built-in literals, then maybe this isn't completely wrong.
@AndrasDeak It doesn't matter much. It can use immutables directly, and make a fast copy of list or dict.
> The other two are classic ways to initialize a variable to an empty list. The middle one sets it to the "short constant" empty list, soon making an individual object when you append to it.
It was wrong.
Yes, but how wrong?
17:37
@Kevin Or maybe it does that. ;) It's been a while since I looked at listobject.c
Maybe it does fetch a "short constant" empty list, but the "making an individual object" happens shortly before the expression finishes evaluating, rather than waiting a whole line for the append call
[] is [] evaluates to False so that puts an upper limit on how lazy it can be
I gladly defer to user2357112's expertise in this topic.
[] is [] is quite the smoking gun here, right?
In any case this is deep in "implementation detail" territory, to the point that you can't empirically test anything using just Python code. Whether there's a canonical empty list that is copied, or whether empty lists are made completely from scratch, it's utterly invisible to us.
If you want to look at the implementation, the BUILD_LIST opcode in ceval.c and PyList_New in listobject.c show there's no canonical empty list involved.
17:43
Ah, you saved me ten minutes of effort :-)
@user2357112 Thanks
I notice that there is a free_list collection that presumably keeps ahold of unused list objects. So it's conceivable that x = [] will cause PyList_New to return an existing list object. But this wouldn't happen for every empty list literal. In particular I would expect free_list to contain no values at the start of the program.
Yeah. I guess I was mis-remembering the possible recycling of dead list objects that op = free_list[numfree]; does.

« first day (3120 days earlier)      last day (2053 days later) »