« first day (3616 days earlier)      last day (1315 days later) » 

2:44 AM
Hello Everyone, Sorry I don't want to derail any ongoing conversion. Can anyone please help me out finding the solution to my question? stackoverflow.com/q/63801304/13866248
The provided solution is good and working for example data frame but not for my actual dataframe throwing a KeyError:None
any inputs please
 
 
1 hour later…
3:56 AM
Hi Guys, i need help in python requests,iam getting remote end closed connection without response.

Here is the code i tried

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36',
'Accept-Encoding': 'gzip, deflate, br',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9',
}
cookies = {'surl':'6jorge19753f@timjarrett.net'}
i tried with and without headers,cookies, but the result is same
 
raf
4:35 AM
So far, I have done this:
```
from geopy.geocoders import Nominatim
def checkl2(T):
geolocator = Nominatim(user_agent='geonames@googlegroups.com')
location = geolocator.geocode(T)
country = location.address.split(',')[-1].strip()
return country
```
I want to apply it on pandas dataframe column `df['user_location']`:
```
df['user_location'].dropna().apply(checkl2)
```
But it's giving me this error:
AttributeError: 'NoneType' object has no attribute 'address'
Can anyone please tell me how to fix it?
 
@raf Reading the docs RN for geopy. let's see if I find something for ya
 
raf
Thank you.
 
What is T here?
 
raf
T is a location name
I guess, the problem is appearing when T is not a location name, for example, in my dataframe a row contains 'Hotel living - various cities! Who needs a home when hotel living is so fabulous!'.
I think my function needs to have a try, except type thing!
 
4:50 AM
That's exactly what I was about to say.
when geolocator is unable to determine a location it just assigns NoneType to location.
 
raf
can you please tell me how should I do it?
 
I tried with a random address, it assigned NoneType to location variable
@raf umm..let's see. I just installed geopy, and reading the docs for the first time for this module, so i can't assure I will come up with something working.
 
raf
oh okay! Kindly check it if you are not busy. :)
basically, I want to apply this check2 here:
4
Q: Converting location names into country names in pandas dataframe

rafI have a dataframe df such that: print(df['user_location'].value_counts()) India 3741 United States 2455 New Delhi, India 1721 Mumbai, India 1401 Washington, DC 1354 ... ...

0
A: Frequency plot of a Pandas Dataframe

rafUsing the concept of the previous answer, firstly, I have tried to get all the locations including cities, unions, states, districts, territories. Then I have made a function checkl() such that it can check if the location is India or USA and then convert it into its country name. Finally the fun...

 
"When there are no results found, returns None." - although nothing surprising but a confirmation quote from the docs about the variable assignment.
It also says that when using with Pandas, Nominatim may not be able to handle too many requests (which may result in a Too Many Requests 429 error)
@raf the docs do not say anything about rows in dataframe which are not a valid location. So i think you should use conditions to determine if the value contained in 'T' is a location name or not, If yes, pass it to the geolocator, else skip that step.
 
raf
yeah
```
from geopy.geocoders import Nominatim
def checkl2(T):
geolocator = Nominatim(user_agent='geonames@googlegroups.com')
location = geolocator.geocode(T)
if location == None:
country = 'Others'
else:
country = location.address.split(',')[-1].strip()
return country
```
how about this?
It's getting really show
By the way, why is the code block not appearing here! :\
 
5:06 AM
Ugh the multi line formatting issue. But This could work. Important note :: the condition needs to say: if location is None:
NoneType values are compared with 'is' rather than '=='
Although i don't think it raises an exception but it is not a good practice though.
@raf does that work?
 
anybody here who can help answer my question on Py Spark ?
 
@Chetan_Vasudevan I don't know PySpark, but I can try to pick it up on the fly. Go oN
 
i am trying to insert 8 mill records from spark df to SQL server so need help in efficiency factoring
 
raf
@PSSolanki okay, Thank you. I will remember it.
@PSSolanki my test cases were working. But as I haven't applied it on my dataframe yet
 
Umm. I always have troubles in optimization, even yesterday i had to close one of my questions on SO. So you might wanna wait for more opinions :)
 
5:15 AM
np :) thanks for that
 
@raf I would assume it will work ;)
 
raf
I am hoping so. My dataframe has a length 142337. It's taking a lot time to compile.
 
yeah, as I said, Too Many Requests 429 Error is a possibility for larger DFs
There are 4 solutions in the docs in a case that happens.
 
raf
@PSSolanki Then, what should I do? Any better idea to do it? If you have checked my stackoverflow and code review question, I wanted to get the frequency of a specific countries. To do that, with this `checkl2(), I need to modify it.
@PSSolanki where? in geopy doc? Can you tell me what would be better for my case?
The error is showing:
GeocoderUnavailable: HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /search?q=Public+Universities%2C+UK&format=json&limit=1 (Caused by ReadTimeoutError("HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Read timed out. (read timeout=1)"))
 
Check HERE
@raf I can try to pick it up. as you already know, I learned geopy about an hour ago, when you asked that question xD
 
raf
5:28 AM
Yes, I am really grateful for your continuous help! :)
 
hehe watermelon :)
 
raf
:v
 
5:44 AM
I'm using the python-crontab module, when creating a CronTab object, I cannot specify the user="root". Why is that so?
I've also tried sudo python3 testcron.py
and interestingly it says ModuleNotFoundError: No module named 'crontab'
`pip3 list | grep crontab`
`python-crontab 2.5.1`
 
6:15 AM
😀Hello guyz
 
raf
6:28 AM
@PSSolanki Kindly check is my code (Pastebin link) and error (Pastebin link)
 
6:45 AM
@JackZakiZakiulFahmiJailani As an IDE? WingPro. I have no real idea of what Spyder is.
 
 
2 hours later…
8:17 AM
Hello, everybody!
Please congratulation me to join this chatroom.
LOL!!!
 
@jis0324 lol
 
@raf Please have a look at the code formatting guide. In specific, practice in the sandbox a bit. Debugging Python code without indentation is pointless.
 
raf
@MisterMiyagi Thank you so much!
 
8:40 AM
Hi i am new to this
I have a query
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df= pd.DataFrame()
for f in ['E:\\olympics\\Olympics-2002.xlsx','E:\\olympics\\Olympics-2006.xlsx','E:\\olympics\\Olympics-2010.xlsx',
'E:\\olympics\\Olympics-2014.xlsx','E:\\olympics\\Olympics-2018.xlsx']:
data = pd.read_excel(f,'Sheet1')
df = df.append(data)

df.to_excel("E:\\olympics\\combineddata.xlsx")
data = pd.read_excel("E:\\olympics\\combineddata.xlsx")


t3=data.groupby('Country').Total.sum()
t2= df['Total'].sum()
t4= t3/t2*100
How do i pull this the percentage in pie plot
the value of t4
 
Which is better Visual Studio code or Pycharm?
:)
 
They both suck in different ways
Try 'em out and see which you like more
 
@Aran-Fey Well I am using VS code currently And I don't want to install pycharm as my laptop is lagging too much.
 
@greg
@Greger thank you
 
8:48 AM
Yeah, pycharm is a heavyweight. If your laptop already struggles with VSCode, Pycharm is a no go
 
raf
@MisterMiyagi Is there any way to display line numbers in fixed width code block?
 
nope
 
Is there any way to make a 'Entry ' larger in Tkinter?
I tried to increase the padding of the entries but every time I do so the Entry gets shifted to another position
 
Of course there is, but it depends on the layout manager you're using. grid or pack or place?
 
@Aran-Fey Pack
 
8:58 AM
Check out the expand and fill options effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack-method
 
 
1 hour later…
10:11 AM
hi are u guys familliar with vscode
 
10:50 AM
more or less
 
@lushain Yup I regularly code on that.
 
@holdenweb well Spyder is also an IDE and it really help me because we can easily see what variable now we have in the pane of variable explorer. Just like Rstudio. For PyCharm, I could not see clearly what variables that I have now stored which makes me cannot trace my progress
 
11:10 AM
@JackZakiZakiulFahmiJailani Pycharm doesn't have the same concept. That's like if you would be running in Debug mode all the time. Just set a breakpoint where you need and run in debug
Any idea how I would go about finding more info about a .dat with this starting line: "?>æ¿œ“ 7ðo<Øݐ7Ml)âž—ùä©*6é{·…˜,{A÷äýŒà¥KXfFp\;w——Ð…4" ? I know it's specifically made to not be readable, but my curiousity makes me want to know more about it
 
@Hakaishin Looks like the DAT file has binary encoding applied to it
you'd have to look for some clues in the data to determine the encoding or compression type
 
11:44 AM
@RoadRunner Do you know some program which guesses a few different compression algorithms? Something like chardet for binary data?
 
12:14 PM
:50413755 Sorry I was rbrb. But looking at the error codes, it either is because of rate_limiter not being able to handle those requests properly or because something wrong happens at the time it tries to fetch the geolocation.

In both cases, try other 3 methods (the last one seems interesting, but I don't know how much size would the downloaded data would acquire)
@raf Consider my above msg as a response to your message. The multi line formatting often beats the hell outta me ;)
 
raf
12:39 PM
@PSSolanki I am kinda busy with my academic courses now. Some days later, I will return to this problem again. And I will let you know then.
 
sounds good :)
 
12:54 PM
morning cabbages, folks
 
cbg inspector ;)
 
Is there a way to check what dns server requests is using?
I found: stackoverflow.com/questions/22609385/… But it looks complicated and before I go on doing that I want to check which one I'm using
 
1:26 PM
actually, the easiest way might be with WireShark
 
🙃
⊙_⊙⊙_⊙(¬_¬)
 
2:00 PM
Is it safe to rename an xml file from python -- without modifying the file, but adding a ".xml.foobar" as the file extension instead of ".xml"
 
@pyeR_biz you will have to specify more what you mean with safe
@inspectorG4dget huh, good idea
 
as in no change in the structure/contents of the xml file
 
@TanishSarmah i have just recently switched from pycharm to vscode cuz i wanted to learn django n after switching i am really confused cuz after each time i run a code for the second time it doesn't remove the output i had gotten previously and it is really confusing me pls help .thanks
 
@pyeR_biz yeah the content of a file is unrelated to the filename
@lushain that's odd and non default setting, but I've seen it happen to some of my students. How do people always manage to do the strangest things :P I can just tell you I don't even know how to get Pycharm into that state and also not how to get it out, but I've seen it happen :P
 
@lushain please don't ping people out of the blue; it's considered rude. From what I can tell, your question isn't something that they, specifically, should be addressing. You also haven't explained the issue particularly clearly
 
2:05 PM
and a parser like lxml.etree.parse("file.xml.foobar") will that still work ?
 
@pyeR_biz depends on the parser. But this is python and programming. Just try: ¯_(ツ)_/¯
 
thanks
 
If there is someone who wrote a parser that doesn't work if the file extension is incorrect, that person must be an unprecedented moron
 
@Aran-Fey which we know the world is full of xD ¯_(ツ)_/¯
I really wish I could type :shrug instead of having to google it every time
 
I hope that's sarcasm, because that moron would be precedented. I remember writing something like that in my first year, back before I understood the (lack of a) relationship between file type, file format, and file extension
 
2:14 PM
@Aran-Fey waves hand
 
I'd like to say that not everyone can be an unprecedented moron, but somehow people seem to pull that off on a regular basis
@inspectorG4dget Okay, but nobody who actually publishes their parser would do that... I hope
 
Well microsoft did this: I can't believe this. Microsoft put all this time in making a package manager and you CAN'T specify the version you want? ARe you freaking kidding me? What good is any package manager if you can't specify the version? the comment has 160 upvotes and some smiling crying emojis on github :D
So I wouldn't be sure about the parser statement :P
 
o/
 
I'm surprised so many people have interest in that feature, to be honest. I'd have thought most people only ever install the latest version
I wonder how package managers on Windows deal with self-updating programs
 
I can kind of relate to version-less package managers. Our infrastructure setup usually only has the one version we want available anyway.
 
2:26 PM
versionless packaging is insane
 
Cannot remember the last time a fixed-version setup was anything but an accident waiting to happen.
 
I mean yeah you would like to keep all your libs up to date all the time, but that's just not realistic for bigger projects
 
@Hakaishin Packaging repo priorities are insane.
 
Lol I just started a new project in C++ and I'm not sure what I think about ++. I first I thought += 1 is stupid. Now ++ looks wrong. So I guess it's all customs in the end. EVERYTHING :O :D
 
Don't forget i++++++++j and the i --> j operator
 
2:32 PM
@JackZakiZakiulFahmiJailani All useful features! Wing has them too, but not all, I believe, in the free version. It's often mostly a matter of what you are used to, and as long as it's doing the job (and not messing with your imports :P) that's fine.
 
@AndrasDeak Ugh. i --> j is (i--) > j I guess?
 
maybe :P
 
Somewhere out there is a Quantum Computer built from the ambiguous interpretation of C++ source code.
 
@Hakaishin Tell that to Widows users, where file name extensions are mostly taken to imply specific data formats ...
 
@MisterMiyagi and that's how the Big Bang happened the last time
 
2:43 PM
@holdenweb by the users yes :D Well what you gonna do when they come for you :P
 
@MisterMiyagi "I'm sorry, sir, the rules of this bank are quite clear: you can only withdraw your most recent deposit."
 
@AndrasDeak The universe messing up dependencies and deciding to reinstall from scratch? That seems surprisingly probable...
 
@Hakaishin Not just by the users, but by quite significant chunks of the OS, unless Windows has changed radically in recent years.
 
@holdenweb I would not mind ATMs just giving me the highest-value bill available. :P
 
@holdenweb It has actually. I'm not sure if it's just me getting more familiar or if windows is actually improving a bit
 
3:23 PM
^^ not just now, I am actually at work (and please don't ping people unless you have a current help thread going)
 
3:33 PM
So from our previous huge import related chat(me accidentally installing my own package and all that), what I am doing now is from module import function and hope that this runs when packaged.
 
@nealkaps please don't ping people unsolicited. In addition, you linked to an answer to your question.
 
@roganjosh Sorry this is the first time I am using chat. My apologies, I wanted to highlight my question here if anyone can help me.
 
There are room rules which you can find in the top right. In particular, wait 48 hours before bringing questions here
 
@lushain Are you running the code in terminal or in the output console..? If it is in the output then u have to click on the four lines like button ...and if it is in the terminal then u have click on the kill terminal button which is basically like a delete button :-)
 
@roganjosh Sure, will keep in the mind thank you for the guidance :)
 
4:02 PM
Hi guys, hope you're well ! Anyone can help me with my issue : datascience.stackexchange.com/…. I would appreciate any help :) Thank you !
 
@holdenweb that's a nice alternative suggestion. thank you
 
@kakarotto that url is borked
 
4:25 PM
That looks suspiciously not like Python...
 
It's not, but chat is "fun" in that you can't move multiple messages in one go from mobile
 
Might want to ask for help on that in the Python channel. I hear they are rather helpful. :P
 
cbg
can anyone tell me why the code snippet does not work?
>>> t='hello world'
>>> t_encoded=t.encode('utf-16_be')
>>> t_encoded.decode('utf-16_be')
'hello world'
>>> t_encoded_split=t_encoded.split()
>>> [x.decode('utf-16_be') for x in t_encoded_split]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/encodings/utf_16_be.py", line 16, in decode
    return codecs.utf_16_be_decode(input, errors, True)
after I split the byte string why I cant I decode it individually?
 
I already posted in datascience room and someone told me that I may find some help here. Sorry..
 
@MisterMiyagi Noted. I want to redesign the chat of a major resource for programmers. H e L P
 
4:31 PM
@python_learner Do you know how UTF works? In specific, do you know that a character can be longer thana byte?
 
I dont really understand the specifics if I am being honest, I was just playing around with the codecs found here docs.python.org/3/library/codecs.html#standard-encodings
 
@python_learner Compare b'\x00h\x00e\x00l\x00l\x00o\x00'.decode('utf-16_be') and b'\x00h\x00e\x00l\x00l\x00o\x00 '.decode('utf-16_be')
Also note the result of ' '.encode('utf-16_be').
 
@MisterMiyagi the second prints hello
 
In utf-16_be, ' ' is the two byte sequence b'\x00 '.
Splitting the encoded string removes only one of the two bytes, leaving the other truncated
 
I see, splitting with the encoded ` `(space) characters does what I expect it
 
4:43 PM
at least until a character that ends with b\x00 and a character that starts with ` ` line up
 
@Aran-Fey so it can still fail for others characters?
 
Well, I'm not entirely sure whether two such characters actually exist, but in theory yes
 
I never really got my head around encodings, but I must look into that soon
 
Hey guys I was trying to make an exe of my .py file So I opened up the powershell window in a directory and installed pyinstaller using pip install pyinstaller and after some wheels are built and etc etc things happened I got an error as ** ERROR: Failed building wheel for pyinstaller**
and an another as ERROR: Could not build wheels for pyinstaller which use PEP 517 and cannot be installed directly . Is it probably because my anti-virus finds a trojan every time I install the module and it repairs the trojan
The "**" Thing didn't made my text bold lol! :|
 
@Aran-Fey 'Ѐ†' is one such pair. There should be 65535 more, but some are ugly.
 
4:50 PM
@TanishSarmah upgrade setuptools and wheel along with pip, most incompatability issues get solved there.
Apart from checking if something.db file exists or not is there any other way I can check if a database exists for sqlite3?
 
@AshwinPhadke What was the upgrade command? ...I forgot it :(
 
@TanishSarmah google next time, pip install --upgrade pip setuptools wheel
On a strange turn of events my project only works if I install it and not from code.
I did not get what this is actually doing : stackoverflow.com/a/11599384
 
5:11 PM
while trying to make an exe of the file **main** using this - **pyinstaller main.txt** I got this error-
**pyinstaller : The term 'pyinstaller' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.**
Can anyone help?
 
os.makedir() gives a permissio denied error, how do I create the directory?
 
5:41 PM
os.makedirs with exist_ok=True would appear to be what you need.
If the containing directory already exist, you may need to change its permisions.
 
6:02 PM
I'm having trouble with Python
 
@AshwinPhadke it does exactly what it states. If the database doesn't exist then it will just make it. So the best course of action is to try query it instead
sqlite3 is more permissive than most would like, even to the point of just making a database for you
 
I have a ball that moves in that path (desmos.com/calculator/e9vwcwpofd), given the equation $y(t) = \frac{QEt^{2}}{2m}$
But when I plug that into Python, my ball just moves in a linear line; I'm very confused
As you can see, my ball travels in a straight path, even though it should be traveling in a parabolic path.
 
I have no idea what that last picture is supposed to add vs. Actual code
 
Well, I don't mean to interrupt but I would like some some assistance from someone :P
I need some help to understand 2 lines of code
 
You're not interrupting. But what are we supposed to be helping with? There's no code
 
6:10 PM
 
One sec
And here's my piece of code
 
Sorry, I've got wires crossed on 2 obscure questions
 
@roganjosh Sorry, my code should be pretty simple; It's just not producing a parabola
 
@Broxigar time**3 should be time**2
 
@MisterMiyagi Oh wow, that's right
Let's see if that fixes it
 
6:13 PM
@MisterMiyagi I suppose you ment to mention @DarkRunner ?
 
@MisterMiyagi Nope, getting the same result -- a straight path
 
@Broxigar please paste the code to something like dpaste. Why is that site asking for my number?
 
Here's my code in a compiler: trinket.io/library/trinkets/810595911e
As you can see, it still produces a straight line, not a parabola
 
@roganjosh asking for your number? It should only require a nickname
Yes sure though, one sec.
 
If anyone can help that would be great
 
6:18 PM
@Broxigar Indeed. I took "called" out of context. Still, I'm bored of things like repl.it where things can be edited
 
@DarkRunner why is the size changing?!? Are you sure you are actually adjusting its position?
 
@MisterMiyagi I think the size looks like it's changing because of a shift in perspective.
i.e., as it gets farther away, it looks smaller
 
anyone work with GoogleSheets API? Could I pick your brain for a minute?
 
@DarkRunner Your v is way too small.
Also, y is up
 
6:24 PM
@MisterMiyagi Let me check ...
 
The shape will end up at 1.0214178556608892e+18, 3000
 
@Broxigar the lambda is called each time it tries to sort the list
It's just a callable
 
@MisterMiyagi Wow, ok -- let me try to fix that
 
how do I download a single sheet out of a google sheets workbook, given the spreadsheetId and the sheetId?
 
Yes but for example:
`
x = lambda v : v+5
`
You are calling the lambda as x(10) for example. Right?
 
6:26 PM
@DarkRunner you need a v of at least 1e10 to see significant x movement
 
@MisterMiyagi That's faster than the speed of light!?
Oh wow, you're right!
This is amazing, thank you so much @MisterMiyagi
The thing I'm struggling to accept, however -- is that v must be greater than $1e10$!
 
@DarkRunner My pleasure. Didn't know GLowScript before.
 
Awesome, I'll investigate on my own now. Thank you again @MisterMiyagi.
 
@Broxigar Can you clarify what you are wondering about? sorted calls the lambda for you.
 
@roganjosh Not quite right - the callable is called once for each item in the list, to determine just how the values should be compared. For instance sorted([-3, -2, -1, 0, 1], key=lambda x: x**2) will sort by the square of each item. Giving [0, -1, 1, -2, -3]
 
6:31 PM
@PaulMcG is it really only called once?
 
That was the big improvement over the old cmp style. Yes, it is called just once per item, vs once per comparison.
 
To ask my question in a more complete way:
In the example I do not understand how does the
`x.items()` assigns a value to lambda's `item` ?
 
(well, a single pass of the collection)
huh, TIL @PaulMcG, thanks
 
@Broxigar - try changing your lambda to a def function, and print out the value of the item argument to see what is happening.
 
Right, let me check that.
 
6:34 PM
@Broxigar Do you understand how the values are passed to the lambda in sorted([-3, 4, -1, 2], key=lambda x: x**2)?
 
No, I am struggling to understand this. I am checking what @PaulMcG proposed. Because to me it seems like the first arguement (the list) passes/calls the second argument.
 
Back in the day, sorted took a comparison function that was called for every comparison - painfully inefficient, especially considering how slow function calls are in Python. So an idiom emerged with the acronym DSU, for Decorate-Sort-Undecorate. In this idiom, each list item would be decorated into a (key, value) tuple, with a key value that was evaluated just once per item, and preferably was an easy to compare value, like int, float, or str. This new list of decorated items was then sorted.
And then Undecorated by walking the decorated sequence and stripping the keys.
 
@Broxigar Are you aware that there is a third entity, namely the sorted/sort function?
 
Yes but sorted is the function that gets called with those 2 arguments. Isn't it ?
 
Yes, and it can do with those two arguments whatever it wants.
 
6:38 PM
Yes, it gets called with a sequence and a function. sorted will use the function on every item in the sequence to determine the correct sorting value for that item.
 
Like, iterating the first argument and passing each element through the second argument.
 
Damn...
 
That's why when I used x**2 as the key, then -3 sorts after 2 (9 being greater than 4)
 
Yes I did not think that the second argument of the sorted() is a 'function'
 
You have learned a great power this day - use it wisely, and for Good not for Evil.
 
6:41 PM
unless you're IBM
@MisterMiyagi key=abs
 
@PaulMcG thanks for that. I'll have to look into it further but it suggests to me that an "in-place" sort actually makes something bigger than a list to do the sort
 
So an equivalent of the aforementioned piece of code would be something like:

def func(list_arg):
    return list_arg[1]

sorted( [ ('a' , 1), ('b', 2), ('c',3) ] , key=func) ?
 
@PaulMcG Schwartzian @ perl
 
Yes, but it won't be very interesting with such a boring list. Try mixing up the integer values, to not correspond with the characters, like ('a', 1000)
 
Yes yes, this was a trivial example.
I have been using python for various stuff in a while...but I was so afraid of using lambdas.
 
6:46 PM
No need to be afraid but also no need to overuse them.
 
They are overused, especially by early learners. But nice for key arguments to sort, sorted, and groupby.
 
As a matter of fact, 2 things I was avoiding all this time. Lambdas and recursion
Yes this is true, everyone is becoming a lambda oneliner nowadays
So, lambda expressions are good to be used for stuff like: mathematical operations , data 'filtering' etc. ?
 
Here is another sort key example, idea borrowed from the link by @AndrasDeak: sorted(['a', 'list', 'of', 'random', 'words'], key=len). You can pass builtins as your sort keys also, as long as they take a single argument of the type in the sequence, and return an easy-to-sort value.
 
It is clear to me now.
Much appreciated guys.
 
We are here all week - be sure to tip your servers and bartenders
 
6:53 PM
^^ Have a good night !
Or day. Depends on your timezones xD
 
7:31 PM
@Broxigar the rule of thumb is that you normally shouldn't bind lambdas to names. Passing a lambda as the key keyword for a function just like we discussed is the idiomatic use case. Or defining short functions in a dict.
 
Dev
Hello All, I am looking for way to append each value in comma separated string with a suffix. in this case string
Before: "id,name,address"
Expected Outcome: "id string,name string,address string"
Any pointers are very appreciated
 
@Dev there's a missing suffix after address
 
Dev
yes @AndrasDeak
 
OK, edited now
@Dev Do you know how list comprehensions work?
 
@roganjosh it does. It uses the"decorate-sort-undecorate" method to create (key, value) pairs for each element to be sorted (hence it's called once for each element) and after the sort the keys are stripped out again.
 
Dev
7:35 PM
@AndrasDeak not much. ramping up on python
 
@Dev then for now just use a regular loop. Define an empty list, then loop over your_string.split(','), then in each iteration append split_substring + suffix to the list, and after the loop call ','.join(that_list).
 
@Dev: Here's a question that I asked a long time ago, about list comprehensions. If you understand the discussion there, you'll understand over 90% of list comps
 
@holdenweb I've seen that the Schwartzian transform mentions Python a few times. Next stop is investigating numpy sorting
I'm not sure it will change anything for me if it does create another array but "in place" seems a little off if it's just going to create a whole new structure anyway
Also, feeling a little silly for not knowing this already
 
7:51 PM
In-place as in "mutates the original list"
 
Dev
Thanks @AndrasDeak @inspectorG4dget
I got my code

new_str = []
old_str="id,name,address"
for split_str in old_str.split(','):
str1 = str(split_str) +" string"
print(str1)
new_str.append(str1)

print(','.join(new_str))
 
@AndrasDeak I didn't think that it would create a new object, potentially bigger than the original list, to do the sorting though
 
Is it potentially bigger?
then again it would be O(N) either way
 
@Dev print(','.join([f"{s} string" for s in old_str.split(',')]))
 
@Dev please see our code formatting guide to chat and practice in the sandbox if necessary
you also can't mix code and text in one message in chat, alas
 
7:55 PM
True. But I guess I was naive in thinking the sort really did call the key each time
In hindsight, I like my mental implementation less than reality
 
Dev
Thanks @inspectorG4dget
Apologies @AndrasDeak
Will be careful going further
 
it's alright
 
if you find my dead, mangled corpse in a dark alley, know that it was gDrive/gSheets API that dragged me there and beat the ever-loving pulp out of me
 
I'd feel partly responsible because I answered about gspread a bit ago
Not culpable, but partly responsible
And on that note, is there a reason that you're not using gspread, and instead going to the API directly?
 
cbg
 
8:09 PM
I /was/ using the API directly, whose documentation is sadly quite abysmal. That being said, I switched over to gsheets, and that rescuied me
 

« first day (3616 days earlier)      last day (1315 days later) »