def dim(): if platform.system() == 'Linux': call(dim_script, shell=True) elif platform.system() == 'Darwin': osascript.osascript(dim_script)
def update(self): ## Sync protocol while self.incoming != b'X': self.incoming = ser.read() logging.debug("Received INCOMING: {}".format(self.incoming)) data = ser.read() logging.debug("Received DATA: {}".format(data)) if data == b'1': data = ser.read() if data == b'L': logging.info("KEYDOWN A") pyautogui.hotkey('ctrl', 's') if data == b'M': logging.info("KEYDOWN B") pyautogui.keyDown(self.mapping.button['B']) if data == b'A': data = ser.read() for k in range(3): data += ser.read() logging.info("KEYDOWN V") print("set volume output volume " + data.decode("utf-8")) data = int(data.decode("utf-8")) data = str(100 * (int(data) / 4095)) osascript.osascript("set volume output volume " + data) elif data == b'0': logging.info("KEYUP A") pyautogui.keyUp('ctrl', 's') logging.info("KEYUP B") pyautogui.keyUp(self.mapping.button['B']) self.incoming = ser.read()
def brighten(): if platform.system() == 'Linux': call(brighten_script, shell=True) elif platform.system() == 'Darwin': osascript.osascript(brighten_script)
def watch(driver, element): element.click() time.sleep(2) sharelinks = element.find_elements_by_css_selector( "div.cover-video-container > iframe") if len(sharelinks) == 0: sharelinks = element.find_elements_by_css_selector( "divdiv > div > form > div.form-compact__content > div.form-compact__part.user-fragment.center.ng-binding.ng-scope > p > a" ) sharelinks[0].click() # play it osascript.osascript("set volume output volume 0") time.sleep(constants.RETRY_VIDEO_CONTINUE_WAIT) osascript.osascript("set volume output volume 20") #In case video has comments box input_boxes = element.find_elements_by_css_selector( "div > div > form > div.form-compact__content > div:nth-child(2) > div > div > div > input" ) if len(input_boxes) == 0: input_boxes = element.find_elements_by_css_selector( "div > div > form > div.form-compact__content > div:nth-child(2) > div > div > textarea" ) if len(input_boxes) > 0: input_boxes[0].clear() input_boxes[0].send_keys(constants.GOOG_ID + " . I'm loving it") time.sleep(2) has_clicked = False while has_clicked == False: has_clicked = type4_click_continue(driver, element, 'watch_pattern') time.sleep(constants.RETRY_VIDEO_CONTINUE_WAIT) element.click()
def current_tab(self,v): cmd=""" tell application "Safari" tell window %s set current tab to tab %s end tell end tell""" % (self.index,v) osascript(cmd)
def adjustVolume(currentVol, rms, THRESHOLD): #This is percent increase of background noise compared to the threshold increaseInput = (rms - THRESHOLD) / THRESHOLD decreaseVol = 1 - increaseInput newVol = decreaseVol * currentVol for i in range(int(currentVol), int(newVol), -10): osascript.osascript("set volume output volume " + str(i))
def popup_macos(title, content): result = None if isinstance(content, str): result = content.split('\n').pop(-2) elif isinstance(content, list): result = content[-1] import osascript osascript.osascript( """display notification \"{}\" with title \"{}\"""".format( result, title))
def dim(): script = """ tell application "System Events" repeat 32 times key code 145 delay 0.02 end repeat end tell """ osascript.osascript(script)
def showBoxes(image, object_data, personData): h, w, c = image.shape try: personZDistance = (focalLength * avgPersonHeight * h) / ( abs(personData['y2'] - personData['y1']) * sensorHeight) except ZeroDivisionError: print("PERSON-QR PAIR NOT DETECTED") return humanLocation = None mmToPixelRatio = None volumeLevel = 0 for object in object_data: qrPoints = len(object.location) midPoint = (0, 0) for i in range(0, qrPoints): midPoint = (midPoint[0] + object.location[i][0], midPoint[1] + object.location[i][1]) cv2.line(image, object.location[i], object.location[(i + 1) % qrPoints], lineColor, 3) midPoint = (int(midPoint[0] / qrPoints), int(midPoint[1] / qrPoints)) sideLength = 0 for i in range(1, qrPoints): sideLength += distance(object.location[i - 1], object.location[i]) sideLength /= qrPoints if mmToPixelRatio is None: mmToPixelRatio = sideLength**2 / actualQRHeight**2 personZDistance *= mmToPixelRatio humanLocation = (personData['midX'], personData['midY'], personZDistance) zDistance = (focalLength * actualQRHeight * h) / (sideLength * sensorHeight) zDistance *= mmToPixelRatio mid3Point = (midPoint[0], midPoint[1], zDistance) cv2.rectangle(image, (personData['x1'], personData['y1']), (personData['x2'], personData['y2']), (0, 255, 0), 2) cv2.circle(image, (int(personData['midX']), int(personData['midY'])), 10, personColor, -1) absDiff = distance(mid3Point, humanLocation) volumeLevel = math.floor(absDiff / max(w, h) * 100) print("\nQR LOCATION: ", mid3Point) print("HUMAN LOCATION: ", humanLocation) print("DISTANCE BETWEEN: ", absDiff, "\n") print("VOLUME LEVEL: ", volumeLevel) if closestQR['data'] == '' or absDiff < closestQR['distance']: closestQR['distance'] = absDiff closestQR['data'] = object.data closestQR['location'] = midPoint osascript.osascript("set volume output volume " + str(volumeLevel)) cv2.circle(image, closestQR['location'], 10, closestColor, -1) cv2.imshow("QR To Human", image)
def setVolume(crease): settings = osascript.osascript("get volume settings")[1] index = 14 curr_vol = 0 while settings[index] != ",": curr_vol = 10 * curr_vol + int(settings[index]) index += 1 # print(settings) print(curr_vol) osascript.osascript("set volume output volume " + str(crease * 7 + curr_vol))
def upload_file(): data = request.get_data() print(data) with open('raw_cv.jpg', 'wb') as f_output: f_output.write(data) if app.firstFrame: app.firstFrame = False app.spatialVolume = qth.SpatialQR("raw_cv.jpg") return -1 volume = app.spatialVolume.getDistanceToVolume("raw_cv.jpg") if volume != -1: osascript.osascript("set volume output volume " + str(volume)) return str(volume)
def get_current_song(): song_name = osascript( 'tell application "iTunes" to get the name of the current track')[1] if song_name == "": song_name == "None" else: return song_name
def addToITunes( song, artist, lyrics ): #to search song with name and its author similar to regex pattern #pass AppleScript to addlyrics to variable cmd #Limitation : artist name should be same as entered cmd = ''' global f,ly,a set a to "%s" set f to "%s" set ly to "%s" tell application "iTunes" set res to (every file track whose name contains f and artist is a) if res is in {{}, {""}, ""} then set lyrics to ly repeat with t in res if lyrics of t is in {{}, {""}, ""} then set lyrics of t to ly end repeat end tell ''' % (artist, song, lyrics.lstrip("\n")) returncode, stdout, stderr = osascript(cmd) #if return code is not zero then error can be debugged by studying stderr if returncode != 0: return False else: return True
def get_current_artist(): artist_name = osascript( 'tell application "iTunes" to artist of current track as string')[1] if artist_name == "": artist_name = "None" return artist_name else: return artist_name
def on_release(self, key): try: if key and key.name and key.name == self.push_to_talk_button: self.last_volume = osascript.osascript( "input volume of (get volume settings)")[1] self.hush_mic() except: pass
def send(message, title): ''' :param message: message will be sent :param title: title will be sent with message ''' returncode, stdout, stderr = osascript( 'display notification "{message}" with title "{title}"'.format( message=message, title=title))
def current_window(): try: resp = osascript(scpt) if not ',' in resp: return '', '' app, title = string.split(resp, ',', 1) return app, title except Exception: return '', ''
def tell(self,code,flags=None): """Tell application %(self.name)s %(code)s end Tell """ return osascript(""" tell application "%s" %s end tell """ % (self.name,code),flags)
def sound(f, length, volume = 40): osascript.osascript("set volume output volume " + str(volume)) frequency = f # Our played note will be 440 Hz fs = 44100 # 44100 samples per second seconds = length # Note duration of 3 seconds # Generate array with seconds*sample_rate steps, ranging between 0 and seconds t = np.linspace(0, seconds, int(seconds * fs), False) # Generate a 440 Hz sine wave note = np.sin(frequency * t * 2 * np.pi) # Ensure that highest value is in 16-bit range audio = note * (2**15 - 1) / np.max(np.abs(note)) # Convert to 16-bit data audio = audio.astype(np.int16) # Start playback play_obj = sa.play_buffer(audio, 1, 2, fs) # Wait for playback to finish before exiting play_obj.wait_done() return audio
def main(): global boolean global stream ORIGINAL_VOLUME = outputVolume() p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) BASELINE = determineBaseline(stream) print(BASELINE) #THRESHOLD = BASELINE * 4 THRESHOLD = 1200 + BASELINE print("Button clicked.") #for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): while boolean == True: data = stream.read(CHUNK, False) rms = audioop.rms(data, 2) # here's where you calculate the volume time.sleep(.1) print(rms) if rms > THRESHOLD: adjustVolume(ORIGINAL_VOLUME, rms, THRESHOLD) if resetOriginalVol(rms, THRESHOLD) == True: for i in range(int(currentVol), int(ORIGINAL_VOLUME), 10): osascript.osascript("set volume output volume " + str(i)) stream.stop_stream() stream.close() p.terminate()
def main(args): file_name = str file_name = osascript( '/Users/albinjonfelt/Documents/programmering/aktier/scripts/return_any_file.scpt' ) first_row_to_indent = int( input('Input first row to indent in the form: 12\nInput: ')) last_row_to_indent = int( input('Input last row to indent in the form: 42\nInput: ')) all_lines = list() with open(file_name[1], 'r') as f: full_file = f.readlines() for i in range(0, len(full_file)): if (i >= first_row_to_indent - 1 and i <= last_row_to_indent - 1): all_lines.append('\t' + full_file[i]) else: all_lines.append(full_file[i]) f.close() with open(file_name[1], 'w') as f: f.writelines(all_lines) f.close()
def main(argv): os.chdir("/Users/albinjonfelt/Documents/programmering/aktier/python/") inputfile = "" desired_file_name = date.isoformat(datetime.now()) + "clean_file.csv" bought_list = list(dict()) sold_list = list(dict()) all_list = list(dict()) bin_path = os.path.join(os.path.dirname(os.getcwd()), 'bin') try: bought_path = os.path.join(bin_path, 'bought.pickle') with open(bought_path, 'rb') as f: bought_list = pickle.load(f) f.close() sold_path = os.path.join(bin_path, 'sold.pickle') with open(sold_path, 'rb') as f: sold_list = pickle.load(f) f.close() all_path = os.path.join(bin_path, 'all.pickle') with open(all_path, 'rb') as f: all_list = pickle.load(f) f.close() except FileNotFoundError: print( "One or more pickle files missing, this will result in creating new pickle files" ) pass # First look in the bin folder after a cleaned file, if there is one, use that one and read from. # If these is none, download a new transaction export from nordnet. # The downloaded file defaults to using the same folder it was run from, which is the python folder. # Would be neat if it actually followed the instructions that are stored in chrome. # Anyhow, then the AppleScript for converting the CSV to utf-8 standard and outputs it to the bin folder. # The AppleScript also runs the "csv_cleaner_transactions.py" which cleans the file from unneccessary values. if desired_file_name not in os.listdir(bin_path): print("No clean file from today, downloading new file...") exec( open( "/Users/albinjonfelt/Documents/programmering/aktier/python/login_and_download.py" ).read(), globals()) print("Done downloading, running cleaning script...") return_val = osascript( '/Users/albinjonfelt/Documents/programmering/aktier/scripts/export_to_utf8.scpt' ) inputfile = return_val[1] print(f"Using file {inputfile} as input...") else: print(f"Using {desired_file_name} as input") inputfile += ( '/Users/albinjonfelt/Documents/programmering/aktier/bin' + "/" + desired_file_name) # Save all the values of one specific row into a dictionary, and append that to a list of dictionaries. # The values of the dictionary can then be accessed through bought/sold/all_list[X]['value_to_access'] # Where X is to be iterable with open(inputfile, "r") as csv_file: my_reader = csv.reader(csv_file, delimiter=";", dialect='excel') for row in my_reader: csv_dict = { 'id': row[0], 'buisday': row[1], 'liqday': row[2], 'transtype': row[3], 'name': row[4], 'instrumenttype': row[5], 'qty': row[6], 'price': row[7], 'fees': row[8], 'totvalue': row[9], 'forex': row[10], 'buytotvalue': row[11], 'result': row[12], 'totqty': row[13], 'balance': row[14], 'forexrate': row[15] } exists = False for each in all_list: if csv_dict['id'] == each['id']: exists = True if exists == False: all_list.append(csv_dict) if csv_dict['transtype'] == 'SÅLT': exists = False for each in sold_list: if csv_dict['id'] == each['id']: exists = True if exists == False: sold_list.append(csv_dict) if csv_dict['transtype'] == 'KÖPT': exists = False for each in bought_list: if csv_dict['id'] == each['id']: exists = True if exists == False: bought_list.append(csv_dict) folder_path = '/Users/albinjonfelt/Documents/programmering/aktier/bin/' with open(folder_path + 'sold.pickle', 'wb') as f: pickle.dump(sold_list, f, pickle.HIGHEST_PROTOCOL) f.close() with open(folder_path + 'bought.pickle', 'wb') as f: pickle.dump(bought_list, f, pickle.HIGHEST_PROTOCOL) f.close() with open(folder_path + 'all.pickle', 'wb') as f: pickle.dump(all_list, f, pickle.HIGHEST_PROTOCOL) f.close() print("All values pickled!")
import LetrasTerraParser import MetrolyricsParser import ChartlyricsParser import LyricsmaniaParser import LeoslyricsParser import LyricwikiParser from osascript import osascript sites = [LyricwikiParser, LetrasTerraParser, MetrolyricsParser, AZLyricsParser, LyricsmaniaParser, ChartlyricsParser, LeoslyricsParser] def fetch(source, artist, title): parser = sites[source].Parser(artist, title) try: lyrics = parser.parse() except Exception: return "" return lyrics state = osascript('tell application "iTunes" to player state as string') artist = osascript('tell application "iTunes" to artist of current track as string') track = osascript('tell application "iTunes" to name of current track as string') if state == "playing": for r in range(0, len(sites)): output = fetch(r, artist, track) if output != "": break print "%s - %s\n\n" % (track, artist) print output.encode('ascii', 'ignore')
import osascript osascript.osascript("set volume output volume 100")
def runAppleScript(self, scpt): scpt = 'tell application "System Events"\n' + scpt + "\nend tell\n" returned = osascript(scpt) return returned
def brighten(): osascript.osascript(brighten_script)
def dim(): osascript.osascript(dim_script)
def hush_mic(self): try: osascript.osascript("set volume input volume 0") except: pass
def get_credentials(): cfg = get_config() watchedLiUser = cfg.get('shores', 'watchedLiUser') watchedLiPass = cfg.get('shores', 'watchedLiPass') return (watchedLiUser, watchedLiPass) def get_videoplayer(): cfg = get_config() return cfg.get('watched', 'videoPlayer') if __name__ == '__main__': video_player = get_videoplayer() debug(video_player) video_path = osascript.osascript(os.path.join(wd, '%s_Log.scpt' % video_player)) if not video_path: print 'Could not get video from %s.' % video_player sys.exit(1) video_info = guess_file_info(video_path, 'autodetect') if not video_info.has_key('type') or video_info['type'] != 'episode': debug(video_info) print '%s is not playing a TV show episode.' % video_player sys.exit(1) show = video_info['series'] episode_id = 'S%02dE%02d' % (int(video_info['season']), int(video_info['episodeNumber'])) debug(show + ' ' + episode_id)
import os from osascript import osascript from datetime import date, datetime os.chdir("/Users/albinjonfelt/Documents/programmering/aktier/python/") bin_path = os.path.join(os.path.dirname(os.getcwd()), 'bin') name_of_files = os.listdir(bin_path) try: found_file = [filename for filename in name_of_files if 'clean_file.csv' in filename] os.remove(os.path.join(bin_path, 'all.pickle')) os.remove(os.path.join(bin_path, 'sold.pickle')) os.remove(os.path.join(bin_path, 'bought.pickle')) for filename in found_file: os.remove(os.path.join(bin_path, filename)) print("Removed pickles and clean transaction data") except (IndexError, FileNotFoundError): print("Some pickle file(s) was not found") pass name_of_files = os.listdir() found_file = next((filename for filename in name_of_files if 'transactions_export' in filename), False) script_path = os.path.join(os.getcwd(), 'csv_to_pickle.py') if found_file != False: print("There was a transactions-file") osascript('/Users/albinjonfelt/Documents/programmering/aktier/scripts/export_to_utf8.scpt') exec(open(script_path).read(), globals()) else: print("There was no transactions-file, will download a new one throught csv_cleaner_transactions.") exec(open(script_path).read(), globals())
def setVolume(vol, mut): # restores Volume to input values (vol, mut as Strings) mute = 'with' if (mut == 'true') else 'without' osascript('set volume %s output muted output volume %s' % (mute, vol))
def getVolume(): # returns the current volume and muted as strings vol = osascript('output volume of (get volume settings)')[1] mut = osascript('output muted of (get volume settings)')[1] return vol, mut
def is_playing(): if osascript('tell application "iTunes" to get player state as string' )[1] == "paused": return False else: return True
def open_mic(self): try: osascript.osascript("set volume input volume " + str(self.last_volume)) except: pass
def get_track_name(): """Retrieve the song title playing in the Spotify""" return osascript("""tell app "Spotify" return name of current track end tell """)[1]
osascript(''' on open_url(address) tell application "Safari" close every window activate open location address end tell end open_url on wait_for_page_to_load() delay 0.5 tell application "Safari" repeat set thePage to source of document in window 1 if thePage contains "</html>" then return true exit repeat else delay 0.5 end if end repeat end tell end wait_for_page_to_load on fill_in_fields(username, passwd) tell application "System Events" tell process "Safari" repeat until not (exists window 1) set allUIElements to entire contents of window 1 repeat with anElement in allUIElements try if role description of anElement is "text field" then set value of anElement to username else if role description of anElement is "secure text field" then set value of anElement to passwd end if end try end repeat try click button "Save Password" of sheet 1 of window 1 end try end repeat end tell end tell end fill_in_fields open_url("%(url)s") wait_for_page_to_load() fill_in_fields("%(username)s", "%(fixed_password)s") ''' % locals())
D = D.reshape((1,1025,87,1)) output_1 = model_1.predict(D) class_pred = np.argmax(output_1) confidence = max(output_1[0]) print(class_pred) print(confidence) os.remove('test.wav') if(class_pred == 0 and confidence > 0.99): vol = osascript.osascript('get volume settings') cur_vol = int(vol[1].split(':')[1].split(',')[0]) cur_vol = cur_vol - 20 if(cur_vol < 0): cur_vol = 0 osascript.osascript("set volume output volume "+str(cur_vol)) elif(class_pred == 1 and confidence > 0.99): vol = osascript.osascript('get volume settings') cur_vol = int(vol[1].split(':')[1].split(',')[0]) cur_vol = cur_vol + 20 if(cur_vol > 100): cur_vol = 100 osascript.osascript("set volume output volume "+str(cur_vol)) elif(class_pred == 2 and confidence > 0.9999):