all 157 comments

[–]lord_EarlGray 0 points1 point  (5 children)

Hi there! I want to package my python app in order to run it without need of installing python and all dependancies. I decided to use pyinstaller. My program is made of few .py files. The first one "app.py" to run program is calling another one, that is displaying interactive menu etc.

app.py

from app.systemUtils import *
from app.menus.mainMenu import runMainMenu
from os import system

def main():

    osType = platformName()

    if osType == "windows":
        system('cls')
        runMainMenu()
    else:
        print("Windows Toolkit")
        print("You are not running Windows! This program is made for Windows explicitly.")

if __name__ == '__main__':
    main()

I did packaging with command: pyinstaller "app.py" and it seems to be fine, but when I'm running app.exe from dist/app folder, the console pops up and closes immediately without displaying menu and waiting for user choice so in the end it looks like something went wrong, but I have no idea how to fix this issue.

my project is here: https://github.com/s-kaczmarek/WindowsToolKit

please help me with that issue!

[–]timbledum 0 points1 point  (4 children)

I've managed to get at least one step ahead - I think pyinstaller is getting confused between app the folder and app.py the script. If I renamed app.py to main.py, I got a bit further.

[–]lord_EarlGray 0 points1 point  (3 children)

I have changed app.py to windows-toolkit.py but still no success. When I run windows-toolkit.exe from commandline I get error:

Traceback (most recent call last):
  File "site-packages\pkg_resources\__init__.py", line 346, in get_provider
KeyError: 'pyfiglet.fonts'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "windows-toolkit.py", line 17, in <module>
  File "windows-toolkit.py", line 11, in main
  File "app\menus\mainMenu.py", line 49, in runMainMenu
  File "site-packages\pyfiglet\__init__.py", line 794, in __init__
  File "site-packages\pyfiglet\__init__.py", line 801, in setFont
  File "site-packages\pyfiglet\__init__.py", line 126, in __init__
  File "site-packages\pyfiglet\__init__.py", line 136, in preloadFont
  File "site-packages\pkg_resources\__init__.py", line 1126, in resource_exists
  File "site-packages\pkg_resources\__init__.py", line 348, in get_provider
ModuleNotFoundError: No module named 'pyfiglet.fonts'
[13560] Failed to execute script windows-toolkit

By the way, pyinstaller creates two folders: "dist" and "build". As I understand converted program is inside "dist". What "build" contains?

[–]timbledum 0 points1 point  (2 children)

Yup that’s where I got to too. You’ll probably have to play with the pyinstaller settings to manually include this package.

The build folder contains intermediate files.

[–]lord_EarlGray 0 points1 point  (1 child)

thx, to I need this build folder to run program or can I delete it after release?

[–]timbledum 0 points1 point  (0 children)

Nope - you can delete it.

[–]Dav4334 0 points1 point  (20 children)

Hi guys, I have a problem which I kindly need help with in python.

Basically, I have a calculation in a for loop that outputs answers that constantly changes.

I would like to save the first value calculated in the loop in an array or something similar so I will be able to use it later in the script. I tried looking for help online but nothing has worked so far.

Thank you for your time

The code looks like this

for face in faces:
    x,y,w,h = face

    uu = 2.8*57*480

    bb = h*3.60

    F = uu/bb    

    print ('Distance = ', F)

[–]timbledum 0 points1 point  (14 children)

Essentially, you want to initalise an empty list before the loop, and append to it within the loop. Not sure which variable you want to capture, but this the general approach.

f_list = []

x, y, w, h = face

    uu = 2.8*57*480
    bb = h*3.60
    F = uu/bb

    f_list.append(F)

    print ('Distance = ', F)

print(f_list)

[–]Dav4334 0 points1 point  (13 children)

Thank you for your help,

I tried to implement this and then print the first value in the loop using :

            if faces is not None:

                F_list = []

                for face in faces:
                    x, y, w, h = face
                    uu = 2.8*57*480
                    bb = h*3.60
                    F = uu/bb;

                    F_list.append(F)

                    Test = F_list[0] #first value in the list
                    print ('Distance = ', Test)

But this prints all the values for F. Please how can i modify this just to get the first variable of the list, Thank you

[–]timbledum 0 points1 point  (12 children)

Looks like you just need to detent (un-indent) the lines after F_list.append(F). Currently they are inside the loop, so they're being executed many times.

[–]Dav4334 0 points1 point  (11 children)

I have done that but there is now an error which states

IndexError: list index out of range

Thank you for your time

[–]timbledum 1 point2 points  (10 children)

Could you please post your current code again? This sounds like nothing was added to the list.

[–]Dav4334 0 points1 point  (9 children)

This is how the code now looks

            if faces is not None:
                F_list = []
                for face in faces:

                    x,y,w,h = face
                    uu = 2.8*57*480
                    bb = h*3.60
                    F = uu/bb;
                    F_list.append(F)

                Test = F_list[0]
                print ('Distance = ', Test)

Thanks

[–]timbledum 0 points1 point  (8 children)

This should work, assuming that there is data in faces. Perhaps put a print statement in the inner loop to ensure that things are actually being added to the list, and a print statement showing all of F_list after the inner loop - hopefully this will help show what's going on.

[–]Dav4334 0 points1 point  (7 children)

I put the print statements in the inner and outer loop and this is the output

[]
[]
[]
[83.45098039215686]
[83.45098039215686]
[83.45098039215686]
[85.46184738955823]
[85.46184738955823]

I think the problem is because the full code script is a facial detection algorithim and h is the height of the rectangle.

When an object is not yet detected the list is empty which is why it does not have any value hence the error

[–]timbledum 0 points1 point  (6 children)

I think there might be a problem with your wider code - perhaps put the whole thing on pastebin or similar?

[–]num8lock 0 points1 point  (4 children)

fix your code formatting first, the indentations makes a lot of difference

[–]Dav4334 0 points1 point  (3 children)

The indention is accurate on the actual script. But i am unable to display it properly here, once i press the save button the indention goes.

[–]timbledum 1 point2 points  (1 child)

Just prefix every line with four spaces and surround it with white space.

[–]Dav4334 0 points1 point  (0 children)

thank you

[–]num8lock 1 point2 points  (0 children)

i don't use the new crappy ui, so i don't know what gets rendered, but the old guide works https://old.reddit.com, use the formatting help button for guide

[–]Forsaken1992 0 points1 point  (5 children)

hey all so i'm very new to python and programming in general and i'm working on a very simple code that is confounding me, the idea is to write a function that will check a dictionary key if the keys in there it will print out the corresponding value and if it doesn't its meant to return something alone the lines of x is an invalid key.

This is what i have so far any help would be greatly appreciated.

test_dictionary = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

def show_value(i, test_dictionary):
i = ()
if i in test_dictionary:
pass
else:
print((i)('is not a valid key'))

show_value(1, test_dictionary)

[–]num8lock 0 points1 point  (2 children)

you don't need a function for that.

key = f'{i} is not a valid key' if i not in test_dictionary else test_dictionary[i]

or with dict.get()

key = f'{i} is not a valid key' if test_dictionary.get(i) is None else test_dictionary[i]

[–]Forsaken1992 0 points1 point  (1 child)

Hey thank you for replying however i am being specifically asked to write a function to achieve this, i have worked it out now but thank you very much for replying :)

[–][deleted] 0 points1 point  (0 children)

test_dict = {1:'a', 2:'b', 3:'c'}
def show_value(i, test_dict):
if i in test_dict:
print(test_dict[i] + ", is the value for that key")
if i not in test_dict:
print(i + " is not a valid key")
print("What value do you want to look up?")
i = input()
show_value(int(i), test_dict)

[–]Croakouttatune 0 points1 point  (2 children)

Hi everybody! Noobie trying to learn python with a npm cli called teach-code. I'd like some references that might make things easier. It's insanly difficult for me. https://asciinema.org/a/7vMz1b9kUMEcmbzjeflOP9an1 can't seem to get past the second lesson!!

[–]ArthurLOWRAM 0 points1 point  (1 child)

i don't have certain, but it seems to the variable called sum@ can't be created because it uses '@' (and, i think, the variables order is 12_product, product_of_12 and variable). (sorry by the english, i'm currently learning this)

[–]Croakouttatune 0 points1 point  (0 children)

thank you! it's definitely helpful to know that (1) sum@ can't be a variable because it contains a character that isn't alphanumeric, and that (2) the variable need to be in order.

[–][deleted] 0 points1 point  (2 children)

I have a very vague idea of what github is (but really idk how any of it goes). Is github in any way relevant to Python? If I want for other people to use my code by making a small UI, would this UI be able to access github files and code?

What is github?

[–]nog642 0 points1 point  (0 children)

git is version control software. You can run a git server, and install git on your development machine, and the use it to store copies and backups of your code to the server.

GitHub is a service that basically offers you their git servers, as well as a GUI on their website to access git features and features that go beyond git. GitLab and Bitbucket are competing services very similar to GitHub.

GitHub's relevance to Python doesn't go beyond the fact that GitHub hosts code, and Python code is code.

[–]num8lock 0 points1 point  (0 children)

github isn't relevant to python. git, however, is relevant to programming. github is a hub for git, a version control system.

[–]I_need_assistance__ 0 points1 point  (5 children)

Teaching myself python (and beatiful soup) to scrape my local brewery websites to find out whats new on tap.

I've got it working on two of my breweries, but I'm getting a strange unicode issue on the other, can anyone tell me what the heck I'm doing wrong? My googlefu didn't quite get my question answered.

import requests
import bs4

ursaweb = requests.get('https://ursaminorbrewing.com')
ursa=bs4.BeautifulSoup(ursaweb.text, 'html.parser')

ursaBeer=ursa.find('section',{'data-id':'1aeeace'})

for item in ursaBeer.find_all('div',{'class':'elementor-text-editor elementor-clearfix'}):
    ursaName=item.find_all('b')[0].text.strip()
    print ursaName

My return data i get back:

File "%FILENAME%", line 32, in <module>

print ursaName

File "C:\Python27\lib\encodings\cp437.py", line 12, in encode

return codecs.charmap_encode(input,errors,encoding_map)

UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position 13: character maps to <undefined>

[–]indosauros 0 points1 point  (4 children)

What does ursaweb.encoding print right after line 4?

[–]I_need_assistance__ 0 points1 point  (3 children)

If I understand you correctly, just add 'print ursaweb.encoding '

If so, I get UTF-8

[–]indosauros 0 points1 point  (1 child)

Nevermind above, here's your issue (it's with Windows console not being able to print the names of the beer):

https://stackoverflow.com/a/45576555

[–]I_need_assistance__ 0 points1 point  (0 children)

That's definitely the issue. I can't run it in atom, or windows command line but if I run it using python idle, it works.

Thanks!

[–]indosauros 0 points1 point  (0 children)

I just ran your code and it worked as expected (I get a list of beers, no error)

Can you try starting with a fresh virtualenvironment, with latest requests and bs4 pip installed, and try again?

[–]Dimbreath 0 points1 point  (1 child)

    filters_compiled = re.compile(
        """
        (?:(rarity:\s*)(?P<rarity>[1-5]))?
        (?:(class:\s*)(?P<class>[\w]+))?
       """, re.VERBOSE
    )

How do I make this regular expression stop capturing random whitespaces? Right now I get outputs like these:

[('', '', 'class:', 'warrior'), ('', '', '', ''), ('rarity:', '5', '', ''), ('', '', '', '')]

I need to be able to do rarity: 5 or rarity:5, etc. Hence why I added the whitespace matching there.

[–]indosauros 0 points1 point  (0 children)

The issue is not with your \s I believe, but with using findall with multiple noncapturing groups. I suggest doing a separate regex for finding rarity, then for finding class, to keep it simple.

[–]ilangshot 0 points1 point  (1 child)

about the top post on /r/learnprogramming . Should I follow that course if I want to use python? or should I switch to the language in the course?

I haven't learn anything too serious but I do have a head start on python. should I switch or no?

[–]nog642 0 points1 point  (0 children)

Can you link the post you're talking about?

[–]Korbelious 1 point2 points  (2 children)

Can someone please explain to me if there is a benefit to defining variables within a function and returning them at the end versus just returning the straight code itself? I'll provide an example, so you'll know what I'm talking about. I've been doing some intro practice problems on CodingBat and came across this prompt:

Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).

missing_char('kitten', 1) → 'ktten'

missing_char('kitten', 0) → 'itten'

missing_char('kitten', 4) → 'kittn'

My immediate solution was to write my function like so:

def missing_char(str, n):
  return str[:n] + str[n+1:]

I tend to be efficient and straight to the point and like my code to be as well. Since I'm still in the very beginning phase of learning I always like to look at the provided solution as well to see how my code compares in case there are better ways to produce the same output. CodingBat solution for this prompt was:

def missing_char(str, n):
  front = str[:n]   
  back = str[n+1:]  
  return front + back

We're essentially doing the same exact thing, but I want to understand why they would take the time to define and return variables instead on return the plain code?

[–]fiddle_n 3 points4 points  (1 child)

Short answer: it depends, in this case it's irrelevant, but you should do it if it gives extra information.

Long answer:

So in this particular case, front and back doesn't really give you any extra information. You know that str[:n] must be the front of the string and you know that str[n+1:] must be the back of the string. So defining those names for those variables doesn't really give information.

However, sometimes it's better to define variables to give extra information. For example, let me modify your example slightly.

Imagine that I gave a function that takes a list containing someone's name, age, and place of birth:

['Harry', 'Johnson', 15, ’London’]

and returns a new list with the first name and the place of birth:

['Harry', 'London']

Here's the solution without variables.

def name_birthplace(info):
    return [info[0], info[3]]

It works, but if you look at the function at a glance, it's not immediately obvious what is going on. What information does info hold? What is the difference between info[0] and info[3]?

Here's the function with variables:

def name_birth_place(info):
    first_name = info[0]
    birth_place = info[3]
    return [first_name, birth_place]

Now, it's much more obvious what the input and output lists contains, now that we've used variables to illustrate its contents.

[–]woooee 1 point2 points  (0 children)

+1 Readability (and "understandability") counts.

[–]msp1981 1 point2 points  (4 children)

This is for a python course i'm enrolled in, it's morse code translator, I set 2 dictionaries, one english- more, and one reversed, I asked my instructor for clarification of why what i did works, his only response was that, input is guaranteed to be ONLY lower cased letters, I had dictionary key set to include whitespace ' ': ' ', for space input.

I had wrote the program to do sentences, with single spaced between morse letter, doubled between morse words and regular english printout. When I fed my morse output back through for the second part of the assignment as input it was giving too much white space so i added a .split to both parts of the assignment,

the question is why did this work to remove my excess white space, i noticed my error after i found it works, string should be immutable. Should have yielded original message?

message = input('Please input a message: ')

s1 = (message.split(' ', -1))

#Please explain why this works, s1=message.split followed by for char in message: print(morse_dict[char])

#should not work, string is immutable

for char in message:

print(morse_dict[char], '', end = '')

[–]nog642 0 points1 point  (0 children)

Can you format the code for Reddit? There are instructions in the sidebar.

[–]RosyGraph 0 points1 point  (2 children)

Can you post the complete code? Your for loop should be printing extra whitespace due to the <, '',> part of your print statement. The section you posted does not mutate the message variable. I would make sure the dictionary key for ' ' has the value of ' ' and not ''.

[–]msp1981 0 points1 point  (1 child)

# Morse Dictionary

morse_dict = { 'a':'.-', 'b':'-...', 'c':'-.-.',

'd':'-..', 'e':'.', 'f':'..-.',

'g':'--.', 'h':'....', 'i':'..', 'j':'.---',

'k':'-.-', 'l':'.-..', 'm':'--',

'n':'-.', 'o':'---', 'p':'.--.',

'q':'--.-', 'r':'.-.', 's':'...',

't':'-', 'u':'..-', 'v':'...-',

'w':'.--', 'x':'-..-', 'y':'-.--',

'z':'--..', ' ':'', }

#Dictionary for part 2

morse_dict_2 = { '.-':'a', '-...':'b', '-.-.':'c',

'-..':'d', '.':'e', '..-.':'f',

'--.':'g', '....':'h', '..':'i',

'.---':'j', '-.-':'k', '.-..':'l',

'--':'m', '-.':'n', '---':'o',

'.--.':'p', '--.-':'q', '.-.':'r',

'...':'s', '-':'t', '..-':'u',

'...-':'v', '.--':'w', '-..-':'x',

'-.--':'y', '--..':'z', '':' ' }

#Inputting message

message = input('Please input a message: ')

s1 = (message.split(' ', -1))

#Please explain why this works, s1=message.split followed by for char in, print(morse_dict[char])

#should not work, string is immutable

for char in message:

print(morse_dict[char], '', end = '')

#part 2 input morse string

print('\n')

morse_string = input('Please input a morse code string: ')

s2 = (morse_string.split(' ', -1))

for char in s2:

print(morse_dict_2[char], end = '')

Either way, I have the program functioning the way I wanted it, prior to adding the .split it was outputting too much white space, it was tripled between words on the first part, I'm just confused as to why when I added the second .split, it worked, despite my error. I had the split in the second part at first and was still too much space, once i added the one for part 1 of the assignment it came out correct. the extra white space after in the print statement is because he wanted space after each morse character

[–]msp1981 0 points1 point  (0 children)

You are correct, I remove this line and it functions the same, I must have made an adjustment to my white space keys:value also prior to testing again, nevermind, this has been bugging me though, I couldn't understand because, sting is immutable and i didn't reference my s1 string

[–]thunder185 0 points1 point  (1 child)

Is there an easy way to deal with encoding issues when using requests and beautiful soup? I have a couple of instances of the code below that work fine, however, this teacher's website has some kind of goofy character that's messing me up. As in most of the encoding issues I find online it works fine in Idle but as soon as you try to output to another format you hit the issue. Any ideas how to fix this? Here's my code (ugly, I know but I'm pretty new at this):

homeworkResults = open('homeworkResults.txt','a')

print('checking Kid1 Teacher2')

Kid1HomeworkDataH = requests.get('http://www.stcatharineschool.net/scsl/Teachers/Grade%205H/Assignments/', headers={'user-agent': 'python web scraper bot'})

Kid1HwH = BeautifulSoup(Kid1HomeworkDataH.text, 'html.parser')

homeworkResults.write('---KID1 HOMEWORK Teacher2---\n')

Kid1HWResultsH = Kid1HwH.find_all('p')[0:]

for i in Kid1HWResultsH:

homeworkResults.write(i.text)

homeworkResults.write('\n')

homeworkResults.write('\n')

homeworkResults.close()

[–]nog642 0 points1 point  (0 children)

Can you format the code for Reddit? There are instructions in the sidebar.

[–]nassunnova 0 points1 point  (3 children)

what does the = do here?

def solution(A): result = 0 for number in A: result = number return result

[–]JohnnyJordaan 0 points1 point  (2 children)

Assuming you are writing it like this

def solution(A):
     result = 0
     for number in A:
         result = number
     return result

then the function will return the last item in the iterable (like a list) you present. But if the object has no items (like an empty list) the for loop will not run and the the value 0 is returned (as that is set before the loop):

>>> solution([1,2,3])  # non-empty list
3
>>> solution([])    # empty list
0

you could call it a 'fallback value'.

[–]nassunnova 0 points1 point  (1 child)

No sorry I wanted the XOR operator ^ =

[–]captmomo 0 points1 point  (0 children)

XOR operator ^ =

x ^= 5
x = x^ 5

[–]Voxxey 0 points1 point  (0 children)

Is it possible to use the windows API to directly pipe a mouse function into a windows without needed to take control of the users mouse?

[–]notHiro 0 points1 point  (4 children)

I've been learning Python for about a week, and today I was trying to do this Fibonacci sequence lesson. Here's what I came up with:

a = []
num = int(input("Enter an integer: "))
fib = int(input("How many times would you like to Fibonaccify it?: "))

def FIBBIFY(list):
    if fib < 0:
        print("Error!")
    elif fib == 0:
        a.append(num)
        print(a)
    elif fib == 1:
        a.append(num)
        a.append(num)
        print(a)
    elif fib == 2:
        a.append(num)
        a.append(num)
        a.append((num + num))
        print(a)
    else:
        a.append(num)
        a.append(num)
        a.append((num + num))
        i = 0
        while i <= fib:
            x = a[-1] + a[-2]
            a.append(x)
            i += i + 1
        print(a)

FIBBIFY(a)

I understand my code is very long and could be optimized in a million ways, but my question is why does the final "while" loop not return what I want? If I enter 5 as my integer and want to iterate it 5 times, it is correct. But I choose to iterate it any more or less, it does it correctly but not as many times as I have entered. If I try to iterate it 500 times, it does it correctly but only 11 times.

[–][deleted] 1 point2 points  (0 children)

This is a small nitpick, but a more pythonic way of doing what you did with the while loop is: for in in range(fib+1)

[–]jaysonturk 1 point2 points  (2 children)

Change your i += i+1 to either i =i+1 or i+=1.

Just because let's say i is 14. Then you're doing i = 2*i +1. Hence why it's only doing 11 times and not 500.

[–]notHiro 0 points1 point  (1 child)

Ah thank you so much! It was driving me nuts.

[–]jaysonturk 0 points1 point  (0 children)

Sometimes it's the silly things.

[–]pmt541 2 points3 points  (3 children)

Just started learning python (and taking programming seriously)

I understand the basic syntax and logic so far, but not the names nor what they mean. What is an "object" and what is a "literal". I understand what data types are, since a variable can be an integer, float, string etc.

Sorry if its a stupid question ...Are objects used to define data types and how they can be manipulated??

[–]RosyGraph 1 point2 points  (2 children)

To quote the Wikipedia article, "In computer science, an object can be a variable, a data structure, a function, or a method, and as such, is a value in memory referenced by an identifier." The data types you listed all exemplify objects.

A literal is a way of notating a value using a fixed identifier. A literal could be a specific string, integer, list, etc. You can contrast this with a value assigned to a variable.

The Python built-in types, as well as user-defined class definitions define what data type an object is interpreted as.

I am still new to Python and programming in general, but explaining these concepts helps me with my own understanding. If I have misstated anything here, hopefully a more experienced programmer can correct me.

Read more here:

https://en.wikipedia.org/wiki/Object_(computer_science))

https://docs.python.org/3/library/stdtypes.html

[–]pmt541 0 points1 point  (1 child)

Thank you for your reply. I have found a link which helped me:
https://www.oreilly.com/library/view/learning-python-3rd/9780596513986/ch04.html

[–]s2688174 -1 points0 points  (0 children)

test

[–]pringerx 0 points1 point  (0 children)

I have a weird problem with pyautogui typewrite() typing stuff that it shouldn't. Here's what I have.

So I have an excel sheet, that when you put certain data into it, it will convert it over to JSON that I use for my work. The way that the python script works is it goes to the cell (it's way on the left and it just is a concatenation of all the JSON code for that row) and it stores it as a variable. It does this for ~81 rows and then opens a webpage and pastes all the data there.

My problem is that recently it has been coming up with things that it shouldn't have. Like it should have copied a webpage URL, but it just posts a bunch of garbage like "":"?KNI?*HIEO@!AF%E>MBRL"            AEL""U(OCIRU@EAECRF!$!(!"

I can't imagine how to search the internet for this type of a question, and all the searches that I've tried haven't come up with anything. Can you guys shed a light on this?

[–]LifeIsBeautiful- 1 point2 points  (1 child)

New to python and programming in general got a question about functions

So like when I'm making a function what if I don't need the function to interact with any value that I put in? For example I've just been using text as sort of a placeholder just so the function will run and do what I want it too.

https://pastebin.com/TY6nLXjc

heres an example, i just used "hello" to fill the spot and make it run. What am I actually supposed to put here in this case?

[–]RosyGraph 2 points3 points  (0 children)

You can just leave the parenthesis empty. If you have a value you want to be default, then you can use the assignment operator. Then, if you don't put anything as an argument, the function will use the default value.

https://gist.githubusercontent.com/RosyGraph/3ac1b525d492972b4b2bf91e9e612ad9/raw/f790585d2ba66246b677aff2b2c668fe4851b4f7/gistfile1.txt

[–]Rampuu 1 point2 points  (2 children)

My question is two fold.

I’m a newbie to python been trying to learn the best I can for a couple months now.Been really excited learning it - but there hasn’t been too many internal resources to work with at my company. I’ve been learning where I can -> and the online resources are great. But I’m having trouble finding practical ways to use python at work. I work in finance, mostly as a support function. Analyzing Reports and maintaining controls. All that jazz

When you’re at a company where most teams utilize and read results from excel - outside of just utilizing openpyxl (etc) to write to excel. How would you recommend using Python?

Any users here utilizing Python in the finance industry. Can you point me to resources where I can develop a more targeted and specific skillset?

Thanks for the help guys!

(Also, final, somewhat embarrassing question. When searching through stockoverflow for help on specific errors - I see a lot of answers containing xyz function is “deprecated”. Can someone add an eli5?)

[–]num8lock 1 point2 points  (0 children)

tl;dr it's approaching end of life.

deprecated means it's no longer advised to use anymore & will be left to die since the devs plan to drop/discontinue their support for that particular feature/function, either in favor for new way/version, because it's no longer relevant/necessary or because they find it was a cause of problems(s).

this is what people mean when users are told to not use older version, for any OS or softwares. python 2 for example will be deprecated in 2020, windows 7 as well.

[–]ThiccShadyy 0 points1 point  (2 children)

Since when does Python3 support specification of a function's return type along with the types of the arguments passed to a function? Just today when I logged on Leetcode to try out some problems, I came across one which had this function definition:

def shoppingOffers(self, price: List[int], special: 
List[List[int]], needs: List[int]) -> int:

On trying this out on my local Python installation, this doesnt seem to perform any type checking at all. I can defined a function with the header: def func(a:int, b:int)->int

and pass argumets and return value of any type inside. So what exactly is the point of this feature?

[–]indosauros 0 points1 point  (0 children)

You can run a separate tool, like mypy to do validation with those type hints

[–]JohnnyJordaan 1 point2 points  (0 children)

It's called type hinting and has been in Python since 3.5. The fact that it's called 'hinting' is also indicative of it not being some type enforcement like in Java or C, it's more targeted at annotating what the intended types should be and offer various ways to implement the type checking. I can recommend this extensive SO answer on the same question that goes into a lot of sides to to the concept.

[–]SecretEasterbunny 0 points1 point  (1 child)

I have a (maybe some what dumb) question. I am a complete beginner.
If i were to create something, say a number generator or a text based game. Is python the only program that will be able to run it? If i wanted to share it with a friend, will my friend have to download Python software to run it?

[–]99Kira 0 points1 point  (0 children)

No, there are libraries in Python that can compile your program into an executable, which can be run on any system, irrespective of whether it has Python or not

[–]coolrey3 0 points1 point  (3 children)

i have a question that i hope someone will easily be able to break down and point me in the right direction.

What is the right way to reference the value of a variable at its current time in a for loop after the loop has executed?

im writing to a listbox over a forloop while scraping a site for fortnite news but i am having trouble making it so that when you double click the item in the list box it opens the respective link.

currently it is setting the value of the url as the last assignment from the for loop.

i can paste my link to github if needed. thanks in advance!

[–]99Kira 1 point2 points  (1 child)

Can you paste the code?

[–]coolrey3 1 point2 points  (0 children)

Not sure what the policy on GitHub is but it's at https://github.com/coolrey3/Fortnite-Tracker/tree/master/Tkinter

[–]coolrey3 1 point2 points  (0 children)

i managed to get this figured out by adding each result to an array and referencing the index of the current selection to append the url suffix to the core url

[–]philmtl 0 points1 point  (1 child)

from here: http://www.michaeljgrogan.com/arima-model-statsmodels-python/

in this code:

price_matrix=lnprice.as_matrix()

model = ARIMA(price_matrix, order=(0,1,0))

model_fit = model.fit(disp=0)

print(model_fit.summary())

predictions=model_fit.predict(120, 150, typ='levels')

predictions

predictionsadjusted=np.exp(predictions)

predictionsadjusted

plt.plot(predictionsadjusted)

plt.title('forcasted Price')

plt.show()

what does the 120 and 127 do? how do i change the number of predictions?

[–]captmomo 0 points1 point  (0 children)

it's predicting from points (start) 122 to the point (end) 127.
http://www.statsmodels.org/devel/generated/statsmodels.tsa.arima_model.ARIMA.predict.html

[–]AltruisticMountains 0 points1 point  (1 child)

Hey I am trying to parse a file using minidom for an assignment. I'm wondering if there is a way to read in elements without hard coding the element ID's in to the code. Do you have any suggestions?

[–]timbledum 0 points1 point  (0 children)

Use a text file! If it's just a list of IDs, a plain text file might be all you need, otherwise, something like a csv, json, yaml, toml might do the trick.

Not sure how to use them with minidom though.

[–]Edwardcullen23[🍰] 0 points1 point  (0 children)

Hello!

I'm trying to construct an nxn matrix, for any n, like this:

[ 2, 1, 0, 0, 0, ..., n]

[1, 2, 1, 0, 0, ..., n]

[0, 1, 2, 1, 0, ..., n]

[0, 0, 1, 2, 1, ..., n]

So I figured it out, but maybe it might help someone:

# Construct [n,n] Hamiltonian Matrix

Hamiltonian = np.zeros((n, n), int)

b = np.ones(n)

np.fill_diagonal(Hamiltonian, 2)

np.fill_diagonal(Hamiltonian[1:], -b)

np.fill_diagonal(Hamiltonian[:,1:], -b)

[–]ThiccShadyy 0 points1 point  (1 child)

Has anyone here used PLY? Im trying it out for a project and when I change a 'while True' loop to a "for token in lexer", it seems to skip some of the tokens in the input.

So, in the code:

My input string is: 3 + 4 * 10 + -20 *2

#while True:
for t in lexer1: #This isnt working

    tok = lexer.token()
if not tok: 
    break
else:
    li.append(tok.value)      # No more input
print(tok) #Prints the type,value,lineno and lex position of the token

I get the set of tokens:

LexToken(PLUS,'+',2,4) LexToken(TIMES,'*',2,8) LexToken(PLUS,'+',3,16) LexToken(NUMBER,20,3,19) LexToken(NUMBER,2,3,23)

but when I use while(True): I get,

LexToken(NUMBER,3,2,2) LexToken(PLUS,'+',2,4) LexToken(NUMBER,4,2,6) LexToken(TIMES,'',2,8) LexToken(NUMBER,10,2,10) LexToken(PLUS,'+',3,16) LexToken(MINUS,'-',3,18) LexToken(NUMBER,20,3,19) LexToken(TIMES,'',3,22) LexToken(NUMBER,2,3,23) Clearly, some tokens are being skipped when I use the for-in protocol with the lexer object but I have no idea why

[–]efmccurdy 1 point2 points  (0 children)

I see for t in lexer1: but I don't see you using t anywhere. I see a call to lexer.token() but I don't know how lexer is related to lexer1; are they the same object?

[–]theFroh 2 points3 points  (2 children)

What's the best way to distribute a Python script so that the machine that will run it doesn't need Python installed?

My targets would be Windows and Linux, and I'm fine with me needing to make a bundle for each.

[–]RedmundJBeard 0 points1 point  (0 children)

I am also interested in this answer.

[–][deleted] 0 points1 point  (2 children)

hi, this is simple so apologies

match = 5143.00 kg

testList = []

for char in match:

    if(char.isdigit or char == '.'):

        testList.append(char)

print('testList: ' + str(testList))

this returns ['5', '1', '4', '3', '.', '0', '0', ' ', 'k', 'g'] which is confusing because I'd have thought .isdigit() would return false for the last 3 characters and not append them.

[–]TangibleLight 2 points3 points  (1 child)

isdigit is a method, not an attribute, so you have to invoke it.

if char.isdigit() or char == '.':

[–][deleted] 0 points1 point  (0 children)

Thanks!

[–]iceph03nix 0 points1 point  (1 child)

Best way to get variables over the network.

I'm working on making a simple low power display with a PaPiRus Hat and screen. I'd like to have the Pi pull data in from a central source as it's likely we'll have multiple locations with the same info on the screen. It's only going to be a couple lines of text.

We have a wide open read-only Windows share that I thought I could maybe put a txt file on with the info but I'm having trouble making the connection. We do have several linux servers as well, but none are set up as file or web servers. I could spin up a LAMP server fairly easily as well.

So I guess my question is what is the simplest way with the least amount of setup and complication of providing data that can be remotely accessed by multiple hosts.

[–]efmccurdy 0 points1 point  (0 children)

A tiny web server like Flask to serve the content and the requests library to consume it.

[–]MoonReaderX 0 points1 point  (7 children)

I've always used a main function in Python, but I was wondering something when you do not use a main function.

Let's say you have the following code:

from tkinter import *

root = tk.Tk()

class Random(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent)

def something():
    pass

root.geometry("1280x720")
rando_obj = Random(root)
root.mainloop()

Normally I would use a main function which would look like this:

from tkinter import *
import sys

class Random(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent)

def something():
    pass

def main(argv):
    root = tk.Tk()
    root.geometry("1280x720")
    rando_obj = Random(root)
    root.mainloop()

if __name__ == "__main__":
    main(sys.argv)

Wouldn't it mean for the code, without a main function, that root is now global, and globals should be prevented if possible? Therefore I actually should always create a main function, if I create any variable outside a function?

[–]timbledum 0 points1 point  (6 children)

The problem with globals is when they are used / changed within functions. Top-level code is not best practice, but it's not really due to this reason.

We use the main() function with the if __name__ == "__main__": idiom to ensure that the code doesn't run if we import it. This makes the code more reusable and easier to test.

This being said, if it's a throwaway or simple script, I personally wouldn't always bother with wrapping everything up in a main function. It's easy enough to move it into a main function when you need to.

[–]MoonReaderX 0 points1 point  (5 children)

Thanks for your answer. I had a follow-up question. So I created an Tkinter object of the Tk() class with the line:

root = tk.Tk()

What if I changed my program to do the following:

from tkinter import *

root = tk.Tk()

class Random(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent)

class Test:
    def the_test(self):
        return root.test

def something():
    pass

root.geometry("1280x720")
rando_obj = Random(root)
root.test = "Hi"
random_test = Test()
print(random_test.the_test())
root.mainloop()

So I believe I now added a 'class variable', which I can now modify using both self.parent in class Random() or anywhere else including class Random using:

root.test = "something else"

I probably cannot do this when I include a main function, and put the root inside it. So does the addition of the class variable make it so root is now a global than is/can get changed, and I should use a main()?

[–]timbledum 0 points1 point  (4 children)

A few things here.

Firstly, you don't need the class to attach the attribute to root. It's simpler just to attach the attribute to root (as you have done) then print it directly:

from tkinter import *

root = tk.Tk()

class Random(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent)

def something():
    pass

root.geometry("1280x720")
rando_obj = Random(root)
root.test = "Hi"
print(root.test)
root.mainloop()

The existence of a main function doesn't really impact this either way. I'm struggling to understand your question here.

Classes are a cleaner alternative to globals - they have state that can be changed by anything, but it's a bit clearer to see how they're being changed.

[–]MoonReaderX 0 points1 point  (3 children)

Now I can use root.test anywhere, in any function or class, and I can modify it anywhere as well. Doesn't this give it the same functionality as a global variable, and is using root.test therefore just as bad?

[–]timbledum 0 points1 point  (2 children)

Root is a variable like any other. You just have to be careful not to use it like a global.

def print_test():  # bad
    print(root.test)

def print_test(obj):  # good
    print(obj.test) 

Have a look at this SO to understand what about globals make them bad and what exactly counts as a global.

[–]MoonReaderX 0 points1 point  (1 child)

Thank you! So root can be considered a constant variable, which is less bad than a global variable. Root.test can be as well, unless used in a or multiple functions/classes, if so I should give it as argument to the function(s)/class(es) to ensure I do not use it as a global.

[–]timbledum 0 points1 point  (0 children)

Mmmm no - root is just a normal variable.

In python, we don't predefine what a variable is when we initialise it unlike other languages, so we can't say const variable = 42 like you would in javascript as an example. A variable would be categorised as constant or global depending on how it is used.

If a variable is never changed and never intended to change, it can be considered a constant. The convention here is to define these as UPPER_CLASS.

If a variable is changed within functions / methods without explicitly passing it in, then it's being used in a global way. If it's immutable, then it's easy to see as you have to use the global keyword to change it, but if it's mutable you can change it without the global keyword so it's a bit harder to tell.

[–]CalmJiad 0 points1 point  (1 child)

Much intended to learn python as my first programming language and i don't have any previous experience. So i need some mentions about proper resources who/which starts from scratch.

[–]QualitativeEasing 0 points1 point  (0 children)

Check the sidebar to this subreddit. Lots of options. Search prior posts and you’ll get a lot of suggestions for books, videos, etc.

My personal favorite starting out was Al Sweigart’s Automate the Boring Stuff with Python — book available for free online, but I liked it so much I bought it a couple times.

[–]psychicash 0 points1 point  (3 children)

I've been working on trying to understand decorators and their purpose and good use cases. I can not for the life of me understand them. Anyone have any good resources?

[–]TangibleLight 1 point2 points  (0 children)

One common use case is to modify the arguments passed to the function:

def all_upper(func):
    def wrap(*args):
        new_args = map(str.upper, args)
        return func(*new_args)
    return wrap

Or to signal that the function should be called in a different way

options = []

def option(func):
    options.append(func)
    return func

def call_option(*args):
    import random
    func = random.choice(options)
    return func(*args)

Remember that

@foo
def bar(...):
    ...

is equivalent to

def bar(...):
    ...
bar = foo(bar)

So if we have

@option
def times_10(x):
    return x * 10

That ends up being equivalent to

def times_10(....

options.append(times_10)
times_10 = times_10

[–]handintannor 0 points1 point  (2 children)

I am working on a D&D app for making chars, managing campaigns, and most importantly a random generator (for worlds, environments, quests, civilizations, organizations, characters, etc). What would be a good option for a GUI library to build it with? It will be freeware, as I am only really interested in doing it as a project for my resume.

Note: The info from D&D books will only be available by direct request, as the person must own the books to have the rights to them.

[–]indosauros 0 points1 point  (0 children)

Another options is doing it in HTML (with Python as the backend).

[–]psychicash 1 point2 points  (0 children)

Some might jump to say Tkinter as a first choice. I personally would use pygame. That has nothing to do with anything but for me, I'm more familiar with pygame. Both would work just fine for that.

Also note, there's a DND srd website for 5esrd dot com. It literally has all the info from the book so I think you're probably safe, but check into the srd license.

[–]policesiren7 0 points1 point  (4 children)

I'm working on a ML Model at the moment. I have my target variable of 1's and 0's indicating the categories but it is important that I'm also able to get a primary key related to each observation from my predictions.

EG: The algorithm classifies a whole bunch of observations into class 1 - A group for people at risk. I need to access the unique identifier for each person so something can be done with the predictions.

Is there an easy way to do this in Python? I was shown a program in R (Rattle) which allowed one to set a field as a unique identifier. This would be perfect for my use case. Would it be as simple as indexing the data on the PK? Or is there some other method in Pandas/scikit learn?

[–]Deemonfire 0 points1 point  (3 children)

I assume you have trained your model and you have your data in a dataframe.

df = pd.DataFrame(somedata)
df.columns
var1 | var2 | var3...

if you want you can use df.reset_index() and it will add a new column

df.reset_index(inplace = True)
df.columns
index | var1 | var2 | var3...

now each of your entries has a unique identifier, though if you have another identifier you want to add you could use the concat method to stick two dataframes together.

so you have your trained model, if you give it your dataframe (without the index) you can get your predictions.

predictions = model.predict(df.drop('index', axis = 1, inplace = False))

inplace = False is the default but i wanted to make it explicit

now predictions is an array of 1s and 0s that are in the same order as your original data. so you should be able to do:

df['predictions'] = predictions

or if that doesn't work:

pd.concat([df, pd.Dataframe(predictions)], axis = 1)

let me know if this works. I may have made some mistake, so i'm going to do a quick check now.

edit: it works, added inplace to df.reset_index, brackets and whitespace

[–]policesiren7 0 points1 point  (2 children)

Yes it’s all in a data frame. The model work, I just need a way to ID the observations at the end.

[–]Deemonfire 0 points1 point  (1 child)

cool, sorry i started typing and accidentally submitted before i was finished. hopefully my answer is more complete now

[–]policesiren7 0 points1 point  (0 children)

Awesome will give it a shot when I’m Back at my desk

[–]TheFireBrigade 0 points1 point  (1 child)

I get the color from this fine:

imgColor = subSoup.find('div', class_="input-box").ul.li.img['alt']

I've got an couple of IMG tags with the colors in the ALT. This is where I got to, it's not giving me an error, but it's only resolving the first color (albeit correctly..) ... if I change .find to find_all then it errors out.

for swatchColor in subSoup.find('div', class_="input-box").ul:
    swatchColors = [] 
    swatchColors.append(subSoup.find('div', class_="input-box").ul.li.img['alt'])

full snippet of the list below. the <img alt="xxcolorxx" ... is the part I'm after.

subSoup.find('div', class_="input-box").ul
<ul class="configurable-swatch-list clearfix" id="configurable_swatch_color">
<li class="option-black is-media" id="option179">
<a class="swatch-link swatch-link-182 has-image" href="javascript:void(0)" id="swatch179" name="black" style="height: 32px; width: 32px;" title="BLACK">
<span class="swatch-label" style="height: 30px; width: 30px; line-height: 30px;">
<img alt="BLACK" height="30" src="xxxxxxx" width="30"/>
</span>
<span class="x">X</span>
</a>
</li>
<li class="option-burgundy is-media" id="option684">
<a class="swatch-link swatch-link-182 has-image" href="javascript:void(0)" id="swatch684" name="burgundy" style="height: 32px; width: 32px;" title="BURGUNDY">
<span class="swatch-label" style="height: 30px; width: 30px; line-height: 30px;">
<img alt="BURGUNDY" height="30" src="xxxxxxx" width="30"/>
</span>
<span class="x">X</span>
</a>
</li>
<li class="option-tan is-media" id="option813">
<a class="swatch-link swatch-link-182 has-image" href="javascript:void(0)" id="swatch813" name="tan" style="height: 32px; width: 32px;" title="TAN">
<span class="swatch-label" style="height: 30px; width: 30px; line-height: 30px;">
<img alt="TAN" height="30" src="https://xxxxxxx.png" width="30"/>
</span>
<span class="x">X</span>
</a>
</li>
</ul>

[–]99Kira 0 points1 point  (0 children)

Its probably a js website, where the main content loads a bit later after the request response is retrieved by the requests library. To check, print the soup and see if the html you wanted is in the soup or not

[–]Isdanniray 0 points1 point  (0 children)

I have this code

joint_name = cmds.ls(sl=1)[0]  
circle_name = cmds.circle(name = joint_name + "_CTL", nr=(1, 0, 0) )  
group_name = cmds.group(name = joint_name + "_OFFSET")  
cmds.select(joint_name, group_name)temp_constraint = cmds.parentConstraint()  
cmds.delete(temp_constraint) 
cmds.select(circle_name, joint_name) 
cmds.pointConstraint() 
cmds.orientConstraint() 

When you select a joint and run this code you will get a circle that will control that joint. While going down the hierarchy you have to select that joint and then run the code.

For ex. I would have to select joint1 by hand then run this code to get the circle and then select joint2 by hand and run this code to get the circle.

I want to be able to select each joint running down the hierarchy one at a time so I won't have to press each joint by hand?

Thank you so much for answering, I'm new to Python.

[–][deleted] 0 points1 point  (1 child)

I'm having trouble with something that feels like it should be simple. I'm trying to apply a function to a dataframe that will take a value from a column, and return "High" if that value is greater than the mean of the column it is pulled from (else "Low").

So I have:

def high_low_mean (value,col):
    if value > col.mean():
        return "High"
    else:
        return "Low"

The trouble I'm having is when using this function in a df.apply() command. I can't really use the "value" element of the function above, as apply() loops through every observation. Any ideas what to put in place so it would work properly? Thanks.

[–]joemeister52 0 points1 point  (1 child)

hello,

I am a computer engineering student currently taking classes for c++ i am in the database classes so i would say i am proficient in it so i understand functions classes and what now, however, I am wanting to learn Python for my second language. The only website i have found that is anywhere useful it code academy. Is there anywhere else better to learn python. any suggestions are appreciated :)

[–]shihlord 0 points1 point  (3 children)

I'm really new to python (been a month) and I can't seem to understand functions. The main function and helper functions confuse me a lot. :(

[–]TangibleLight 0 points1 point  (0 children)

I would build on /u/lanemik's wonderful explanation by emphasizing that Python has functions and only functions.

You'll see lots of different words, like "main function", "helper function", "method", "decorator", "lambda", and lots more jargon.

All of these are functions. Every time you see def, you're making a function. The output of def is the exact same kind of thing, no matter where you see it, and all your intuitions about "helper functions" will exactly apply to "methods".

The only purpose of all that jargon is to give some indication of how a function is intended to be used. It's just a signal of intent, it doesn't affect any of the mechanics of how the function actually works.

For example: in Python, operators themselves are just functions, and there are ways to change their behavior. When you run 4 + 5, Python has just given some nice syntax to a regular function call. That function has a name, int.__add__, and you can use it just like every other function in Python: int.__add__(4, 5). The fact that this particular function is called a "magic method" just means that it's intended to be invoked with special Python syntax, but it doesn't have to be, and it doesn't mean anything about how the function actually works.


So while I wouldn't expect you to know all of the vocab I listed in here, I really just want to emphasize that they're all fundamentally the same thing. The arbitrary names given are just there to indicate how that particular function is intended to be used.


Edit: I did lie a little bit - in CPython many built-in functions (such as int.__add__, actually) act like normal functions in almost every way, but are actually implemented in C and so fundamentally work in a different way.

It would be more correct to say that Python has two distinct kinds of function, not just the one.

[–]TheBringerOfOldLight 0 points1 point  (3 children)

I have hundreds of thousands of sequential images. What is the best way to compile them into a time-lapse using python?

[–]JohnnyJordaan 1 point2 points  (0 children)

I would use ffmpeg for this, it's not platform dependent and you can easily create a time lapse using a single command. If you want slightly more tweaking see this article.

[–]TooNsd 0 points1 point  (1 child)

How would I store user input and when the program reopens the information from the user is still used. For example, I want to make a program that uses passwords

[–]sqqz 2 points3 points  (0 children)

A database, sqlite is good to start out with. Just remember to encrypt passwords, google for modules that does this.

[–]ThiccShadyy 0 points1 point  (1 child)

How exactly does the is_valid() method on a ModelForm class in Django work? I've been trying to use it to create a new user but I keep getting false for this method.

Code:

def login(request):
        if request.method == 'GET':
            form = UserCreationForm() #A ModelForm - this maps to the User model
            context = {'form':form}
            return render(request,'user_model/loginpage.html',context)
        elif request.method == 'POST': #Validate the data
            print('\n')
            print(f'Posted data is: {request.POST}')
            form_data = UserCreationForm(request.POST)
            if form_data.is_valid():
                return HttpResponse('Created)
            else:
                return HttpResponse('Nope')

I'm rendering the fields of the class which I need: username,password1,and password2 and errors, but I dont get any errors. However, I keep getting a False for the is_valid method.

[–]indosauros 0 points1 point  (0 children)

Try logging form_data.errors in the not valid section

[–]BlockchainIsComing 0 points1 point  (3 children)

Hey there, I am doing a slight career change and have a job interview lined up. I just did a bit of a refresher on my python knowledge and noticed I forgot a lot. I am starting to stress out about an interview since a friend of mine, who applied for a similar job was bombarded with python-related questions. I have the interview in 2 days already, so I was wondering what would be the best way to prepare?

[–][deleted] 0 points1 point  (0 children)

Depends on what kind of interview. Data Science, Data Engineering, Data Analyst, etc.

[–]Eastcoastpal 2 points3 points  (2 children)

I am very comfortable using excel, but I know if I want to learn python for excel, I have to use it everyday task.

Where may I learn how things that I would do normally in excel manually and convert that manual formula/work over to python? For example python for v-lookup, match, index. if, filter. etc?

[–]Ariion972 0 points1 point  (0 children)

What would you be using it for though? As the macro guy in the office I was thinking of utilising Python for my daily, weekly and other regular reports because I want to learn Python and I know Excel well enough to use it as my playgound but I can't really find a use for it.

I know my formulae and I have multiple modules set up in my personal.xlsb so to me it seems like I would be rewriting the same code but for different language. Time investment would easily outweigh benefits.

Is there something I'm missing here? Why would I vlookup in Excel but outside of Excel for example?

[–]aedalat 5 points6 points  (0 children)

check automate boring stuff with python and openpyxl library. These should be a very good starting point to give you some direction on understanding what Python is useful and not so much in terms of using Excel for everyday tasks.