Getting a random track - python

Is there a way to get a random track from soundcloud API ? A work around I was thinking of also is getting a the total number of tracks, and picking a random number. But I can't find the way to get the total number of tracks either.
At the moment I am just wrapping the thing in a try/except, but then I do useless requests. If there's a way to avoid that !?
while (not track):
try:
track = client.get('/tracks/%s' % random.randint(0, 100000))
except requests.exceptions.HTTPError as e:
logger.error(e)

Are there any other requirements for the track you want to pick out? Doing a simple GET request on /tracks will return 50 track instances unless you specify a limit. You could just pick a random one out of that set?
import random
import soundcloud
client = soundcloud.Client(access_token='YOUR_ACCESS_TOKEN')
tracks = client.get('/tracks')
track = random.choice(tracks)
Hope that helps! Otherwise comment and I'll edit my answer with more details.

Related

Python can't circumvent ConnectionResetError:104

I'm getting a ConnectionResetError(104, 'Connection reset by peer'), and its not really in my control, from the other posts about this I've seen on SO, I've seen people add sleeps and it works for them. Here's my code:
for i,id in enumerate(id_list):
base_endpoint=f"https://endpoint.io/v1/resource/{id}/"
print("i:",i)
if i % 100 == 0:
print("sleeping")
sleep(10) #told it to sleep every 100 calls
with requests.Session() as session:
session.auth = (key, '')
sleep(1) #even added this
r = session.get(base_endpoint)
This is a toy example, I know I can add better exception handling, but point is there a better way to get around this stingy api? This is a SaaS product that we pay for, the api isn't meant to be used this way, but going to the devs is a several week long haul even to get a meeting.
Is there a different way to do this beyond just increasing the sleep time until it works?

python try statement or if statement

Hello everyone I have my code almost done but I'm trying to add in some sort of check to avoid errors. But I'm not really understanding what statement would be better to use to test the code. I know there are a few options of either using a loop, if-statement, or try. But here is the code in regards to doing captcha. I need it to run the first set of code which if the captcha doesn't pop up I continue on. But if the captcha does pop up solve it then continue on.
Some times captcha doesnt appear and if I run the whole set of code I get an error because we are expecting captcha to pop up.
Or if the captcha does appear to solve it which would.
I would really appreciate any help please as I'm not sure the right statement to use.
try should be used when something would return an error and would otherwise cause your program to stop/crash. An example of this would be:
try:
import pandas
except:
print("Unable to import pandas. Module not installed")
In this example your program will attempt to import the pandas module. If this fails it will then print out a line of text and continue running.
if statements are used to decided when to do something or not based on the returned logic. The key difference is that logic IS returned and not an error.
if x > 10:
print("This is a large number")
else:
print("This is a small number")
With this example, if 'x' did not exist it would produce an error, no more code will be executed, and the program will crash. The main difference between IF and TRY is whether logic is returned as true/false or is something just plains fails.
With your specific example it is important to know if the captcha appearing or not will break your code. Does the logic boil down to captcha = false or does captcha not exist at all and logic fails entirely?
Q: How do you define sometimes captcha doesn't appear (1%, 20%, 50%, ...)?
A: Maybe 5% of the time captcha doesn't appear.
In this case, I prefer to use Exception handling: do stuff and if something goes wrong, fix it
try:
# > 95% of the time the code below works when the captcha appears
except SomeException:
# < 5% of the time the code is called when the captcha doesn't appear
IMHO, you have not really 2 different codes: you have one and a fallback solution, it's really different than:
if x % 2:
...
else:
...

Naoqi ALSound energy values

I'm working on some energy computation about the sounds perceived by the Nao robot.
I'm using naoqi 2-1-4 and the following snippet of code to show the values:
import time
from naoqi import ALProxy
robotIP = "194.119.214.185"
port = 9559
soundDevice = ALProxy("ALAudioDevice", robotIP, port)
soundDevice.enableEnergyComputation()
try:
header = 'Left\t\t\t\tRight\t\t\t\tFront\t\t\t\tRear'
fmt = '{Left:.2f}\t\t\t\t{Right:.2f}\t\t\t\t{Front:.2f}\t\t\t\t{Rear:.2f}'
while True:
time.sleep(0.5)
left = soundDevice.getLeftMicEnergy()
right = soundDevice.getRightMicEnergy()
front = soundDevice.getFrontMicEnergy()
rear = soundDevice.getRearMicEnergy()
print header
print fmt.format(Left=left,Right=right,
Front=front,Rear=rear)
except KeyboardInterrupt:
print "Stopped by user."
I was not able to understand what is the nature of this values.
I've looked into this code from this page (at the bottom. Yeah I know it's c++ code but I could not find more, I assume that is the same concept, except for the language) and found in a comment that the RMS power is calculated.
I can't understand how are these values possible (tried to express them in dB but they made no sense anyway).
Does anyone have any idea of what these values stand for? How can I relate them to some "real" measuring units?
By the way here is a list of all methods.
Thanks in advance
Looking at the source, it seems to be just the sum of the square of each sample, then divided by the length of the buffer, finally squared.
sqrt(sum(each_sample*each_sample)/len(samples))
Hope it helps you...
As you don't provide us what are the strange values you've got (numbers?letters?) All I can do to help you is this link about another way to compute those values: NAO robot remote audio problems

tweepy (python): rate limit exceeded code 88

I'm writing a Twitter application with tweepy that crawls up the tweets by looking at in_reply_to_status_ID.
Everything works fine up to the rate limit, after a few minutes, I have to wait another 15 minutes or so.
This is strange because I used nearly identical code until a few months ago before API 1.0 got deprecated, and it didn't have the rate limit problem.
Is there a known way I can get rid of, or at least increase the rate limit?
Or is there a workaround?
Seems like a lot of people are having trouble with this, but can't find a definite solution..
i will greatly appreciate it if you could help.
auth1 = tweepy.auth.OAuthHandler('consumer_token','consumer_secret')
auth1.set_access_token('access_token','access_secret')
api=tweepy.API(auth1)
def hasParent(s):
#return true if s is not None, i.e., s is an in_reply_to_status_id numbe
....
while hasParent(ps):
try:
parent=api.get_status(ps)
except tweepy.error.TweepError:
print 'tweeperror'
break
newparent = parent.in_reply_to_status_id
......
ps=newparent
I put a limit and worked:
def index(request):
statuses = tweepy.Cursor(api.user_timeline).items(10)
return TemplateResponse(request, 'index.html', {'statuses': statuses})
This is due to you reached max limit. Just disconnect your internet connection and reconnect again, no need to wait.
Use cursor:
statuses = tweepy.Cursor(api.user_timeline).items(2)
If you get the error again, just reduce items.

Why do my threads stop?

I have a list consisting of ID's, about 50k per day.
and i have to make 50k request per day to the server { the server is at the same city } , and fetch the information and store it into database ... i've done that using loop and Threads
and i've notice that after unknown period of time it's stop fetching and storing ...
take a look of my code fragment
import re,urllib,urllib2
import mysql.connector as sql
import threading
from time import sleep
import idvalid
conn = sql.connect(user="example",password="example",host="127.0.0.1",database="students",collation="cp1256_general_ci")
cmds = conn.cursor()
ids=[] #here is going to be stored the ID's
def fetch():
while len(ids)>0:#it will loop until the list of ID's is finish
try:
idnumber = ids.pop()
content = urllib2.urlopen("http://www.example.com/fetch.php?id="+idnumber,timeout=120).read()
if content.find('<font color="red">') != -1:
pass
else:
name=content[-20:]
cmds.execute("INSERT INTO `students`.`basic` (`id` ,`name`)VALUES ('%s', '%s');"%(idnumber,name))
except Exception,r:
print r,"==>",idnumber
sleep(0.5)#i think sleep will help in threading ? i'm not sure
pass
print len(ids)#print how many ID's left
for i in range(0,50):#i've set 50 threads
threading.Thread(target=fetch).start()
output:it will continue printing how many ID's left and at unknown moment it stops printing and fetching & storing
Both networking and threading are non-trivial... most probably the cause is a networking event that results in a hanging thread. I'd be interested to hear whether people have solutions for this, because I have suffered the same problem of threads that stop responding.
But there are some things I would definitely change in your code:
I would never catch "Exception". Just catch those exceptions that you know how to deal with. If a network error occurs in one of your threads, you could retry rather than giving up on the id.
There is a race condition in your code: you first check whether there is remaining content, and then you take it out. At the second point in time, the remaining work may have disappeared, resulting in an exception. If you find this difficult to fix, there is a brilliant python object that is meant to pass objects between threads without race conditions and deadlocks: the Queue object. Check it out.
The "sleep(0.5)" is not helping threading in general. It should not be necessary. It may reduce the chance of hitting race conditions, but it is better to program race conditions totally out. On the other hand, having 50 threads at full spead banging the web server may not be a very friendly thing to do. Make sure to stay within the limits of what the service can offer.

Categories