including a scope in spotipy - scope

I'm using spotipy to extract information from a playlist (specifically the ten most listened songs by the user) and I'm asked for a scope. I'm not sure where I should include the scope so that it gives me permission. I leave the code that I have written in case someone could help me.
import requests
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
scope= 'user-top-read'
client_credentials_manager =
SpotifyClientCredentials(client_id='6b78bf9e892b4e8184c8e906885108bc', client_secret='3c2c0c7374374ab98062f342860369a5')
sp = spotipy.Spotify(client_credentials_manager = client_credentials_manager(scope=scope)
playlist_link = "https://open.spotify.com/playlist/75bo0xrhJrSf0Gf0iqEPuS"
playlist_URI = playlist_link.split("/")[-1].split("?")[0]
track_uris = [x["track"]["uri"] for x in sp.playlist_tracks(playlist_URI)["items"]]
for track in sp.playlist_tracks(playlist_URI)["items"]:
#URI
track_uri = track["track"]["uri"]
#Track name
track_name = track["track"]["name"]
#Top ten artists
artist_uri = track["track"]["artists"][0]["uri"]
artist_info = sp.current_user_top_artists(limit=10, offset=0, time_range='medium_term')
print(artist_info)

Related

is there any way to switch ImageJ macro code to python3 code?

I'm making an app in python3 and I want to use some function in imagej. I used macro recorder to switch to python code but it got really messy, now I don't know how to do next. Can someone help me, please.
Here is the marco recorder code and my marco code
imp = IJ.openImage("D:/data/data_classify/data_train/1/9700TEST.6.tiff40737183_2.jpg");
//IJ.setTool("line");
//IJ.setTool("polyline");
xpoints = [177,155,114,101,100,159,179];
ypoints = [82,94,109,121,133,163,173];
imp.setRoi(new PolygonRoi(xpoints,ypoints,Roi.POLYLINE));
IJ.run(imp, "Straighten...", "title=9700TEST.6.tiff40737183_2-1.jpg line=30");
my python3 code
mport imagej
from scyjava import jimport
ij = imagej.init('2.5.0', mode='interactive')
print(ij.getVersion())
imp = ij.IJ.openImage("D:/data/data_classify/data_train/1/9700TEST.6.tiff40737183_2.jpg")
xpoints = [177,155,114,101,100,159,179]
xpoints_int = ij.py.to_java(xpoints)
ypoints = [82,94,109,121,133,163,173]
ypoints_int = ij.py.to_java(xpoints)
straightener = jimport('ij.plugin.Straightener')
polyRoi = jimport('ij.gui.PolygonRoi')
and I don't know how to do next...
After a few days, I finally found the answer. It is important to understand the parameters of the function to write, I have referenced in:
https://pyimagej.readthedocs.io/en/latest/
https://imagej.nih.gov/ij/developer/api/ij/module-summary.html
in my example the next thing i need is polygonroi from the given coordinates. I found the required coefficients of PolygonRoi in the above website and determined to take as parameters PolygonRoi​(int[] xPoints, int[] yPoints, int nPoints, int type)
Next, I found a way to convert my list of coordinates to an int[] which was shown in the pyimagej tutorial.
In the type section, I can find it by trying print(int(roi.PolygonRoi)) and the result is 6, you can also find the reason in the website above in the Roi section
The rest, the last thing you need to do is put that PolygonRoi into the Straightener function with the line value you want
Here is my code for using macro Imagej in Python3
import imagej
from scyjava import jimport
from jpype import JArray, JInt
ij = imagej.init('2.5.0', mode='interactive')
print(ij.getVersion())
imp = ij.IJ.openImage("D:/AI lab/joint_detection/data/1/9700TEST.6.tiff133328134_1.jpg")
xpoints = [124,126,131,137,131,128,121,114]
xpoints_int = JArray(JInt)(xpoints)
ypoints = [44,63,105,128,148,172,194,206]
ypoints_int = JArray(JInt)(ypoints)
straightener = jimport('ij.plugin.Straightener')
polyRoi = jimport('ij.gui.PolygonRoi')
roi = jimport('ij.gui.Roi')
new_polyRoi = polyRoi(xpoints_int,ypoints_int,len(xpoints), int(roi.POLYLINE))
imp.setRoi(new_polyRoi)
straightened_img = ij.IJ.run(imp, "Straighten...", "title=9700TEST.6.tiff40737183_2-1.jpg line=30")
ij.IJ.saveAs(straightened_img, 'Jpeg', './test.jpg')

Not able to retrieve tick data - Zerodha Web Socket

I am using the below code to connect to the Web Socket API of Zerodha to pull tick data information for a particular instrument that I am interested in. When I run the below piece of code, I am not able to pull any information. I am not sure whether I am calling the functions in the Streaming_Ticks class properly.
The instrument token, which is the input, is placed in the "parameter_file.csv" and this token needs to be passed on to on_connect callback function present inside Streaming_Ticks class.
Would welcome your comments on how to run this code correctly.
from kiteconnect import KiteConnect
from kiteconnect import KiteTicker
import os
import csv
#cwd = os.chdir("E:\\Algorthmic Trading\\Zerodha_Training")
class Streaming_Ticks:
def __init__(self):
access_token = open("access_token.txt",'r').read()
key_secret = open("key_info.txt",'r').read().split()
self.kite = KiteConnect(api_key=key_secret[0])
self.kite.set_access_token(access_token)
self.kws = KiteTicker(key_secret[0],self.kite.access_token)
def on_ticks(ws,ticks):
# Callback to receive ticks.
#logging.debug("Ticks: {}".format(ticks))
print(ticks)
def on_connect(ws,response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
#logging.debug("on connect: {}".format(response))
print(token_list)
ws.subscribe(token_list)
ws.set_mode(ws.MODE_FULL,token_list) # Set all token tick in `full` mode.
#ws.set_mode(ws.MODE_FULL,[tokens[0]]) # Set one token tick in `full` mode.
if __name__ == "__main__":
cwd = os.chdir("E:\\Algorthmic Trading\\Zerodha_Training")
tick_data = Streaming_Ticks()
token_list= []
with open('parameter_file.csv') as param_file:
param_reader = csv.DictReader(param_file, )
for row in param_reader:
token_list.append(int(row['token']))
tick_data.on_ticks = tick_data.on_ticks
tick_data.on_connect = tick_data.on_connect
tick_data.kws.connect()

How do I check if a twitter users likes has been updated without exceeding twitters rate limit? (Tweepy)

I need to check if a user has liked a new post without exceeding twitters rate limit.
Basically, I'm just making a fun code to prank my friend. It will detect when he likes a new post and send that post to him with some snarky comment. All love between me and him, and I've made it obvious who made the bot.
I understand what the rate limit is and why its there, and I have wait_on_rate_limit = True, but that stops the code from working.
Here's what I currently have.
import tweepy, random
comments = open('dumbcomments.txt', 'r')
# Authenticate to Twitter
auth = tweepy.OAuthHandler("authkey", "securityauthkey")
auth.set_access_token("accesstoken", "securityaccesstoken")
# Create API object
api = tweepy.API(auth, wait_on_rate_limit = True)
lines = comments.readlines()
friend = api.get_user(friendUser)
likes = api.favorites(friendUser, count = 1)
lastlike = likes
while True:
likes = api.favorites(friendUser, count = 1)
if likes != lastlike:
comment = random.randint(0, 23)
api.send_direct_message(friend.id, lines[comment] + '\n' + str(likes[0].text))
lastlike = likes
comments.close()
The code works, so long as I haven't exceeded the rate, which happens quickly.

Spotify denying access for valid Id

I am trying to access Spotify playlists using the spotipy and pbl libraries. See http://pbl.readthedocs.io/en/latest/ for the latter.
I have this:
import sys
from pbl import *
import spotipy
import spotipy.util as util
def fetch(): #pbl methods here
classic_rock = Sample(PlaylistSource('Rock Classics'), sample_size=10)
new_music = Sample(PlaylistSource('New Music Tuesday'), sample_size=5)
combined = Shuffler(Concatenate([classic_rock, new_music]))
show_source(combined)
scope = 'playlist-modify-public'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope, client_id='a_valid_id', client_secret='a_valid_secret', redirect_uri='http://localhost:8888/callback')
if token:
sp = spotipy.Spotify(auth=token)
fetch()
If I bypass the snippet relative to pbl methods and the pbl function call above and proceed, I am granted access.
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
Otherwise access is denied, and I get spotipy.oauth2.SpotifyOauthError: No client id
What is going on here?

CoSign API: Sending SOAP from Python client generated by suds

I need to access the signing appliance from Python. To this end, using suds, I generated a Python client from the WSDL at https://cosigndemo.arx.com:8080/sapiws/dss.asmx?wsdl .
I then used the generated client to build a simple signature request which more or less does the same as shown in the Java example provided by ARX (only, I'm asking for an invisible signature).
The problem is that when I send the request to the demo appliance, here's what I receive in return:
(DssSignResult){
Result =
(Result){
ResultMajor = "urn:oasis:names:tc:dss:1.0:resultmajor:ResponderError"
ResultMinor = "urn:oasis:names:tc:dss:1.0:resultminor:GeneralError"
ResultMessage =
(ResultMessage){
value = "Exception occured"
_lang = "en"
}
}
}
Here's the Python code I wrote:
from suds.client import Client
from suds.plugin import MessagePlugin
from suds.sax.attribute import Attribute
import logging
class MyPlugin(MessagePlugin):
def marshalled(self, context):
foo = context.envelope.getChild('ns2:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:InputDocuments').getChild('ns1:Document')
foo[0].attributes.append(Attribute('MimeType', 'application/pdf'))
print context.envelope
url = 'https://cosigndemo.arx.com:8080/sapiws/dss.asmx?wsdl'
client = Client(url, plugins=[MyPlugin()])
cid = client.factory.create("ns4:ClaimedIdentity")
cid.Name = "John Miller"
cid.SupportingInfo.LogonPassword = "12345678"
sigReq = client.factory.create("ns4:RequestBaseType")
sigReq._RequestID = "DummyRequestId"
sigReq.OptionalInputs.ClaimedIdentity = cid
sigReq.OptionalInputs.SignatureType="http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign"
sigReq.OptionalInputs.SAPISigFieldSettings._Name = "SigField"
sigReq.OptionalInputs.SAPISigFieldSettings._Invisible = "true"
sigReq.OptionalInputs.SAPISigFieldSettings._DependencyMode = "Independent"
sigReq.OptionalInputs.SAPISigFieldSettings._SignatureType = "Digital"
sigReq.OptionalInputs.SAPISigFieldSettings._EmptyFieldLabel = ""
sigReq.OptionalInputs.SAPISigFieldSettings._Page = "1"
sigReq.OptionalInputs.ReturnPDFTailOnly = "true"
sigReq.OptionalInputs.IncludeObject=None
sigReq.OptionalInputs.SignaturePlacement=None
doc = client.factory.create("ns4:DocumentType")
doc.Base64Data = open("/Users/mar/CoSignWSDL/factures-comptat217.pdf", "rb").read().encode("base64")
sigReq.InputDocuments.Document = doc
result = client.service.DssSign(sigReq)
print result
And here's the SOAP that (at least I think) it is sending to the appliance:
<SOAP-ENV:Envelope xmlns:ns3="http://arx.com/SAPIWS/DSS/1.0" xmlns:ns0="http://arx.com/SAPIWS/DSS/1.0/" xmlns:ns1="urn:oasis:names:tc:dss:1.0:core:schema" xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns2:Body>
<ns0:DssSign>
<ns0:SignRequest RequestID="DummyRequestId">
<ns1:OptionalInputs>
<ns1:ClaimedIdentity>
<ns1:Name>John Miller</ns1:Name>
<ns1:SupportingInfo>
<ns3:LogonPassword>12345678</ns3:LogonPassword>
</ns1:SupportingInfo>
</ns1:ClaimedIdentity>
<ns1:SignatureType>http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign</ns1:SignatureType>
<ns1:SAPISigFieldSettings Name="SigField" DependencyMode="Independent" SignatureType="Digital" Page="1" Invisible="true"/>
<ns1:ReturnPDFTailOnly>true</ns1:ReturnPDFTailOnly>
</ns1:OptionalInputs>
<ns1:InputDocuments>
<ns1:Document>
<ns1:Base64Data MimeType="application/pdf">...</ns1:Base64Data>
</ns1:Document>
</ns1:InputDocuments>
</ns0:SignRequest>
</ns0:DssSign>
</ns2:Body>
</SOAP-ENV:Envelope>
Note that I replaced the (very long) Base64Data content with "..." here for space reasons.
Why is it not working?
Update Problem solved thanks to the answer. Here is the working code that adds a sig to a PDF:
from suds.client import Client
from suds.plugin import MessagePlugin
from suds.sax.attribute import Attribute
from suds.bindings import binding
import logging
import xml.dom.minidom as minidom
import base64
class MyPlugin(MessagePlugin):
def marshalled(self, context):
documentNode = context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:InputDocuments').getChild('ns1:Document')
documentNode[0].attributes.append(Attribute('MimeType', 'application/pdf'))
SAPISigFieldSettingsNode = context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:OptionalInputs').getChild('ns1:SAPISigFieldSettings')
SAPISigFieldSettingsNode.setPrefix('ns2')
ReturnPDFTailOnlyNode = context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:OptionalInputs').getChild('ns1:ReturnPDFTailOnly')
ReturnPDFTailOnlyNode.setPrefix('ns2')
signRequestNode = context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest')
signRequestNode.setPrefix('ns1')
binding.envns = ('SOAP-ENV', 'http://www.w3.org/2003/05/soap-envelope')
url = 'https://cosigndemo.arx.com:8080/sapiws/dss.asmx?wsdl'
client = Client(url, plugins=[MyPlugin()])
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.plugin').setLevel(logging.DEBUG)
cid = client.factory.create("ns4:ClaimedIdentity")
cid.Name = "John Miller"
cid.SupportingInfo.LogonPassword = "12345678"
sigReq = client.factory.create("ns4:RequestBaseType")
sigReq._RequestID = "DummyRequestId"
sigReq.OptionalInputs.ClaimedIdentity = cid
sigReq.OptionalInputs.SignatureType="http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign"
sigReq.OptionalInputs.SAPISigFieldSettings._Name = "SigField"
sigReq.OptionalInputs.SAPISigFieldSettings._Invisible = "true"
sigReq.OptionalInputs.SAPISigFieldSettings._DependencyMode = "Independent"
sigReq.OptionalInputs.SAPISigFieldSettings._SignatureType = "Digital"
sigReq.OptionalInputs.SAPISigFieldSettings._EmptyFieldLabel = ""
sigReq.OptionalInputs.SAPISigFieldSettings._Page = "1"
sigReq.OptionalInputs.ReturnPDFTailOnly = "true"
sigReq.OptionalInputs.IncludeObject=None
sigReq.OptionalInputs.SignaturePlacement=None
doc = client.factory.create("ns4:DocumentType")
f = open('/Users/mar/CoSignWSDL/factures-comptat217.pdf', 'r+b')
doc.Base64Data = f.read().encode("base64")
sigReq.InputDocuments.Document = doc
result = client.service.DssSign(sigReq)
signature = base64.b64decode(result.SignatureObject.Base64Signature.value)
f.seek(0, 2) #go to the end of the file
f.write(signature)
f.close()
Your SOAP request is passing ns0:SignRequest Should be: ns1:SignRequest
Also Bear in mind that there is a missing part in your code--checking the appliance's SSL certificate. It is not a must, but generally required in order to verify that the response wasn't sent by a fraudulent entity.
In .Net and Java it is done automatically when accessing web service in HTTPS (based on Microsoft certificate Store and Java certificate Store)- but as far as I see there is no equivalent in Python.

Resources